github.com/yaling888/clash@v1.53.0/component/trie/domain_test.go (about) 1 package trie 2 3 import ( 4 "net/netip" 5 "testing" 6 7 "github.com/stretchr/testify/assert" 8 ) 9 10 var localIP = netip.AddrFrom4([4]byte{127, 0, 0, 1}) 11 12 func TestTrie_Basic(t *testing.T) { 13 tree := New[netip.Addr]() 14 domains := []string{ 15 "example.com", 16 "google.com", 17 "localhost", 18 } 19 20 for _, domain := range domains { 21 tree.Insert(domain, localIP) 22 } 23 24 node := tree.Search("example.com") 25 assert.NotNil(t, node) 26 assert.True(t, node.Data == localIP) 27 assert.NotNil(t, tree.Insert("", localIP)) 28 assert.Nil(t, tree.Search("")) 29 assert.NotNil(t, tree.Search("localhost")) 30 assert.Nil(t, tree.Search("www.google.com")) 31 } 32 33 func TestTrie_Wildcard(t *testing.T) { 34 tree := New[netip.Addr]() 35 domains := []string{ 36 "*.example.com", 37 "sub.*.example.com", 38 "*.dev", 39 ".org", 40 ".example.net", 41 ".apple.*", 42 "+.foo.com", 43 "+.stun.*.*", 44 "+.stun.*.*.*", 45 "+.stun.*.*.*.*", 46 "stun.l.google.com", 47 } 48 49 for _, domain := range domains { 50 tree.Insert(domain, localIP) 51 } 52 53 assert.NotNil(t, tree.Search("sub.example.com")) 54 assert.NotNil(t, tree.Search("sub.foo.example.com")) 55 assert.NotNil(t, tree.Search("test.org")) 56 assert.NotNil(t, tree.Search("test.example.net")) 57 assert.NotNil(t, tree.Search("test.apple.com")) 58 assert.NotNil(t, tree.Search("test.foo.com")) 59 assert.NotNil(t, tree.Search("foo.com")) 60 assert.NotNil(t, tree.Search("global.stun.website.com")) 61 assert.Nil(t, tree.Search("foo.sub.example.com")) 62 assert.Nil(t, tree.Search("foo.example.dev")) 63 assert.Nil(t, tree.Search("example.com")) 64 } 65 66 func TestTrie_Priority(t *testing.T) { 67 tree := New[int]() 68 domains := []string{ 69 ".dev", 70 "example.dev", 71 "*.example.dev", 72 "test.example.dev", 73 } 74 75 assertFn := func(domain string, data int) { 76 node := tree.Search(domain) 77 assert.NotNil(t, node) 78 assert.Equal(t, data, node.Data) 79 } 80 81 for idx, domain := range domains { 82 tree.Insert(domain, idx+1) 83 } 84 85 assertFn("test.dev", 1) 86 assertFn("foo.bar.dev", 1) 87 assertFn("example.dev", 2) 88 assertFn("foo.example.dev", 3) 89 assertFn("test.example.dev", 4) 90 } 91 92 func TestTrie_Boundary(t *testing.T) { 93 tree := New[netip.Addr]() 94 tree.Insert("*.dev", localIP) 95 96 assert.NotNil(t, tree.Insert(".", localIP)) 97 assert.NotNil(t, tree.Insert("..dev", localIP)) 98 assert.Nil(t, tree.Search("dev")) 99 } 100 101 func TestTrie_WildcardBoundary(t *testing.T) { 102 tree := New[netip.Addr]() 103 tree.Insert("+.*", localIP) 104 tree.Insert("stun.*.*.*", localIP) 105 106 assert.NotNil(t, tree.Search("example.com")) 107 }