testdb

package module
v0.0.0-...-c4845cc Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2020 License: Apache-2.0 Imports: 7 Imported by: 0

README

Test databases for MongoDB, made easy.

Build Status Go Report Card Coverage Status GoDoc

This is a small Go package that makes it easy to create databases/collections for MongoDB tests. It's useful when you want to run tests against an actual MongoDB instance.

Setup

Install the package with "go get".

go get "github.com/mongo-go/testdb"

This package should only be imported in tests; you should never use it in actual code.

Usage

Here is an example of how to use this package:

package main_test

import (
        "testing"

        "github.com/mongo-go/testdb"
)

var testDb *testdb.TestDB

func setup(t *testing.T) *mgo.Collection {
	if testDb == nil {
		testDb = testdb.NewTestDB("mongodb://localhost", "your_db", time.Duration(2) * time.Second)

		err := testDb.Connect()
		if err != nil {
			t.Fatal(err)
		}
        }

        coll, err := testDb.CreateRandomCollection(testdb.NoIndexes)
        if err != nil {
                t.Fatal(err)
        }

        return coll // random *mongo.Collection in "your_db"
}

func Test1(t *testing.T) {
        coll := setup(t)
	defer coll.Drop(context.Background())

        // Test queries using coll
}

Overriding Defaults with Environement Variables

One of the benefits of using this package is that it allows you to override certain defaults with environment variables. These are the env vars currently supported:

  • TEST_MONGO_URL: overrides the url of the MongoDB instance being used for testing.
  • TEST_MONGO_DB: overrides the database name being used for testing.

By default, even if these env vars are set, they will not be used. To use them, you must call the OverrideWithEnvVars on a TestDB before calling Connect, like so:

// export TEST_MONGO_URL="their_url"
// export TEST_MONGO_DB="their_db"

testDb := testdb.NewTestDB("mongodb://localhost", "your_db", time.Duration(2) * time.Second)
testDb.OverrideWithEnvVars()

err := testdb.Conect() {
        // ...
}

Why is this useful? Say you have some tests that connect to MongoDB, which you always have running locally at "mongodb://localhost". Hardcoding your tests to create a TestDB with that url works fine for you, but what about when someone else who has MongoDB running locally at "their_url" tries to run your tests? By calling OverrideWithEnvVars in your tests you give whoever is invoking them the ability to change the url and database of the TestDB without having to change any code.

Tests

Tests for this package require an instance of MongoDB to be running at "localhost" (no port). They write into the db "test" and collection "testdb_collection", and delete all documents from that collection after they run.

Run the tests from the root directory of this repo like so:

go test `go list ./... | grep -v "/vendor/"` --race

Documentation

Overview

Package testdb provides the ability to easily create MongoDB databases/ collections within tests.

Index

Constants

View Source
const (
	// ENV_VAR_TEST_MONGO_URL is an environment variable that, if set, can
	// override the MongoDB url used in a TestDB. The OverrideWithEnvVars
	// method must be called for it to take effect.
	ENV_VAR_TEST_MONGO_URL = "TEST_MONGO_URL"

	// ENV_VAR_TEST_MONGO_DB is an environment variable that, if set, can
	// override the MongoDB database used in a TestDB. The OverrideWithEnvVars
	// method must be called for it to take effect.
	ENV_VAR_TEST_MONGO_DB = "TEST_MONGO_DB"
)

Variables

View Source
var NoIndexes []mongo.IndexModel

NoIndexes can be passed to CreateRandomCollection to create a collection without indexes.

Functions

func IsDupeKeyError

func IsDupeKeyError(err error) bool

IsDupeKeyError returns true if the error is a Mongo duplicate key error.

Types

type TestDB

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

A TestDB represents a MongoDB database used for running tests against.

func NewTestDB

func NewTestDB(url, db string, timeout time.Duration) *TestDB

NewTestDB creates a new TestDB with the provided url, database name, and timeout. It doesn't actually connect to MongoDB; the Connect method must be called to do that.

func (*TestDB) Close

func (t *TestDB) Close()

Close terminates the TestDB's connection to MongoDB.

func (*TestDB) Connect

func (t *TestDB) Connect() error

Connect initializes a connection to the TestDB. It will return an error if it cannot connect to MongoDB.

func (*TestDB) CreateRandomCollection

func (t *TestDB) CreateRandomCollection(indexes []mongo.IndexModel) (*mongo.Collection, error)

CreateRandomCollection creates a collection with the details of info, and ensures it has the provided indexes. The name of the collection will be random, following the format of "test_" + 8 random characters. The DropCollection method should always be called to clean up collections created by this method.

TestDB only supports creating random collections due to the fact that tests run concurrently. If multiple tests used the same collection, they would probably stomp on each other.

func (*TestDB) OverrideWithEnvVars

func (t *TestDB) OverrideWithEnvVars()

OverrideWithEnvVars overrides the url and database in a TestDB if certain environment variables are set. This makes it easy for multiple people to run tests that require a MongoDB instance even if they have it running at different urls or if they want to use different databases.

This method will only do anything if Connect hasn't already been called on the TestDB.

Jump to

Keyboard shortcuts

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