modules/postgres/pgtest
Package pgtest gives each test its own PostgreSQL database on the Docker PostgreSQL server started with `docker compose up -d --wait` (ADR-0028).
func TestInsertUser(t *testing.T) {
pool := pgtest.New(t, pgtest.WithMigrations(migrations.FS))
store := repository.NewUserStore(pool)
// ...
}
The server URL comes from APISTOCK_TEST_DATABASE_URL. When it is unset, tests are skipped with instructions; set APISTOCK_REQUIRE_DB=1 (as CI does) to fail them instead.
Migrations are applied once per distinct set of files into a template database, and each test's database is cloned from it, so tests stay fast and fully isolated. Old templates remain until `docker compose down -v`.
Stability: pre-1.0 (ADR-0015).
Constants#
const EnvURL, …#
const (
EnvURL = "APISTOCK_TEST_DATABASE_URL"
EnvRequire = "APISTOCK_REQUIRE_DB"
)Environment variables read by this package.
Functions#
func New#
func New(t testing.TB, opts ...Option) *pgxpool.PoolNew creates a database for this test and returns a pool connected to it. When the test ends, the pool is closed and the database dropped.
func NewDatabase#
func NewDatabase(t testing.TB, opts ...Option) stringNewDatabase creates a database for this test and returns its connection URL, for tests that start a whole application from configuration. The database is dropped when the test ends; close every connection first. EnvURL must be in URL form (postgres://…).
func URL#
func URL(t testing.TB) stringURL returns the test server's connection URL. It skips the test when EnvURL is unset, or fails it when EnvRequire is "1".
Types#
type Option#
type Option interface {
// contains filtered or unexported methods
}An Option configures New and NewDatabase.
func WithMaxConns#
func WithMaxConns(n int32) OptionWithMaxConns sets the returned pool's size. Default: 4. NewDatabase ignores it.
func WithMigrations#
func WithMigrations(fsys fs.FS) OptionWithMigrations applies the goose migrations in fsys to the new database.