//go:build integration package integration_test import ( "context" "crypto/rand" "io/fs" "net/url" "strconv" "strings" "testing" "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "lincodex/backend/db" postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" ) // applyMigrations brings the database at databaseURL to the latest embedded // schema with the same runner the backend uses at startup. func applyMigrations(ctx context.Context, t *testing.T, databaseURL string) { t.Helper() migrator := newMigrator(t, databaseURL) if _, err := migrator.Up(ctx); err != nil { t.Fatalf("apply migrations: %v", err) } } func newMigrator(t *testing.T, databaseURL string) *postgresadapter.Migrator { t.Helper() migrations, err := db.Migrations() if err != nil { t.Fatalf("load embedded migrations: %v", err) } migrator, err := postgresadapter.NewMigrator(databaseURL, migrations) if err != nil { t.Fatalf("create migrator: %v", err) } t.Cleanup(func() { if err := migrator.Close(); err != nil { t.Errorf("close migrator: %v", err) } }) return migrator } // embeddedMigrationCount derives the expected count from the embedded files. func embeddedMigrationCount(t *testing.T) int { t.Helper() migrations, err := db.Migrations() if err != nil { t.Fatalf("load embedded migrations: %v", err) } files, err := fs.Glob(migrations, "*.sql") if err != nil { t.Fatalf("list embedded migrations: %v", err) } if len(files) == 0 { t.Fatal("no embedded migrations") } return len(files) } // newPool opens a pool to the bootstrap database and closes it with t. func (env *testEnvironment) newPool(ctx context.Context, t *testing.T) *pgxpool.Pool { t.Helper() return newPoolFor(ctx, t, env.Config.DatabaseURL) } func newPoolFor(ctx context.Context, t *testing.T, databaseURL string) *pgxpool.Pool { t.Helper() pool, err := postgresadapter.NewPool(ctx, databaseURL) if err != nil { t.Fatalf("create PostgreSQL pool: %v", err) } t.Cleanup(pool.Close) return pool } // newPoolWithMaxConns opens a pool sized for a concurrency test, so goroutines // run their transactions at the same time instead of queueing for connections. func (env *testEnvironment) newPoolWithMaxConns(ctx context.Context, t *testing.T, maxConns int32) *pgxpool.Pool { t.Helper() poolConfig, err := pgxpool.ParseConfig(env.Config.DatabaseURL) if err != nil { t.Fatalf("parse bootstrap database URL: %v", err) } poolConfig.MaxConns = maxConns pool, err := pgxpool.NewWithConfig(ctx, poolConfig) if err != nil { t.Fatalf("create sized PostgreSQL pool: %v", err) } t.Cleanup(pool.Close) return pool } // newPoolWithLockTimeout opens a pool whose sessions fail a lock wait after // timeout, so a test can prove that a statement never waits for a lock. func (env *testEnvironment) newPoolWithLockTimeout(ctx context.Context, t *testing.T, timeout time.Duration) *pgxpool.Pool { t.Helper() poolConfig, err := pgxpool.ParseConfig(env.Config.DatabaseURL) if err != nil { t.Fatalf("parse bootstrap database URL: %v", err) } poolConfig.ConnConfig.RuntimeParams["lock_timeout"] = strconv.FormatInt(timeout.Milliseconds(), 10) pool, err := pgxpool.NewWithConfig(ctx, poolConfig) if err != nil { t.Fatalf("create PostgreSQL pool with a lock timeout: %v", err) } t.Cleanup(pool.Close) return pool } // createIsolatedDatabase creates an empty database in the bootstrap container // for tests that must change the whole schema, and drops it with t. func (env *testEnvironment) createIsolatedDatabase(ctx context.Context, t *testing.T) string { t.Helper() if env.Config.DatabaseURL == "" { t.Fatal("PostgreSQL was not selected in bootstrap") } admin := env.newPool(ctx, t) name := "isolated_" + strings.ToLower(rand.Text()) identifier := pgx.Identifier{name}.Sanitize() if _, err := admin.Exec(ctx, "CREATE DATABASE "+identifier); err != nil { t.Fatalf("create isolated database: %v", err) } t.Cleanup(func() { ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout) defer cancel() if _, err := admin.Exec(ctx, "DROP DATABASE IF EXISTS "+identifier+" WITH (FORCE)"); err != nil { t.Errorf("drop isolated database: %v", err) } }) databaseURL, err := url.Parse(env.Config.DatabaseURL) if err != nil { t.Fatalf("parse bootstrap database URL: %v", err) } databaseURL.Path = "/" + name return databaseURL.String() } // truncateTables resets shared tables between sequential subtests. Callers // must not run subtests that use these tables in parallel. func truncateTables(ctx context.Context, t *testing.T, pool *pgxpool.Pool, tables ...pgx.Identifier) { t.Helper() names := make([]string, 0, len(tables)) for _, table := range tables { names = append(names, table.Sanitize()) } if _, err := pool.Exec(ctx, "TRUNCATE "+strings.Join(names, ", ")); err != nil { t.Fatalf("truncate test tables: %v", err) } }