Skip to content

Commit

Permalink
fix(mongodb): replica test failures (testcontainers#2699)
Browse files Browse the repository at this point in the history
Fix mongodb replica test failures due to client using the internal
container addresses when direct connection is not requested.

Fix invalid use of log.Fatal instead of tt.Fatal which was causing
failures to no be output correctly due to os.Exit.
  • Loading branch information
stevenh authored Aug 7, 2024
1 parent 40098cf commit 8f90dcf
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
2 changes: 1 addition & 1 deletion modules/mongodb/mongodb.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ func WithReplicaSet(replSetName string) testcontainers.CustomizeRequestOption {
func(ctx context.Context, c testcontainers.Container) error {
ip, err := c.ContainerIP(ctx)
if err != nil {
return err
return fmt.Errorf("container ip: %w", err)
}

cmd := eval("rs.initiate({ _id: '%s', members: [ { _id: 0, host: '%s:27017' } ] })", replSetName, ip)
Expand Down
8 changes: 5 additions & 3 deletions modules/mongodb/mongodb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package mongodb_test

import (
"context"
"log"
"testing"

"go.mongodb.org/mongo-driver/mongo"
Expand Down Expand Up @@ -73,14 +72,17 @@ func TestMongoDB(t *testing.T) {
tt.Fatalf("failed to get connection string: %s", err)
}

mongoClient, err := mongo.Connect(ctx, options.Client().ApplyURI(endpoint))
// 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"))
if err != nil {
tt.Fatalf("failed to connect to MongoDB: %s", err)
}

err = mongoClient.Ping(ctx, nil)
if err != nil {
log.Fatalf("failed to ping MongoDB: %s", err)
tt.Fatalf("failed to ping MongoDB: %s", err)
}

if mongoClient.Database("test").Name() != "test" {
Expand Down

0 comments on commit 8f90dcf

Please sign in to comment.