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

fix: avoid panics when checking container state and container.raw is nil #635

Merged
merged 2 commits into from Nov 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 4 additions & 1 deletion docker.go
Expand Up @@ -355,7 +355,10 @@ func (c *DockerContainer) Name(ctx context.Context) (string, error) {
func (c *DockerContainer) State(ctx context.Context) (*types.ContainerState, error) {
inspect, err := c.inspectRawContainer(ctx)
if err != nil {
return c.raw.State, err
if c.raw != nil {
return c.raw.State, err
}
return nil, err
}
return inspect.State, nil
}
Expand Down
58 changes: 58 additions & 0 deletions docker_test.go
Expand Up @@ -460,6 +460,64 @@ func TestContainerTerminationResetsState(t *testing.T) {
}
}

func TestContainerStateAfterTermination(t *testing.T) {
createContainerFn := func(ctx context.Context) (Container, error) {
return GenericContainer(ctx, GenericContainerRequest{
ProviderType: providerType,
ContainerRequest: ContainerRequest{
Image: nginxAlpineImage,
ExposedPorts: []string{
nginxDefaultPort,
},
},
Started: true,
})
}

t.Run("Nil State after termination", func(t *testing.T) {
ctx := context.Background()
nginx, err := createContainerFn(ctx)
if err != nil {
t.Fatal(err)
}

// terminate the container before the raw state is set
err = nginx.Terminate(ctx)
if err != nil {
t.Fatal(err)
}

state, err := nginx.State(ctx)
assert.Error(t, err, "expected error from container inspect.")

assert.Nil(t, state, "expected nil container inspect.")
})

t.Run("Non-nil State after termination if raw as already set", func(t *testing.T) {
ctx := context.Background()
nginx, err := createContainerFn(ctx)
if err != nil {
t.Fatal(err)
}

state, err := nginx.State(ctx)
assert.NoError(t, err, "unexpected error from container inspect before container termination.")

assert.NotNil(t, state, "unexpected nil container inspect before container termination.")

// terminate the container before the raw state is set
err = nginx.Terminate(ctx)
if err != nil {
t.Fatal(err)
}

state, err = nginx.State(ctx)
assert.Error(t, err, "expected error from container inspect after container termination.")

assert.NotNil(t, state, "unexpected nil container inspect after container termination.")
})
}

func TestContainerStopWithReaper(t *testing.T) {
ctx := context.Background()

Expand Down