Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[docker] Helper function to get exposed host ports for -P flag #807

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
ThelonKarrde marked this conversation as resolved.
Show resolved Hide resolved
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