-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache_fuzzing_test.go
100 lines (75 loc) · 1.93 KB
/
cache_fuzzing_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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package cache_test
import (
"crypto/rand"
"encoding/base64"
"fmt"
"testing"
"time"
cache "github.com/microup/vcache"
)
func TestFuzzing_Add(t *testing.T) {
t.Parallel()
testCache := cache.New(time.Second, time.Minute)
keys := []string{}
for index := 0; index < 1000; index++ {
key := generateRandomKey(32)
value, err := generateRandomValue()
if err != nil {
t.Fatalf("failed test, get err: %v", err)
}
keys = append(keys, key)
_ = testCache.Add(key, value)
_, foundKey := testCache.Get(key)
if !foundKey {
t.Fatalf("Key %s not found in cache", key)
}
// Ensure that each key added to the cache is unique
for _, existingKey := range keys[:index] {
if existingKey == key {
t.Fatalf("Key %s is not unique", key)
}
}
}
}
func TestFuzzingCache_Delete(t *testing.T) {
t.Parallel()
testCache := cache.New(time.Second, time.Minute)
keys := []string{}
for index := 0; index < 1000; index++ {
key := generateRandomKey(32)
value, err := generateRandomValue()
if err != nil {
t.Fatalf("failed test, get err: %v", err)
}
keys = append(keys, key) //nolint:staticcheck
err = testCache.Add(key, value)
if err != nil {
continue
}
testCache.Delete(key)
_, foundKey := testCache.Get(key)
if foundKey {
t.Fatalf("Key %s should not be found in cache after deletion", key)
}
}
}
func generateRandomKey(length int) string {
chars := []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
key := make([]byte, length)
_, err := rand.Read(key)
if err != nil {
return ""
}
for i, b := range key {
key[i] = chars[b%byte(len(chars))]
}
return base64.RawURLEncoding.EncodeToString(key)
}
func generateRandomValue() (interface{}, error) {
randomInt := make([]byte, 4)
_, err := rand.Read(randomInt)
if err != nil {
return nil, fmt.Errorf("%w", err)
}
return int(randomInt[0])*256*256*256 + int(randomInt[1])*256*256 + int(randomInt[2])*256 + int(randomInt[3]), nil
}