Skip to content

Commit

Permalink
fix: avoid panics when checking container state and container.raw is …
Browse files Browse the repository at this point in the history
…nil (#635)
  • Loading branch information
mdelapenya committed Nov 24, 2022
1 parent 84832a6 commit 559a1b0
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
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

0 comments on commit 559a1b0

Please sign in to comment.