Documentation
¶
Overview ¶
Package dbtest gives each test BINARY (i.e. each Go package's test process) its own isolated, freshly-migrated PostgreSQL database.
Why: before this, every DB-touching package read the single OPENWATCH_TEST_DSN, ran migrations against that one shared database, and TRUNCATEd shared tables between tests. That works only when packages run serially — under package parallelism (`go test -p N`) two packages would truncate and write each other's rows mid-test. The whole suite therefore ran `-p 1`, serializing every DB package and dominating CI wall-clock.
With dbtest, package A's tests run against `owt_<hashA>` and package B's against `owt_<hashB>`, so they can't see each other and `-p N` is safe.
Speed: migrating ~35 migrations in every one of ~35 parallel package processes overwhelms Postgres. Instead dbtest migrates ONCE into a shared TEMPLATE database (keyed by a hash of the migration files, so it is rebuilt only when migrations change) and each package CLONEs it with `CREATE DATABASE ... TEMPLATE` — a fast file copy, no re-migration. A PostgreSQL advisory lock makes the one-time template build race-free across the parallel processes.
Usage — replace a package's hand-rolled `freshPool` body:
func freshPool(t *testing.T) *pgxpool.Pool {
pool := dbtest.Pool(t) // isolated, migrated, skips if no DSN
// ... TRUNCATE the tables this package owns, as before ...
return pool
}
Pool must be called DIRECTLY from the package's own test code (so the runtime caller resolves to that package's directory).
Index ¶
Constants ¶
const EnvDSN = "OPENWATCH_TEST_DSN"
EnvDSN is the base DSN env var. It is interpreted as a connection to the PostgreSQL SERVER (the database in its path is only used to reach the server + as the per-package name prefix); dbtest creates and migrates its own per-package databases off it.
Variables ¶
This section is empty.
Functions ¶
func DSN ¶ added in v0.8.0
DSN returns the connection string for this package's isolated database, provisioned exactly as Pool provisions it.
Use it only when a test must open the connection itself, which in practice means a test that closes a pool and reopens it to stand in for a process restart. Everywhere else, call Pool: a test that holds a DSN can reach the server, and the point of this package is that it cannot reach another package's data.
Like Pool, it must be called DIRECTLY from the package's own test code.
func Pool ¶
Pool returns a pgxpool connected to this package's isolated database (cloned from a freshly-migrated template). It skips the test when OPENWATCH_TEST_DSN is unset. Each call returns a NEW pool (closed via t.Cleanup) against the same per-package database, matching the historical "new pool per freshPool call" behavior. The database is provisioned once per process.
Types ¶
This section is empty.