github.com/binbinly/pkg@v0.0.11-0.20240321014439-f4fbf666eb0f/util/host_test.go (about) 1 package util 2 3 import ( 4 "net" 5 "testing" 6 7 "github.com/stretchr/testify/assert" 8 ) 9 10 func TestValidIP(t *testing.T) { 11 tests := []struct { 12 addr string 13 expect bool 14 }{ 15 {"127.0.0.1", false}, 16 {"255.255.255.255", false}, 17 {"0.0.0.0", false}, 18 {"localhost", false}, 19 {"10.1.0.1", true}, 20 {"172.16.0.1", true}, 21 {"192.168.1.1", true}, 22 {"8.8.8.8", true}, 23 {"1.1.1.1", true}, 24 {"9.255.255.255", true}, 25 {"10.0.0.0", true}, 26 {"10.255.255.255", true}, 27 {"11.0.0.0", true}, 28 {"172.15.255.255", true}, 29 {"172.16.0.0", true}, 30 {"172.16.255.255", true}, 31 {"172.23.18.255", true}, 32 {"172.31.255.255", true}, 33 {"172.31.0.0", true}, 34 {"172.32.0.0", true}, 35 {"192.167.255.255", true}, 36 {"192.168.0.0", true}, 37 {"192.168.255.255", true}, 38 {"192.169.0.0", true}, 39 {"fbff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", true}, 40 {"fc00::", true}, 41 {"fcff:1200:0:44::", true}, 42 {"fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", true}, 43 {"fe00::", true}, 44 } 45 for _, test := range tests { 46 t.Run(test.addr, func(t *testing.T) { 47 res := isValidIP(test.addr) 48 assert.Equal(t, res, test.expect) 49 }) 50 } 51 } 52 53 func TestExtract(t *testing.T) { 54 tests := []struct { 55 addr string 56 expect string 57 }{ 58 {"127.0.0.1:80", "127.0.0.1:80"}, 59 {"10.0.0.1:80", "10.0.0.1:80"}, 60 {"172.16.0.1:80", "172.16.0.1:80"}, 61 {"192.168.1.1:80", "192.168.1.1:80"}, 62 {"0.0.0.0:80", ""}, 63 {"[::]:80", ""}, 64 {":80", ""}, 65 } 66 for _, test := range tests { 67 t.Run(test.addr, func(t *testing.T) { 68 res, err := Extract(test.addr, nil) 69 assert.Nil(t, err) 70 if res != test.expect && (test.expect == "" && test.addr == test.expect) { 71 t.Fatalf("expected %s got %s", test.expect, res) 72 } 73 }) 74 } 75 } 76 77 func TestExtract2(t *testing.T) { 78 addr := "localhost:9001" 79 lis, err := net.Listen("tcp", addr) 80 assert.Nil(t, err) 81 res, err := Extract(addr, lis) 82 assert.Nil(t, err) 83 assert.Equal(t, res, "localhost:9001") 84 } 85 86 func TestPort(t *testing.T) { 87 lis, err := net.Listen("tcp", ":0") 88 assert.Nil(t, err) 89 port, ok := Port(lis) 90 assert.Equal(t, ok, true) 91 assert.NotEqual(t, port, 0) 92 } 93 94 func TestExtractHostPort(t *testing.T) { 95 host, port, err := ExtractHostPort("127.0.0.1:8000") 96 assert.Nil(t, err) 97 assert.Equal(t, host, "127.0.0.1") 98 assert.Equal(t, port, uint64(8000)) 99 100 host, port, err = ExtractHostPort("www.bilibili.com:80") 101 assert.Nil(t, err) 102 assert.Equal(t, host, "www.bilibili.com") 103 assert.Equal(t, port, uint64(80)) 104 105 host, port, err = ExtractHostPort("consul://2/33") 106 assert.Error(t, err) 107 }