From 185c5f1dfdb5c3317d0207c48eb1a202c662fde1 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Thu, 29 May 2025 14:53:46 +0200 Subject: [PATCH] nat: PortBinding: implement stringer Signed-off-by: Sebastiaan van Stijn --- nat/nat.go | 10 ++++++++ nat/nat_test.go | 62 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) diff --git a/nat/nat.go b/nat/nat.go index 1ffe0355..335f3f73 100644 --- a/nat/nat.go +++ b/nat/nat.go @@ -17,6 +17,16 @@ type PortBinding struct { HostPort string } +func (pb *PortBinding) String() string { + if pb.HostPort == "" { + return "" + } + if pb.HostIP == "" { + return pb.HostPort + } + return net.JoinHostPort(pb.HostIP, pb.HostPort) +} + // PortMap is a collection of PortBinding indexed by Port type PortMap map[Port][]PortBinding diff --git a/nat/nat_test.go b/nat/nat_test.go index 6ee59e1f..c13049a0 100644 --- a/nat/nat_test.go +++ b/nat/nat_test.go @@ -842,6 +842,68 @@ func TestStringer(t *testing.T) { } } +func TestPortBinding(t *testing.T) { + tests := []struct { + doc string + binding *PortBinding + expect string + }{ + { + doc: "no host mapping", + binding: &PortBinding{}, + expect: "", + }, + { + doc: "ipv4 missing port", + binding: &PortBinding{ + HostIP: "192.168.1.100", + }, + expect: "", + }, + { + doc: "ipv4", + binding: &PortBinding{ + HostIP: "192.168.1.100", + HostPort: "6000", + }, + expect: "192.168.1.100:6000", + }, + { + doc: "ipv6 missing port", + binding: &PortBinding{ + HostIP: "::1", + }, + expect: "", + }, + { + doc: "ipv6", + binding: &PortBinding{ + HostIP: "::1", + HostPort: "6000", + }, + expect: "[::1]:6000", + }, + // FIXME(thaJeztah): this should be invalid + { + doc: "ipv6 with braces", + binding: &PortBinding{ + HostIP: "[::1]", + HostPort: "6000", + }, + expect: "[[::1]]:6000", + }, + } + + for _, tc := range tests { + t.Run(tc.doc, func(t *testing.T) { + actual := tc.binding.String() + if actual != tc.expect { + t.Errorf("Expected %s got %s", tc.expect, actual) + } + }) + } +} + func BenchmarkParsePortSpecs(b *testing.B) { specs := [][]string{ {"1234/tcp", "2345/udp", "3456/sctp"},