From f3a41585d20b050146ed0a2fec5ab084a9d98294 Mon Sep 17 00:00:00 2001 From: Stephen Adamson Date: Thu, 25 Jun 2026 00:47:18 +0100 Subject: [PATCH] ci: add TEST_DB_HOST env var for service container connectivity --- .gitea/workflows/backend-tests.yaml | 2 +- backend/testutils/testdb/testdb.go | 15 ++++++++++++--- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/.gitea/workflows/backend-tests.yaml b/.gitea/workflows/backend-tests.yaml index 990849f..2ccc258 100644 --- a/.gitea/workflows/backend-tests.yaml +++ b/.gitea/workflows/backend-tests.yaml @@ -58,7 +58,7 @@ jobs: working-directory: backend run: go test -tags "test,dev" -count=1 -v -timeout 120s ./handlers/... ./auth/... ./mw/... ./internal/... ./db/... env: - PGHOST: postgres + TEST_DB_HOST: postgres PGUSER: myuser PGPASSWORD: mypassword PGDATABASE: mydb diff --git a/backend/testutils/testdb/testdb.go b/backend/testutils/testdb/testdb.go index 697207d..9a4b978 100644 --- a/backend/testutils/testdb/testdb.go +++ b/backend/testutils/testdb/testdb.go @@ -29,6 +29,13 @@ const ( adminDatabaseDSN = "postgres://myuser:mypassword@localhost:5432/mydb?sslmode=disable" ) +func dbHost() string { + if h := os.Getenv("TEST_DB_HOST"); h != "" { + return h + } + return "localhost" +} + // 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 @@ -36,7 +43,8 @@ const ( func CreateTestDatabase(dbName string) *pgxpool.Pool { ctx := context.Background() - adminPool, err := pgxpool.New(ctx, adminDatabaseDSN) + adminDSN := fmt.Sprintf("postgres://myuser:mypassword@%s:5432/mydb?sslmode=disable", dbHost()) + adminPool, err := pgxpool.New(ctx, adminDSN) if err != nil { log.Fatalf("testdb: failed to connect to admin database: %v", err) } @@ -68,7 +76,7 @@ func CreateTestDatabase(dbName string) *pgxpool.Pool { } adminPool.Close() - testDSN := fmt.Sprintf("postgres://myuser:mypassword@localhost:5432/%s?sslmode=disable", dbName) + testDSN := fmt.Sprintf("postgres://myuser:mypassword@%s:5432/%s?sslmode=disable", dbHost(), dbName) poolCfg, err := pgxpool.ParseConfig(testDSN) if err != nil { log.Fatalf("testdb: failed to parse config: %v", err) @@ -105,7 +113,8 @@ func DestroyTestDatabase(pool *pgxpool.Pool, dbName string) { } ctx := context.Background() - adminPool, err := pgxpool.New(ctx, adminDatabaseDSN) + adminDSN := fmt.Sprintf("postgres://myuser:mypassword@%s:5432/mydb?sslmode=disable", dbHost()) + adminPool, err := pgxpool.New(ctx, adminDSN) if err != nil { log.Printf("testdb: warning: failed to connect to drop %s: %v", dbName, err) return