package utils
import (
"log/slog"
"os"
"testing"
)
func TestSanitizePort(t *testing.T) {
logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
tests := []struct {
name string
port string
want uint16
}{
{"valid port", "80", 80},
{"valid port with desc", "22(ssh)", 22},
{"empty port", "", 0},
{"invalid port", "abc", 0},
{"out of range low", "0", 0},
{"out of range high", "65536", 0},
{"max port", "65535", 65535},
{"min port", "1", 1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := SanitizePort(tt.port, logger); got != tt.want {
t.Errorf("SanitizePort(%v) = %v, want %v", tt.port, got, tt.want)
}
})
}
}
func TestSplitAddr(t *testing.T) {
logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
tests := []struct {
name string
addr string
wantHost string
wantPort uint16
}{
{"valid addr", "127.0.0.1:80", "127.0.0.1", 80},
{"ipv6 addr", "[::1]:443", "::1", 443},
{"invalid addr", "localhost", "", 0},
{"addr with desc port", "1.2.3.4:22(ssh)", "1.2.3.4", 22},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotHost, gotPort := SplitAddr(tt.addr, logger)
if gotHost != tt.wantHost {
t.Errorf("SplitAddr(%v) gotHost = %v, want %v", tt.addr, gotHost, tt.wantHost)
}
if gotPort != tt.wantPort {
t.Errorf("SplitAddr(%v) gotPort = %v, want %v", tt.addr, gotPort, tt.wantPort)
}
})
}
}
func TestBuildAddress(t *testing.T) {
tests := []struct {
name string
listenAddr string
port uint16
want string
}{
{"ipv4", "0.0.0.0", 80, "0.0.0.0:80"},
{"ipv6", "::", 443, "[::]:443"},
{"localhost", "127.0.0.1", 22, "127.0.0.1:22"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := BuildAddress(tt.listenAddr, tt.port); got != tt.want {
t.Errorf("BuildAddress(%v, %v) = %v, want %v", tt.listenAddr, tt.port, got, tt.want)
}
})
}
}
func TestIPToInt(t *testing.T) {
tests := []struct {
name string // description of this test case
// Named input parameters for target function.
ip string
want uint32
wantErr bool
}{
{"valid ip", "127.0.0.1", 2130706433, false},
{"valid ip", "1.2.3.4", 16909060, false},
{"invalid ip", "327.68.0.1", 0, true},
{"invalid ip", "localhost", 0, true},
{"ipv6 ip", "::1", 0, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, gotErr := IPToInt(tt.ip)
if gotErr != nil {
if !tt.wantErr {
t.Errorf("IPToInt() failed: %v", gotErr)
}
return
}
if tt.wantErr {
t.Fatal("IPToInt() succeeded unexpectedly")
}
if got != tt.want {
t.Errorf("IPToInt() = %v, want %v", got, tt.want)
}
})
}
}