Skip to content

Commit

Permalink
Add support for MongoDB testing module (#1447)
Browse files Browse the repository at this point in the history
* Add support for MongoDB testing module

This commit introduces functionalities for MongoDB testing, achieving 3 main goals:

1. Added mongodb module, `github.com/testcontainers/testcontainers-go/modules/mongodb`, in `dependabot.yml` with a monthly update cycle.

2. Created new `.md` documentation file for this module, providing details on how to add MongoDB to the Go dependencies, how to use this module, the MongoDB module reference, and other related details.

3. Implemented test files to verify MongoDB connection and integration, and added a `Makefile` for test execution.

Justification:
This helps users in testing their mongodb related go functionalities, effectively and efficiently.

* Remove MongoDB example and associated files

* fix: add schedule.day

* Removed MongoDB from the CI test-examples matrix

* Add ConnectionString method details in MongoDB documentation

* Added code snippet

* "Corrected error message in MongoDB test

The error message was updated to clarify its meaning in modules/mongodb/mongodb_test.go. It now specifically states "failed to get connection string" instead of "failed to get endpoint", which enhances the readability and precision in case of a related error occurrence."

* "Update MongoDB documentation and test example

This update corrects the MongoDB usage example in our documentation in file docs/modules/mongodb.md and improves the corresponding test case in modules/mongodb/mongodb_test.go. Previously, the reference to 'Creating a MongoDB container' in documentation was missing the actual code block. The test has been modified to highlight the container setup steps visually within the code, which enhances test readability. This helps developers understand how to use the MongoDB module more effectively."

* fix doc

* docs: remove code snippet

---------

Co-authored-by: Manuel de la Peña <[email protected]>
Co-authored-by: Manuel de la Peña <[email protected]>
  • Loading branch information
3 people authored Aug 10, 2023
1 parent 82c79f7 commit f4d9b1d
Show file tree
Hide file tree
Showing 11 changed files with 153 additions and 70 deletions.
26 changes: 15 additions & 11 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -81,17 +81,6 @@ updates:
all:
patterns:
- '*'
- package-ecosystem: gomod
directory: /examples/mongodb
schedule:
interval: monthly
day: sunday
open-pull-requests-limit: 3
rebase-strategy: disabled
groups:
all:
patterns:
- '*'
- package-ecosystem: gomod
directory: /examples/nats
schedule:
Expand Down Expand Up @@ -165,6 +154,10 @@ updates:
day: sunday
open-pull-requests-limit: 3
rebase-strategy: disabled
groups:
all:
patterns:
- '*'
- package-ecosystem: gomod
directory: /modules/compose
schedule:
Expand Down Expand Up @@ -209,6 +202,17 @@ updates:
all:
patterns:
- '*'
- package-ecosystem: gomod
directory: /modules/mongodb
schedule:
interval: monthly
day: sunday
open-pull-requests-limit: 3
rebase-strategy: disabled
groups:
all:
patterns:
- '*'
- package-ecosystem: gomod
directory: /modules/mysql
schedule:
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ jobs:
matrix:
go-version: [1.19.x, 1.x]
platform: [ubuntu-latest, macos-latest]
module: [clickhouse, compose, couchbase, k3s, localstack, mysql, neo4j, postgres, pulsar, redis, redpanda, vault]
module: [clickhouse, compose, couchbase, k3s, localstack, mongodb, mysql, neo4j, postgres, pulsar, redis, redpanda, vault]
exclude:
- module: compose
go-version: 1.19.x
Expand All @@ -100,7 +100,7 @@ jobs:
matrix:
go-version: [1.19.x, 1.x]
platform: [ubuntu-latest, macos-latest]
module: [bigtable, cockroachdb, consul, datastore, firestore, mongodb, nats, nginx, pubsub, spanner, toxiproxy]
module: [bigtable, cockroachdb, consul, datastore, firestore, nats, nginx, pubsub, spanner, toxiproxy]
uses: ./.github/workflows/ci-test-go.yml
with:
go-version: ${{ matrix.go-version }}
Expand Down
9 changes: 0 additions & 9 deletions docs/examples/mongodb.md

This file was deleted.

74 changes: 74 additions & 0 deletions docs/modules/mongodb.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# MongoDB

Not available until the next release of testcontainers-go <a href="https://github.com/testcontainers/testcontainers-go"><span class="tc-version">:material-tag: main</span></a>

## Introduction

The Testcontainers module for MongoDB.

## Adding this module to your project dependencies

Please run the following command to add the MongoDB module to your Go dependencies:

```
go get github.com/testcontainers/testcontainers-go/modules/mongodb
```

## Usage example

<!--codeinclude-->
[Creating a MongoDB container](../../modules/mongodb/mongodb_test.go) inside_block:createMongoDBContainer
<!--/codeinclude-->

## Module reference

The MongoDB module exposes one entrypoint function to create the MongoDB container, and this function receives two parameters:

```golang
func RunContainer(ctx context.Context, opts ...testcontainers.ContainerCustomizer) (*MongoDBContainer, error)
```

- `context.Context`, the Go context.
- `testcontainers.ContainerCustomizer`, a variadic argument for passing options.

### Container Options

When starting the MongoDB container, you can pass options in a variadic way to configure it.

#### Image

If you need to set a different MongoDB Docker image, you can use `testcontainers.WithImage` with a valid Docker image
for MongoDB. E.g. `testcontainers.WithImage("mongo:6")`.

#### Wait Strategies

If you need to set a different wait strategy for MongoDB, you can use `testcontainers.WithWaitStrategy` with a valid wait strategy
for MongoDB.

!!!info
The default deadline for the wait strategy is 60 seconds.

At the same time, it's possible to set a wait strategy and a custom deadline with `testcontainers.WithWaitStrategyAndDeadline`.

#### Docker type modifiers

If you need an advanced configuration for MongoDB, you can leverage the following Docker type modifiers:

- `testcontainers.WithConfigModifier`
- `testcontainers.WithHostConfigModifier`
- `testcontainers.WithEndpointSettingsModifier`

Please read the [Create containers: Advanced Settings](../features/creating_container.md#advanced-settings) documentation for more information.

### Container Methods

The MongoDB container exposes the following methods:

#### ConnectionString

This method returns the connection string to connect to the MongoDB container.
It returns a string with the format `mongodb://<host>:<port>`.

<!--codeinclude-->
[Get connection string](../../modules/mongodb/mongodb_test.go) inside_block:connectionString
<!--/codeinclude-->
34 changes: 0 additions & 34 deletions examples/mongodb/mongodb.go

This file was deleted.

2 changes: 1 addition & 1 deletion mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ nav:
- modules/couchbase.md
- modules/k3s.md
- modules/localstack.md
- modules/mongodb.md
- modules/mysql.md
- modules/neo4j.md
- modules/postgres.md
Expand All @@ -78,7 +79,6 @@ nav:
- examples/consul.md
- examples/datastore.md
- examples/firestore.md
- examples/mongodb.md
- examples/nats.md
- examples/nginx.md
- examples/pubsub.md
Expand Down
File renamed without changes.
4 changes: 2 additions & 2 deletions examples/mongodb/go.mod → modules/mongodb/go.mod
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
module github.com/testcontainers/testcontainers-go/examples/mongodb
module github.com/testcontainers/testcontainers-go/modules/mongodb

go 1.19

require (
github.com/testcontainers/testcontainers-go v0.22.0
go.mongodb.org/mongo-driver v1.12.0
go.mongodb.org/mongo-driver v1.12.1
)

require (
Expand Down
4 changes: 2 additions & 2 deletions examples/mongodb/go.sum → modules/mongodb/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,8 @@ github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7Jul
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.mongodb.org/mongo-driver v1.12.0 h1:aPx33jmn/rQuJXPQLZQ8NtfPQG8CaqgLThFtqRb0PiE=
go.mongodb.org/mongo-driver v1.12.0/go.mod h1:AZkxhPnFJUoH7kZlFkVKucV20K387miPfm7oimrSmK0=
go.mongodb.org/mongo-driver v1.12.1 h1:nLkghSU8fQNaK7oUmDhQFsnrtcoNy7Z6LVFKsEecqgE=
go.mongodb.org/mongo-driver v1.12.1/go.mod h1:/rGBTebI3XYboVmgz+Wv3Bcbl3aD0QF9zl6kDDw18rQ=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
Expand Down
49 changes: 49 additions & 0 deletions modules/mongodb/mongodb.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package mongodb

import (
"context"

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

// defaultImage is the default MongoDB container image
const defaultImage = "mongo:6"

// MongoDBContainer represents the MongoDB container type used in the module
type MongoDBContainer struct {
testcontainers.Container
}

// RunContainer creates an instance of the MongoDB container type
func RunContainer(ctx context.Context, opts ...testcontainers.ContainerCustomizer) (*MongoDBContainer, error) {
req := testcontainers.ContainerRequest{
Image: defaultImage,
ExposedPorts: []string{"27017/tcp"},
WaitingFor: wait.ForAll(
wait.ForLog("Waiting for connections"),
wait.ForListeningPort("27017/tcp"),
),
}

genericContainerReq := testcontainers.GenericContainerRequest{
ContainerRequest: req,
Started: true,
}

for _, opt := range opts {
opt.Customize(&genericContainerReq)
}

container, err := testcontainers.GenericContainer(ctx, genericContainerReq)
if err != nil {
return nil, err
}

return &MongoDBContainer{Container: container}, nil
}

// ConnectionString returns the connection string for the MongoDB container
func (c *MongoDBContainer) ConnectionString(ctx context.Context) (string, error) {
return c.Endpoint(ctx, "mongodb")
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@ import (
func TestMongoDB(t *testing.T) {
ctx := context.Background()

container, err := startContainer(ctx)
// createMongoDBContainer {
container, err := RunContainer(ctx)
if err != nil {
t.Fatal(err)
}
// }

// Clean up the container after the test is complete
t.Cleanup(func() {
Expand All @@ -26,21 +28,18 @@ func TestMongoDB(t *testing.T) {

// perform assertions

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

mongoClient, err := mongo.NewClient(options.Client().ApplyURI(endpoint))
mongoClient, err := mongo.Connect(ctx, 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))
Expand Down

0 comments on commit f4d9b1d

Please sign in to comment.