Documentation
¶
Overview ¶
Package dbtest is a lightweight way to run Postgres in Docker for tests: one call starts a disposable container (via testcontainers), hands back an open, migrated pool, and removes the container when the test is done.
NewPostgres starts a Postgres container, opens a connection, optionally applies migrations, and registers teardown with tb.Cleanup, so a test gets a clean, isolated database with one call. StartPostgres does the same without a testing.TB, for TestMain: one container serves every test of the package, and the caller closes it. Importing this package pulls in testcontainers and the Docker client, so it is intended for test binaries only, and tests using it should be guarded with `if testing.Short() { t.Skip(...) }` since they require a running Docker daemon.
Usage ¶
//go:embed migrations/*.sql
var migrationsFS embed.FS
func TestWidgets(t *testing.T) {
if testing.Short() {
t.Skip("requires docker")
}
ctx := context.Background()
pg := dbtest.NewPostgres(ctx, t, dbtest.Config{Migrations: migrationsFS})
repo := widget.NewStore(pg.DB) // pg.DB is an open, migrated *dbx.DB
// ... exercise repo against a real Postgres ...
}
One container for the whole package, in TestMain. testing.Short needs the flags parsed, hence flag.Parse; under -short the tests run without it and skip themselves:
var pg *dbtest.Postgres
func TestMain(m *testing.M) {
flag.Parse()
if testing.Short() {
os.Exit(m.Run())
}
ctx := context.Background()
cfg := dbtest.Config{Migrations: migrationsFS}
var err error
pg, err = dbtest.StartPostgres(ctx, cfg)
if err != nil {
log.Fatal(err)
}
code := m.Run()
_ = pg.Close(ctx)
os.Exit(code)
}
The returned Postgres also exposes Config, a pg.Config pointing at the container, for handing to application code that opens its own pool.
API ¶
- NewPostgres: a container per test, closed by tb.Cleanup; fails the test on error.
- StartPostgres / Close: a container the caller owns, for TestMain; on a start error nothing is left running.
Config ¶
The zero Config is valid; every field has a default:
- Image: container image (default "postgres:17-alpine").
- Database, User, Password: the bootstrapped database and superuser (defaults "skit", "postgres", "postgres").
- Migrations: an fs.FS (typically an embed.FS of `*.sql` files) applied with the migrate package once the database is ready; nil skips migrations.
- StartupTimeout: bound on waiting for the database to accept connections (default 60s).
Example ¶
A test gets a migrated database in a container of its own, removed when the test ends. It needs Docker: the test skips itself under -short.
package main
import (
"context"
"testing"
"testing/fstest"
"github.com/matryer/is"
"github.com/assanoff/skit/dbtest"
"github.com/assanoff/skit/dbx"
)
// migrations stands in for the embed.FS of a service's *.sql files.
var migrations = fstest.MapFS{
"00001_widgets.sql": {Data: []byte(`-- +goose Up
CREATE TABLE widgets (id BIGINT PRIMARY KEY, name TEXT NOT NULL);
-- +goose Down
DROP TABLE widgets;
`)},
}
func main() {
var t *testing.T // the *testing.T of the test
is := is.New(t)
ctx := context.Background()
db := dbtest.NewPostgres(ctx, t, dbtest.Config{Migrations: migrations}).DB
const ins = `INSERT INTO widgets (id, name) VALUES (:id, :name)`
err := dbx.NamedExec(ctx, db, ins, map[string]any{"id": 1, "name": "gear"})
is.NoErr(err)
n, err := dbx.QueryOne[int](ctx, db, `SELECT count(*) FROM widgets`)
is.NoErr(err)
is.Equal(n, 1)
}
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// Image is the container image (default "postgres:17-alpine").
Image string
// Database, User, Password name the bootstrapped database and superuser
// (defaults "skit", "postgres", "postgres").
Database string
User string
Password string
// Migrations, when non-nil, is applied with goose after the database is
// ready — typically an embed.FS of `*.sql` files.
Migrations fs.FS
// StartupTimeout bounds waiting for the database to accept connections
// (default 60s).
StartupTimeout time.Duration
}
Config tunes the Postgres container. The zero value is valid and uses the defaults documented on each field.
type Postgres ¶
type Postgres struct {
// DB is an open, migrated connection pool to the container.
DB *dbx.DB
// Config is a pg.Config pointing at the container, suitable for handing
// to application code that opens its own pool.
Config pg.Config
// contains filtered or unexported fields
}
Postgres is a running Postgres test container with an open connection.
func NewPostgres ¶
NewPostgres starts a Postgres container with StartPostgres and registers Close with tb.Cleanup. It fails the test on any error. Skip the calling test under `go test -short`, as it needs Docker.
func StartPostgres ¶ added in v0.14.0
StartPostgres starts a Postgres container, opens a connection and applies cfg.Migrations (when set). The caller calls Close, so it suits TestMain, where one container serves every test of the package. On error nothing is left running.
Example ¶
StartPostgres runs one container for every test of a package, from TestMain; the caller closes it. Config points at the container, for code that opens its own pool.
package main
import (
"context"
"log"
"testing/fstest"
"github.com/assanoff/skit/dbtest"
"github.com/assanoff/skit/dbx"
"github.com/assanoff/skit/dbx/pg"
)
// migrations stands in for the embed.FS of a service's *.sql files.
var migrations = fstest.MapFS{
"00001_widgets.sql": {Data: []byte(`-- +goose Up
CREATE TABLE widgets (id BIGINT PRIMARY KEY, name TEXT NOT NULL);
-- +goose Down
DROP TABLE widgets;
`)},
}
func main() {
ctx := context.Background()
container, err := dbtest.StartPostgres(ctx, dbtest.Config{Migrations: migrations})
if err != nil {
log.Fatal(err)
}
defer func() { _ = container.Close(ctx) }()
db, err := pg.Open(container.Config)
if err != nil {
log.Fatal(err)
}
defer func() { _ = db.Close() }()
if err := dbx.StatusCheck(ctx, db); err != nil {
log.Fatal(err)
}
}
Output: