github.com/turingchain2020/turingchain@v1.1.21/p2p/utils/util_test.go (about) 1 package utils 2 3 import ( 4 "testing" 5 "time" 6 7 "github.com/stretchr/testify/assert" 8 ) 9 10 func Test_spaceLimitCache(t *testing.T) { 11 12 c := NewSpaceLimitCache(3, 10) 13 assert.Equal(t, 3, c.capacity) 14 assert.True(t, c.Add(1, 1, 1)) 15 assert.True(t, c.Add(1, 1, 1)) 16 assert.False(t, c.Add(2, 2, 20)) 17 assert.Nil(t, c.Get(2)) 18 assert.True(t, c.Add(2, 1, 10)) 19 c.Add(3, 2, 2) 20 c.Add(4, 2, 2) 21 c.Add(5, 2, 2) 22 c.Add(6, 2, 1) 23 assert.False(t, c.Contains(3)) 24 assert.Equal(t, 3, c.data.Len()) 25 assert.Equal(t, 3, len(c.sizeMap)) 26 assert.Equal(t, 5, c.currSize) 27 assert.True(t, c.Contains(4)) 28 assert.True(t, c.Contains(5)) 29 assert.True(t, c.Add(7, 7, 8)) 30 assert.True(t, c.Contains(7)) 31 assert.Equal(t, 2, c.data.Len()) 32 assert.Equal(t, 2, len(c.sizeMap)) 33 assert.Equal(t, 9, c.currSize) 34 _, exist := c.Remove(6) 35 assert.True(t, exist) 36 _, exist = c.Remove(5) 37 assert.False(t, exist) 38 assert.Equal(t, 8, c.currSize) 39 } 40 41 func testChannelVersion(t *testing.T, channel, version int32) { 42 43 chanVer := CalcChannelVersion(channel, version) 44 chann, ver := DecodeChannelVersion(chanVer) 45 46 assert.True(t, chann == channel) 47 assert.True(t, ver == version) 48 } 49 50 func Test_ChannelVersion(t *testing.T) { 51 52 testChannelVersion(t, 0, 100) 53 testChannelVersion(t, 128, 100) 54 } 55 56 func TestFilter(t *testing.T) { 57 filter := NewFilter(10) 58 go filter.ManageRecvFilter(time.Millisecond) 59 defer filter.Close() 60 filter.GetAtomicLock() 61 62 now := time.Now().Unix() 63 assert.Equal(t, false, filter.Add("key", now)) 64 assert.Equal(t, true, filter.Contains("key")) 65 val, ok := filter.Get("key") 66 assert.Equal(t, true, ok) 67 assert.Equal(t, now, val.(int64)) 68 filter.Remove("key") 69 assert.Equal(t, false, filter.Contains("key")) 70 filter.ReleaseAtomicLock() 71 assert.Equal(t, false, filter.AddWithCheckAtomic("key", time.Now().Unix())) 72 assert.Equal(t, true, filter.AddWithCheckAtomic("key", time.Now().Unix())) 73 assert.False(t, filter.isClose()) 74 time.Sleep(time.Millisecond * 10) 75 }