1
16
17 package net
18
19 import (
20 "testing"
21 )
22
23 func ExampleLocalPort() {
24 lp, err := NewLocalPort(
25 "TCP port",
26 "",
27 IPv4,
28 443,
29 TCP,
30 )
31 if err != nil {
32 panic(err)
33 }
34 port, err := ListenPortOpener.OpenLocalPort(lp)
35 if err != nil {
36 panic(err)
37 }
38 port.Close()
39 }
40
41 func TestLocalPortString(t *testing.T) {
42 testCases := []struct {
43 description string
44 ip string
45 family IPFamily
46 port int
47 protocol Protocol
48 expectedStr string
49 expectedErr bool
50 }{
51 {"IPv4 UDP", "1.2.3.4", "", 9999, UDP, `"IPv4 UDP" (1.2.3.4:9999/udp)`, false},
52 {"IPv4 TCP", "5.6.7.8", "", 1053, TCP, `"IPv4 TCP" (5.6.7.8:1053/tcp)`, false},
53 {"IPv6 TCP", "2001:db8::1", "", 80, TCP, `"IPv6 TCP" ([2001:db8::1]:80/tcp)`, false},
54 {"IPv4 TCP, all addresses", "", IPv4, 1053, TCP, `"IPv4 TCP, all addresses" (:1053/tcp4)`, false},
55 {"IPv6 TCP, all addresses", "", IPv6, 80, TCP, `"IPv6 TCP, all addresses" (:80/tcp6)`, false},
56 {"No ip family TCP, all addresses", "", "", 80, TCP, `"No ip family TCP, all addresses" (:80/tcp)`, false},
57 {"IP family mismatch", "2001:db8::2", IPv4, 80, TCP, "", true},
58 {"IP family mismatch", "1.2.3.4", IPv6, 80, TCP, "", true},
59 {"Unsupported protocol", "2001:db8::2", "", 80, "http", "", true},
60 {"Invalid IP", "300", "", 80, TCP, "", true},
61 {"Invalid ip family", "", "5", 80, TCP, "", true},
62 }
63
64 for _, tc := range testCases {
65 lp, err := NewLocalPort(
66 tc.description,
67 tc.ip,
68 tc.family,
69 tc.port,
70 tc.protocol,
71 )
72 if tc.expectedErr {
73 if err == nil {
74 t.Errorf("Expected err when creating LocalPort %v", tc)
75 }
76 continue
77 }
78 if err != nil {
79 t.Errorf("Unexpected err when creating LocalPort %s", err)
80 continue
81 }
82 str := lp.String()
83 if str != tc.expectedStr {
84 t.Errorf("Unexpected output for %s, expected: %s, got: %s", tc.description, tc.expectedStr, str)
85 }
86 }
87 }
88
View as plain text