github.com/Asutorufa/yuhaiin@v0.3.6-0.20240502055049-7984da7023a0/pkg/net/trie/trie_test.go (about) 1 package trie 2 3 import ( 4 "context" 5 "net" 6 "testing" 7 8 "github.com/Asutorufa/yuhaiin/pkg/net/netapi" 9 "github.com/Asutorufa/yuhaiin/pkg/utils/assert" 10 ) 11 12 func TestNewMatcher(t *testing.T) { 13 matcher := NewTrie[string]() 14 matcher.Insert("*.baidu.com", "test_baidu") 15 matcher.Insert("10.2.2.1/18", "test_cidr") 16 matcher.Insert("*.163.com", "163") 17 matcher.Insert("music.126.com", "126") 18 matcher.Insert("*.advertising.com", "advertising") 19 matcher.Insert("api.sec.miui.*", "ad_miui") 20 21 search := func(s string) string { 22 addr, _ := netapi.ParseAddress(0, net.JoinHostPort(s, "0")) 23 res, _ := matcher.Search(context.TODO(), addr) 24 return res 25 } 26 assert.Equal(t, "test_cidr", search("10.2.2.1")) 27 assert.Equal(t, "test_baidu", search("www.baidu.com")) 28 assert.Equal(t, "test_baidu", search("passport.baidu.com")) 29 assert.Equal(t, "test_baidu", search("tieba.baidu.com")) 30 assert.Equal(t, "", search("www.google.com")) 31 assert.Equal(t, "163", search("test.music.163.com")) 32 assert.Equal(t, "advertising", search("guce.advertising.com")) 33 assert.Equal(t, "", search("www.twitter.com")) 34 assert.Equal(t, "", search("www.facebook.com")) 35 assert.Equal(t, "", search("127.0.0.1")) 36 assert.Equal(t, "", search("ff::")) 37 assert.Equal(t, "ad_miui", search("api.sec.miui.com")) 38 } 39 40 func BenchmarkMapper(b *testing.B) { 41 b.StopTimer() 42 matcher := NewTrie[string]() 43 matcher.Insert("*.baidu.com", "test_baidu") 44 matcher.Insert("10.2.2.1/18", "test_cidr") 45 a1, _ := netapi.ParseAddress(0, "www.example.baidu.com:0") 46 a2, _ := netapi.ParseAddress(0, "10.2.2.1:0") 47 b.StartTimer() 48 for i := 0; i < b.N; i++ { 49 if i%2 == 1 { 50 matcher.Search(context.TODO(), a1) 51 } else { 52 matcher.Search(context.TODO(), a2) 53 } 54 } 55 }