Skip to content

Commit

Permalink
[docker] Helper function to get exposed host ports for -P flag (#807)
Browse files Browse the repository at this point in the history
* Add GetExposedHostPort function

* Update modules/docker/inspect.go

Co-authored-by: Yoriyasu Yano <[email protected]>

Co-authored-by: Yoriyasu Yano <[email protected]>
  • Loading branch information
ThelonKarrde and yorinasub17 authored Mar 17, 2021
1 parent f8ed0b6 commit 6f5944e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
10 changes: 10 additions & 0 deletions modules/docker/inspect.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
20 changes: 20 additions & 0 deletions modules/docker/inspect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down

0 comments on commit 6f5944e

Please sign in to comment.