refactor(backend): migrate test infrastructure to isolated databases
Add CreateTestDatabase function for parallel isolated test databases per package. - Add CreateTestDatabase() for isolated test DBs (parallel-safe) - Move all TestMain functions to per-package testmain_test.go files - Remove old TestMain from handlers_test.go, jwt_test.go, main_test.go - Add JWT init guard in main.go to skip when -test.* flags detected - Update testdb.go with admin DSN and proper cleanup - Rename test database to crussell_test_db for consistency - Replace testdb.NewPool + testdb.Migrate pattern with CreateTestDatabase Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
This commit is contained in:
@@ -14,35 +14,13 @@ package auth
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"crussell/db"
|
"crussell/db"
|
||||||
"crussell/testutils/testdb"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestMain(m *testing.M) {
|
|
||||||
InitJWT("test-secret-key-for-jwt-test")
|
|
||||||
|
|
||||||
pool, err := testdb.NewPool("")
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "WARN: No test DB available — JTI revocation tests will fail: %v\n", err)
|
|
||||||
} else {
|
|
||||||
// Run migration to ensure the revoked_jtis and refresh_tokens tables exist
|
|
||||||
testdb.Migrate(&testing.T{}, pool)
|
|
||||||
db.DB = pool
|
|
||||||
}
|
|
||||||
|
|
||||||
code := m.Run()
|
|
||||||
if pool != nil {
|
|
||||||
pool.Close()
|
|
||||||
}
|
|
||||||
os.Exit(code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// requiresDB skips the test if the database is not available (e.g. running
|
// requiresDB skips the test if the database is not available (e.g. running
|
||||||
// tests standalone without test DB setup). DB-backed JTI revocation tests
|
// tests standalone without test DB setup). DB-backed JTI revocation tests
|
||||||
// need a connection to the revoked_jtis table.
|
// need a connection to the revoked_jtis table.
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
//go:build test
|
||||||
|
// +build test
|
||||||
|
|
||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"crussell/db"
|
||||||
|
"crussell/testutils/testdb"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMain(m *testing.M) {
|
||||||
|
InitJWT("test-secret-key-for-jwt-test")
|
||||||
|
|
||||||
|
pool := testdb.CreateTestDatabase("crussell_test_auth")
|
||||||
|
db.DB = pool
|
||||||
|
|
||||||
|
code := m.Run()
|
||||||
|
testdb.DestroyTestDatabase(pool, "crussell_test_auth")
|
||||||
|
os.Exit(code)
|
||||||
|
}
|
||||||
@@ -15,7 +15,7 @@ func resetEnv() {
|
|||||||
os.Setenv("POSTGRES_USER", "myuser")
|
os.Setenv("POSTGRES_USER", "myuser")
|
||||||
os.Setenv("POSTGRES_PASSWORD", "mypassword")
|
os.Setenv("POSTGRES_PASSWORD", "mypassword")
|
||||||
os.Setenv("POSTGRES_HOST", "localhost")
|
os.Setenv("POSTGRES_HOST", "localhost")
|
||||||
os.Setenv("POSTGRES_DB", "crussell_test")
|
os.Setenv("POSTGRES_DB", "crussell_test_db")
|
||||||
}
|
}
|
||||||
|
|
||||||
func closePool() {
|
func closePool() {
|
||||||
@@ -25,6 +25,8 @@ func closePool() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var testDBName = "crussell_test_db"
|
||||||
|
|
||||||
// =============================================================================
|
// =============================================================================
|
||||||
// Happy path — connect + ping
|
// Happy path — connect + ping
|
||||||
// =============================================================================
|
// =============================================================================
|
||||||
@@ -177,9 +179,4 @@ func TestGetEnv_ReturnsEmptyWhenUnset(t *testing.T) {
|
|||||||
// Clean-up — restore env after all tests
|
// Clean-up — restore env after all tests
|
||||||
// =============================================================================
|
// =============================================================================
|
||||||
|
|
||||||
func TestMain(m *testing.M) {
|
|
||||||
resetEnv()
|
|
||||||
code := m.Run()
|
|
||||||
closePool()
|
|
||||||
os.Exit(code)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
//go:build test
|
||||||
|
// +build test
|
||||||
|
|
||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"crussell/testutils/testdb"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMain(m *testing.M) {
|
||||||
|
pool := testdb.CreateTestDatabase(testDBName)
|
||||||
|
pool.Close() // db.Connect() creates its own pool
|
||||||
|
resetEnv()
|
||||||
|
code := m.Run()
|
||||||
|
closePool()
|
||||||
|
testdb.DestroyTestDatabase(nil, testDBName)
|
||||||
|
os.Exit(code)
|
||||||
|
}
|
||||||
@@ -13,14 +13,10 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestMain(m *testing.M) {
|
func TestMain(m *testing.M) {
|
||||||
pool, err := testdb.NewPool("")
|
pool := testdb.CreateTestDatabase("crussell_test_handlers_admin")
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
testdb.Migrate(&testing.T{}, pool)
|
|
||||||
db.DB = pool
|
db.DB = pool
|
||||||
jwt.Init()
|
jwt.Init()
|
||||||
code := m.Run()
|
code := m.Run()
|
||||||
pool.Close()
|
testdb.DestroyTestDatabase(pool, "crussell_test_handlers_admin")
|
||||||
os.Exit(code)
|
os.Exit(code)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
//go:build test
|
||||||
|
// +build test
|
||||||
|
|
||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"crussell/db"
|
||||||
|
"crussell/internal/dav"
|
||||||
|
"crussell/testutils/jwt"
|
||||||
|
"crussell/testutils/testdb"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMain(m *testing.M) {
|
||||||
|
pool := testdb.CreateTestDatabase("crussell_test_handlers_auth")
|
||||||
|
db.DB = pool
|
||||||
|
jwt.Init()
|
||||||
|
dav.Service = &dav.BaseService{}
|
||||||
|
code := m.Run()
|
||||||
|
testdb.DestroyTestDatabase(pool, "crussell_test_handlers_auth")
|
||||||
|
os.Exit(code)
|
||||||
|
}
|
||||||
@@ -15,16 +15,12 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestMain(m *testing.M) {
|
func TestMain(m *testing.M) {
|
||||||
pool, err := testdb.NewPool("")
|
pool := testdb.CreateTestDatabase("crussell_test_handlers_bookings")
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
testdb.Migrate(&testing.T{}, pool)
|
|
||||||
db.DB = pool
|
db.DB = pool
|
||||||
jwt.Init()
|
jwt.Init()
|
||||||
square.Client = square.NewDevClient()
|
square.Client = square.NewDevClient()
|
||||||
payments.SquareClient = square.Client
|
payments.SquareClient = square.Client
|
||||||
code := m.Run()
|
code := m.Run()
|
||||||
pool.Close()
|
testdb.DestroyTestDatabase(pool, "crussell_test_handlers_bookings")
|
||||||
os.Exit(code)
|
os.Exit(code)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,29 +17,14 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"os"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"crussell/db"
|
"crussell/db"
|
||||||
"crussell/mw"
|
"crussell/mw"
|
||||||
"crussell/testutils/fixtures"
|
"crussell/testutils/fixtures"
|
||||||
"crussell/testutils/jwt"
|
"crussell/testutils/jwt"
|
||||||
"crussell/testutils/testdb"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestMain(m *testing.M) {
|
|
||||||
pool, err := testdb.NewPool("")
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
testdb.Migrate(&testing.T{}, pool)
|
|
||||||
db.DB = pool
|
|
||||||
jwt.Init()
|
|
||||||
code := m.Run()
|
|
||||||
pool.Close()
|
|
||||||
os.Exit(code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestHealthCheck verifies the health check endpoint returns HTTP 200 OK.
|
// TestHealthCheck verifies the health check endpoint returns HTTP 200 OK.
|
||||||
// This test ensures the basic HTTP server is responding and the health
|
// This test ensures the basic HTTP server is responding and the health
|
||||||
// check handler is properly wired up to return a status response.
|
// check handler is properly wired up to return a status response.
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
//go:build test
|
||||||
|
// +build test
|
||||||
|
|
||||||
|
package notifications
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"crussell/db"
|
||||||
|
"crussell/testutils/jwt"
|
||||||
|
"crussell/testutils/testdb"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMain(m *testing.M) {
|
||||||
|
pool := testdb.CreateTestDatabase("crussell_test_handlers_notifications")
|
||||||
|
db.DB = pool
|
||||||
|
jwt.Init()
|
||||||
|
code := m.Run()
|
||||||
|
testdb.DestroyTestDatabase(pool, "crussell_test_handlers_notifications")
|
||||||
|
os.Exit(code)
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
//go:build test && dev
|
||||||
|
// +build test,dev
|
||||||
|
|
||||||
|
package payments
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"crussell/db"
|
||||||
|
"crussell/internal/square"
|
||||||
|
"crussell/testutils/jwt"
|
||||||
|
"crussell/testutils/testdb"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMain(m *testing.M) {
|
||||||
|
pool := testdb.CreateTestDatabase("crussell_test_handlers_payments")
|
||||||
|
db.DB = pool
|
||||||
|
jwt.Init()
|
||||||
|
square.Client = square.NewDevClient()
|
||||||
|
SquareClient = square.Client
|
||||||
|
code := m.Run()
|
||||||
|
testdb.DestroyTestDatabase(pool, "crussell_test_handlers_payments")
|
||||||
|
os.Exit(code)
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
//go:build test
|
||||||
|
// +build test
|
||||||
|
|
||||||
|
package portfolio
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"crussell/db"
|
||||||
|
"crussell/testutils/jwt"
|
||||||
|
"crussell/testutils/testdb"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMain(m *testing.M) {
|
||||||
|
pool := testdb.CreateTestDatabase("crussell_test_handlers_portfolio")
|
||||||
|
db.DB = pool
|
||||||
|
jwt.Init()
|
||||||
|
code := m.Run()
|
||||||
|
testdb.DestroyTestDatabase(pool, "crussell_test_handlers_portfolio")
|
||||||
|
os.Exit(code)
|
||||||
|
}
|
||||||
@@ -13,14 +13,10 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestMain(m *testing.M) {
|
func TestMain(m *testing.M) {
|
||||||
pool, err := testdb.NewPool("")
|
pool := testdb.CreateTestDatabase("crussell_test_handlers_scheduling")
|
||||||
if err != nil {
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
testdb.Migrate(&testing.T{}, pool)
|
|
||||||
db.DB = pool
|
db.DB = pool
|
||||||
jwt.Init()
|
jwt.Init()
|
||||||
code := m.Run()
|
code := m.Run()
|
||||||
pool.Close()
|
testdb.DestroyTestDatabase(pool, "crussell_test_handlers_scheduling")
|
||||||
os.Exit(code)
|
os.Exit(code)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
//go:build test
|
||||||
|
// +build test
|
||||||
|
|
||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"crussell/db"
|
||||||
|
"crussell/testutils/jwt"
|
||||||
|
"crussell/testutils/testdb"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMain(m *testing.M) {
|
||||||
|
pool := testdb.CreateTestDatabase("crussell_test_handlers_services")
|
||||||
|
db.DB = pool
|
||||||
|
jwt.Init()
|
||||||
|
code := m.Run()
|
||||||
|
testdb.DestroyTestDatabase(pool, "crussell_test_handlers_services")
|
||||||
|
os.Exit(code)
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
//go:build test
|
||||||
|
// +build test
|
||||||
|
|
||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"crussell/db"
|
||||||
|
"crussell/testutils/jwt"
|
||||||
|
"crussell/testutils/testdb"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMain(m *testing.M) {
|
||||||
|
pool := testdb.CreateTestDatabase("crussell_test_handlers")
|
||||||
|
db.DB = pool
|
||||||
|
jwt.Init()
|
||||||
|
code := m.Run()
|
||||||
|
testdb.DestroyTestDatabase(pool, "crussell_test_handlers")
|
||||||
|
os.Exit(code)
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
//go:build test
|
||||||
|
// +build test
|
||||||
|
|
||||||
|
package today
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"crussell/db"
|
||||||
|
"crussell/testutils/jwt"
|
||||||
|
"crussell/testutils/testdb"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMain(m *testing.M) {
|
||||||
|
pool := testdb.CreateTestDatabase("crussell_test_handlers_today")
|
||||||
|
db.DB = pool
|
||||||
|
jwt.Init()
|
||||||
|
code := m.Run()
|
||||||
|
testdb.DestroyTestDatabase(pool, "crussell_test_handlers_today")
|
||||||
|
os.Exit(code)
|
||||||
|
}
|
||||||
@@ -13,14 +13,10 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestMain(m *testing.M) {
|
func TestMain(m *testing.M) {
|
||||||
pool, err := testdb.NewPool("")
|
pool := testdb.CreateTestDatabase("crussell_test_handlers_user")
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
testdb.Migrate(&testing.T{}, pool)
|
|
||||||
db.DB = pool
|
db.DB = pool
|
||||||
jwt.Init()
|
jwt.Init()
|
||||||
code := m.Run()
|
code := m.Run()
|
||||||
pool.Close()
|
testdb.DestroyTestDatabase(pool, "crussell_test_handlers_user")
|
||||||
os.Exit(code)
|
os.Exit(code)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -35,6 +36,16 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
// The testing framework passes -test.* to the binary; skip JWT init
|
||||||
|
// because test packages handle it via testutils/jwt. This is more
|
||||||
|
// precise than checking GO_TESTING env var, which can leak from the
|
||||||
|
// test runner into the environment during seeding.
|
||||||
|
for _, arg := range os.Args {
|
||||||
|
if strings.HasPrefix(arg, "-test.") {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
jwtSecret := os.Getenv("JWT_SECRET_KEY")
|
jwtSecret := os.Getenv("JWT_SECRET_KEY")
|
||||||
if jwtSecret == "" {
|
if jwtSecret == "" {
|
||||||
log.Fatal("FATAL: JWT_SECRET_KEY environment variable not set. Application cannot start.")
|
log.Fatal("FATAL: JWT_SECRET_KEY environment variable not set. Application cannot start.")
|
||||||
|
|||||||
@@ -7,25 +7,12 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"os"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"crussell/db"
|
"crussell/db"
|
||||||
"crussell/testutils/testdb"
|
"crussell/testutils/testdb"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestMain(m *testing.M) {
|
|
||||||
pool, err := testdb.NewPool("")
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
testdb.Migrate(&testing.T{}, pool)
|
|
||||||
db.DB = pool
|
|
||||||
code := m.Run()
|
|
||||||
pool.Close()
|
|
||||||
os.Exit(code)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHealthCheck_OK(t *testing.T) {
|
func TestHealthCheck_OK(t *testing.T) {
|
||||||
testdb.TruncateTables(t, db.DB)
|
testdb.TruncateTables(t, db.DB)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
//go:build test
|
||||||
|
// +build test
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"crussell/db"
|
||||||
|
"crussell/testutils/testdb"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMain(m *testing.M) {
|
||||||
|
pool := testdb.CreateTestDatabase("crussell_test")
|
||||||
|
db.DB = pool
|
||||||
|
code := m.Run()
|
||||||
|
testdb.DestroyTestDatabase(pool, "crussell_test")
|
||||||
|
os.Exit(code)
|
||||||
|
}
|
||||||
+157
-163
@@ -6,17 +6,131 @@ package testdb
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
)
|
)
|
||||||
|
|
||||||
const defaultTestDSN = "postgres://myuser:mypassword@localhost:5432/crussell_test?sslmode=disable&require_auth=scram-sha-256"
|
const (
|
||||||
|
defaultTestDSN = "postgres://myuser:mypassword@localhost:5432/crussell_test?sslmode=disable"
|
||||||
|
adminDatabaseDSN = "postgres://myuser:mypassword@localhost:5432/mydb?sslmode=disable"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CreateTestDatabase creates a fresh isolated test database, runs the schema migration,
|
||||||
|
// and returns a pool connected to it. If a database with the same name exists, it's
|
||||||
|
// dropped first. This enables parallel test execution across packages since each
|
||||||
|
// package gets its own database running migrations in parallel.
|
||||||
|
func CreateTestDatabase(dbName string) *pgxpool.Pool {
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
adminPool, err := pgxpool.New(ctx, adminDatabaseDSN)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("testdb: failed to connect to admin database: %v", err)
|
||||||
|
}
|
||||||
|
defer adminPool.Close()
|
||||||
|
|
||||||
|
safeName := pgx.Identifier{dbName}.Sanitize()
|
||||||
|
|
||||||
|
// Drop existing database with retries (terminate connections first)
|
||||||
|
for attempt := 0; attempt < 3; attempt++ {
|
||||||
|
_, _ = adminPool.Exec(ctx, fmt.Sprintf(`
|
||||||
|
SELECT pg_terminate_backend(pid)
|
||||||
|
FROM pg_stat_activity
|
||||||
|
WHERE datname = '%s' AND pid != pg_backend_pid()
|
||||||
|
`, dbName))
|
||||||
|
|
||||||
|
_, err = adminPool.Exec(ctx, fmt.Sprintf("DROP DATABASE IF EXISTS %s", safeName))
|
||||||
|
if err == nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
log.Printf("testdb: retry %d dropping %s: %v", attempt+1, dbName, err)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("testdb: failed to drop database %s after retries: %v", dbName, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = adminPool.Exec(ctx, fmt.Sprintf("CREATE DATABASE %s", safeName))
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("testdb: failed to create database %s: %v", dbName, err)
|
||||||
|
}
|
||||||
|
adminPool.Close()
|
||||||
|
|
||||||
|
testDSN := fmt.Sprintf("postgres://myuser:mypassword@localhost:5432/%s?sslmode=disable", dbName)
|
||||||
|
pool, err := pgxpool.New(ctx, testDSN)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("testdb: failed to connect to %s: %v", dbName, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := pool.Ping(ctx); err != nil {
|
||||||
|
log.Fatalf("testdb: failed to ping %s: %v", dbName, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := migratePool(pool); err != nil {
|
||||||
|
log.Fatalf("testdb: migration failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return pool
|
||||||
|
}
|
||||||
|
|
||||||
|
// DestroyTestDatabase closes the pool (if non-nil) and drops the test database.
|
||||||
|
// Retries aggressively with exponential backoff, pg_terminate_backend between
|
||||||
|
// attempts, and a final DROP DATABASE WITH (FORCE) on PostgreSQL 13+.
|
||||||
|
func DestroyTestDatabase(pool *pgxpool.Pool, dbName string) {
|
||||||
|
if dbName == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if pool != nil {
|
||||||
|
pool.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
adminPool, err := pgxpool.New(ctx, adminDatabaseDSN)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("testdb: warning: failed to connect to drop %s: %v", dbName, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer adminPool.Close()
|
||||||
|
|
||||||
|
safeName := pgx.Identifier{dbName}.Sanitize()
|
||||||
|
|
||||||
|
// Aggressive retry with pg_terminate_backend between attempts and final FORCE option.
|
||||||
|
for attempt := 0; attempt < 10; attempt++ {
|
||||||
|
// Kill all connections to the target database.
|
||||||
|
_, _ = adminPool.Exec(ctx, fmt.Sprintf(`
|
||||||
|
SELECT pg_terminate_backend(pid)
|
||||||
|
FROM pg_stat_activity
|
||||||
|
WHERE datname = '%s' AND pid != pg_backend_pid()
|
||||||
|
`, dbName))
|
||||||
|
|
||||||
|
// Try DROP DATABASE WITH (FORCE) first (PG13+) — this kills remaining connections atomically.
|
||||||
|
_, err = adminPool.Exec(ctx, fmt.Sprintf("DROP DATABASE IF EXISTS %s WITH (FORCE)", safeName))
|
||||||
|
if err == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback to plain DROP (may work if pg_terminate_backend was sufficient).
|
||||||
|
_, err = adminPool.Exec(ctx, fmt.Sprintf("DROP DATABASE IF EXISTS %s", safeName))
|
||||||
|
if err == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exponential backoff: 100ms, 200ms, 400ms, 800ms, 1.6s, 3.2s, 6.4s, 12.8s, 25.6s, 51.2s
|
||||||
|
wait := time.Duration(100*(1<<attempt)) * time.Millisecond
|
||||||
|
log.Printf("testdb: retry %d dropping %s: %v (retrying in %v)", attempt+1, dbName, err, wait)
|
||||||
|
time.Sleep(wait)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("testdb: warning: failed to drop database %s after 10 attempts: %v", dbName, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pool creates a new test database pool using TEST_DB_DSN env var or default DSN.
|
||||||
func Pool(t *testing.T) *pgxpool.Pool {
|
func Pool(t *testing.T) *pgxpool.Pool {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
|
|
||||||
@@ -56,116 +170,23 @@ func NewPool(dsn string) (*pgxpool.Pool, error) {
|
|||||||
return pool, nil
|
return pool, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func Migrate(t *testing.T, pool *pgxpool.Pool) {
|
// migratePool executes the full schema migration on the given pool.
|
||||||
t.Helper()
|
// This internal version returns errors directly for use by CreateTestDatabase.
|
||||||
|
func migratePool(pool *pgxpool.Pool) error {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
// Acquire a dedicated connection so advisory lock, migration, and unlock all use the same session
|
|
||||||
conn, err := pool.Acquire(ctx)
|
conn, err := pool.Acquire(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Failed to acquire connection for migration: %v", err)
|
return fmt.Errorf("failed to acquire connection for migration: %w", err)
|
||||||
}
|
}
|
||||||
defer conn.Release()
|
defer conn.Release()
|
||||||
|
return migrateSchema(ctx, conn)
|
||||||
|
}
|
||||||
|
|
||||||
_, err = conn.Exec(ctx, "SELECT pg_advisory_lock(1337)")
|
// migrateSchema executes the schema migration on an existing connection.
|
||||||
if err != nil {
|
// Returns an error if any step fails.
|
||||||
t.Fatalf("Failed to acquire migration advisory lock: %v", err)
|
// NOTE: This is always called on a fresh database (created via CreateTestDatabase),
|
||||||
}
|
// so no defensive cleanup of types/tables/sequences is needed.
|
||||||
defer conn.Exec(ctx, "SELECT pg_advisory_unlock(1337)")
|
func migrateSchema(ctx context.Context, conn *pgxpool.Conn) error {
|
||||||
|
|
||||||
// Check if database already has tables or types
|
|
||||||
var typeCount int
|
|
||||||
err = conn.QueryRow(ctx, "SELECT COUNT(*) FROM pg_type WHERE typnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')").Scan(&typeCount)
|
|
||||||
if err == nil && typeCount > 0 {
|
|
||||||
// Drop TYPES FIRST (they have CASCADE dependencies on tables)
|
|
||||||
typeDrops := []string{
|
|
||||||
"DROP TYPE IF EXISTS account_role CASCADE",
|
|
||||||
"DROP TYPE IF EXISTS account_type CASCADE",
|
|
||||||
"DROP TYPE IF EXISTS payment_type CASCADE",
|
|
||||||
"DROP TYPE IF EXISTS payment_method CASCADE",
|
|
||||||
"DROP TYPE IF EXISTS payment_status CASCADE",
|
|
||||||
"DROP TYPE IF EXISTS booking_status CASCADE",
|
|
||||||
"DROP TYPE IF EXISTS verification_purpose CASCADE",
|
|
||||||
"DROP TYPE IF EXISTS admin_notification_reason CASCADE",
|
|
||||||
"DROP TYPE IF EXISTS campaign_type CASCADE",
|
|
||||||
"DROP TYPE IF EXISTS milestone_type CASCADE",
|
|
||||||
"DROP TYPE IF EXISTS milestone_unit CASCADE",
|
|
||||||
"DROP TYPE IF EXISTS discount_campaign_scope CASCADE",
|
|
||||||
"DROP TYPE IF EXISTS discount_campaign_status CASCADE",
|
|
||||||
"DROP TYPE IF EXISTS till_item_type CASCADE",
|
|
||||||
}
|
|
||||||
for _, stmt := range typeDrops {
|
|
||||||
if _, err := conn.Exec(ctx, stmt); err != nil {
|
|
||||||
t.Logf("Warning dropping type: %v (expected if using IF EXISTS)", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Drop all tables, sequences, and views in correct order
|
|
||||||
dropOrder := []string{
|
|
||||||
"till_sales",
|
|
||||||
"admin_audit_log",
|
|
||||||
"gift_card_transactions",
|
|
||||||
"gift_card_expired_balances",
|
|
||||||
"booking_discounts",
|
|
||||||
"loyalty_redemptions",
|
|
||||||
"discount_campaigns",
|
|
||||||
"forgiven_no_shows",
|
|
||||||
"admin_notifications",
|
|
||||||
"user_notification_preferences",
|
|
||||||
"user_referrals",
|
|
||||||
"booking_custom_services",
|
|
||||||
"booking_services",
|
|
||||||
"refunds",
|
|
||||||
"payments",
|
|
||||||
"user_saved_cards",
|
|
||||||
"square_deposits",
|
|
||||||
"affiliate_payouts",
|
|
||||||
"financial_aggregates",
|
|
||||||
"gift_cards",
|
|
||||||
"user_giftcard_balances",
|
|
||||||
"bookings",
|
|
||||||
"user_patch_tests",
|
|
||||||
"patch_tests",
|
|
||||||
"booking_edit_requests",
|
|
||||||
"services",
|
|
||||||
"custom_services",
|
|
||||||
"verification_codes",
|
|
||||||
"user_social_logins",
|
|
||||||
"users",
|
|
||||||
"images",
|
|
||||||
"tags",
|
|
||||||
"time_blockers",
|
|
||||||
"working_hours",
|
|
||||||
"exceptional_group_applications",
|
|
||||||
"exceptional_working_hours",
|
|
||||||
"exceptional_working_hours_groups",
|
|
||||||
"business_settings",
|
|
||||||
"login_audit",
|
|
||||||
"refresh_tokens",
|
|
||||||
"revoked_jtis",
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, table := range dropOrder {
|
|
||||||
stmt := fmt.Sprintf("DROP TABLE IF EXISTS %s CASCADE", table)
|
|
||||||
if _, err := conn.Exec(ctx, stmt); err != nil {
|
|
||||||
t.Logf("Warning dropping table %s: %v (expected if using IF EXISTS)", table, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Drop sequences last
|
|
||||||
seqDrops := []string{
|
|
||||||
"DROP SEQUENCE IF EXISTS invoice_number_seq",
|
|
||||||
"DROP SEQUENCE IF EXISTS tags_id_seq",
|
|
||||||
"DROP SEQUENCE IF EXISTS exceptional_working_hours_id_seq",
|
|
||||||
"DROP SEQUENCE IF EXISTS exceptional_working_hours_groups_id_seq",
|
|
||||||
}
|
|
||||||
for _, stmt := range seqDrops {
|
|
||||||
if _, err := conn.Exec(ctx, stmt); err != nil {
|
|
||||||
t.Logf("Warning dropping sequence: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
paths := []string{
|
paths := []string{
|
||||||
"../../../init-scripts/init-script.sql",
|
"../../../init-scripts/init-script.sql",
|
||||||
"../../init-scripts/init-script.sql",
|
"../../init-scripts/init-script.sql",
|
||||||
@@ -182,7 +203,7 @@ func Migrate(t *testing.T, pool *pgxpool.Pool) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if schemaSQL == "" {
|
if schemaSQL == "" {
|
||||||
t.Fatal("Could not find init-script.sql in any expected location")
|
return fmt.Errorf("could not find init-script.sql in any expected location")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Split and execute the schema SQL statement-by-statement for robust execution and diagnostic visibility
|
// Split and execute the schema SQL statement-by-statement for robust execution and diagnostic visibility
|
||||||
@@ -197,11 +218,19 @@ func Migrate(t *testing.T, pool *pgxpool.Pool) {
|
|||||||
firstLine = firstLine[:80] + "..."
|
firstLine = firstLine[:80] + "..."
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = conn.Exec(ctx, stmt)
|
_, err := conn.Exec(ctx, stmt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Failed to execute migration statement [%d]: %s\nError: %v", i+1, firstLine, err)
|
return fmt.Errorf("failed to execute migration statement [%d]: %s\nError: %w", i+1, firstLine, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func Migrate(t *testing.T, pool *pgxpool.Pool) {
|
||||||
|
t.Helper()
|
||||||
|
if err := migratePool(pool); err != nil {
|
||||||
|
t.Fatal(err.Error())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func splitSQLStatements(sql string) []string {
|
func splitSQLStatements(sql string) []string {
|
||||||
@@ -263,68 +292,33 @@ func TruncateTables(t *testing.T, pool *pgxpool.Pool) {
|
|||||||
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
// Acquire a dedicated connection so advisory lock, truncations, and unlock all use the same session
|
|
||||||
conn, err := pool.Acquire(ctx)
|
conn, err := pool.Acquire(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Failed to acquire connection for truncation: %v", err)
|
t.Fatalf("Failed to acquire connection for truncation: %v", err)
|
||||||
}
|
}
|
||||||
defer conn.Release()
|
defer conn.Release()
|
||||||
|
|
||||||
_, err = conn.Exec(ctx, "SELECT pg_advisory_lock(1338)")
|
// Single TRUNCATE with all tables — one round-trip instead of ~44.
|
||||||
|
// CASCADE handles FK dependencies so order doesn't matter.
|
||||||
|
// Advisory lock removed: each package has its own database now.
|
||||||
|
_, err = conn.Exec(ctx, `
|
||||||
|
TRUNCATE TABLE
|
||||||
|
till_sales, admin_audit_log, gift_card_transactions,
|
||||||
|
gift_card_expired_balances, booking_discounts, loyalty_redemptions,
|
||||||
|
discount_campaigns, forgiven_no_shows, name_history, referral_discounts,
|
||||||
|
user_social_logins, verification_codes, booking_custom_services,
|
||||||
|
booking_services, refunds, payments, user_saved_cards, square_deposits,
|
||||||
|
affiliate_payouts, financial_aggregates, gift_cards, user_giftcard_balances,
|
||||||
|
bookings, booking_edit_requests, user_patch_tests, patch_tests, services,
|
||||||
|
custom_services, admin_notifications, user_referrals,
|
||||||
|
user_notification_preferences, time_blockers, working_hours,
|
||||||
|
exceptional_group_applications, exceptional_working_hours,
|
||||||
|
exceptional_working_hours_groups, business_settings, users, images, tags,
|
||||||
|
login_audit, refresh_tokens, revoked_jtis
|
||||||
|
CASCADE
|
||||||
|
`)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Failed to acquire truncate advisory lock: %v", err)
|
t.Logf("Warning: truncation failed: %v", err)
|
||||||
}
|
|
||||||
defer conn.Exec(ctx, "SELECT pg_advisory_unlock(1338)")
|
|
||||||
|
|
||||||
tables := []string{
|
|
||||||
"till_sales",
|
|
||||||
"admin_audit_log",
|
|
||||||
"gift_card_transactions",
|
|
||||||
"gift_card_expired_balances",
|
|
||||||
"booking_discounts",
|
|
||||||
"loyalty_redemptions",
|
|
||||||
"discount_campaigns",
|
|
||||||
"forgiven_no_shows",
|
|
||||||
"user_social_logins",
|
|
||||||
"verification_codes",
|
|
||||||
"booking_custom_services",
|
|
||||||
"booking_services",
|
|
||||||
"refunds",
|
|
||||||
"payments",
|
|
||||||
"user_saved_cards",
|
|
||||||
"square_deposits",
|
|
||||||
"affiliate_payouts",
|
|
||||||
"financial_aggregates",
|
|
||||||
"gift_cards",
|
|
||||||
"user_giftcard_balances",
|
|
||||||
"bookings",
|
|
||||||
"booking_edit_requests",
|
|
||||||
"user_patch_tests",
|
|
||||||
"patch_tests",
|
|
||||||
"services",
|
|
||||||
"custom_services",
|
|
||||||
"admin_notifications",
|
|
||||||
"user_referrals",
|
|
||||||
"user_notification_preferences",
|
|
||||||
"time_blockers",
|
|
||||||
"working_hours",
|
|
||||||
"exceptional_group_applications",
|
|
||||||
"exceptional_working_hours",
|
|
||||||
"exceptional_working_hours_groups",
|
|
||||||
"business_settings",
|
|
||||||
"users",
|
|
||||||
"images",
|
|
||||||
"tags",
|
|
||||||
"login_audit",
|
|
||||||
"refresh_tokens",
|
|
||||||
"revoked_jtis",
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, table := range tables {
|
|
||||||
_, err := conn.Exec(ctx, fmt.Sprintf("TRUNCATE TABLE %s CASCADE", table))
|
|
||||||
if err != nil {
|
|
||||||
t.Logf("Warning: could not truncate %s: %v", table, err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user