// Package testdb gives a test its own freshly migrated PostgreSQL database, // so database tests never touch real data and can run in parallel. // // TEST_DATABASE_URL names a server and a role that may CREATE DATABASE, e.g. // the compose Postgres (`make up`). Without it, tests that need a database // are skipped: // // TEST_DATABASE_URL=postgres://tracker:tracker@localhost:5432/tracker?sslmode=disable go test ./... package testdb import ( "context" "crypto/rand" "encoding/hex" "os" "testing" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "ccp/internal/migrations" ) // New creates an empty, migrated database for t and drops it when t ends. func New(t testing.TB) *pgxpool.Pool { t.Helper() url := os.Getenv("TEST_DATABASE_URL") if url == "" { t.Skip("TEST_DATABASE_URL not set") } ctx := context.Background() admin, err := pgx.Connect(ctx, url) if err != nil { t.Fatalf("testdb: connect: %v", err) } b := make([]byte, 6) rand.Read(b) name := "tracker_test_" + hex.EncodeToString(b) if _, err := admin.Exec(ctx, "CREATE DATABASE "+name); err != nil { admin.Close(ctx) t.Fatalf("testdb: %v", err) } t.Cleanup(func() { if _, err := admin.Exec(ctx, "DROP DATABASE "+name+" WITH (FORCE)"); err != nil { t.Errorf("testdb: drop %s: %v", name, err) } admin.Close(ctx) }) cfg, err := pgxpool.ParseConfig(url) if err != nil { t.Fatalf("testdb: %v", err) } cfg.ConnConfig.Database = name pool, err := pgxpool.NewWithConfig(ctx, cfg) if err != nil { t.Fatalf("testdb: %v", err) } t.Cleanup(pool.Close) // registered last, so it runs before the drop if err := migrations.Up(ctx, pool); err != nil { t.Fatalf("testdb: %v", err) } return pool }