filecache_pruner_test.go (2522B)
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
15
16 import (
17 "fmt"
18 "testing"
19 "time"
20
21 "github.com/spf13/afero"
22
23 qt "github.com/frankban/quicktest"
24 )
25
26 func TestPrune(t *testing.T) {
27 t.Parallel()
28
29 c := qt.New(t)
30
31 configStr := `
32 resourceDir = "myresources"
33 contentDir = "content"
34 dataDir = "data"
35 i18nDir = "i18n"
36 layoutDir = "layouts"
37 assetDir = "assets"
38 archeTypedir = "archetypes"
39
40 [caches]
41 [caches.getjson]
42 maxAge = "200ms"
43 dir = "/cache/c"
44 [caches.getcsv]
45 maxAge = "200ms"
46 dir = "/cache/d"
47 [caches.assets]
48 maxAge = "200ms"
49 dir = ":resourceDir/_gen"
50 [caches.images]
51 maxAge = "200ms"
52 dir = ":resourceDir/_gen"
53 `
54
55 for _, name := range []string{cacheKeyGetCSV, cacheKeyGetJSON, cacheKeyAssets, cacheKeyImages} {
56 msg := qt.Commentf("cache: %s", name)
57 p := newPathsSpec(t, afero.NewMemMapFs(), configStr)
58 caches, err := NewCaches(p)
59 c.Assert(err, qt.IsNil)
60 cache := caches[name]
61 for i := 0; i < 10; i++ {
62 id := fmt.Sprintf("i%d", i)
63 cache.GetOrCreateBytes(id, func() ([]byte, error) {
64 return []byte("abc"), nil
65 })
66 if i == 4 {
67 // This will expire the first 5
68 time.Sleep(201 * time.Millisecond)
69 }
70 }
71
72 count, err := caches.Prune()
73 c.Assert(err, qt.IsNil)
74 c.Assert(count, qt.Equals, 5, msg)
75
76 for i := 0; i < 10; i++ {
77 id := fmt.Sprintf("i%d", i)
78 v := cache.getString(id)
79 if i < 5 {
80 c.Assert(v, qt.Equals, "")
81 } else {
82 c.Assert(v, qt.Equals, "abc")
83 }
84 }
85
86 caches, err = NewCaches(p)
87 c.Assert(err, qt.IsNil)
88 cache = caches[name]
89 // Touch one and then prune.
90 cache.GetOrCreateBytes("i5", func() ([]byte, error) {
91 return []byte("abc"), nil
92 })
93
94 count, err = caches.Prune()
95 c.Assert(err, qt.IsNil)
96 c.Assert(count, qt.Equals, 4)
97
98 // Now only the i5 should be left.
99 for i := 0; i < 10; i++ {
100 id := fmt.Sprintf("i%d", i)
101 v := cache.getString(id)
102 if i != 5 {
103 c.Assert(v, qt.Equals, "")
104 } else {
105 c.Assert(v, qt.Equals, "abc")
106 }
107 }
108
109 }
110 }