Debian Codegraph @

hostport_test.go

raw
1 package utils
2
3 import (
4 "net"
5 "testing"
6
7 "github.com/stretchr/testify/require"
8 )
9
10 func hostPortSamples() []string {
11 return []string{
12 "",
13 ":",
14 "::",
15 ":80",
16 "example.com",
17 "example.com:",
18 "example.com:80",
19 "example.com:8080:90",
20 "host%eth0:1",
21 "[::1]",
22 "[::1]:",
23 "[::1]:8080",
24 "[fe80::1%eth0]:443",
25 "[::1]x:80",
26 "[::1]:80:90",
27 "[::1:80",
28 "::1]:80",
29 "[]:80",
30 "[[::1]]:80",
31 "[::1]]:80",
32 "a[b:80",
33 "a]b:80",
34 "[a]:[b]",
35 "[a]:b]",
36 "1.2.3.4:65535",
37 " example.com:80",
38 "example.com :80",
39 "\x00:\x00",
40 }
41 }
42
43 // checkSplitHostPort compares both input types with net.SplitHostPort.
44 func checkSplitHostPort(tb testing.TB, in string) {
45 tb.Helper()
46 wantHost, wantPort, err := net.SplitHostPort(in)
47 host, port, ok := SplitHostPort(in)
48 require.Equal(tb, err == nil, ok, "input %q: %v", in, err)
49 if !ok {
50 require.Empty(tb, host, "input %q", in)
51 require.Empty(tb, port, "input %q", in)
52 } else {
53 require.Equal(tb, wantHost, host, "input %q", in)
54 require.Equal(tb, wantPort, port, "input %q", in)
55 }
56
57 bh, bp, bok := SplitHostPort([]byte(in))
58 require.Equal(tb, ok, bok, "input %q bytes", in)
59 require.Equal(tb, host, string(bh), "input %q bytes", in)
60 require.Equal(tb, port, string(bp), "input %q bytes", in)
61 if !bok {
62 require.Nil(tb, bh, "input %q bytes", in)
63 require.Nil(tb, bp, "input %q bytes", in)
64 }
65 }
66
67 func Test_SplitHostPort(t *testing.T) {
68 t.Parallel()
69 for _, in := range hostPortSamples() {
70 checkSplitHostPort(t, in)
71 }
72
73 // The parts alias the input.
74 in := []byte("[::1]:8080")
75 host, port, ok := SplitHostPort(in)
76 require.True(t, ok)
77 require.Same(t, &in[1], &host[0])
78 require.Same(t, &in[6], &port[0])
79 }
80
81 func FuzzSplitHostPort(f *testing.F) {
82 for _, s := range hostPortSamples() {
83 f.Add(s)
84 }
85 f.Fuzz(func(t *testing.T, s string) {
86 checkSplitHostPort(t, s)
87 })
88 }
89
90 func Benchmark_SplitHostPort(b *testing.B) {
91 inputs := []struct {
92 name string
93 value string
94 }{
95 {"host-port", "example.com:8080"},
96 {"ipv6-port", "[2001:db8::1]:8080"},
97 {"missing-port", "example.com"},
98 }
99 var host, port string
100 var ok bool
101 for _, input := range inputs {
102 b.Run(input.name+"/fiber", func(b *testing.B) {
103 b.ReportAllocs()
104 for b.Loop() {
105 host, port, ok = SplitHostPort(input.value)
106 }
107 })
108 b.Run(input.name+"/default", func(b *testing.B) {
109 b.ReportAllocs()
110 for b.Loop() {
111 var err error
112 host, port, err = net.SplitHostPort(input.value)
113 ok = err == nil
114 }
115 })
116 }
117 _ = host + port
118 _ = ok
119 }