github.com/pingcap/badger@v1.5.1-0.20230103063557-828f39b09b6d/cache/ring_test.go (about) 1 package cache 2 3 import ( 4 "sync" 5 "testing" 6 ) 7 8 type testConsumer struct { 9 push func([]uint64) 10 save bool 11 } 12 13 func (c *testConsumer) Push(items []uint64) bool { 14 if c.save { 15 c.push(items) 16 return true 17 } 18 return false 19 } 20 21 func TestRingDrain(t *testing.T) { 22 drains := 0 23 r := newRingBuffer(&testConsumer{ 24 push: func(items []uint64) { 25 drains++ 26 }, 27 save: true, 28 }, 1) 29 for i := 0; i < 100; i++ { 30 r.Push(uint64(i)) 31 } 32 if drains != 100 { 33 t.Fatal("buffers shouldn't be dropped with BufferItems == 1") 34 } 35 } 36 37 func TestRingReset(t *testing.T) { 38 drains := 0 39 r := newRingBuffer(&testConsumer{ 40 push: func(items []uint64) { 41 drains++ 42 }, 43 save: false, 44 }, 4) 45 for i := 0; i < 100; i++ { 46 r.Push(uint64(i)) 47 } 48 if drains != 0 { 49 t.Fatal("testConsumer shouldn't be draining") 50 } 51 } 52 53 func TestRingConsumer(t *testing.T) { 54 mu := &sync.Mutex{} 55 drainItems := make(map[uint64]struct{}) 56 r := newRingBuffer(&testConsumer{ 57 push: func(items []uint64) { 58 mu.Lock() 59 defer mu.Unlock() 60 for i := range items { 61 drainItems[items[i]] = struct{}{} 62 } 63 }, 64 save: true, 65 }, 4) 66 for i := 0; i < 100; i++ { 67 r.Push(uint64(i)) 68 } 69 l := len(drainItems) 70 if l == 0 || l > 100 { 71 t.Fatal("drains not being processed correctly") 72 } 73 }