-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathport_test.go
127 lines (117 loc) · 2.12 KB
/
port_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
// Copyright (c) 2021, Roel Schut. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package serv
import (
"fmt"
"log"
"testing"
"github.com/stretchr/testify/assert"
)
func ExampleParsePort() {
port, err := ParsePort(":8080")
if err != nil {
log.Fatal(err)
}
fmt.Println(port)
// Output:
// 8080
}
func ExampleSplitHostPort() {
host, port, err := SplitHostPort("localhost:8080")
if err != nil {
log.Fatal(err)
}
fmt.Println(host, port)
// Output:
// localhost 8080
}
func TestParsePort(t *testing.T) {
tests := []struct {
input string
wantPort Port
wantErr error
}{
{
input: "",
wantErr: ErrMissingPort,
},
{
input: "443",
wantPort: 443,
},
{
input: ":8080",
wantPort: 8080,
},
{
input: "localhost:123",
wantErr: ErrInvalidFormat,
},
}
for _, tc := range tests {
t.Run(tc.input, func(t *testing.T) {
have, err := ParsePort(tc.input)
assert.Equal(t, tc.wantPort, have)
if tc.wantErr == nil {
assert.Nil(t, err)
} else {
// assert.ErrorIs(t, err, ParseError)
assert.ErrorIs(t, err, tc.wantErr)
}
})
}
}
func TestSplitHostPort(t *testing.T) {
tests := []struct {
input string
wantHost string
wantPort Port
wantErr error
}{
{
input: "",
wantErr: ErrMissingPort,
},
{
input: ":8080",
wantPort: 8080,
},
{
input: "localhost",
wantErr: ErrMissingPort,
},
{
input: "localhost:4040",
wantHost: "localhost",
wantPort: 4040,
},
{
input: "[::1]",
wantErr: ErrMissingPort,
},
{
input: "[::1]:123",
wantHost: "::1",
wantPort: 123,
},
{
input: "[::1%lo0]:456",
wantHost: "::1%lo0",
wantPort: 456,
},
}
for _, tc := range tests {
t.Run(tc.input, func(t *testing.T) {
haveHost, havePort, err := SplitHostPort(tc.input)
assert.Equal(t, tc.wantHost, haveHost)
assert.Equal(t, tc.wantPort, havePort)
if tc.wantErr == nil {
assert.Nil(t, err)
} else {
// assert.ErrorIs(t, err, newServer(ParseError))
assert.ErrorIs(t, err, tc.wantErr)
}
})
}
}