Skip to content

Commit ee02df0

Browse files
committed
fix: use random hex for test database names to prevent collisions
- Replace nanosecond+pid with crypto/rand generated hex (16 chars) - Fixes race condition where parallel tests starting at same nanosecond would share the same database name - Ensures true isolation even with hundreds of concurrent tests - Resolves duplicate key constraint violations in CI (perf-doc, test-doc, etc.)
1 parent 8ca23ce commit ee02df0

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

backend/internal/infrastructure/database/testutils.go

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44
package database
55

66
import (
7+
"crypto/rand"
78
"database/sql"
9+
"encoding/hex"
810
"fmt"
911
"os"
1012
"path/filepath"
@@ -38,7 +40,14 @@ func SetupTestDB(t *testing.T) *TestDB {
3840
}
3941

4042
// Create unique test database name to enable parallel test execution
41-
// Format: testdb_{nanosecond}_{pid}_{testname}
43+
// Format: testdb_{random}_{testname}
44+
// Use random bytes to ensure uniqueness even when tests start at the same nanosecond
45+
randomBytes := make([]byte, 8)
46+
if _, err := rand.Read(randomBytes); err != nil {
47+
t.Fatalf("Failed to generate random database name: %v", err)
48+
}
49+
randomHex := hex.EncodeToString(randomBytes)
50+
4251
// PostgreSQL converts unquoted identifiers to lowercase, so we normalize to lowercase
4352
testName := strings.ReplaceAll(t.Name(), "/", "_")
4453
testName = strings.ReplaceAll(testName, " ", "_")
@@ -47,7 +56,7 @@ func SetupTestDB(t *testing.T) *TestDB {
4756
if len(testName) > 30 {
4857
testName = testName[:30]
4958
}
50-
dbName := fmt.Sprintf("testdb_%d_%d_%s", time.Now().UnixNano(), os.Getpid(), testName)
59+
dbName := fmt.Sprintf("testdb_%s_%s", randomHex, testName)
5160

5261
// Truncate database name to PostgreSQL's 63-character limit
5362
if len(dbName) > 63 {

0 commit comments

Comments
 (0)