-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage_test.go
81 lines (71 loc) · 1.73 KB
/
storage_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
75
76
77
78
79
80
81
package main
import (
"testing"
"time"
)
var userSet1 = Users{
{ID: 1, Name: "Aldous Huxley", Email: "[email protected]"},
{ID: 2, Name: "Ray Bradbery", Email: "[email protected]"},
{ID: 3, Name: "George Orwell", Email: "[email protected]"},
}
var userSet2 = Users{
{ID: 4, Name: "Brad Pitt", Email: "[email protected]"},
{ID: 5, Name: "Marsha B", Email: "[email protected]"},
}
type mockUserGetter struct {
used bool
userSet Users
}
func NewMockUserGetter() *mockUserGetter {
return &mockUserGetter{
userSet: userSet1,
}
}
func (mock *mockUserGetter) Search(_ string) (Users, error) {
mock.used = true
return mock.userSet, nil
}
func TestStorageSearch(t *testing.T) {
tt := []struct {
name, term string
cacheExpiry time.Duration
users Users
fetcherUsed, injectCache bool
}{
{
name: "fetches when data not cached",
term: "test",
cacheExpiry: 0 * time.Second,
users: userSet1,
fetcherUsed: true,
injectCache: false,
},
{
name: "uses cached data when present",
term: "test",
cacheExpiry: 9999 * time.Hour,
users: userSet1,
fetcherUsed: false,
injectCache: true,
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
mockFetcher := NewMockUserGetter()
storage := NewStorage(mockFetcher, tc.cacheExpiry)
if tc.injectCache {
storage.cache[tc.term] = UserCache{
createdAt: time.Now(),
users: tc.users,
}
}
_, err := storage.Search(tc.term)
if err != nil {
t.Errorf("wanted no error, got %v", err)
}
if mockFetcher.used != tc.fetcherUsed {
t.Errorf("wanted fetcher use to == %v, got %v", tc.fetcherUsed, mockFetcher.used)
}
})
}
}