Skip to content

Commit

Permalink
GenericContainer: in case of error: return a reference to the failed …
Browse files Browse the repository at this point in the history
…container

This way, the caller has an opportunity to clean things up and call
Destroy on the failed container.
  • Loading branch information
JordanP committed Jan 9, 2024
1 parent 34325b3 commit f150875
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
3 changes: 2 additions & 1 deletion generic.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@ func GenericContainer(ctx context.Context, req GenericContainerRequest) (Contain
c, err = provider.CreateContainer(ctx, req.ContainerRequest)
}
if err != nil {
return nil, fmt.Errorf("%w: failed to create container", err)
// At this point `c` might not be nil. Give the caller an opportunity to call Destroy on the container.
return c, fmt.Errorf("%w: failed to create container", err)
}

if req.Started && !c.IsRunning() {
Expand Down
21 changes: 21 additions & 0 deletions generic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"testing"
"time"

"github.com/stretchr/testify/require"

Expand Down Expand Up @@ -96,3 +97,23 @@ func TestGenericReusableContainer(t *testing.T) {
})
}
}

func TestGenericContainerShouldReturnRefOnError(t *testing.T) {
// In this test, we are going to cancel the context to exit the `wait.Strategy`.
// We want to make sure that the GenericContainer call will still return a reference to the
// created container, so that we can Destroy it.
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

c, err := GenericContainer(ctx, GenericContainerRequest{
ProviderType: providerType,
ContainerRequest: ContainerRequest{
Image: nginxAlpineImage,
WaitingFor: wait.ForLog("this string should not be present in the logs"),
},
Started: true,
})
require.Error(t, err)
require.NotNil(t, c)
terminateContainerOnEnd(t, context.Background(), c)
}

0 comments on commit f150875

Please sign in to comment.