TestDock is a Go library that simplifies database testing by providing an easy way to create and manage test databases in realistic scenarios, instead of using mocks. It supports running tests against both Docker containers and external databases, with built-in support for MongoDB and various SQL databases.
-
Multiple Database Support
- MongoDB:
GetMongoDatabase
function - PostgreSQL (with both
pgx
andpq
drivers):GetPgxPool
andGetPqConn
functions - MySQL:
GetMySQLConn
function - Any other SQL database supported by
database/sql
https://go.dev/wiki/SQLDrivers:GetSQLConn
function
- MongoDB:
-
Flexible Test Environment
- Docker container support for isolated testing
- External database support for CI/CD environments
- Auto-mode that switches based on environment variables
-
Database Migration Support
- Integration with goose
- Integration with golang-migrate
- User provided migration tool
- Automatic migration application during test setup
-
Robust Connection Handling
- Automatic retry mechanisms
- Automatic selection of a free host port when deploying containers
- Graceful cleanup after tests
go get github.com/n-r-w/testdock/v2@latest
GetPgxPool
: PostgreSQL connection pool (pgx driver)GetPqConn
: PostgreSQL connection (libpq driver)GetMySQLConn
: MySQL connectionGetSQLConn
: Generic SQL database connectionGetMongoDatabase
: MongoDB database
The connection string format is driver-specific. For example:
- For PostgreSQL:
postgres://user:password@localhost:5432/database?sslmode=disable
- For MySQL:
root:password@tcp(localhost:3306)/database?parseTime=true
- For MongoDB:
mongodb://user:password@localhost:27017/database
Depending on the chosen mode (WithMode
), the connection string is used differently:
- The connection string is used directly to connect to the database
- The connection string is used to generate the Docker container configuration
- The port value is used 1) as the port inside the container, 2) as the external access port to the database
- If this port is already taken on the host, then TestDock tries to find a free port by incrementing its value by 1 until a free port is found
- If the environment variable
TESTDOCK_DSN_<DRIVER_NAME>
is not set, then TestDock chooses theRunModeDocker
mode and uses the input string as the container configuration - If the environment variable
TESTDOCK_DSN_<DRIVER_NAME>
is set, then TestDock chooses theRunModeExternal
mode and uses the string from the environment variable to connect to the external database. In this case, thedsn
parameter of the constructor function is ignored. Thus, in this mode, thedsn
parameter is used as a fallback if the environment variable is not set.
import (
"testing"
"github.com/n-r-w/testdock/v2"
)
func TestDatabase(t *testing.T) {
// Get a connection pool to a test database.
/*
If the environment variable TESTDOCK_DSN_PGX is set, then the input
connection string is ignored and the value from the environment variable
is used. If the environment variable TESTDOCK_DSN_PGX is not set,
then the input connection string is used to generate the Docker container
configuration.
*/
pool, _ := testdock.GetPgxPool(t,
testdock.DefaultPostgresDSN,
testdock.WithMigrations("migrations", testdock.GooseMigrateFactoryPGX),
)
// Use the pool for your tests
// The database will be automatically cleaned up after the test
}
import (
"testing"
"github.com/n-r-w/testdock/v2"
)
func TestMongoDB(t *testing.T) {
// Get a connection to a test database
db, _ := testdock.GetMongoDatabase(t, testdock.DefaultMongoDSN,
testdock.WithMode(testdock.RunModeDocker),
testdock.WithMigrations("migrations", testdock.GolangMigrateFactory),
)
// Use the database for your tests
// The database will be automatically cleaned up after the test
}
TESTDOCK_DSN_PGX
,TESTDOCK_DSN_POSTGRES
- PostgreSQL-specific connection stringsTESTDOCK_DSN_MYSQL
- MySQL-specific connection stringTESTDOCK_DSN_MONGODB
- MongoDB-specific connection stringTESTDOCK_DSN_<DRIVER_NAME>
- Custom connection string for a specific driver
WithRetryTimeout(duration)
: Configure connection retry timeout (default 3s). Must be less than totalRetryDurationWithTotalRetryDuration(duration)
: Configure total retry duration (default 30s). Must be greater than retryTimeout
WithDockerSocketEndpoint(endpoint)
: Custom Docker daemon socketWithDockerPort(port)
: Override container port mappingWithUnsetProxyEnv(bool)
: Unset proxy environment variables
WithConnectDatabase(name)
: Override connection databaseWithPrepareCleanUp(func)
: Custom cleanup handlers. The default is empty, butGetPgxPool
andGetPqConn
functions use it to automatically apply cleanup handlers to disconnect all users from the database before cleaning up.WithLogger(logger)
: Custom logging implementation
DefaultPostgresDSN
: Default PostgreSQL connection stringDefaultMySQLDSN
: Default MySQL connection stringDefaultMongoDSN
: Default MongoDB connection string
TestDock supports two popular migration tools:
https://github.com/pressly/goose
db, _ := GetPqConn(t,
"postgres://postgres:[email protected]:5432/postgres?sslmode=disable",
testdock.WithMigrations("migrations/pg/goose", testdock.GooseMigrateFactoryPQ),
testdock.WithDockerImage("17.2"),
)
https://github.com/golang-migrate/migrate
db, _ := GetMongoDatabase(t,
testdock.DefaultMongoDSN,
WithDockerRepository("mongo"),
WithDockerImage("6.0.20"),
WithMigrations("migrations/mongodb", testdock.GolangMigrateFactory),
)
You can also use a custom migration tool implementing the testdock.MigrateFactory
interface.
- Go 1.23 or higher
- Docker (when using
RunModeDocker
orRunModeAuto
)
MIT License - see LICENSE for details