1
16
17 package util
18
19 import (
20 "testing"
21 )
22
23 func TestIPPart(t *testing.T) {
24 const noError = ""
25
26 testCases := []struct {
27 endpoint string
28 expectedIP string
29 expectedError string
30 }{
31 {"1.2.3.4", "1.2.3.4", noError},
32 {"1.2.3.4:9999", "1.2.3.4", noError},
33 {"2001:db8::1:1", "2001:db8::1:1", noError},
34 {"[2001:db8::2:2]:9999", "2001:db8::2:2", noError},
35 {"1.2.3.4::9999", "", "too many colons"},
36 {"1.2.3.4:[0]", "", "unexpected '[' in address"},
37 {"1.2.3:8080", "", "invalid ip part"},
38 }
39
40 for _, tc := range testCases {
41 ip := IPPart(tc.endpoint)
42 if tc.expectedError == noError {
43 if ip != tc.expectedIP {
44 t.Errorf("Unexpected IP for %s: Expected: %s, Got %s", tc.endpoint, tc.expectedIP, ip)
45 }
46 } else if ip != "" {
47 t.Errorf("Error did not occur for %s, expected: '%s' error", tc.endpoint, tc.expectedError)
48 }
49 }
50 }
51
52 func TestPortPart(t *testing.T) {
53 tests := []struct {
54 name string
55 endpoint string
56 want int
57 wantErr bool
58 }{
59 {
60 "no error parsing from ipv4-ip:port",
61 "1.2.3.4:1024",
62 1024,
63 false,
64 },
65 {
66 "no error parsing from ipv6-ip:port",
67 "[2001:db8::2:2]:9999",
68 9999,
69 false,
70 },
71 {
72 "error: missing port",
73 "1.2.3.4",
74 -1,
75 true,
76 },
77 {
78 "error: invalid port '1-2'",
79 "1.2.3.4:1-2",
80 -1,
81 true,
82 },
83 {
84 "error: invalid port 'port'",
85 "100.200.3.4:port",
86 -1,
87 true,
88 },
89 }
90 for _, tt := range tests {
91 t.Run(tt.name, func(t *testing.T) {
92 got, err := PortPart(tt.endpoint)
93 if (err != nil) != tt.wantErr {
94 t.Errorf("PortPart() error = %v, wantErr %v", err, tt.wantErr)
95 return
96 }
97 if got != tt.want {
98 t.Errorf("PortPart() = %v, want %v", got, tt.want)
99 }
100 })
101 }
102 }
103
View as plain text