From 6f5944ecd2730a7a3f0b9078950232565cdf31dc Mon Sep 17 00:00:00 2001 From: Aliaksandr Shulyak <26464290+ThelonKarrde@users.noreply.github.com> Date: Wed, 17 Mar 2021 15:25:06 +0000 Subject: [PATCH] [docker] Helper function to get exposed host ports for -P flag (#807) * Add GetExposedHostPort function * Update modules/docker/inspect.go Co-authored-by: Yoriyasu Yano <430092+yorinasub17@users.noreply.github.com> Co-authored-by: Yoriyasu Yano <430092+yorinasub17@users.noreply.github.com> --- modules/docker/inspect.go | 10 ++++++++++ modules/docker/inspect_test.go | 20 ++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/modules/docker/inspect.go b/modules/docker/inspect.go index acfb9d574..c507aa745 100644 --- a/modules/docker/inspect.go +++ b/modules/docker/inspect.go @@ -230,6 +230,16 @@ func transformContainerPorts(container inspectOutput) ([]Port, error) { return ports, nil } +// GetExposedHostPort returns an exposed host port according to requested container port. Returns 0 if the requested port is not exposed. +func (inspectOutput ContainerInspect) GetExposedHostPort(containerPort uint16) uint16 { + for _, port := range inspectOutput.Ports { + if port.ContainerPort == containerPort { + return port.HostPort + } + } + return uint16(0) +} + // transformContainerVolumes converts Docker's volume bindings from the // format "/foo/bar:/foo/baz" into a more testable one func transformContainerVolumes(container inspectOutput) []VolumeBind { diff --git a/modules/docker/inspect_test.go b/modules/docker/inspect_test.go index 4f963716e..e32a43136 100644 --- a/modules/docker/inspect_test.go +++ b/modules/docker/inspect_test.go @@ -56,6 +56,26 @@ func TestInspectWithExposedPort(t *testing.T) { require.EqualValues(t, port, c.Ports[0].HostPort) } +func TestInspectWithRandomExposedPort(t *testing.T) { + t.Parallel() + + var expectedPort uint16 = 80 + var unexpectedPort uint16 = 1234 + options := &RunOptions{ + Detach: true, + OtherOptions: []string{fmt.Sprintf("-P")}, + } + + id := RunAndGetID(t, dockerInspectTestImage, options) + defer removeContainer(t, id) + + c := Inspect(t, id) + + require.NotEmptyf(t, c.Ports, "Container's exposed ports should not be empty") + require.NotEqualf(t, uint16(0), c.GetExposedHostPort(expectedPort), fmt.Sprintf("There are no exposed port %d!", expectedPort)) + require.Equalf(t, uint16(0), c.GetExposedHostPort(unexpectedPort), fmt.Sprintf("There is an unexpected exposed port %d!", unexpectedPort)) +} + func TestInspectWithHostVolume(t *testing.T) { t.Parallel()