Skip to content

Commit

Permalink
feat(mongodb): Wait for mongodb module with a replicaset to finish (#…
Browse files Browse the repository at this point in the history
…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 <[email protected]>
  • Loading branch information
smgt and stevenh authored Sep 17, 2024
1 parent 060734b commit e2bd70f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
5 changes: 5 additions & 0 deletions modules/mongodb/mongodb.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package mongodb
import (
"context"
"fmt"
"time"

"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
Expand Down Expand Up @@ -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 {
Expand Down
13 changes: 12 additions & 1 deletion modules/mongodb/mongodb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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 {
Expand All @@ -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)
})
}
}

0 comments on commit e2bd70f

Please sign in to comment.