Skip to content

Instantly share code, notes, and snippets.

@avneesh91
Created May 3, 2023 00:31
Show Gist options
  • Save avneesh91/6cc205521e6c1e4b0cf5974b8289bbc2 to your computer and use it in GitHub Desktop.
Save avneesh91/6cc205521e6c1e4b0cf5974b8289bbc2 to your computer and use it in GitHub Desktop.
package repositories
import (
"context"
"fmt"
"github.com/ory/dockertest/v3"
"github.com/ory/dockertest/v3/docker"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
"os"
"testing"
)
func RunMongoAndSetValue() func() {
pool, err := dockertest.NewPool("")
if err != nil {
log.Fatalf("Could not construct pool: %s", err)
}
// uses pool to try to connect to Docker
err = pool.Client.Ping()
if err != nil {
log.Fatalf("Could not connect to Docker: %s", err)
}
// pulls an image, creates a container based on it and runs it
mongoResource, err := pool.RunWithOptions(&dockertest.RunOptions{
Repository: "mongo",
Tag: "5.0",
Env: []string{
// username and password for mongodb superuser
"MONGO_INITDB_ROOT_USERNAME=root",
"MONGO_INITDB_ROOT_PASSWORD=password",
},
}, func(config *docker.HostConfig) {
// set AutoRemove to true so that stopped container goes away by itself
config.AutoRemove = true
config.RestartPolicy = docker.RestartPolicy{
Name: "no",
}
})
if err != nil {
log.Fatalf("Could not start resource: %s", err)
}
err = pool.Retry(func() error {
var err error
dbClient, err := mongo.Connect(
context.TODO(),
options.Client().ApplyURI(
fmt.Sprintf("mongodb://root:password@localhost:%s", mongoResource.GetPort("27017/tcp")),
),
)
if err != nil {
return err
}
return dbClient.Ping(context.TODO(), nil)
})
mongoResource.Expire(300)
os.Setenv("DB_URL", fmt.Sprintf("mongodb://root:password@localhost:%s", mongoResource.GetPort("27017/tcp")))
os.Setenv("DB_NAME", "scheduly")
return func() {
if err = pool.Purge(mongoResource); err != nil {
log.Fatalf("Could not purge resource: %s", err)
}
}
}
func TestMain(m *testing.M) {
stopFunc := RunMongoAndSetValue()
code := m.Run()
stopFunc()
os.Exit(code)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment