dbtest starts a real database server in a Docker container for a Go test.
For MongoDB it hands the test a connected client of the official MongoDB Go
driver, and removes the container when the test ends. For PostgreSQL it
hands the test a pgx pool and a *sql.DB, both connected.
go get github.com/tophergopher/dbtest/mongotest # if you use go.mongodb.org/mongo-driver
go get github.com/tophergopher/dbtest/mongotestv2 # if you use go.mongodb.org/mongo-driver/v2Starting a new project with no driver yet? Use mongotestv2: driver v1 is
in maintenance.
dbtest needs Go 1.26 or newer, and a running Docker or Podman daemon. Without a daemon, the test fails rather than skipping. For Podman, see the Podman guide.
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/tophergopher/dbtest/mongotest"
"go.mongodb.org/mongo-driver/bson"
)
func TestOrders(t *testing.T) {
orders := mongotest.Run(t).Database("shop").Collection("orders")
_, err := orders.InsertOne(t.Context(), bson.M{"item": "book"})
require.NoError(t, err)
}With driver v2, import github.com/tophergopher/dbtest/mongotestv2 and
go.mongodb.org/mongo-driver/v2/bson, and write mongotestv2.Run(t).
Nothing else changes. Do not leave bson on v1: a v1 bson value passed
to a v2 client compiles, but at run time it is stored as the wrong type or
refused.
Upgrading from github.com/tophergopher/mongotest? It used driver v1, so
import github.com/tophergopher/dbtest/mongotest instead. The names the old
module exported at v0.2.9 are gone, and
CHANGELOG.md
lists what replaces each. If you set MONGOTEST_HOST_IP, rename it to
DBTEST_HOST_IP: the old name is ignored. MONGOTEST_IMAGE and
MONGOTEST_START_TIMEOUT keep their names.
go get github.com/tophergopher/dbtest/pgtestfunc TestOrders(t *testing.T) {
db := pgtest.Run(t).DB // import "github.com/tophergopher/dbtest/pgtest"
_, err := db.ExecContext(t.Context(), "CREATE TABLE orders (item text)")
require.NoError(t, err)
}To use both clients, keep the instance: inst := pgtest.Run(t), then
inst.DB and inst.Pool, which is pgx's own pool. They share one pool of
connections. Each call to Run starts another container. For another
driver, such as lib/pq, the postgres package in the root module
starts the server and returns its connection string, with no driver
imported. See
The pgtest package
and The postgres package.
Every container dbtest starts carries the label mongotest=regression. If
a killed test run leaves containers behind, this command removes them and
their unnamed volumes:
docker ps -aq --filter label=mongotest=regression | xargs -r docker rm -fvThe command keeps volumes you named with mongod.Options.WithNamedVolume.
Remove those with docker volume rm <name>.
The documentation site lives in docs/ and is built with
Zensical. It is published to GitHub Pages from main by
.github/workflows/docs.yml. New usage
patterns go in docs/guides/.
Writing a new page
says how to preview the site locally and what a page must hold.