dbtest

package module
v0.28.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 27, 2020 License: MIT Imports: 11 Imported by: 0

README

Docker Test

Master CI GoDoc

hard working man

This is a Go library to run database containers as part of running the integration tests. The following databases are supported:

  • Postgres
  • MongoDB - DocumentDB

How to use

Running Postgres container

An example of running postgres container is present in this project. See the following files:

Running MongoDB container

Integration test snipppet

func TestPublishAppStatus_WithInvalidAppPlatformReturnBadRequestResponse(t *testing.T) {

	t.Logf("Given the app status api is up and running")
	{
		platform := "dummy"
		t.Logf("\tWhen Sending Publish App status request to endpoint with unsupported platform value:  \"%s\"", platform)
		{
		
            mockUnleash := test.GetMockUnleashClient(t)
			handler := NewAppStatusHandler(Repository, mockUnleash)
			router := handler.CreateRouter()
			version := "1.0"

			body := model.ReleaseRequest{Version: version, Platform: platform}
			req, err := test.HttpRequest(body, "/status", http.MethodPost, test.ValidToken)
			w := httptest.NewRecorder()
			router.ServeHTTP(w, req)

			// check call success
			test.Ok(err, t)

			if w.Code == http.StatusBadRequest {
				t.Logf("\t\tShould receive a \"%d\" status. %v", http.StatusBadRequest, test.CheckMark)
			} else {
				t.Errorf("\t\tShould receive a \"%d\" status. %v %v", http.StatusBadRequest, test.BallotX, w.Code)
			}
		}
	}
}

In the same package include a test file with the name: init_test.go and include the following

import (
	"github.com/akhettar/app-features-manager/repository"
	"context"
	"flag"
	"github.com/akhettar/docker-db"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"

	"net/http/httptest"
	"os"
	"testing"
)

const ProfileEnvVar = "PROFILE"

var (
	  
  // The repository instance configured to run against the Docker DB Test container
	Repository *repository.MongoRepository

)

// TestFixture wraps all tests with the needed initialized mock DB and fixtures
// This test runs before other integration test. It starts an instance of mongo db in the background (provided you have mongo
// installed on the server on which this test will be running) and shuts it down.
func TestMain(m *testing.M) {

	container := dbtest.StartMongoContainer()
	log.Printf("running mongo with Ip %s", container.Host())

	uri := fmt.Sprintf("mongodb://%s:%d", container.Host(), container.Port())
	clientOptions := options.Client().ApplyURI(uri)

	client, err := mongo.Connect(context.TODO(), clientOptions)

	if err != nil {
		panic(err)
	}

	// Check the connection
	err = client.Ping(context.TODO(), nil)

	if err != nil {
		log.Fatal(err)
	}

	Repository = &repository.MongoRepository{client, repository.DBInfo{uri, repository.DefaultDBName, repository.DefaultCollection}}

	// Run the test suite
	retCode := m.Run()

	c.Destroy()

	// call with result of m.Run()
	os.Exit(retCode)
}

License

MIT

Documentation

Overview

Package dbtest provides a way of starting a MongoDB or Postgres docker container prior to running the integration test suite. This packages manages the life cycle of the of this docker container it fires off the container, kill the container and remove its volume after the test suite is completed.

Here is an example on how to run these supported db containers:

import (
	"github.com/akhettar/docker-db"
)
func main() {

	// Starting Postgres container with an initialised schema file
	con1 := dbtest.StartPostgresContainerWithInitialisationScript("dbname", "schema.sql")
	fmt.Printf("mongo container with id running %s", con1.id)

	// Staring mongo container
	con2 := dbtest.StartMongoContainer()
	fmt.Printf("mongo container with id running %s", con2.id)
}

Index

Constants

View Source
const (
	PostgresUsername = "docker"
	PostgresPassword = "docker"
	IPAddressRegex   = "(.*IPAddress\"\\: \")(.*)(\",)"
	VolumeRegex      = "(volumes\\/)(.*)(\\/)"
)

Variables

This section is empty.

Functions

func Pull

func Pull(image string) error

Pull retrieves the docker image with 'docker pull'.

Types

type Container

type Container struct {
	// contains filtered or unexported fields
}

Container holding the docker container info

func StartMongoContainer

func StartMongoContainer() Container

StartMongoContainer

func StartPostgresContainer

func StartPostgresContainer(dbname string) Container

StartPostgresContainer starts a postgres container

func StartPostgresContainerWithInitialisationScript

func StartPostgresContainerWithInitialisationScript(dbname, schema string) Container

StartPostgresContainerWithInitialisationScript start a postgres container with an initialisation script.

func (Container) Destroy

func (c Container) Destroy()

Destroy stop and remove the container

func (Container) Host

func (c Container) Host() string

Host container defaulting to local host

func (Container) Password

func (c Container) Password() string

Password is the database password

func (Container) Port

func (c Container) Port() int

Port on which the container is running on

func (Container) Username

func (c Container) Username() string

Username is the user name database

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL