github.com/anakojm/hugo-katex@v0.0.0-20231023141351-42d6f5de9c0b/cache/filecache/filecache_pruner_test.go (about) 1 // Copyright 2018 The Hugo Authors. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package filecache_test 15 16 import ( 17 "fmt" 18 "testing" 19 "time" 20 21 "github.com/gohugoio/hugo/cache/filecache" 22 "github.com/spf13/afero" 23 24 qt "github.com/frankban/quicktest" 25 ) 26 27 func TestPrune(t *testing.T) { 28 t.Parallel() 29 30 c := qt.New(t) 31 32 configStr := ` 33 resourceDir = "myresources" 34 contentDir = "content" 35 dataDir = "data" 36 i18nDir = "i18n" 37 layoutDir = "layouts" 38 assetDir = "assets" 39 archeTypedir = "archetypes" 40 41 [caches] 42 [caches.getjson] 43 maxAge = "200ms" 44 dir = "/cache/c" 45 [caches.getcsv] 46 maxAge = "200ms" 47 dir = "/cache/d" 48 [caches.assets] 49 maxAge = "200ms" 50 dir = ":resourceDir/_gen" 51 [caches.images] 52 maxAge = "200ms" 53 dir = ":resourceDir/_gen" 54 ` 55 56 for _, name := range []string{filecache.CacheKeyGetCSV, filecache.CacheKeyGetJSON, filecache.CacheKeyAssets, filecache.CacheKeyImages} { 57 msg := qt.Commentf("cache: %s", name) 58 p := newPathsSpec(t, afero.NewMemMapFs(), configStr) 59 caches, err := filecache.NewCaches(p) 60 c.Assert(err, qt.IsNil) 61 cache := caches[name] 62 for i := 0; i < 10; i++ { 63 id := fmt.Sprintf("i%d", i) 64 cache.GetOrCreateBytes(id, func() ([]byte, error) { 65 return []byte("abc"), nil 66 }) 67 if i == 4 { 68 // This will expire the first 5 69 time.Sleep(201 * time.Millisecond) 70 } 71 } 72 73 count, err := caches.Prune() 74 c.Assert(err, qt.IsNil) 75 c.Assert(count, qt.Equals, 5, msg) 76 77 for i := 0; i < 10; i++ { 78 id := fmt.Sprintf("i%d", i) 79 v := cache.GetString(id) 80 if i < 5 { 81 c.Assert(v, qt.Equals, "") 82 } else { 83 c.Assert(v, qt.Equals, "abc") 84 } 85 } 86 87 caches, err = filecache.NewCaches(p) 88 c.Assert(err, qt.IsNil) 89 cache = caches[name] 90 // Touch one and then prune. 91 cache.GetOrCreateBytes("i5", func() ([]byte, error) { 92 return []byte("abc"), nil 93 }) 94 95 count, err = caches.Prune() 96 c.Assert(err, qt.IsNil) 97 c.Assert(count, qt.Equals, 4) 98 99 // Now only the i5 should be left. 100 for i := 0; i < 10; i++ { 101 id := fmt.Sprintf("i%d", i) 102 v := cache.GetString(id) 103 if i != 5 { 104 c.Assert(v, qt.Equals, "") 105 } else { 106 c.Assert(v, qt.Equals, "abc") 107 } 108 } 109 110 } 111 }