pgtest

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 11, 2026 License: MIT Imports: 19 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

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.

Documentation

Overview

Package pgtest provides native PostgreSQL fixtures for pgx v5 tests. A Suite owns a migrated template; each Database owns a clone and a pgxpool. Normally each suite starts a server. Under the pgtest command, all suites attach to one server owned by that command across package processes. Create one suite in a parent test or TestMain, then use distinct databases for parallel tests. No Docker, Node.js, or CGO is required.

Index

Constants

This section is empty.

Variables

View Source
var ErrClosed = errors.New("pgtest: suite closed")

ErrClosed is returned when creating a database after its suite has closed.

Functions

func Run added in v0.2.0

func Run(ctx context.Context, cmd *exec.Cmd, opts Options) (err error)

Run starts one PostgreSQL server for cmd and its descendant package tests. Open and New in those processes attach automatically. Every suite still runs its own migration callback against its own template. Run's Migrate must be nil.

cmd must be unstarted. Its directory, environment and streams are preserved; Run appends its connection capability to cmd.Env. The caller owns the command streams. Run returns command errors (including *exec.ExitError) and joins any server cleanup errors. The server is stopped even if cmd fails or ctx is canceled. On Unix, Run owns a new process group and kills remaining descendants on exit. On other platforms cancellation terminates the direct child only.

Types

type Database

type Database struct {
	// contains filtered or unexported fields
}

Database owns a unique database and its pool. Do not close Pool() directly when you want to destroy the fixture: use Close. Additional connections are allowed but must be closed by their owner before cleanup.

func (*Database) Close

func (db *Database) Close() error

Close closes the pool, then drops the database. Release acquired connections, finish transactions, and stop application workers first: pgxpool.Close waits for borrowed connections to return. Repeated calls return the same result.

func (*Database) DSN

func (db *Database) DSN() string

DSN returns a connection string for this fixture's database.

func (*Database) Name

func (db *Database) Name() string

Name returns this fixture's unique database name.

func (*Database) Pool

func (db *Database) Pool() *pgxpool.Pool

Pool returns the application pool owned by this fixture.

type Options

type Options struct {
	// Migrate runs once against the template. It may also insert shared seed data.
	// The connection belongs to pgtest: do not retain it, leave transactions open,
	// or keep other connections to the template alive after this callback returns.
	Migrate func(context.Context, *pgx.Conn) error
	// Version is an embedded-postgres binary version, e.g. "18.3.0".
	// Empty uses embedded-postgres's default version.
	Version string
	// CacheDir holds downloaded archives and immutable extracted binaries. Empty uses the
	// OS user cache directory under "pgtest". Database files are always temporary.
	CacheDir string
	// MaxConns limits each application's pool. Zero defaults to 4.
	MaxConns int32
	// Timeout bounds SQL setup and database-drop operations. Zero defaults to 30s.
	// The embedded binary downloader and migration callback must also cooperate:
	// embedded-postgres Start does not expose context cancellation.
	Timeout time.Duration
	// Logger receives embedded Postgres startup/server logs. Nil discards them.
	Logger io.Writer
	// ServerMaxConns sets the native server's connection limit. Zero uses PostgreSQL's
	// default (100). Under Run, set this on the owner; attached suites cannot change it.
	ServerMaxConns int
}

Options controls suite initialization. The zero value starts the default embedded-postgres version with an empty application template.

type Suite

type Suite struct {
	// contains filtered or unexported fields
}

Suite owns its immutable template and every database it creates. It also owns the server unless it attached to a run started by the pgtest command. It is safe for concurrent Create and Close calls. Creation is serialized to keep provisioning and shutdown ownership simple; test queries run concurrently.

func New

func New(t testing.TB, opts Options) *Suite

New creates a suite owned by a parent test. Cleanup runs after its parallel subtests and their cleanup finish. It fails the test if setup fails.

func Open

func Open(ctx context.Context, opts Options) (*Suite, error)

Open prepares a suite and its template. Under the pgtest command it attaches to the run-owned server; otherwise it starts a private server. ctx controls setup only; its cancellation after Open returns does not terminate the suite. Always Close it.

func (*Suite) Close

func (s *Suite) Close() error

Close rejects new fixtures, closes all owned databases, and synchronously stops its private Postgres before removing temporary files. An attached suite drops only its own databases and template, leaving the run-owned server alive. Repeated/concurrent calls are safe. It must run after application workers have released all borrowed connections.

func (*Suite) Create

func (s *Suite) Create(ctx context.Context) (*Database, error)

Create provisions a clone, opens its pool, and verifies connectivity. ctx bounds setup only; an earlier deadline wins over Options.Timeout.

func (*Suite) Database

func (s *Suite) Database(t testing.TB) *Database

Database creates a fixture owned by t and registers cleanup. Construct your application's normal store from Pool(); no repository API is imposed.

Directories

Path Synopsis
cmd
pgtest command
Command pgtest runs package tests against one temporary PostgreSQL server.
Command pgtest runs package tests against one temporary PostgreSQL server.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址