apistockdocs
v0.4 GitHub apistock.dev
Technical/Test helpers

modules/postgres/pgtest

import "apistock.dev/modules/postgres/pgtest"Source on GitHub

Package pgtest gives each test its own PostgreSQL database on the Docker PostgreSQL server started with `docker compose up -d --wait` (ADR-0028).

func TestInsertUser(t *testing.T) {
	pool := pgtest.New(t, pgtest.WithMigrations(migrations.FS))
	store := repository.NewUserStore(pool)
	// ...
}

The server URL comes from APISTOCK_TEST_DATABASE_URL. When it is unset, tests are skipped with instructions; set APISTOCK_REQUIRE_DB=1 (as CI does) to fail them instead.

Migrations are applied once per distinct set of files into a template database, and each test's database is cloned from it, so tests stay fast and fully isolated. Old templates remain until `docker compose down -v`.

Stability: pre-1.0 (ADR-0015).

Constants#

const EnvURL, …#

go
const (
	EnvURL     = "APISTOCK_TEST_DATABASE_URL"
	EnvRequire = "APISTOCK_REQUIRE_DB"
)

Environment variables read by this package.

Functions#

func New#

go
func New(t testing.TB, opts ...Option) *pgxpool.Pool

New creates a database for this test and returns a pool connected to it. When the test ends, the pool is closed and the database dropped.

func NewDatabase#

go
func NewDatabase(t testing.TB, opts ...Option) string

NewDatabase creates a database for this test and returns its connection URL, for tests that start a whole application from configuration. The database is dropped when the test ends; close every connection first. EnvURL must be in URL form (postgres://…).

func URL#

go
func URL(t testing.TB) string

URL returns the test server's connection URL. It skips the test when EnvURL is unset, or fails it when EnvRequire is "1".

Types#

type Option#

go
type Option interface {
	// contains filtered or unexported methods
}

An Option configures New and NewDatabase.

func WithMaxConns#

go
func WithMaxConns(n int32) Option

WithMaxConns sets the returned pool's size. Default: 4. NewDatabase ignores it.

func WithMigrations#

go
func WithMigrations(fsys fs.FS) Option

WithMigrations applies the goose migrations in fsys to the new database.

v0.4
esc
↑↓ move↵ openesc close