forked from cilium/cilium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cidr_test.go
80 lines (68 loc) · 1.88 KB
/
cidr_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
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package ip
import (
"net"
"net/netip"
"testing"
"github.com/stretchr/testify/assert"
)
func TestAddrToIPNet(t *testing.T) {
_, v4IPNet, err := net.ParseCIDR("1.1.1.1/32")
assert.NoError(t, err)
_, v6IPNet, err := net.ParseCIDR("::ff/128")
assert.NoError(t, err)
ip4 := netip.MustParseAddr("1.1.1.1")
assert.NoError(t, err)
assert.Equal(t, v4IPNet, AddrToIPNet(ip4))
ip6 := netip.MustParseAddr("::ff")
assert.NoError(t, err)
assert.Equal(t, v6IPNet, AddrToIPNet(ip6))
var nilNet *net.IPNet
assert.Equal(t, nilNet, AddrToIPNet(netip.Addr{}))
}
func TestIPToNetPrefix(t *testing.T) {
v4, _, err := net.ParseCIDR("1.1.1.1/32")
assert.NoError(t, err)
v6, _, err := net.ParseCIDR("::ff/128")
assert.NoError(t, err)
assert.Equal(t, netip.PrefixFrom(netip.MustParseAddr(v4.String()), 32), IPToNetPrefix(v4.To4()))
assert.Equal(t, netip.PrefixFrom(netip.MustParseAddr(v6.String()), 128), IPToNetPrefix(v6.To16()))
assert.Equal(t, netip.Prefix{}, IPToNetPrefix(nil))
}
func mustParseCIDR(t *testing.T, s string) *net.IPNet {
_, n, err := net.ParseCIDR(s)
assert.NoError(t, err)
return n
}
func TestNetsContainsAny(t *testing.T) {
tests := []struct {
name string
a []*net.IPNet
b []*net.IPNet
ret bool
}{
{
name: "a contains b",
a: []*net.IPNet{mustParseCIDR(t, "0.0.0.0/0")},
b: []*net.IPNet{mustParseCIDR(t, "192.0.0.1/32")},
ret: true,
},
{
name: "b contains a",
a: []*net.IPNet{mustParseCIDR(t, "192.0.0.1/32")},
b: []*net.IPNet{mustParseCIDR(t, "0.0.0.0/0")},
},
{
name: "a equals b",
a: []*net.IPNet{mustParseCIDR(t, "192.0.0.1/32")},
b: []*net.IPNet{mustParseCIDR(t, "192.0.0.1/32")},
ret: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.ret, NetsContainsAny(tt.a, tt.b))
})
}
}