{"modulePath":"github.com/LeanerCloud/cloud-commitments-platform","version":"v0.0.0-20261202160902-a99bcb5bfea3","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package testhelpers\n\n## Functions\n\n```go\nfunc Await[T any](t *testing.T, done \u003c-chan T) T\n```\nAwait returns the value a background writer sends on done, failing fast instead of hanging until the go test timeout when the writer is stuck.\n\n```go\nfunc AwaitArrivalsOrLockWaits(ctx context.Context, db LockDB, parties int, arrived func() int, queryLike string) error\n```\nAwaitArrivalsOrLockWaits is a race-test barrier: it returns once each of parties has either arrived (arrived reports how many have) or is waiting on a lock in a statement matching queryLike. Under a serializing lock the parties that have not arrived are provably parked on it, so waiting longer cannot change the outcome; without the lock every party arrives. Either way the barrier opens on observed state, never on a guessed timeout. It returns an error rather than failing a test so the goroutine under test can call it.\n\n```go\nfunc AwaitBlockedBy[T any](ctx context.Context, t *testing.T, db LockDB, holderPID int, done \u003c-chan T) (T, bool)\n```\nAwaitBlockedBy proves a contender is queued behind holderPID's transaction: it returns once some backend waits on a lock that holderPID holds, so the contender cannot finish before the holder ends. If done delivers first, the contender answered without contending; AwaitBlockedBy returns that value and true. A fixed quiet window (select on done against time.After) cannot tell \"blocked\" from \"not there yet\", so on a slow runner it passes a contender that never contends. This observation cannot.\n\nQuery db from a connection other than the holder's: pg\\_locks is read live, but the holder's session is busy holding the lock.\n\n```go\nfunc BackendPID(ctx context.Context, t *testing.T, tx pgx.Tx) int\n```\nBackendPID returns the server process ID of tx's session, the holderPID that AwaitBlockedBy takes.\n\n```go\nfunc LockWaiters(ctx context.Context, db LockDB, queryLike string) (int, error)\n```\nLockWaiters counts backends of this database that wait on a lock in a statement matching queryLike (a SQL LIKE pattern).\n\n```go\nfunc NewIsolatedSchema(ctx context.Context, t *testing.T, c *PostgresContainer) *pgxpool.Pool\n```\nNewIsolatedSchema creates a schema of its own on the database c points at and returns a pool whose search\\_path is that schema, so tests can run in parallel on one database without seeing each other's rows. The schema is named from t.Name() plus a unique suffix and dropped, with the pool closed, in t.Cleanup.\n\nApply migrations with the same call RequireMigratedDatabase uses, passing the returned pool: migrations.RunMigrations(ctx, pool, path, \"\", \"\"). The migrator creates its tables and schema\\_migrations in the first schema on search\\_path, which is the isolated one.\n\n\"public\" stays second on search\\_path because the migrations install the uuid-ossp and pg\\_trgm extensions. Left to the migrations they would land in the first test's schema and vanish with it while other schemas still use them, so they are created once in public here.\n\n```go\nfunc TerminateSharedPostgres() error\n```\nTerminateSharedPostgres stops the shared container if one was started. Call it from TestMain after m.Run. Ryuk reaps the container if the process dies first, so this is tidiness rather than the only line of defense.\n\n```go\nfunc WaitForLockWait(ctx context.Context, t *testing.T, db LockDB, queryLike string)\n```\nWaitForLockWait blocks until some backend is waiting on a lock in a statement matching queryLike (a SQL LIKE pattern; \"\" matches any), which proves the writer under test is queued behind the footprint.\n\n## Types\n\n```go\ntype Footprint struct {\n\tpgx.Tx\n\tExecutions []string\n}\n```\nFootprint stands in for the editor command's lock footprint on one plan so the race tests of legacy writers run before the command exists: the plan row FOR UPDATE, then its executions ordered FOR UPDATE, then its accounts FOR SHARE. It does NOT take the command's first two lock levels, the identity advisory lock and the sorted provider advisory locks (LockPlanProvidersTx). The embedded Tx is the command's transaction: Exec applies the command's writes (SetManaged, inserted roots) and Commit/Rollback end it. Executions lists the rows the footprint locked, i.e. what the command captured: a writer that committed before the footprint must appear here.\n\nSwap contract for the ExecutePlanScheduleCommand race tests: replace HoldCommandFootprint with the real command paused after its capture, wrapped as a \\*Footprint (Tx = the command's transaction, Executions = its captured set). Then (1) the notifier claim queues first on the provider advisory lock, so its WaitForLockWait pattern changes from \"%FOR UPDATE%\" to the advisory wait (wait\\_event 'advisory'; match the pg\\_advisory\\_xact\\_lock statement); (2) the direct Exec/QueryRow calls of the retry, prune and account-delete tests become the command's own writes and reads; every other assertion stays.\n\n```go\nfunc HoldCommandFootprint(ctx context.Context, t *testing.T, db LockDB, planID string) *Footprint\n```\nHoldCommandFootprint opens the footprint on planID. The transaction rolls back at test end unless the test ended it first.\n\n```go\nfunc (f *Footprint) SetManaged(ctx context.Context, t *testing.T, planID string)\n```\nSetManaged writes the editor marker inside the footprint's transaction.\n\n```go\ntype LockDB interface {\n\tBegin(ctx context.Context) (pgx.Tx, error)\n\tQueryRow(ctx context.Context, sql string, args ...any) pgx.Row\n}\n```\nLockDB is the slice of a pool the lock helpers need. The config store's dbConn and a \\*pgxpool.Pool both satisfy it.\n\n```go\ntype PostgresContainer struct {\n\tContainer testcontainers.Container\n\tConfig    *database.Config\n\tDB        *database.Connection\n}\n```\nPostgresContainer wraps a testcontainers PostgreSQL instance.\n\n```go\nfunc RequireEmptyDatabase(ctx context.Context, t *testing.T) *PostgresContainer\n```\nRequireEmptyDatabase gives t an empty database of its own on the same shared container RequireMigratedDatabase uses: no tables, no schema\\_migrations, nothing but what CREATE DATABASE ... TEMPLATE template0 puts there. It is for tests whose subject is the migration chain itself (up, down, dirty, heal), which need to start from nothing and must not see a template another test migrated.\n\nCleanup, skips and the missing Container are exactly as for RequireMigratedDatabase. Being per database, it is no substitute for a dedicated server where a test touches server-wide state (roles, ALTER SYSTEM, connection limits, other sessions' backends); see RequirePostgresContainer for those.\n\n```go\nfunc RequireMigratedDatabase(ctx context.Context, t *testing.T, migrationsPath string) *PostgresContainer\n```\nRequireMigratedDatabase gives t a database of its own on a PostgreSQL container shared by the whole test binary, with every migration under migrationsPath already applied. The database is dropped when t ends, and the connection pool is closed before that, so callers have nothing to clean up.\n\nSkips follow RequirePostgresContainer: only an unusable Docker provider skips. A container that will not start or a migration that will not apply fails the test (issue #1597).\n\nThe returned value has no Container: it is shared, and terminating it is the job of TerminateSharedPostgres, called from the package's TestMain.\n\n```go\nfunc RequirePostgresContainer(ctx context.Context, t *testing.T) *PostgresContainer\n```\nRequirePostgresContainer starts a PostgreSQL test container for t, skipping the test only when this environment has no usable Docker provider and failing loudly for every other error.\n\nDrawing that line is the whole point (issue #1597). \"No usable Docker daemon\" is an environment fact and the one legitimate reason to skip, so it is probed explicitly before anything is started. Past that probe the daemon answered a health check, which makes a container that still refuses to come up -- a missing image, a database that never accepts connections -- a real failure. Reporting it as a skip would turn a broken run green, which is indistinguishable from a run that had nothing to say.\n\nThe probe owns the whole environment side of that line, so a daemon that is present but unhealthy skips too, rather than failing.\n\nCallers remain responsible for Cleanup, matching SetupPostgresContainer.\n\nPrefer RequireMigratedDatabase or RequireEmptyDatabase, which share one server per test binary. Use this only for a test that needs a server to itself (see SetupPostgresContainer for when), with a comment saying why.\n\n```go\nfunc SetupPostgresContainer(ctx context.Context, t *testing.T) (*PostgresContainer, error)\n```\nSetupPostgresContainer creates and starts a PostgreSQL test container.\n\nPrefer RequireMigratedDatabase or RequireEmptyDatabase in tests. Each call here starts a server of its own, about 2s before the test has even migrated it, where those hand out a fresh database on one server per test binary in milliseconds. A dedicated server is still right when a test changes or depends on server-wide state: roles, ALTER SYSTEM or other server settings, terminating other sessions' backends, connection limits, or stopping the server. Say why next to the call. Tests should go through RequirePostgresContainer, which only skips when Docker is unusable; this function remains for the shared server itself and for that wrapper.\n\nNot marked Deprecated: the shared server is built on it and the dedicated cases above are legitimate, so a staticcheck SA1019 warning on every call would be noise rather than guidance.\n\n```go\nfunc (c *PostgresContainer) Cleanup(ctx context.Context) error\n```\nCleanup terminates the test container and closes database connection.\n\n```go\nfunc (c *PostgresContainer) ResetDatabase(ctx context.Context) error\n```\nResetDatabase drops and recreates all tables (useful for clean state).\n\n```go\nfunc (c *PostgresContainer) TruncateTables(ctx context.Context, tables ...string) error\n```\nTruncateTables removes all data from tables (useful between tests).\n\n","path":"github.com/LeanerCloud/cloud-commitments-platform/internal/database/postgres/testhelpers","name":"testhelpers","synopsis":"","isRedistributable":true}
