github.com/TeaOSLab/EdgeNode@v1.3.8/internal/iplibrary/ip_item_test.go (about) 1 package iplibrary_test 2 3 import ( 4 "github.com/TeaOSLab/EdgeCommon/pkg/iputils" 5 "github.com/TeaOSLab/EdgeNode/internal/iplibrary" 6 "github.com/TeaOSLab/EdgeNode/internal/utils/testutils" 7 "github.com/iwind/TeaGo/assert" 8 "math/rand" 9 "runtime" 10 "strconv" 11 "testing" 12 "time" 13 ) 14 15 func TestIPItem_Contains(t *testing.T) { 16 var a = assert.NewAssertion(t) 17 18 { 19 var item = &iplibrary.IPItem{ 20 IPFrom: iputils.ToBytes("192.168.1.100"), 21 IPTo: nil, 22 ExpiredAt: 0, 23 } 24 a.IsTrue(item.Contains(iputils.ToBytes("192.168.1.100"))) 25 } 26 27 { 28 var item = &iplibrary.IPItem{ 29 IPFrom: iputils.ToBytes("192.168.1.100"), 30 IPTo: nil, 31 ExpiredAt: time.Now().Unix() + 1, 32 } 33 a.IsTrue(item.Contains(iputils.ToBytes("192.168.1.100"))) 34 } 35 36 { 37 var item = &iplibrary.IPItem{ 38 IPFrom: iputils.ToBytes("192.168.1.100"), 39 IPTo: nil, 40 ExpiredAt: time.Now().Unix() - 1, 41 } 42 a.IsFalse(item.Contains(iputils.ToBytes("192.168.1.100"))) 43 } 44 { 45 var item = &iplibrary.IPItem{ 46 IPFrom: iputils.ToBytes("192.168.1.100"), 47 IPTo: nil, 48 ExpiredAt: 0, 49 } 50 a.IsFalse(item.Contains(iputils.ToBytes("192.168.1.101"))) 51 } 52 53 { 54 var item = &iplibrary.IPItem{ 55 IPFrom: iputils.ToBytes("192.168.1.1"), 56 IPTo: iputils.ToBytes("192.168.1.101"), 57 ExpiredAt: 0, 58 } 59 a.IsTrue(item.Contains(iputils.ToBytes("192.168.1.100"))) 60 } 61 62 { 63 var item = &iplibrary.IPItem{ 64 IPFrom: iputils.ToBytes("192.168.1.1"), 65 IPTo: iputils.ToBytes("192.168.1.100"), 66 ExpiredAt: 0, 67 } 68 a.IsTrue(item.Contains(iputils.ToBytes("192.168.1.100"))) 69 } 70 71 { 72 var item = &iplibrary.IPItem{ 73 IPFrom: iputils.ToBytes("192.168.1.1"), 74 IPTo: iputils.ToBytes("192.168.1.101"), 75 ExpiredAt: 0, 76 } 77 a.IsTrue(item.Contains(iputils.ToBytes("192.168.1.1"))) 78 } 79 } 80 81 func TestIPItem_Memory(t *testing.T) { 82 var isSingleTest = testutils.IsSingleTesting() 83 84 var list = iplibrary.NewIPList() 85 var count = 100 86 if isSingleTest { 87 count = 2_000_000 88 } 89 for i := 0; i < count; i++ { 90 list.Add(&iplibrary.IPItem{ 91 Type: "ip", 92 Id: uint64(i), 93 IPFrom: iputils.ToBytes("192.168.1.1"), 94 IPTo: nil, 95 ExpiredAt: time.Now().Unix(), 96 EventLevel: "", 97 }) 98 } 99 100 runtime.GC() 101 102 t.Log("waiting") 103 if isSingleTest { 104 time.Sleep(10 * time.Second) 105 } 106 } 107 108 func BenchmarkIPItem_Contains(b *testing.B) { 109 runtime.GOMAXPROCS(1) 110 111 var item = &iplibrary.IPItem{ 112 IPFrom: iputils.ToBytes("192.168.1.1"), 113 IPTo: iputils.ToBytes("192.168.1.101"), 114 ExpiredAt: 0, 115 } 116 117 b.ResetTimer() 118 119 b.RunParallel(func(pb *testing.PB) { 120 for pb.Next() { 121 var ip = iputils.ToBytes("192.168.1." + strconv.Itoa(rand.Int()%255)) 122 item.Contains(ip) 123 } 124 }) 125 }