From e2bd70faa82e7338c56d352f79a13314215d9371 Mon Sep 17 00:00:00 2001 From: Simon Gate Date: Wed, 18 Sep 2024 01:26:57 +0200 Subject: [PATCH] feat(mongodb): Wait for mongodb module with a replicaset to finish (#2777) * Insert a document in mongodb during tests To be able to catch `NotWritablePrimary` error * Add mongo:7 to replica set tests * Add new waiting strategy for mongodb replicaset * Extend default wait strategy Thanks @stevenh --------- Co-authored-by: Steven Hartland --- modules/mongodb/mongodb.go | 5 +++++ modules/mongodb/mongodb_test.go | 13 ++++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/modules/mongodb/mongodb.go b/modules/mongodb/mongodb.go index 4923473593..3f73e5dc70 100644 --- a/modules/mongodb/mongodb.go +++ b/modules/mongodb/mongodb.go @@ -3,6 +3,7 @@ package mongodb import ( "context" "fmt" + "time" "github.com/testcontainers/testcontainers-go" "github.com/testcontainers/testcontainers-go/wait" @@ -89,6 +90,10 @@ func WithPassword(password string) testcontainers.CustomizeRequestOption { func WithReplicaSet(replSetName string) testcontainers.CustomizeRequestOption { return func(req *testcontainers.GenericContainerRequest) error { req.Cmd = append(req.Cmd, "--replSet", replSetName) + req.WaitingFor = wait.ForAll( + req.WaitingFor, + wait.ForExec(eval("rs.status().ok")), + ).WithDeadline(60 * time.Second) req.LifecycleHooks = append(req.LifecycleHooks, testcontainers.ContainerLifecycleHooks{ PostStarts: []testcontainers.ContainerHook{ func(ctx context.Context, c testcontainers.Container) error { diff --git a/modules/mongodb/mongodb_test.go b/modules/mongodb/mongodb_test.go index 663f05cff6..03d669bb7e 100644 --- a/modules/mongodb/mongodb_test.go +++ b/modules/mongodb/mongodb_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" @@ -48,6 +49,13 @@ func TestMongoDB(t *testing.T) { mongodb.WithReplicaSet("rs"), }, }, + { + name: "With Replica set and mongo:7", + img: "mongo:7", + opts: []testcontainers.ContainerCustomizer{ + mongodb.WithReplicaSet("rs"), + }, + }, } for _, tc := range testCases { @@ -67,12 +75,15 @@ func TestMongoDB(t *testing.T) { // Force direct connection to the container to avoid the replica set // connection string that is returned by the container itself when // using the replica set option. - mongoClient, err := mongo.Connect(ctx, options.Client().ApplyURI(endpoint+"/?connect=direct")) + mongoClient, err := mongo.Connect(ctx, options.Client().ApplyURI(endpoint).SetDirect(true)) require.NoError(tt, err) err = mongoClient.Ping(ctx, nil) require.NoError(tt, err) require.Equal(t, "test", mongoClient.Database("test").Name()) + + _, err = mongoClient.Database("testcontainer").Collection("test").InsertOne(context.Background(), bson.M{}) + require.NoError(tt, err) }) } }