github.com/Bytom/bytom@v1.1.2-0.20210127130405-ae40204c0b09/p2p/netaddress_test.go (about) 1 // +build !network 2 3 package p2p 4 5 import ( 6 "net" 7 "testing" 8 9 "github.com/stretchr/testify/assert" 10 "github.com/stretchr/testify/require" 11 ) 12 13 func TestNewNetAddress(t *testing.T) { 14 assert, require := assert.New(t), require.New(t) 15 16 tcpAddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:8080") 17 require.Nil(err) 18 addr := NewNetAddress(tcpAddr) 19 20 assert.Equal("127.0.0.1:8080", addr.String()) 21 22 assert.NotPanics(func() { 23 NewNetAddress(&net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8000}) 24 }, "Calling NewNetAddress with UDPAddr should not panic in testing") 25 } 26 27 func TestNewNetAddressString(t *testing.T) { 28 assert := assert.New(t) 29 30 tests := []struct { 31 addr string 32 correct bool 33 }{ 34 {"127.0.0.1:8080", true}, 35 // {"127.0.0:8080", false}, 36 {"a", false}, 37 {"127.0.0.1:a", false}, 38 {"a:8080", false}, 39 {"8082", false}, 40 {"127.0.0:8080000", false}, 41 } 42 43 for _, t := range tests { 44 addr, err := NewNetAddressString(t.addr) 45 if t.correct { 46 if assert.Nil(err, t.addr) { 47 assert.Equal(t.addr, addr.String()) 48 } 49 } else { 50 assert.NotNil(err, t.addr) 51 } 52 } 53 } 54 55 func TestNewNetAddressStrings(t *testing.T) { 56 assert, require := assert.New(t), require.New(t) 57 addrs, err := NewNetAddressStrings([]string{"127.0.0.1:8080", "127.0.0.2:8080"}) 58 require.Nil(err) 59 60 assert.Equal(2, len(addrs)) 61 } 62 63 func TestNewNetAddressIPPort(t *testing.T) { 64 assert := assert.New(t) 65 addr := NewNetAddressIPPort(net.ParseIP("127.0.0.1"), 8080) 66 67 assert.Equal("127.0.0.1:8080", addr.String()) 68 } 69 70 func TestNetAddressProperties(t *testing.T) { 71 assert, require := assert.New(t), require.New(t) 72 73 // TODO add more test cases 74 tests := []struct { 75 addr string 76 valid bool 77 local bool 78 routable bool 79 }{ 80 {"127.0.0.1:8080", true, true, false}, 81 {"ya.ru:80", true, false, true}, 82 } 83 84 for _, t := range tests { 85 addr, err := NewNetAddressString(t.addr) 86 require.Nil(err) 87 88 assert.Equal(t.valid, addr.Valid()) 89 assert.Equal(t.local, addr.Local()) 90 assert.Equal(t.routable, addr.Routable()) 91 } 92 } 93 94 func TestNetAddressReachabilityTo(t *testing.T) { 95 assert, require := assert.New(t), require.New(t) 96 97 // TODO add more test cases 98 tests := []struct { 99 addr string 100 other string 101 reachability int 102 }{ 103 {"127.0.0.1:8080", "127.0.0.1:8081", 0}, 104 {"ya.ru:80", "127.0.0.1:8080", 1}, 105 } 106 107 for _, t := range tests { 108 addr, err := NewNetAddressString(t.addr) 109 require.Nil(err) 110 111 other, err := NewNetAddressString(t.other) 112 require.Nil(err) 113 114 assert.Equal(t.reachability, addr.ReachabilityTo(other)) 115 } 116 }