github.com/QuangTung97/bigcache@v0.1.0/bigcache_test.go (about) 1 package bigcache 2 3 import ( 4 "github.com/stretchr/testify/assert" 5 "testing" 6 ) 7 8 func TestNextPowerOfTwo(t *testing.T) { 9 assert.Equal(t, 1, nextPowerOfTwo(1)) 10 assert.Equal(t, 2, nextPowerOfTwo(2)) 11 assert.Equal(t, 4, nextPowerOfTwo(3)) 12 assert.Equal(t, 16, nextPowerOfTwo(15)) 13 assert.Equal(t, 16, nextPowerOfTwo(12)) 14 assert.Equal(t, 16, nextPowerOfTwo(16)) 15 assert.Equal(t, 64, nextPowerOfTwo(59)) 16 } 17 18 func TestGetSegmentIndex(t *testing.T) { 19 mask, shift := computeSegmentMask(1) 20 assert.Equal(t, uint64(0x0), mask) 21 assert.Equal(t, 64, shift) 22 23 mask, shift = computeSegmentMask(16) 24 assert.Equal(t, uint64(0xf<<60), mask) 25 assert.Equal(t, 60, shift) 26 27 assert.Equal(t, 0, getSegmentIndex(0xf<<60, 60, 0x0033445500000000)) 28 assert.Equal(t, 2, getSegmentIndex(0xf<<60, 60, 0x2033445500000000)) 29 30 mask, shift = computeSegmentMask(64) 31 assert.Equal(t, uint64(0xfc<<56), mask) 32 assert.Equal(t, 58, shift) 33 34 assert.Equal(t, 0b010110, getSegmentIndex(mask, shift, 0x5933445500000000)) 35 } 36 37 func TestCache(t *testing.T) { 38 c := New(3, 12345) 39 40 c.Put([]byte{10, 11, 12}, []byte{20, 21, 22, 20}) 41 c.Put([]byte{10, 11, 13}, []byte{20, 21, 22, 21}) 42 c.Put([]byte{10, 11, 14}, []byte{20, 21, 22, 22}) 43 44 value := make([]byte, 20) 45 46 n, ok := c.Get([]byte{10, 11, 12}, value) 47 assert.Equal(t, true, ok) 48 assert.Equal(t, []byte{20, 21, 22, 20}, value[:n]) 49 50 n, ok = c.Get([]byte{10, 11, 13}, value) 51 assert.Equal(t, true, ok) 52 assert.Equal(t, []byte{20, 21, 22, 21}, value[:n]) 53 54 n, ok = c.Get([]byte{10, 11, 15}, value) 55 assert.Equal(t, false, ok) 56 assert.Equal(t, []byte{}, value[:n]) 57 58 assert.Equal(t, uint64(3), c.GetTotal()) 59 assert.Equal(t, uint64(2), c.GetHitCount()) 60 61 ok = c.Delete([]byte{10, 11, 12}) 62 assert.Equal(t, true, ok) 63 64 ok = c.Delete([]byte{10, 11, 12}) 65 assert.Equal(t, false, ok) 66 67 n, ok = c.Get([]byte{10, 11, 12}, value) 68 assert.Equal(t, false, ok) 69 assert.Equal(t, []byte{}, value[:n]) 70 71 assert.Equal(t, uint64(2), c.GetTotal()) 72 assert.Equal(t, uint64(2), c.GetHitCount()) 73 assert.Equal(t, uint64(4), c.GetAccessCount()) 74 } 75 76 func TestCache_New_Panic(t *testing.T) { 77 assert.PanicsWithValue(t, "numSegments must not be < 1", func() { 78 New(0, 12345) 79 }) 80 }