-
Notifications
You must be signed in to change notification settings - Fork 24
/
addr_test.go
128 lines (114 loc) · 2.29 KB
/
addr_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package ndp
import (
"net"
"net/netip"
"testing"
"github.com/google/go-cmp/cmp"
)
func Test_chooseAddr(t *testing.T) {
// Assumed zone for all tests.
const zone = "eth0"
var (
ip4 = net.IPv4(192, 168, 1, 1).To4()
ip6 = mustIPv6("2001:db8::1000")
gua = mustIPv6("2001:db8::1")
ula = mustIPv6("fc00::1")
lla = mustIPv6("fe80::1")
)
addrs := []net.Addr{
// Ignore non-IP addresses.
&net.TCPAddr{IP: gua},
&net.IPNet{IP: ip4},
&net.IPNet{IP: ula},
&net.IPNet{IP: lla},
// The second GUA IPv6 address should only be found when
// Addr specifies it explicitly.
&net.IPNet{IP: gua},
&net.IPNet{IP: ip6},
}
tests := []struct {
name string
addrs []net.Addr
addr Addr
ip netip.Addr
ok bool
}{
{
name: "empty",
},
{
name: "IPv4 Addr",
addr: Addr(ip4.String()),
},
{
name: "no IPv6 addresses",
addrs: []net.Addr{
&net.IPNet{
IP: ip4,
},
},
addr: LinkLocal,
},
{
name: "ok, unspecified",
ip: netip.IPv6Unspecified(),
addr: Unspecified,
ok: true,
},
{
name: "ok, GUA",
addrs: addrs,
ip: netip.MustParseAddr("2001:db8::1"),
addr: Global,
ok: true,
},
{
name: "ok, ULA",
addrs: addrs,
ip: netip.MustParseAddr("fc00::1"),
addr: UniqueLocal,
ok: true,
},
{
name: "ok, LLA",
addrs: addrs,
ip: netip.MustParseAddr("fe80::1"),
addr: LinkLocal,
ok: true,
},
{
name: "ok, arbitrary",
addrs: addrs,
ip: netip.MustParseAddr("2001:db8::1000"),
addr: Addr(ip6.String()),
ok: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ipa, err := chooseAddr(tt.addrs, zone, tt.addr)
if err != nil && tt.ok {
t.Fatalf("unexpected error: %v", err)
}
if err == nil && !tt.ok {
t.Fatal("expected an error, but none occurred")
}
if err != nil {
t.Logf("OK error: %v", err)
return
}
ttipa := tt.ip.WithZone(zone)
if diff := cmp.Diff(ttipa, ipa, cmp.Comparer(addrEqual)); diff != "" {
t.Fatalf("unexpected IPv6 address (-want +got):\n%s", diff)
}
})
}
}
// MustIPv6 parses s as a valid IPv6 address, or it panics.
func mustIPv6(s string) net.IP {
ip := net.ParseIP(s)
if ip == nil || ip.To4() != nil {
panicf("invalid IPv6 address: %q", s)
}
return ip
}