tailscale/portlist/netstat_test.go
Brad Fitzpatrick 120273d7f6 portlist: document, clean up, fix an open fd spike, optimize a bit
I noticed portlist when looking at some profiles and hadn't looked at
the code much before. This is a first pass over it. It allocates a
fair bit. More love remains, but this does a bit:

name       old time/op    new time/op    delta
GetList-8    9.92ms ± 8%    9.64ms ±12%     ~     (p=0.247 n=10+10)

name       old alloc/op   new alloc/op   delta
GetList-8     931kB ± 0%     869kB ± 0%   -6.70%  (p=0.000 n=10+10)

name       old allocs/op  new allocs/op  delta
GetList-8     4.59k ± 0%     3.69k ± 1%  -19.71%  (p=0.000 n=10+10)

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-13 21:06:41 -07:00

87 lines
2.3 KiB
Go

// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package portlist
import (
"testing"
)
func TestParsePort(t *testing.T) {
type InOut struct {
in string
expect int
}
tests := []InOut{
InOut{"1.2.3.4:5678", 5678},
InOut{"0.0.0.0.999", 999},
InOut{"1.2.3.4:*", 0},
InOut{"5.5.5.5:0", 0},
InOut{"[1::2]:5", 5},
InOut{"[1::2].5", 5},
InOut{"gibberish", -1},
}
for _, io := range tests {
got := parsePort(io.in)
if got != io.expect {
t.Fatalf("input:%#v expect:%v got:%v\n", io.in, io.expect, got)
}
}
}
var netstat_output = `
// linux
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN
udp 0 0 0.0.0.0:5353 0.0.0.0:*
udp6 0 0 :::5353 :::*
udp6 0 0 :::5354 :::*
// macOS
tcp4 0 0 *.23 *.* LISTEN
tcp6 0 0 *.24 *.* LISTEN
udp6 0 0 *.5453 *.*
udp4 0 0 *.5553 *.*
// Windows 10
Proto Local Address Foreign Address State
TCP 0.0.0.0:32 0.0.0.0:0 LISTENING
[sshd.exe]
UDP 0.0.0.0:5050 *:*
CDPSvc
[svchost.exe]
UDP 0.0.0.0:53 *:*
[chrome.exe]
UDP 10.0.1.43:9353 *:*
[iTunes.exe]
UDP [::]:53 *:*
UDP [::]:53 *:*
[funball.exe]
`
func TestParsePortsNetstat(t *testing.T) {
want := List{
Port{"tcp", 22, "", ""},
Port{"tcp", 23, "", ""},
Port{"tcp", 24, "", ""},
Port{"tcp", 32, "sshd", ""},
Port{"udp", 53, "chrome", ""},
Port{"udp", 53, "funball", ""},
Port{"udp", 5050, "CDPSvc", ""},
Port{"udp", 5353, "", ""},
Port{"udp", 5354, "", ""},
Port{"udp", 5453, "", ""},
Port{"udp", 5553, "", ""},
Port{"udp", 9353, "iTunes", ""},
}
pl := parsePortsNetstat(netstat_output)
for i := range pl {
if pl[i] != want[i] {
t.Errorf("row#%d\n got: %#v\n\nwant: %#v\n",
i, pl[i], want[i])
}
}
}