github.com/blong14/gache@v0.0.0-20240124023949-89416fd8bbfa/internal/db/table_test.go (about) 1 package db_test 2 3 import ( 4 "encoding/binary" 5 "math/rand" 6 "os" 7 "path/filepath" 8 "sync" 9 "testing" 10 "time" 11 12 gdb "github.com/blong14/gache/internal/db" 13 ) 14 15 func tearDown(t *testing.T) { 16 err := os.Remove(filepath.Join("testdata", "default-wal.dat")) 17 if err != nil { 18 t.Log(err) 19 } 20 err = os.Remove(filepath.Join("testdata", "default.dat")) 21 if err != nil { 22 t.Log(err) 23 } 24 } 25 26 func setUp(t *testing.T, count int) [][]byte { 27 keys := make([][]byte, 0) 28 rng := rand.New(rand.NewSource(time.Now().UnixNano())) 29 for i := 0; i < count; i++ { 30 buf := make([]byte, 8) 31 key := random(rng, buf) 32 keys = append(keys, key) 33 } 34 return keys 35 } 36 37 func random(rng *rand.Rand, b []byte) []byte { 38 key := rng.Uint32() 39 key2 := rng.Uint32() 40 binary.LittleEndian.PutUint32(b, key) 41 binary.LittleEndian.PutUint32(b[4:], key2) 42 return b 43 } 44 45 func TestFileDB(t *testing.T) { 46 t.Skip("skipping...") 47 t.Cleanup(func() { 48 tearDown(t) 49 }) 50 db := gdb.New( 51 &gdb.TableOpts{ 52 DataDir: []byte("testdata"), 53 TableName: []byte("default"), 54 InMemory: false, 55 WalMode: true, 56 }, 57 ) 58 count := 64 59 keys := setUp(t, count) 60 // given 61 var wg sync.WaitGroup 62 for _, key := range keys { 63 wg.Add(1) 64 go func(k []byte) { 65 defer wg.Done() 66 err := db.Set(k, k) 67 if err != nil { 68 t.Error(err) 69 } 70 }(key) 71 } 72 wg.Wait() 73 // when 74 for _, i := range keys { 75 wg.Add(1) 76 go func(k []byte) { 77 defer wg.Done() 78 if _, ok := db.Get(k); !ok { 79 t.Errorf("missing rawKey %s", k) 80 } 81 }(i) 82 } 83 wg.Wait() 84 db.Close() 85 } 86 87 func TestInMemoryDB(t *testing.T) { 88 db := gdb.New( 89 &gdb.TableOpts{ 90 DataDir: []byte("testdata"), 91 TableName: []byte("default"), 92 InMemory: true, 93 WalMode: false, 94 }, 95 ) 96 count := 64 97 keys := setUp(t, count) 98 // given 99 var wg sync.WaitGroup 100 for _, key := range keys { 101 wg.Add(1) 102 go func(k []byte) { 103 defer wg.Done() 104 err := db.Set(k, k) 105 if err != nil { 106 t.Error(err) 107 } 108 }(key) 109 } 110 wg.Wait() 111 // when 112 for _, i := range keys { 113 wg.Add(1) 114 go func(k []byte) { 115 defer wg.Done() 116 if _, ok := db.Get(k); !ok { 117 t.Errorf("missing rawKey %s", k) 118 } 119 }(i) 120 } 121 wg.Wait() 122 db.Close() 123 }