Skip to content

Commit 4bc6777

Browse files
committed
Add dktesting.Cleanup() method
1 parent e913336 commit 4bc6777

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

dktesting/dktesting.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
11
package dktesting
22

33
import (
4+
"context"
5+
"fmt"
46
"testing"
57
)
68

79
import (
810
"github.com/dhui/dktest"
11+
"github.com/docker/docker/api/types"
12+
"github.com/docker/docker/client"
913
)
1014

1115
// ContainerSpec holds Docker testing setup specifications
@@ -14,6 +18,26 @@ type ContainerSpec struct {
1418
Options dktest.Options
1519
}
1620

21+
// Cleanup cleanups the ContainerSpec after a test run by removing the ContainerSpec's image
22+
func (s *ContainerSpec) Cleanup() (retErr error) {
23+
// copied from dktest.RunContext()
24+
dc, err := client.NewClientWithOpts(client.FromEnv, client.WithVersion("1.41"))
25+
if err != nil {
26+
return err
27+
}
28+
defer func() {
29+
if err := dc.Close(); err != nil && retErr == nil {
30+
retErr = fmt.Errorf("error closing Docker client: %w", err)
31+
}
32+
}()
33+
ctx, timeoutCancelFunc := context.WithTimeout(context.Background(), s.Options.CleanupTimeout)
34+
defer timeoutCancelFunc()
35+
if _, err := dc.ImageRemove(ctx, s.ImageName, types.ImageRemoveOptions{Force: true, PruneChildren: true}); err != nil {
36+
return err
37+
}
38+
return nil
39+
}
40+
1741
// ParallelTest runs Docker tests in parallel
1842
func ParallelTest(t *testing.T, specs []ContainerSpec,
1943
testFunc func(*testing.T, dktest.ContainerInfo)) {

0 commit comments

Comments
 (0)