-
Notifications
You must be signed in to change notification settings - Fork 61
/
caching_file_reader_test.go
74 lines (62 loc) · 1.5 KB
/
caching_file_reader_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package kubeauth
import (
"io/ioutil"
"os"
"testing"
"time"
)
func TestCachingFileReader(t *testing.T) {
content1 := "before"
content2 := "after"
// Create temporary file.
f, err := ioutil.TempFile("", "testfile")
if err != nil {
t.Error(err)
}
f.Close()
defer os.Remove(f.Name())
currentTime := time.Now()
r := newCachingFileReader(f.Name(), 1*time.Minute,
func() time.Time {
return currentTime
})
// Write initial content to file and check that we can read it.
err = ioutil.WriteFile(f.Name(), []byte(content1), 0o644)
if err != nil {
t.Error(err)
}
got, err := r.ReadFile()
if err != nil {
t.Error(err)
}
if got != content1 {
t.Errorf("got '%s', expected '%s'", got, content1)
}
// Write new content to the file.
err = ioutil.WriteFile(f.Name(), []byte(content2), 0o644)
if err != nil {
t.Error(err)
}
// Advance simulated time, but not enough for cache to expire.
currentTime = currentTime.Add(30 * time.Second)
// Read again and check we still got the old cached content.
got, err = r.ReadFile()
if err != nil {
t.Error(err)
}
if got != content1 {
t.Errorf("got '%s', expected '%s'", got, content1)
}
// Advance simulated time for cache to expire.
currentTime = currentTime.Add(30 * time.Second)
// Read again and check that we got the new content.
got, err = r.ReadFile()
if err != nil {
t.Error(err)
}
if got != content2 {
t.Errorf("got '%s', expected '%s'", got, content2)
}
}