testutil

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: Apache-2.0 Imports: 33 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 testutil is the integration-test harness: a real PostgreSQL in a container plus per-test throwaway schemas. Integration tests are the workhorse of this repo — core logic is validated against a real database, not mocks.

Index

Constants

View Source
const DefaultPGVersion = "16"

DefaultPGVersion is the major used when PG_VERSION is unset. CI overrides it across the full supported matrix (14 → 18).

View Source
const DifferenceLimit = 20

DifferenceLimit bounds how many differing keys one direction reports; a diverged table is diagnosed from its lowest keys, not enumerated.

View Source
const RefusalClassesDoc = "docs/refusal-classes.md"

RefusalClassesDoc is the repository path of the routing contract that classifies every typed refusal cause the engine can raise. Each package that declares a cause type keeps its own cause table in this document honest with the readers below.

View Source
const UnlimitedDisk int64 = math.MaxInt64

UnlimitedDisk is the free-disk figure a test hands to the copy-and-swap environment check when the volume is not measured: more free space than any fixture table needs, so the proof under test is the shape, the privileges, or the decoding facts rather than disk headroom. It is a test stand-in only; a run against a real volume measures the figure.

Variables

This section is empty.

Functions

func AssertConverged added in v0.3.2

func AssertConverged(t *testing.T, pool *pgxpool.Pool, source, shadow RelationRef, opts ConvergeOptions)

AssertConverged requires that source and shadow contain equal rows.

func ExecInSchema added in v0.4.0

func ExecInSchema(t *testing.T, pool *pgxpool.Pool, schema, sql string)

ExecInSchema runs sql with search_path set to schema, so unqualified fixture SQL lands there.

func InstallEventTrigger added in v0.4.0

func InstallEventTrigger(t *testing.T, pool *pgxpool.Pool, event TriggerEvent, schema, name, body string)

InstallEventTrigger creates the plpgsql event-trigger function schema.name() with the given body and an event trigger on event that calls it, and registers their drop for the end of the test. Event triggers are database-global, so every test that installs one goes through this: the drop keeps the function alive until every transaction that may still hold the trigger in its event-trigger cache has ended (see dropEventTrigger), which an inline DROP EVENT TRIGGER followed by the function's drop — or the schema's cascade — does not.

The function runs for every other test's DDL too, as whatever role that DDL runs as, and such a role need not hold USAGE on schema. So the body must not name schema in anything its IF condition evaluates: a '<schema>.t'::regclass cast, to_regclass('<schema>.t') inside a subquery, or a schema-qualified relation in a subquery's FROM is resolved while the condition is planned, even when an earlier condition is false, and raises "permission denied for schema" in the other test. Find the test's objects by name in the catalogs (pg_namespace.nspname, pg_class.relname) instead. Names in the THEN branch are safe: plpgsql analyzes a statement only when it runs. A DDL trigger's body is held to this at install, by a probe DDL run as a role without access to schema.

func LoseConnectionAtCommit added in v0.4.0

func LoseConnectionAtCommit(t *testing.T, pool *pgxpool.Pool, schema, marker string)

LoseConnectionAtCommit makes the next ALTER TABLE whose text contains marker lose its backend while the COMMIT is being processed: the DDL queues a row in a table guarded by a deferred constraint trigger, and that trigger runs inside COMMIT and terminates its own backend. The client's COMMIT then ends without a success reply — the same observable state as a COMMIT the server applied whose reply never arrived. The probe table, its trigger, and the event trigger live in schema and go with it. The event trigger fires for every package's DDL on a shared database, so it also requires the command to touch an object in schema: another schema's ALTER TABLE with the same marker text keeps its connection.

func NewCatalogShadowingPool added in v0.3.2

func NewCatalogShadowingPool(t *testing.T, serverURL, schema string) *pgxpool.Pool

NewCatalogShadowingPool returns a pool whose every session has schema ahead of pg_catalog on search_path, so impostor relations, views, functions, and operators created in schema answer unqualified catalog names. It is a raw pgx pool on purpose: pools from pkg/dbconn remove a shadowed pg_catalog entry on connect, which would make the impostors unreachable, and the tests that use this pool prove that the queries themselves stay pg_catalog-qualified for a pool the library caller built. It carries none of pkg/dbconn's session defaults.

func NewDatabase

func NewDatabase(t *testing.T, serverURL string) string

NewDatabase creates a unique throwaway database on the server at serverURL, sets it up for cleanup, and returns a URL that connects to it. Throwaway schemas do not isolate pg_stat_activity, so a test that must observe an exact session set (e.g. none) on a shared server gets a database of its own. serverURL must be in URL form (postgres://...), which StartPostgres always returns.

func NewDatabaseFromTemplate added in v0.4.0

func NewDatabaseFromTemplate(t *testing.T, serverURL, templateURL string) string

NewDatabaseFromTemplate is NewDatabase for a database cloned from the one templateURL connects to, for tests whose subject is what a clone shares with its template: the relations keep their OIDs. The server must hold no other session on the template while it is copied, so the caller closes every pool on it first.

func NewDatabaseWithEncoding added in v0.4.0

func NewDatabaseWithEncoding(t *testing.T, serverURL, encoding string) string

NewDatabaseWithEncoding is NewDatabase for a database created with the given server encoding (e.g. "SQL_ASCII") under the C locale, for tests whose subject is how the engine treats the bytes a database stores. template0 is the template, as a server encoding other than the cluster's requires.

func NewPublicTable

func NewPublicTable(t *testing.T, pool *pgxpool.Pool, columns string) string

NewPublicTable creates a uniquely named throwaway table in the public schema — for tests that exercise unqualified-statement resolution, where a dedicated schema would defeat the point — and returns its name. The unique name keeps a shared PG_DSN database safe; cleanup drops the table.

func NewRole

func NewRole(t *testing.T, pool *pgxpool.Pool, options string) string

NewRole creates a throwaway cluster-level role with the given options and registers its drop. Roles are cluster-scoped, so names are unique per process the same way throwaway schemas are.

func NewSchema

func NewSchema(t *testing.T, pool *pgxpool.Pool) string

NewSchema creates a unique throwaway schema on pool, sets it up for cleanup, and returns its name. Tests qualify their objects with it so parallel tests on one container never collide.

func PGVersion

func PGVersion() string

PGVersion returns the PostgreSQL major version under test.

func RefusalCauseRow added in v0.4.0

func RefusalCauseRow(cause string) string

RefusalCauseRow is the row keyed on cause in a cause table: the cause, what the refusal says, its class, and why.

func RefusalCauseTable added in v0.4.0

func RefusalCauseTable(t *testing.T, heading string) string

RefusalCauseTable returns the text of the section of RefusalClassesDoc under heading, up to the next heading of any level: one package's cause table, read from the repository checkout the test runs in. Two tables in the document list some of the same cause names under their own meanings, so a guard looks rows up in its own section alone.

func RefusalClassCell added in v0.4.0

func RefusalClassCell(t *testing.T, table, cause string) string

RefusalClassCell returns the `class` cell of the row keyed on cause in a cause table whose columns are the cause, what it says, its class, and why; the test fails when the table has no such row.

func RunDuringDDL added in v0.3.2

func RunDuringDDL(t *testing.T, pool *pgxpool.Pool, event TriggerEvent, tag, schema, table, sql string)

RunDuringDDL installs an event trigger that executes sql from inside the next DDL command with the given tag whose text names schema.table, at the given event. It is the fault-injection seam for the windows a single-statement DDL leaves open — between a probe and the server's choice of names, or between a commit and the read that verifies it — made deterministic. The trigger is server-wide (event triggers are), so the schema qualifier scopes it to the test's own objects; the trigger and its function are dropped when the test ends.

func SkipOnSharedServer added in v0.4.1

func SkipOnSharedServer(t *testing.T, reason string)

SkipOnSharedServer skips a test that needs a PostgreSQL server of its own — one that creates a cluster-level role or a tablespace, or checks which image the harness chose — when PG_DSN points the suite at a shared long-lived server. reason names what the test does to the cluster.

The long-lived-database targets (make test-db and the CI matrix) never run such a test, so make test-own-server runs exactly these tests the container way; the own-server completeness test holds that target's list to the set of callers of this helper.

func StartPostgres

func StartPostgres(t *testing.T) string

StartPostgres returns a PostgreSQL connection URL for the test.

By default it starts a disposable container (terminated when the test ends). When PG_DSN is set, that external server is used instead and no container is started — the compose/ workflow and CI variants that run a long-lived server use this. Set SKIP_INTEGRATION=1 to skip tests that need a database entirely.

func StartPostgresBehindPgBouncer added in v0.3.3

func StartPostgresBehindPgBouncer(t *testing.T, mode PoolMode) (pooledURL string)

StartPostgresBehindPgBouncer starts a PostgreSQL server with a PgBouncer in front of it in the given pool mode and returns the pooled connection URL — the one a hosted platform would hand an operator.

It always starts its own containers: the pooling mode is the fixture, so an external PG_DSN cannot substitute for it.

func StartPostgresBehindPgBouncerWith added in v0.4.0

func StartPostgresBehindPgBouncerWith(t *testing.T, mode PoolMode, settings map[string]string) (pooledURL string)

StartPostgresBehindPgBouncerWith is StartPostgresBehindPgBouncer with PgBouncer settings overridden, keyed by the image's environment names (DEFAULT_POOL_SIZE, QUERY_WAIT_TIMEOUT, …), for a test about how the pooler behaves when it is short of backends.

func StartPostgresWithSettings added in v0.4.0

func StartPostgresWithSettings(t *testing.T, settings ...string) string

StartPostgresWithSettings returns a connection URL for a dedicated PostgreSQL container started with the given postgresql.conf settings (each "name=value"), for tests that control a restart-only setting such as wal_level or max_replication_slots. Unlike StartPostgres it never uses PG_DSN — a shared server cannot change those settings — and so costs a container start of its own. Set SKIP_INTEGRATION=1 to skip.

Types

type CatalogColumn added in v0.4.0

type CatalogColumn struct {
	Name    string
	Type    string
	NotNull bool
	// Default is the default or generation expression, empty when none.
	Default string
	// Identity is pg_attribute.attidentity: empty, 'a' always, 'd' by
	// default.
	Identity string
	// Generated is pg_attribute.attgenerated: empty, 's' stored, 'v'
	// virtual.
	Generated string
	// Collation is the column's collation when it differs from its type's
	// default, empty otherwise.
	Collation string
	// Storage is pg_attribute.attstorage.
	Storage string
	// Compression is pg_attribute.attcompression, empty for the default.
	Compression string
	// StatisticsTarget is the per-column statistics target, -1 for the
	// default.
	StatisticsTarget int
	// Options are the column's attribute options (pg_attribute.attoptions),
	// e.g. "n_distinct=100", in the order the server stores them.
	Options []string
	// Sequence is the sequence the column owns — a serial's or an identity
	// column's — and nil when it owns none.
	Sequence *CatalogSequence
}

CatalogColumn is one column's catalog record.

type CatalogConstraint added in v0.4.0

type CatalogConstraint struct {
	Name string
	// Type is pg_constraint.contype.
	Type string
	// Def is pg_get_constraintdef, which spells NOT VALID, NO INHERIT, and
	// deferrability.
	Def       string
	Validated bool
}

CatalogConstraint is one table constraint's catalog record.

type CatalogIndex added in v0.4.0

type CatalogIndex struct {
	Name string
	// Def is pg_get_indexdef with the ON clause's schema stripped: the
	// server always qualifies it, whatever the search_path.
	Def             string
	Valid           bool
	ReplicaIdentity bool
	Clustered       bool
}

CatalogIndex is one index's catalog record.

type CatalogSequence added in v0.4.0

type CatalogSequence struct {
	Type      string
	Start     int64
	Increment int64
	Min       int64
	Max       int64
	Cache     int64
	Cycle     bool
}

CatalogSequence is the parameters of a column-owned sequence. Its name is left out: a serial's sequence is named after the table, and the parameters are what the column's values depend on.

type ConvergeOptions added in v0.3.2

type ConvergeOptions struct{ IgnoreColumns []string }

ConvergeOptions controls convergence comparison.

type DirectionDiff added in v0.3.2

type DirectionDiff struct {
	Direction string
	Keys      []int64
}

DirectionDiff reports differing primary keys in one EXCEPT direction.

type LoadGenerator added in v0.3.2

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

LoadGenerator owns running workload workers.

func StartLoad added in v0.3.2

func StartLoad(t *testing.T, pool *pgxpool.Pool, table WorkloadTable, spec LoadSpec) *LoadGenerator

StartLoad starts bounded, cancellable workload workers. An invalid spec fails the test immediately rather than starting a generator that writes nothing.

func (*LoadGenerator) Snapshot added in v0.4.0

func (g *LoadGenerator) Snapshot() Summary

Snapshot returns the summary accumulated so far and leaves the workers running, so a test can mark how much the load had committed when it observed some point in the run under test.

func (*LoadGenerator) Stop added in v0.3.2

func (g *LoadGenerator) Stop() (Summary, error)

Stop promptly cancels workers and waits a bounded time for completion. It always returns the summary accumulated so far; when workers do not stop in time the error joins the deadline with any worker error already recorded, so a wedged worker's cause is not lost behind the timeout.

type LoadSpec added in v0.3.2

type LoadSpec struct {
	Seed                 int64
	Workers              int
	RatePerSecond        int
	Mix                  Mix
	HotRowFraction       float64
	ToastRewriteFraction float64
}

LoadSpec configures a deterministic concurrent workload.

RatePerSecond is the mutation rate of each worker, so the aggregate rate is Workers × RatePerSecond. HotRowFraction is the share of updates aimed at the ten lowest ids (contention on a hot set); ToastRewriteFraction is the share of updates that rewrite the out-of-line blob column — the rest leave it unchanged, so their change records omit it.

type Mix added in v0.3.2

type Mix struct {
	Insert     int
	Update     int
	Delete     int
	UniqueMove int
	KeyMove    int
}

Mix gives relative weights to workload mutations. KeyMove is an update of a row's primary key to a fresh identity value, the change that arrives as an image under a new key with a delete under the old one.

type PoolMode added in v0.3.3

type PoolMode string

PoolMode is a connection pooler's pooling granularity, which is what decides whether a client connection keeps one server session.

const (
	// TransactionPooling returns the backend to the pooler's own pool at
	// the end of every transaction, so a client connection has no stable
	// server session. It is the default on hosted PostgreSQL platforms.
	TransactionPooling PoolMode = "transaction"
	// SessionPooling gives a client connection its own backend for the
	// connection's lifetime, which is all a session-scoped lock needs.
	SessionPooling PoolMode = "session"
	// StatementPooling returns the backend to the pooler's own pool after
	// every statement and refuses a transaction that spans more than one,
	// so a client connection keeps neither a session nor a transaction.
	StatementPooling PoolMode = "statement"
)

type RelationRef added in v0.3.2

type RelationRef struct {
	Schema string
	Table  string
}

RelationRef identifies a relation.

type Report added in v0.3.2

type Report struct {
	SourceCount int64
	ShadowCount int64
	Differences []DirectionDiff
}

Report contains row counts and bounded symmetric differences, all read from one REPEATABLE READ snapshot so the numbers describe one instant.

func Diff added in v0.3.2

func Diff(ctx context.Context, pool *pgxpool.Pool, source, shadow RelationRef, opts ConvergeOptions) (Report, error)

Diff compares source against the shadow's visible column contract.

Every catalog read, both counts, and both difference queries run in one read-only REPEATABLE READ transaction, so a Report is a single snapshot: a count difference and a row difference can never disagree about the instant they describe.

func (Report) Converged added in v0.3.2

func (r Report) Converged() bool

Converged reports whether the relations hold equal rows. The counts are diagnostic only: the primary key is always projected and both counts come from the same snapshot as the differences, so any count skew necessarily surfaces as a differing key.

type Summary added in v0.3.2

type Summary struct {
	Inserts     int
	Updates     int
	Deletes     int
	UniqueMoves int
	KeyMoves    int
	Races       int
	InsertedIDs []int64
	DeletedIDs  []int64
}

Summary reports committed operations, inserted and deleted IDs, and the number of mutations that aborted on an expected race (a unique-key collision, a serialization failure, a deadlock, or a vanished row) and were dropped rather than retried. A run whose Races dwarf its committed counts wrote far less than its spec suggests.

func (Summary) Committed added in v0.4.0

func (s Summary) Committed() int

Committed returns how many mutations of every kind committed.

type TLSPostgres

type TLSPostgres struct {
	// URL is the connection URL without an sslmode parameter, so the
	// caller's TLS configuration decides the handshake.
	URL string
	// CACertPath is the PEM CA certificate that signed the server
	// certificate — the trust anchor for verify-full connections.
	CACertPath string
	// UntrustedCACertPath is a valid CA certificate that did NOT sign the
	// server certificate, for negative verification tests.
	UntrustedCACertPath string
}

TLSPostgres describes a TLS-capable PostgreSQL started by StartPostgresTLS or StartPostgresTLSOrPlaintext.

func StartPostgresTLS

func StartPostgresTLS(t *testing.T) TLSPostgres

StartPostgresTLS starts a disposable PostgreSQL container that accepts only TLS connections, using a CA generated for this test. Unlike StartPostgres it never uses PG_DSN — the whole point is controlling the server's TLS posture. Set SKIP_INTEGRATION=1 to skip.

func StartPostgresTLSOrPlaintext added in v0.4.0

func StartPostgresTLSOrPlaintext(t *testing.T) TLSPostgres

StartPostgresTLSOrPlaintext is StartPostgresTLS for a server that also accepts plaintext TCP connections, so a client that falls back from a failed TLS handshake would succeed rather than be refused.

type TableCatalog added in v0.4.0

type TableCatalog struct {
	// Persistence is pg_class.relpersistence: 'p' permanent, 'u' unlogged.
	Persistence string
	// AccessMethod is the table access method (pg_class.relam), "heap"
	// for an ordinary table and empty when it has none.
	AccessMethod string
	// Tablespace is the table's tablespace, empty for the database
	// default.
	Tablespace string
	// ReplicaIdentity is pg_class.relreplident: 'd' default, 'n' nothing,
	// 'f' full, 'i' index.
	ReplicaIdentity string
	// Options are the storage parameters (pg_class.reloptions), e.g.
	// "fillfactor=70", in the order the server stores them.
	Options []string
	// ToastOptions are the storage parameters of the table's TOAST table,
	// set with the "toast." prefix, in the order the server stores them.
	ToastOptions []string
	// PartitionKey is pg_get_partkeydef, empty for a plain table.
	PartitionKey string
	// RowSecurity and ForceRowSecurity are the ENABLE / FORCE ROW LEVEL
	// SECURITY settings.
	RowSecurity      bool
	ForceRowSecurity bool
	// Columns are the live columns in attribute order.
	Columns []CatalogColumn
	// Constraints are the table constraints, name-sorted.
	Constraints []CatalogConstraint
	// Indexes are every index on the table, constraint-backed ones
	// included, name-sorted.
	Indexes []CatalogIndex
}

TableCatalog is a table's definition as the server's catalogs record it, read with direct catalog queries and never through pkg/schemadiff. It is the reference side of the round-trip oracle: two tables whose catalogs match are the same table, whatever the diff model records about them. A property the model does not carry still differs here, so a plan that converges the model but not the table fails the comparison instead of re-planning to silence.

Definitions are decompiled under a search_path of the table's own schema, so a table in one schema compares equal to the same table in another. Policies, triggers, grants, comments, and ownership are not part of it.

func ReadTableCatalog added in v0.4.0

func ReadTableCatalog(ctx context.Context, pool *pgxpool.Pool, schema, table string) (TableCatalog, error)

ReadTableCatalog reads the catalog record of schema.table in one read-only snapshot.

type TriggerEvent added in v0.4.0

type TriggerEvent string

TriggerEvent is the event an event trigger fires on: a point in a DDL command, or a session's login.

const (
	// DDLCommandStart fires before the command runs: the objects it will
	// create do not exist yet, so a name can still be taken from under it.
	DDLCommandStart TriggerEvent = "ddl_command_start"
	// DDLCommandEnd fires after the command has run but inside its
	// transaction: the objects it created exist and can be altered before
	// the caller sees the commit.
	DDLCommandEnd TriggerEvent = "ddl_command_end"
	// Login fires once a session has authenticated and its startup
	// parameters have been applied, so what it does to the session
	// outranks them. Login triggers exist from PostgreSQL 17.
	Login TriggerEvent = "login"
)

type WorkloadShape added in v0.4.0

type WorkloadShape struct {
	// IDType is the declared type of the identity primary key; empty is
	// bigint. A test that retypes the key itself starts from integer.
	IDType string
}

WorkloadShape is the part of the workload table's shape a test may vary. The zero value is the default shape.

type WorkloadTable added in v0.3.2

type WorkloadTable struct {
	Schema string
	Table  string
	// contains filtered or unexported fields
}

WorkloadTable is the table copy convergence tests run on: one shape, with the few variations WorkloadShape allows.

func NewWorkloadTable added in v0.3.2

func NewWorkloadTable(t *testing.T, pool *pgxpool.Pool) WorkloadTable

NewWorkloadTable creates an empty workload relation in a unique schema.

The shape exercises every convergence race the copy path must survive: an identity primary key, a unique secondary key whose values tests swap between rows, a numeric column for widening changes, and a text column that is always stored out of line so an update leaving it unchanged produces a change record with that column omitted. Compression is turned off for that column: pglz would otherwise keep a repetitive value inline and the omission would never occur.

func NewWorkloadTableOf added in v0.4.0

func NewWorkloadTableOf(t *testing.T, pool *pgxpool.Pool, shape WorkloadShape) WorkloadTable

NewWorkloadTableOf is NewWorkloadTable with shape's variations applied. Every generator and oracle works over the varied table too: the key is still a single identity column, so the load's key moves still draw from its sequence.

func (WorkloadTable) Qualified added in v0.3.2

func (w WorkloadTable) Qualified() string

Qualified returns the safely quoted relation name.

func (WorkloadTable) SeedRows added in v0.3.2

func (w WorkloadTable) SeedRows(ctx context.Context, n int) error

SeedRows inserts n deterministic rows.

func (WorkloadTable) ToastBytes added in v0.3.2

func (w WorkloadTable) ToastBytes(ctx context.Context) (int64, error)

ToastBytes returns the on-disk size of the table's TOAST relation, so a test can prove that the blob column really is stored out of line.

Directories

Path Synopsis
Package modeltest compares schemadiff models in tests.
Package modeltest compares schemadiff models in tests.

Jump to

Keyboard shortcuts

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