pgtest
Go test fixtures for pgx v5 with one native PostgreSQL server across all
package test processes in a test run. Each suite gets a migrated template, and
each test gets an isolated database and pool. Tests can run in parallel, use real
transactions and multiple sessions, and rely on automatic cleanup.
The Go library and CLI build with CGO_ENABLED=0. PostgreSQL runs as a native
child process; Docker and Node.js are not required. Go 1.25 or newer is required
for the library. License: MIT.
Install
Install the CLI through Homebrew:
brew install dio/tap/pgtest
Or install it with Go:
go install github.com/dio/pgtest/cmd/pgtest@v0.2.0
Add the library to your application:
go get github.com/dio/pgtest@v0.2.0
Both the CLI and the library used by your tests must be v0.2.0 or newer for
cross-package sharing. pgtest version prints the CLI version.
One server across all packages
Wrap your normal test command:
pgtest -- go test -count=1 ./...
The wrapper starts one PostgreSQL server, runs go test, and stops that
server after the command finishes, including command failures. Its inherited
PGTEST_RUN capability tells Open and New in every package test process to
attach instead of starting another server. An invalid or stale capability fails
setup; it never silently falls back to a second server.
Keep one Suite in each package's TestMain, then call suite.Database(t) in
every parallel test. Each suite has a unique template and database-name prefix,
so different packages can use different schemas and repeat primary keys safely.
Migrations run once per suite, not once globally across all packages.
suite.Database(t) creates a database and pool on the shared server.
suite.Close() drops that suite's databases and template; sibling suites keep
running on the same server.
- The wrapper owns the server for the entire command, even during gaps between
package processes. There is no persistent daemon or cross-process reference count.
- Outside the wrapper,
Open and New preserve their original behavior and each
start a private server. This supports focused IDE and single-package test runs.
The wrapper inherits the current directory and forwards standard input/output,
so commands and test flags work normally. -count=1 makes verification explicit
instead of relying on Go's test-result cache. Put wrapper flags before --:
pgtest -version 18.3.0 -max-connections 200 -- go test -count=1 -p=4 -parallel=4 ./...
Size the server connection limit against package concurrency (-p), test
concurrency (-parallel) and per-fixture Options.MaxConns (default 4). Pools open
connections lazily; each suite also has an admin pool of up to two connections.
Configure the server version, binary cache, and connection limit on the wrapper.
An explicitly requested package version must match the wrapper's version.
On Unix, cancellation (including Ctrl-C or SIGTERM to the CLI) kills the command's
process group before stopping PostgreSQL. A crashing test process can leave
fixtures until run shutdown; shutting down the server removes the entire temporary
cluster. SIGKILL to the wrapper cannot run cleanup. On non-Unix platforms, command
cancellation currently terminates only the direct child; recursive cancellation
is verified on Linux/macOS only.
The runnable TestMain example uses the same API
with or without the wrapper. The cross-process regression starts two real Go
package tests concurrently and checks that their fixtures use one data directory
and distinct database names.
Programmatic command ownership
cmd := exec.Command("go", "test", "-count=1", "./...")
cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
err := pgtest.Run(ctx, cmd, pgtest.Options{ServerMaxConns: 200})
Run preserves the command's directory, environment and streams. On Unix it
requires cmd.SysProcAttr == nil so it can own a process group. Command exit
errors remain discoverable with errors.As(err, &exitErr). Supply migrations to
package suites, not to Run. Nested wrappers are rejected.
Parent test with parallel subtests
package repository_test
import (
"context"
"testing"
"github.com/dio/pgtest"
"github.com/jackc/pgx/v5"
)
func TestRepository(t *testing.T) {
suite := pgtest.New(t, pgtest.Options{
Version: "18.3.0", // Pin this to the PostgreSQL version you want to test.
Migrate: func(ctx context.Context, conn *pgx.Conn) error {
_, err := conn.Exec(ctx, `
CREATE TABLE widgets(id int PRIMARY KEY, name text NOT NULL);
`)
return err
},
})
for _, name := range []string{"first", "second"} {
t.Run(name, func(t *testing.T) {
t.Parallel()
db := suite.Database(t)
// Your real repository can receive db.Pool().
_, err := db.Pool().Exec(t.Context(),
"INSERT INTO widgets VALUES($1, $2)", 1, name)
if err != nil {
t.Fatal(err)
}
})
}
}
The repeated primary key is safe because each subtest gets its own database. The
suite belongs to the parent test: t.Cleanup keeps it alive until all parallel
subtests and their cleanup finish. Do not use defer suite.Close() in that parent;
a parent's function returns before its parallel subtests run.
See example_test.go for a compiled and executed public-API example.
TestMain ownership
For many top-level tests in one Go package, open one suite around m.Run():
var suite *pgtest.Suite
func TestMain(m *testing.M) {
os.Exit(run(m))
}
func run(m *testing.M) int {
var err error
suite, err = pgtest.Open(context.Background(), pgtest.Options{
Migrate: migrate, // func(context.Context, *pgx.Conn) error
})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
code := m.Run()
if err := suite.Close(); err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
return code
}
func TestSomething(t *testing.T) {
t.Parallel()
db := suite.Database(t)
// repository := NewRepository(db.Pool())
_ = db
}
This sketch additionally imports os and fmt; migrate is your migration
function. Keep os.Exit outside the function that owns cleanup. Each Go package's
test executable owns its own suite. Under the wrapper all those suites attach to
the run-owned server; without it each suite starts its own server.
API
| Operation |
Purpose |
pgtest.Run(ctx, cmd, Options) |
Own one server around a command and its package test processes |
pgtest.New(t, Options) |
Create or attach a suite and register test cleanup; fail the test on error |
suite.Database(t) |
Create a database and register its cleanup |
pgtest.Open(ctx, Options) |
Error-returning suite setup |
suite.Create(ctx) |
Error-returning database setup |
db.Pool() |
Fixture's *pgxpool.Pool |
db.DSN() / db.Name() |
Connection string / unique database name |
db.Close() |
Close pool, then drop database |
suite.Close() |
Close owned databases/template; stop server only for a private suite |
Close methods are idempotent and safe to call concurrently. Create after suite
shutdown returns pgtest.ErrClosed. Database creation is serialized within a
suite to make ownership and shutdown predictable; queries on separate fixtures
run concurrently. Do not call Close while application workers still need the
suite or fixture.
Migrations and options
Migrate runs once against a dedicated template connection. It can apply schema
and common seed data. The package closes that connection and seals the template
before cloning. Migrations must finish their transactions; an open transaction
is rejected. Returned errors, panics, and setup cancellation trigger cleanup.
The callback accepts pgx directly, so this package does not impose a migration
framework. If your migrator opens its own connection using
conn.Config().ConnString(), it must close every connection to that template
before returning. Never retain the provided connection. Callbacks must propagate
the supplied context to SQL operations.
| Option |
Default |
Meaning |
Migrate |
nil |
Template schema/seed callback |
Version |
embedded-postgres default, currently 18.3.0 |
Pin a native binary release |
CacheDir |
OS user cache directory / pgtest |
Download and binary cache |
MaxConns |
4 |
Maximum connections per test's application pool |
ServerMaxConns |
native default (100) |
Server connection limit; configure on the run owner |
Timeout |
30 seconds |
SQL setup/drop and native startup health timeout |
Logger |
discarded |
Writer for embedded Postgres logs |
An earlier context deadline takes precedence during SQL setup. Open/Create
contexts apply to setup only; cancellation after a successful return does not
terminate a fixture. The migration callback must cooperate with cancellation.
Upstream native download/start/stop operations do not expose a cancellable context,
so Timeout is not a hard wall-clock limit on the complete Open or Close call.
Resource and cache ownership
Cleanup order is: stop your application workers, release acquired connections and
finish transactions, close the fixture pool, drop its database, close the admin
pool, stop native PostgreSQL, then remove temporary runtime files. In shared mode,
suite cleanup drops its template and closes its admin pool; only the wrapper
stops the server and removes the runtime.
pgxpool.Close waits for borrowed connections to return. Additional connections
opened from db.DSN() also belong to their caller. The package uses normal
DROP DATABASE, not forced termination, so leaked external sessions cause cleanup
to report an error. Suite shutdown reports errors and still attempts server cleanup.
If server stop fails, its runtime files are kept and their path is reported.
Downloads are cached. On macOS/Linux a cold suite extracts binaries into a private
staging directory and publishes it atomically only after that server has stopped.
Later suites use the immutable version/OS/architecture-specific cache. Concurrent
publishers can safely accept the first completed cache entry. This avoids both
re-extracting binaries on every warm run and sharing a partially extracted tree.
Windows uses private per-suite binary extraction because the upstream binary-cache
probe checks for pg_ctl without .exe; shared archive downloads remain cached.
Interrupted processes may leave private staging/runtime directories behind.
Database isolation does not isolate cluster-wide objects such as roles. The
package manages its own servers. The wrapper supplies a run-specific connection
capability, verified before attached suites create databases. Do not set
PGTEST_RUN manually or use it to point at an unrelated PostgreSQL server. Port selection has the usual reserve/release race because the native
launcher cannot inherit a listening socket; a collision fails setup rather than
connecting to somebody else's server. PostgreSQL binary availability and OS/user
restrictions are inherited from embedded-postgres (for example, native PostgreSQL
cannot run as root).
Verification
CGO_ENABLED=0 go test ./...
CGO_ENABLED=0 go test -tags=integration -count=1 -timeout=5m ./...
CGO_ENABLED=1 go test -tags=integration -race -count=1 -timeout=5m ./...
CGO_ENABLED=0 go vet -tags=integration ./...
Integration tests start real PostgreSQL and may download binaries on their first
run. The race detector itself requires CGO; the package does not. CI runs the
checks on Linux and macOS with Go 1.25 and 1.26.
Tests cover one server across separate package processes, command failure and
cancellation, attached-suite cleanup, owner verification, parallel database isolation, migrations
once, cross-session committed writes, SQLSTATE recovery, concurrent create/close,
cleanup, cancelled setup, migration errors/panics/open transactions, and cache
publication. Separate suites are used where lifecycle tests intentionally stop
servers or fail startup.
Origin
The fixture boundary is inspired by
Minder's embedded test store.
This is a fresh implementation: it uses explicit suite ownership, pgx v5, a
migrated template, and owned cleanup instead of Minder's reference-counted
shutdown and migrations per fixture. No Minder source or migration data is vendored.