Skip to content

MongoDB

package mongodb

import (
    "context"

    "github.com/testcontainers/testcontainers-go"
    "github.com/testcontainers/testcontainers-go/wait"
)

// mongodbContainer represents the mongodb container type used in the module
type mongodbContainer struct {
    testcontainers.Container
}

// setupMongoDB creates an instance of the mongodb container type
func setupMongoDB(ctx context.Context) (*mongodbContainer, error) {
    req := testcontainers.ContainerRequest{
        Image:        "mongo:6",
        ExposedPorts: []string{"27017/tcp"},
        WaitingFor: wait.ForAll(
            wait.ForLog("Waiting for connections"),
            wait.ForListeningPort("27017/tcp"),
        ),
    }
    container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
        ContainerRequest: req,
        Started:          true,
    })
    if err != nil {
        return nil, err
    }

    return &mongodbContainer{Container: container}, nil
}
package mongodb

import (
    "context"
    "fmt"
    "testing"

    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

func TestMongoDB(t *testing.T) {
    ctx := context.Background()

    container, err := setupMongoDB(ctx)
    if err != nil {
        t.Fatal(err)
    }

    // Clean up the container after the test is complete
    t.Cleanup(func() {
        if err := container.Terminate(ctx); err != nil {
            t.Fatalf("failed to terminate container: %s", err)
        }
    })

    // perform assertions

    endpoint, err := container.Endpoint(ctx, "mongodb")
    if err != nil {
        t.Error(fmt.Errorf("failed to get endpoint: %w", err))
    }

    mongoClient, err := mongo.NewClient(options.Client().ApplyURI(endpoint))
    if err != nil {
        t.Fatal(fmt.Errorf("error creating mongo client: %w", err))
    }

    err = mongoClient.Connect(ctx)
    if err != nil {
        t.Fatal(fmt.Errorf("error connecting to mongo: %w", err))
    }

    err = mongoClient.Ping(ctx, nil)
    if err != nil {
        t.Fatal(fmt.Errorf("error pinging mongo: %w", err))
    }
}