dbtest

package
v0.217.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 16 Imported by: 0 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.

Documentation

Overview

Package dbtest gives every Postgres-backed test PACKAGE its own database, and decides — in ONE place — whether a missing database is a skip or a failure.

WHY PER-PACKAGE DATABASES

The obvious design is one test database shared by every package. `go test ./...` runs packages in PARALLEL (there is no -p 1), and three things then go wrong, all of them measured on the project muster was extracted from rather than argued:

  • CROSS-PACKAGE CONTAMINATION. One package's fixture DELETEs a table and COUNTs it; another package, running at the same time, writes rows into it. The failure names a row that no test in the failing package wrote, and it is invisible from inside either package.
  • SCHEMA CONTAMINATION. A test that ALTERs the shared schema — dropping a CHECK constraint to ask what an ORDER BY does with an out-of-vocabulary row — leaves every other package running against a weakened schema for the duration.
  • ADVISORY-LOCK CONTENTION. Migrate takes ONE key and advisory locks are DATABASE-scoped, so every package queues on it at fixture setup.

Per-package databases remove all three: nothing another package writes is visible, an ALTER is local, and the migration key is scoped to a database only one package connects to.

HOW

MUSTER_TEST_DATABASE_URL keeps its meaning as the SERVER coordinates, and the database it names becomes the TEMPLATE. On first use inside a test binary dbtest connects to the `postgres` maintenance database, takes a session advisory lock there, and runs

CREATE DATABASE "<pkg db>" TEMPLATE "<the database in the URL>"

which copies an ALREADY-MIGRATED schema instead of replaying every migration. The packages' own Migrate calls then take the no-op path.

🔴 THE CREATES ARE SERIALISED ON PURPOSE. Postgres WAL-logs every block of the template, so firing one CREATE DATABASE per package concurrently is the pathological shape — on a busy node with a slow disk a single one has been observed taking over 90 seconds. One advisory lock in the maintenance database turns the burst into a queue whose total cost is bounded, and every wait is reported with its duration.

⚠ "SERIALISED" IS BEST-EFFORT, NOT GUARANTEED — see ensureWith. A binary that cannot take the lock inside its budget logs that and creates anyway, because an optimisation that can fail the build is worse than no optimisation. So the worst case is the unserialised burst above, never a red run; do not read the paragraph above as a promise that at most one CREATE is ever in flight.

⚠ THOSE REPORTS ARE t.Logf, SO THEY APPEAR ONLY WHEN THE PACKAGE FAILS. `go test` without -v discards a passing package's log. They turn a mystery TIMEOUT into a number, which is what they are for, but a run that degraded and still passed says nothing. Do not read "every wait is reported" as "you will see it".

🔴 NOTHING IS DROPPED. `DROP DATABASE` forces an IMMEDIATE checkpoint across EVERY database on the server. CI's Postgres is a throwaway that dies with the job, so there is nothing to clean up; locally the databases are named deterministically and are REUSED on the next run rather than recreated.

LOCALLY

`make test-db` starts the server this package expects and prints the two exports. By hand, and note the database is NAMED:

docker compose -f docker-compose.test.yml up -d
export MUSTER_TEST_DATABASE_URL='postgres://muster:muster@127.0.0.1:55432/muster_test?sslmode=disable'
DATABASE_URL="$MUSTER_TEST_DATABASE_URL" go run ./cmd/muster-migrate
go test ./...

🔴 NAME A DATABASE, NOT `postgres`. Pointing the variable at `/postgres` makes the TEMPLATE the same database as the maintenance one this package connects to — so binary A's admin session sits on it while binary B runs `CREATE DATABASE ... TEMPLATE postgres`, and B gets `source database "postgres" is being accessed by other users (SQLSTATE 55006)`. A SINGLE package passes (Postgres excludes the asking backend), so it only breaks under `go test ./...`, which is the way anyone actually runs it. adminDatabaseFor below steps aside to `template1` in that case so the mistake is survivable, but the recipe above is the one to copy — and docker-compose.test.yml names the database so the question does not arise.

⚠ If you skip the migrate step nothing BREAKS — the template is copied empty and each package bootstraps its own — but every package then pays the full bootstrap instead of one of them. dbtest says so once, in a t.Log, rather than fixing it silently: it deliberately does not import internal/db, because that would be an import cycle for internal/db's own tests.

Index

Constants

View Source
const EnvVar = "MUSTER_TEST_DATABASE_URL"

EnvVar is the one environment variable this module reads for test-database coordinates. It is named here so the ledger guard in ledger_test.go can assert that NOTHING else in the module reads it.

View Source
const RequireEnvVar = "MUSTER_TEST_REQUIRE_DB"

RequireEnvVar turns an unavailable database from a SKIP into a FAILURE.

🔴 THIS IS THE CONTROL THE DESIGN THIS PACKAGE WAS PORTED FROM DID NOT HAVE, AND ITS ABSENCE IS THE SINGLE MOST LIKELY WAY THIS PROJECT SHIPS BROKEN. With only the DSN gate, a fresh clone runs `go test ./...`, every Postgres-backed test calls t.Skipf, and the suite reports GREEN having executed none of the store logic. A contributor who cannot get Postgres running then opens a pull request against tests they never executed, and the reviewer sees the same green.

A skip is invisible in a verdict. So CI sets this, and in CI an unavailable database is a hard failure with a message that names the variable.

⚠ IT IS DELIBERATELY NOT THE DEFAULT. Requiring Postgres for `go test ./...` on a laptop would make the cheap tests unrunnable, and a gate nobody can run locally is a gate people route around. The default is "skip and say so"; CI is where the requirement is enforced.

Variables

This section is empty.

Functions

func AsOperator

func AsOperator(ctx context.Context) context.Context

AsOperator returns ctx acting as the operator (user 1, admin, NOT scope-all): the principal every Postgres-backed test acts as by default.

🔴 ROW-LEVEL SECURITY (migration 0007) MAKES A PRINCIPAL MANDATORY. Every pool internal/db opens switches to the application role and scopes each query to the context's principal; a test context with NONE sees no rows and cannot insert one. Every row these suites create belongs to user 1, exactly as it does in production today, so acting as the operator keeps each test asserting what it asserted before. A test that wants SOMEBODY ELSE (another user, or authz.System) builds that principal itself.

⚠ IT IS authz.Operator, and this function is therefore a site in internal/authz's Operator ledger. That is safe only because dbtest is a TEST-ONLY package: TestOnlyTestFilesImportDBTest in internal/authz fails if any non-test file in the module imports it.

func Base

func Base(t testing.TB) string

Base returns the value of EnvVar, or ends the test according to the gate.

🔴 EVERY PG-GATED TEST IN THIS MODULE MUST COME THROUGH HERE. It is the ONE place that decides skip-versus-fail; a fixture that reads the variable itself is exempt from the requirement, and its skip is then invisible to a CI run that believes it set the control. ledger_test.go pins the sole-reader property for exactly that reason.

func DSN

func DSN(t testing.TB) string

DSN returns a DSN for a Postgres database private to the CALLING PACKAGE, creating it on first use. When EnvVar is unset it SKIPS — or FAILS, if RequireEnvVar is on; see Base.

The database is created once per test binary and reused by every test in it, so per-test DELETE/TRUNCATE fixtures keep doing what they did — the difference is that no OTHER package can write rows they will see.

func DatabaseName

func DatabaseName(identity string) string

DatabaseName maps a package identity to its database name. Pure, so the guard that proves two packages cannot collide needs no server.

The hash is over the WHOLE identity and the slug is only there to make a pg_database listing readable; truncating the slug can therefore never make two packages share a name.

func Identity

func Identity() string

Identity reports the key DSN would use for the CALLING package. Exported so a `package main` test binary can pin what the runtime actually reports about itself.

func OwnerExec

func OwnerExec(t testing.TB, dsn, sql string, args ...any)

OwnerExec runs sql on a FRESH connection as the database's LOGIN role — not through internal/db's pool, which switches every connection to the application role. It is for fixture RESETS the application role is deliberately not allowed to do: TRUNCATE (which ignores row-level security, so the application role is not granted it) and RESTART IDENTITY (which needs the sequences' owner).

func TemplateName

func TemplateName(base string) (string, error)

TemplateName reports the database EnvVar points at — the one every private database is copied from. Exported for the guards.

Types

This section is empty.

Jump to

Keyboard shortcuts

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