summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/pkg/iprange/pool_test.go
blob: 2864b67116c4dd4addb0b7351e60139947da4ee1 (plain)
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
// SPDX-License-Identifier: GPL-3.0-or-later

package iprange

import (
	"fmt"
	"math/big"
	"net"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestPool_String(t *testing.T) {
	tests := map[string]struct {
		input      string
		wantString string
	}{
		"singe": {
			input:      "192.0.2.0-192.0.2.10",
			wantString: "192.0.2.0-192.0.2.10",
		},
		"multiple": {
			input:      "192.0.2.0-192.0.2.10 2001:db8::-2001:db8::10",
			wantString: "192.0.2.0-192.0.2.10 2001:db8::-2001:db8::10",
		},
	}

	for name, test := range tests {
		t.Run(name, func(t *testing.T) {
			rs, err := ParseRanges(test.input)
			require.NoError(t, err)
			p := Pool(rs)

			assert.Equal(t, test.wantString, p.String())
		})
	}
}

func TestPool_Size(t *testing.T) {
	tests := map[string]struct {
		input    string
		wantSize *big.Int
	}{
		"singe": {
			input:    "192.0.2.0-192.0.2.10",
			wantSize: big.NewInt(11),
		},
		"multiple": {
			input:    "192.0.2.0-192.0.2.10 2001:db8::-2001:db8::10",
			wantSize: big.NewInt(11 + 17),
		},
	}

	for name, test := range tests {
		t.Run(name, func(t *testing.T) {
			rs, err := ParseRanges(test.input)
			require.NoError(t, err)
			p := Pool(rs)

			assert.Equal(t, test.wantSize, p.Size())
		})
	}
}

func TestPool_Contains(t *testing.T) {
	tests := map[string]struct {
		input    string
		ip       string
		wantFail bool
	}{
		"inside first": {
			input: "192.0.2.0-192.0.2.10 192.0.2.20-192.0.2.30 2001:db8::-2001:db8::10",
			ip:    "192.0.2.5",
		},
		"inside last": {
			input: "192.0.2.0-192.0.2.10 192.0.2.20-192.0.2.30 2001:db8::-2001:db8::10",
			ip:    "2001:db8::5",
		},
		"outside": {
			input:    "192.0.2.0-192.0.2.10 192.0.2.20-192.0.2.30 2001:db8::-2001:db8::10",
			ip:       "192.0.2.100",
			wantFail: true,
		},
	}

	for name, test := range tests {
		name = fmt.Sprintf("%s (range: %s, ip: %s)", name, test.input, test.ip)
		t.Run(name, func(t *testing.T) {
			rs, err := ParseRanges(test.input)
			require.NoError(t, err)
			ip := net.ParseIP(test.ip)
			require.NotNil(t, ip)
			p := Pool(rs)

			if test.wantFail {
				assert.False(t, p.Contains(ip))
			} else {
				assert.True(t, p.Contains(ip))
			}
		})
	}
}