Skip to content

Commit

Permalink
chor: do not orphan the network
Browse files Browse the repository at this point in the history
  • Loading branch information
mdelapenya committed Sep 27, 2024
1 parent 2dc6f94 commit 6d73971
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
11 changes: 8 additions & 3 deletions modules/etcd/etcd.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,18 +87,23 @@ func Run(ctx context.Context, img string, opts ...testcontainers.ContainerCustom
// configure CMD with the nodes
genericContainerReq.Cmd = configureCMD(settings)

// Initialise the etcd container with the current settings.
// The cluster network, if needed, is already part of the settings,
// so the following error handling returns a partially initialised container,
// allowing the caller to clean up the resources with the Terminate method.
c := &EtcdContainer{opts: settings}

if settings.clusterNetwork != nil {
// apply the network to the current node
err := tcnetwork.WithNetwork([]string{settings.nodeNames[settings.currentNode]}, settings.clusterNetwork)(&genericContainerReq)
if err != nil {
return nil, fmt.Errorf("with network: %w", err)
return c, fmt.Errorf("with network: %w", err)
}
}

container, err := testcontainers.GenericContainer(ctx, genericContainerReq)
var c *EtcdContainer
if container != nil {
c = &EtcdContainer{Container: container}
c.Container = container
}

if err != nil {
Expand Down
21 changes: 21 additions & 0 deletions modules/etcd/etcd_unit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

"github.com/testcontainers/testcontainers-go"
tcexec "github.com/testcontainers/testcontainers-go/exec"
tcnetwork "github.com/testcontainers/testcontainers-go/network"
)

func TestRunCluster1Node(t *testing.T) {
Expand Down Expand Up @@ -56,6 +57,26 @@ func TestTerminate(t *testing.T) {
require.True(t, errdefs.IsNotFound(err))
}

func TestTerminate_partiallyInitialised(t *testing.T) {
newNetwork, err := tcnetwork.New(context.Background())
require.NoError(t, err)

ctr := &EtcdContainer{
opts: options{
clusterNetwork: newNetwork,
},
}

require.NoError(t, ctr.Terminate(context.Background()))

cli, err := testcontainers.NewDockerClientWithOpts(context.Background())
require.NoError(t, err)
defer cli.Close()

_, err = cli.NetworkInspect(context.Background(), ctr.opts.clusterNetwork.ID, network.InspectOptions{})
require.True(t, errdefs.IsNotFound(err))
}

// testCluster is a helper function to test the creation of an etcd cluster with the specified nodes.
func testCluster(t *testing.T, node1 string, node2 string, nodes ...string) func(t *testing.T) {
t.Helper()
Expand Down

0 comments on commit 6d73971

Please sign in to comment.