param( [string[]]$Packages = @( './internal/deviceauth', './internal/saas', './internal/orchestration', './internal/extraction', './internal/privacy', './internal/media', './internal/retrieval' ), [switch]$KeepDatabase ) $ErrorActionPreference = 'Stop' $PSNativeCommandUseErrorActionPreference = $true $projectRoot = Split-Path -Parent $PSScriptRoot Set-Location -LiteralPath $projectRoot $databaseName = 'voice_platform_test_' + ([guid]::NewGuid().ToString('N')) if ($databaseName -notmatch '^voice_platform_test_[0-9a-f]{32}$') { throw "Refusing to use unexpected integration database name: $databaseName" } function Invoke-PostgresAdmin { param([Parameter(Mandatory = $true)][string]$Sql) docker compose exec -T postgres psql -v ON_ERROR_STOP=1 -U voice -d postgres -c $Sql if ($LASTEXITCODE -ne 0) { throw "PostgreSQL administration command failed with exit code $LASTEXITCODE." } } try { $postgresID = docker compose ps -q postgres if (-not $postgresID) { Write-Host 'Starting the local PostgreSQL service...' docker compose up -d --wait postgres if ($LASTEXITCODE -ne 0) { throw "Starting PostgreSQL failed with exit code $LASTEXITCODE." } } Write-Host "Creating isolated integration database $databaseName" Invoke-PostgresAdmin -Sql "CREATE DATABASE `"$databaseName`" OWNER voice;" $containerDatabaseURL = "postgres://voice:voice_dev_only@postgres:5432/$databaseName`?sslmode=disable" docker compose run --rm --no-deps migrate ` -path=/migrations ` "-database=$containerDatabaseURL" ` up if ($LASTEXITCODE -ne 0) { throw "Database migration failed with exit code $LASTEXITCODE." } docker compose run --rm --no-deps ` -e PGPASSWORD=voice_dev_only ` seed psql -h postgres -U voice -d $databaseName -v ON_ERROR_STOP=1 -f /fixtures/local_seed.sql if ($LASTEXITCODE -ne 0) { throw "Database seed failed with exit code $LASTEXITCODE." } $previousTestDatabaseURL = $env:TEST_DATABASE_URL $env:TEST_DATABASE_URL = "postgres://voice:voice_dev_only@127.0.0.1:55432/$databaseName`?sslmode=disable" try { Write-Host "Running database-backed packages against $databaseName" go test -count=1 -p 1 @Packages if ($LASTEXITCODE -ne 0) { throw "Database integration tests failed with exit code $LASTEXITCODE." } } finally { if ($null -eq $previousTestDatabaseURL) { Remove-Item Env:TEST_DATABASE_URL -ErrorAction SilentlyContinue } else { $env:TEST_DATABASE_URL = $previousTestDatabaseURL } } } finally { if ($KeepDatabase) { Write-Warning "Keeping isolated integration database for inspection: $databaseName" } elseif ($databaseName -match '^voice_platform_test_[0-9a-f]{32}$') { Write-Host "Dropping isolated integration database $databaseName" Invoke-PostgresAdmin -Sql "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='$databaseName' AND pid <> pg_backend_pid();" Invoke-PostgresAdmin -Sql "DROP DATABASE IF EXISTS `"$databaseName`";" } }