-
Notifications
You must be signed in to change notification settings - Fork 715
/
reliable.go
75 lines (65 loc) · 2.41 KB
/
reliable.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
package cachestest
import (
"context"
"encoding/json"
"testing"
"github.com/prebid/prebid-server/v2/stored_requests"
)
const (
reqCacheKey = "known-req"
reqCacheVal = `{"req":true}`
)
// AssertCacheRobustness runs tests which can be used to validate any Cache that is 100% reliable.
// That is, its Save() and Invalidate() functions _alway_ work.
//
// The cacheSupplier should be a function which returns a new Cache (with no data inside) on every call.
// This will be called from separate Goroutines to make sure that different tests don't conflict.
func AssertCacheRobustness(t *testing.T, cacheSupplier func() stored_requests.CacheJSON) {
t.Run("TestCacheMiss", cacheMissTester(cacheSupplier()))
t.Run("TestCacheHit", cacheHitTester(cacheSupplier()))
t.Run("TestCacheSaveInvalidate", cacheSaveInvalidateTester(cacheSupplier()))
}
func cacheMissTester(cache stored_requests.CacheJSON) func(*testing.T) {
return func(t *testing.T) {
storedData := cache.Get(context.Background(), []string{"unknown"})
assertMapLength(t, 0, storedData)
}
}
func cacheHitTester(cache stored_requests.CacheJSON) func(*testing.T) {
return func(t *testing.T) {
cache.Save(context.Background(), map[string]json.RawMessage{
reqCacheKey: json.RawMessage(reqCacheVal),
})
reqData := cache.Get(context.Background(), []string{reqCacheKey})
assertMapLength(t, 1, reqData)
assertHasValue(t, reqData, reqCacheKey, reqCacheVal)
}
}
func cacheSaveInvalidateTester(cache stored_requests.CacheJSON) func(*testing.T) {
return func(t *testing.T) {
cache.Save(context.Background(), map[string]json.RawMessage{
reqCacheKey: json.RawMessage(reqCacheVal),
})
reqData := cache.Get(context.Background(), []string{reqCacheKey})
assertMapLength(t, 1, reqData)
cache.Invalidate(context.Background(), []string{reqCacheKey})
reqData = cache.Get(context.Background(), []string{reqCacheKey})
assertMapLength(t, 0, reqData)
}
}
func assertMapLength(t *testing.T, expectedLen int, theMap map[string]json.RawMessage) {
t.Helper()
if len(theMap) != expectedLen {
t.Errorf("Wrong map length. Expected %d, Got %d.", expectedLen, len(theMap))
}
}
func assertHasValue(t *testing.T, m map[string]json.RawMessage, key string, val string) {
t.Helper()
realVal, ok := m[key]
if !ok {
t.Errorf("Map missing required key: %s", key)
}
if val != string(realVal) {
t.Errorf("Unexpected value at key %s. Expected %s, Got %s", key, val, string(realVal))
}
}