testsupport

package
v0.0.0-...-1cad98a Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: AGPL-3.0 Imports: 15 Imported by: 0

Documentation

Overview

Package testsupport holds helpers shared by the repository's test suites. It is imported only from _test.go files; nothing in the production build depends on it.

Index

Constants

View Source
const ClientError = -4

ClientError as a want status accepts any 4xx answer, for mappers whose exact code is not the point of the case.

View Source
const EnvRequirePostgres = "SP_TEST_REQUIRE_POSTGRES"

EnvRequirePostgres is the environment variable that turns "embedded Postgres would not start" from a silently skipped test into a failed one.

It exists because every Postgres-backed suite in this repository guards itself with the same shape:

svc, err := postgres.New(ctx, &postgres.Config{Embedded: true, ...})
if err != nil {
    t.Skipf("embedded postgres unavailable: %v", err)
}

That is the right behavior on a developer laptop with no Postgres binaries downloaded. It is exactly the wrong behavior in CI: a job whose whole purpose is to exercise Postgres reports `ok` having proven nothing the moment the binary download is blocked, a port clashes, or two packages race over the shared ~/.embedded-postgres-go/extracted/pwfile. Spec 2026-09-12-05 exists because a Postgres-only regression shipped past a green test suite; a CI job built on skip-on-failure would reproduce that bug rather than catch it.

So CI sets SP_TEST_REQUIRE_POSTGRES=1 and every one of those skips becomes a hard failure. Local runs leave it unset and keep skipping.

View Source
const MaxFaults = 40

MaxFaults caps how many queries of one scenario are failed in turn.

View Source
const MaxFreshFaults = 400

MaxFreshFaults caps how many queries SweepFresh fails in turn.

Variables

This section is empty.

Functions

func AssertErrorMapping

func AssertErrorMapping(
	t *testing.T, mapper func(http.ResponseWriter, *http.Request, error) error, cases []ErrorCase,
)

AssertErrorMapping runs a handler error mapper over every case and checks the status it writes. An unmapped error must come back as a 500, which is checked with an extra case.

func CallErrorMethods

func CallErrorMethods(t *testing.T, target any, skip ...string) (int, int)

CallErrorMethods calls every exported method of target whose last result is an error, with placeholder arguments (the test context, "x" strings, empty collections, zeroed structs behind non-nil pointers). It is meant for a target whose backing database has been closed: each method must then reach its first query and surface the failure as an error. A panic on the placeholders (a nil interface dereferenced before the first query) is recovered and counted as not failed. It returns how many methods were called and how many returned an error.

func FreePort

func FreePort(testingT TB) uint32

FreePort returns a TCP port nothing listens on, for a test that boots its own embedded PostgreSQL and runs in parallel with others.

The kernel picks it from the ephemeral range (32768+ on Linux, 49152+ on macOS), so it never collides with the hand-numbered 14xxx/15xxx ports other packages still use (see TestFixedTestPortsAreUniqueAcrossPackages).

func PostgresInitFailed

func PostgresInitFailed(t TB, err error)

PostgresInitFailed ends the test because an embedded Postgres instance started but could not be initialized (migrations, seeding): a hard failure when EnvRequirePostgres is set, a skip otherwise. Neither branch returns.

func PostgresUnavailable

func PostgresUnavailable(t TB, err error)

PostgresUnavailable ends the test because an embedded Postgres instance could not be started: a hard failure when EnvRequirePostgres is set, a skip otherwise. Neither branch returns.

func PostgresUnavailableTestMain

func PostgresUnavailableTestMain(out io.Writer, err error) bool

PostgresUnavailableTestMain is the TestMain-shaped counterpart of PostgresUnavailable. A TestMain has no *testing.T, so it cannot reach t.Fatalf; it decides for the whole binary instead.

It writes the explanation to out and reports whether the caller must abort the test binary with a non-zero status. A false return means the caller should keep whatever skip-everything behavior it had — the developer-laptop default.

The one caller today is test/integration/scenario, whose TestMain boots a shared embedded Postgres and, on failure, used to run the suite anyway so that every scenario self-skipped. That is the same hole as a bare t.Skipf, worded differently, and it is inside the backend-postgres job's ./... scope.

func RequirePostgres

func RequirePostgres() bool

RequirePostgres reports whether the caller has asked for an unusable embedded Postgres to fail the run rather than skip it. Anything other than unset, "0", "false", "no" or "off" (case-insensitive) means yes.

func SweepFresh

func SweepFresh(t *testing.T, newRun func() (*FaultHook, func()))

SweepFresh is Sweep for an operation that cannot be replayed on one database (a seeder that skips itself once its data exists). newRun builds a fresh database with a FaultHook installed and returns the hook and the operation; it is called once to count the operation's queries, then once per query with that query failing. The operation must tolerate failing.

Types

type ErrorCase

type ErrorCase struct {
	Err    error
	Status int
}

ErrorCase is one sentinel error and the HTTP status a handler's error mapper must answer it with.

func Case

func Case(err error, status int) ErrorCase

Case builds an ErrorCase.

type FaultHook

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

FaultHook is a bun query hook that fails one chosen query by handing the driver an already canceled context. It lets a test replay one happy-path scenario once per query it issues, failing a different query each time, so every error branch along the path is executed without closing the pool.

func InstallFaults

func InstallFaults(db *bun.DB) *FaultHook

InstallFaults registers a FaultHook on the database. The hook is inert until a scenario arms it.

func (*FaultHook) AfterQuery

func (h *FaultHook) AfterQuery(context.Context, *bun.QueryEvent)

AfterQuery implements bun.QueryHook.

func (*FaultHook) BeforeQuery

func (h *FaultHook) BeforeQuery(ctx context.Context, _ *bun.QueryEvent) context.Context

BeforeQuery implements bun.QueryHook.

func (*FaultHook) Sweep

func (h *FaultHook) Sweep(t *testing.T, scenario func(arm func()))

Sweep runs scenario once to count the queries issued after it calls arm, then once more per counted query with that query failing. The scenario seeds whatever it needs, calls arm right before the operation under test, and must tolerate that operation failing (it must not assert success). A scenario is replayed on the same database, so it must be repeatable.

type TB

type TB interface {
	Helper()
	Skipf(format string, args ...any)
	Fatalf(format string, args ...any)
}

TB is the subset of *testing.T (and *testing.B) these helpers need. It is an interface rather than testing.TB so the helpers' own tests can observe what they did instead of dying inside the assertion under test — a require-helper that has never been seen to fail is the same untrustworthy decoration this package exists to remove.

Jump to

Keyboard shortcuts

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