github.com/Asutorufa/yuhaiin@v0.3.6-0.20240502055049-7984da7023a0/pkg/net/proxy/shadowsocks/internal/bloomring_test.go (about) 1 package internal_test 2 3 import ( 4 "fmt" 5 "os" 6 "testing" 7 8 "github.com/Asutorufa/yuhaiin/pkg/net/proxy/shadowsocks/internal" 9 ) 10 11 var ( 12 bloomRingInstance *internal.BloomRing 13 ) 14 15 func TestMain(m *testing.M) { 16 bloomRingInstance = internal.NewBloomRing(internal.DefaultSFSlot, int(internal.DefaultSFCapacity), 17 internal.DefaultSFFPR) 18 os.Exit(m.Run()) 19 } 20 21 func TestBloomRing_Add(t *testing.T) { 22 defer func() { 23 if any := recover(); any != nil { 24 t.Fatalf("Should not got panic while adding item: %v", any) 25 } 26 }() 27 bloomRingInstance.Add(make([]byte, 16)) 28 } 29 30 func TestBloomRing_NilAdd(t *testing.T) { 31 defer func() { 32 if any := recover(); any != nil { 33 t.Fatalf("Should not got panic while adding item: %v", any) 34 } 35 }() 36 var nilRing *internal.BloomRing 37 nilRing.Add(make([]byte, 16)) 38 } 39 40 func TestBloomRing_Test(t *testing.T) { 41 buf := []byte("shadowsocks") 42 bloomRingInstance.Add(buf) 43 if !bloomRingInstance.Test(buf) { 44 t.Fatal("Test on filter missing") 45 } 46 } 47 48 func TestBloomRing_NilTestIsFalse(t *testing.T) { 49 var nilRing *internal.BloomRing 50 if nilRing.Test([]byte("shadowsocks")) { 51 t.Fatal("Test should return false for nil BloomRing") 52 } 53 } 54 55 func BenchmarkBloomRing(b *testing.B) { 56 // Generate test samples with different length 57 samples := make([][]byte, internal.DefaultSFCapacity-internal.DefaultSFSlot) 58 var checkPoints [][]byte 59 for i := 0; i < len(samples); i++ { 60 samples[i] = []byte(fmt.Sprint(i)) 61 if i%1000 == 0 { 62 checkPoints = append(checkPoints, samples[i]) 63 } 64 } 65 b.Logf("Generated %d samples and %d check points", len(samples), len(checkPoints)) 66 for i := 1; i < 16; i++ { 67 b.Run(fmt.Sprintf("Slot%d", i), benchmarkBloomRing(samples, checkPoints, i)) 68 } 69 } 70 71 func benchmarkBloomRing(samples, checkPoints [][]byte, slot int) func(*testing.B) { 72 filter := internal.NewBloomRing(slot, int(internal.DefaultSFCapacity), internal.DefaultSFFPR) 73 for _, sample := range samples { 74 filter.Add(sample) 75 } 76 return func(b *testing.B) { 77 b.ResetTimer() 78 b.ReportAllocs() 79 for i := 0; i < b.N; i++ { 80 for _, cp := range checkPoints { 81 filter.Test(cp) 82 } 83 } 84 } 85 }