2019-10-07 22:14:47 +08:00
|
|
|
// Copyright (c) Mainflux
|
2018-08-26 19:15:48 +08:00
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
2018-08-08 19:38:34 +08:00
|
|
|
package mongodb_test
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"testing"
|
|
|
|
|
2021-01-19 16:30:48 +08:00
|
|
|
log "github.com/mainflux/mainflux/logger"
|
|
|
|
dockertest "github.com/ory/dockertest/v3"
|
2019-04-16 20:58:56 +08:00
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
2018-08-08 19:38:34 +08:00
|
|
|
)
|
|
|
|
|
2021-01-19 16:30:48 +08:00
|
|
|
var testLog, _ = log.New(os.Stdout, log.Info.String())
|
|
|
|
|
2018-08-08 19:38:34 +08:00
|
|
|
func TestMain(m *testing.M) {
|
|
|
|
pool, err := dockertest.NewPool("")
|
|
|
|
if err != nil {
|
|
|
|
testLog.Error(fmt.Sprintf("Could not connect to docker: %s", err))
|
|
|
|
}
|
|
|
|
|
|
|
|
cfg := []string{
|
|
|
|
"MONGO_INITDB_DATABASE=test",
|
|
|
|
}
|
|
|
|
|
2021-02-05 19:32:21 +08:00
|
|
|
container, err := pool.Run("mongo", "4.4.3-bionic", cfg)
|
2018-08-08 19:38:34 +08:00
|
|
|
if err != nil {
|
|
|
|
testLog.Error(fmt.Sprintf("Could not start container: %s", err))
|
|
|
|
}
|
|
|
|
|
|
|
|
port = container.GetPort("27017/tcp")
|
|
|
|
addr = fmt.Sprintf("mongodb://localhost:%s", port)
|
|
|
|
|
|
|
|
if err := pool.Retry(func() error {
|
2019-04-16 20:58:56 +08:00
|
|
|
_, err := mongo.Connect(context.Background(), options.Client().ApplyURI(addr))
|
2018-08-08 19:38:34 +08:00
|
|
|
return err
|
|
|
|
}); err != nil {
|
|
|
|
testLog.Error(fmt.Sprintf("Could not connect to docker: %s", err))
|
|
|
|
}
|
|
|
|
|
|
|
|
code := m.Run()
|
|
|
|
|
|
|
|
if err := pool.Purge(container); err != nil {
|
|
|
|
testLog.Error(fmt.Sprintf("Could not purge container: %s", err))
|
|
|
|
}
|
|
|
|
|
|
|
|
os.Exit(code)
|
|
|
|
}
|