Documentation ¶
Overview ¶
Package testdb provides the ability to easily create MongoDB databases/ collections within tests.
Index ¶
Constants ¶
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 ¶
var NoIndexes []mongo.IndexModel
NoIndexes can be passed to CreateRandomCollection to create a collection without indexes.
Functions ¶
func IsDupeKeyError ¶
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 ¶
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 ¶
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.