-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdmap_test.go
114 lines (90 loc) · 2.14 KB
/
dmap_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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package dmap
import (
"fmt"
"math/rand"
"os"
"testing"
"github.com/stretchr/testify/require"
)
var keyPrefixes = []string{"key", "otherkey", "oldkey", "keynew", "fookey"}
var keys []string
var bm DMap[string, string] // used for benchmarking Get
func prepareTestData[V any](m DMap[string, V], nkeys int, testval V) {
keys = make([]string, nkeys)
for i := 0; i < nkeys; i++ {
key := fmt.Sprintf("%s_%d", keyPrefixes[rand.Intn(len(keyPrefixes))], i)
m.Set(key, testval)
keys[i] = key
}
}
func TestNew(t *testing.T) {
m := New[string, string](10)
require.NotNil(t, m)
require.Equal(t, 10, len(m))
}
func TestSetGetWithStrKV(t *testing.T) {
m := New[string, string](10)
prepareTestData(m, 10000, "some val")
for i := 0; i < 50; i++ {
val, e := m.Get(keys[rand.Intn(len(keys))])
require.Equal(t, "some val", val)
require.True(t, e)
}
}
func TestKeys(t *testing.T) {
m := New[string, string](10)
prepareTestData(m, 10000, "some val")
got := m.Keys()
require.ElementsMatch(t, got, keys)
}
func TestHas(t *testing.T) {
m := New[string, string](10)
prepareTestData(m, 10000, "some val")
for i := 0; i < 50; i++ {
ok := m.Has(keys[rand.Intn(len(keys))])
require.True(t, ok)
}
ok := m.Has("nonexistentkey")
require.False(t, ok)
}
func TestCount(t *testing.T) {
m := New[string, string](10)
prepareTestData(m, 10000, "some val")
got := m.Count()
require.EqualValues(t, 10000, got)
}
func BenchmarkSet(b *testing.B) {
l := len(keyPrefixes)
for i := 0; i < b.N; i++ {
for _, nkeys := range []int{100000, 1000000} {
b.Run(fmt.Sprintf("%d_keys", nkeys), func(_ *testing.B) {
m := New[string, string](10)
for i := 0; i < nkeys; i++ {
key := fmt.Sprintf("%s_%d", keyPrefixes[i%l], i)
m.Set(key, "some val")
}
})
}
}
}
func BenchmarkGet(b *testing.B) {
for i := 0; i < b.N; i++ {
bm.Get(keys[i%100000])
}
}
func BenchmarkKeys(b *testing.B) {
for i := 0; i < b.N; i++ {
bm.Keys()
}
}
func BenchmarkCount(b *testing.B) {
for i := 0; i < b.N; i++ {
bm.Count()
}
}
func TestMain(m *testing.M) {
rand.Seed(42)
bm = New[string, string](10)
prepareTestData(bm, 100000, "some val")
os.Exit(m.Run())
}