Skip to content

Commit f150875

Browse files
committed
GenericContainer: in case of error: return a reference to the failed container
This way, the caller has an opportunity to clean things up and call Destroy on the failed container.
1 parent 34325b3 commit f150875

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

generic.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,8 @@ func GenericContainer(ctx context.Context, req GenericContainerRequest) (Contain
7474
c, err = provider.CreateContainer(ctx, req.ContainerRequest)
7575
}
7676
if err != nil {
77-
return nil, fmt.Errorf("%w: failed to create container", err)
77+
// At this point `c` might not be nil. Give the caller an opportunity to call Destroy on the container.
78+
return c, fmt.Errorf("%w: failed to create container", err)
7879
}
7980

8081
if req.Started && !c.IsRunning() {

generic_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"context"
55
"errors"
66
"testing"
7+
"time"
78

89
"github.com/stretchr/testify/require"
910

@@ -96,3 +97,23 @@ func TestGenericReusableContainer(t *testing.T) {
9697
})
9798
}
9899
}
100+
101+
func TestGenericContainerShouldReturnRefOnError(t *testing.T) {
102+
// In this test, we are going to cancel the context to exit the `wait.Strategy`.
103+
// We want to make sure that the GenericContainer call will still return a reference to the
104+
// created container, so that we can Destroy it.
105+
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
106+
defer cancel()
107+
108+
c, err := GenericContainer(ctx, GenericContainerRequest{
109+
ProviderType: providerType,
110+
ContainerRequest: ContainerRequest{
111+
Image: nginxAlpineImage,
112+
WaitingFor: wait.ForLog("this string should not be present in the logs"),
113+
},
114+
Started: true,
115+
})
116+
require.Error(t, err)
117+
require.NotNil(t, c)
118+
terminateContainerOnEnd(t, context.Background(), c)
119+
}

0 commit comments

Comments
 (0)