github.com/dolthub/swiss@v0.2.2-0.20240312182618-f4b2babd2bc1/map_fuzz_test.go (about) 1 // Copyright 2023 Dolthub, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package swiss 16 17 import ( 18 "testing" 19 "unsafe" 20 21 "github.com/stretchr/testify/assert" 22 ) 23 24 func FuzzStringMap(f *testing.F) { 25 f.Add(uint8(1), 14, 50) 26 f.Add(uint8(2), 1, 1) 27 f.Add(uint8(2), 14, 14) 28 f.Add(uint8(2), 14, 15) 29 f.Add(uint8(2), 25, 100) 30 f.Add(uint8(2), 25, 1000) 31 f.Add(uint8(8), 0, 1) 32 f.Add(uint8(8), 1, 1) 33 f.Add(uint8(8), 14, 14) 34 f.Add(uint8(8), 14, 15) 35 f.Add(uint8(8), 25, 100) 36 f.Add(uint8(8), 25, 1000) 37 f.Fuzz(func(t *testing.T, keySz uint8, init, count int) { 38 // smaller key sizes generate more overwrites 39 fuzzTestStringMap(t, uint32(keySz), uint32(init), uint32(count)) 40 }) 41 } 42 43 func fuzzTestStringMap(t *testing.T, keySz, init, count uint32) { 44 const limit = 1024 * 1024 45 if count > limit || init > limit { 46 t.Skip() 47 } 48 m := NewMap[string, int](init) 49 if count == 0 { 50 return 51 } 52 // make tests deterministic 53 setConstSeed(m, 1) 54 55 keys := genStringData(int(keySz), int(count)) 56 golden := make(map[string]int, init) 57 for i, k := range keys { 58 m.Put(k, i) 59 golden[k] = i 60 } 61 assert.Equal(t, len(golden), m.Count()) 62 63 for k, exp := range golden { 64 act, ok := m.Get(k) 65 assert.True(t, ok) 66 assert.Equal(t, exp, act) 67 } 68 for _, k := range keys { 69 _, ok := golden[k] 70 assert.True(t, ok) 71 assert.True(t, m.Has(k)) 72 } 73 74 deletes := keys[:count/2] 75 for _, k := range deletes { 76 delete(golden, k) 77 m.Delete(k) 78 } 79 assert.Equal(t, len(golden), m.Count()) 80 81 for _, k := range deletes { 82 assert.False(t, m.Has(k)) 83 } 84 for k, exp := range golden { 85 act, ok := m.Get(k) 86 assert.True(t, ok) 87 assert.Equal(t, exp, act) 88 } 89 } 90 91 type hasher struct { 92 hash func() 93 seed uintptr 94 } 95 96 func setConstSeed[K comparable, V any](m *Map[K, V], seed uintptr) { 97 h := (*hasher)((unsafe.Pointer)(&m.hash)) 98 h.seed = seed 99 }