teqo-backup/tests/helpers/assertTestDatabase.ts
Francisco Ignácio Fontoura Solla 4f0f997c32 Isolate local/dev and tests from the production database
Local dev and the test suite previously defaulted to the live production
Neon database, and running the tests mutated prod data. Add guardrails plus
a proper local Postgres + migrations workflow so production can't be hit by
mistake:

- docker-compose: local Postgres 17 (matches prod) + auto-created teqo_test
- dev guard refuses a non-local DATABASE_URL; tests refuse non-_test databases
- .env.test isolates the suite; vitest/playwright load it and fail closed
- Payload migrations set up (push disabled); build runs `payload migrate`,
  so deploys apply pending migrations to prod automatically
- baseline `initial` migration + idempotent consent.text varchar->jsonb fix
- `pnpm db:pull` copies prod content locally, excluding supporter PII
- docs (README, AGENTS.md) + agent skills for the local-db/migration workflow
2026-07-15 13:52:30 -03:00

32 lines
1.2 KiB
TypeScript

/**
* Fail-closed guard for the automated test suite.
*
* The tests delete and recreate records (see seedUser.ts), so they must NEVER
* run against the production database. Rather than trying to detect prod (an
* allowlist we could forget to update), we require the opposite: the database
* name MUST end with `_test`. Anything else — including the production Neon
* database — is rejected.
*/
export function assertTestDatabase(databaseUrl: string | undefined): void {
if (!databaseUrl) {
throw new Error(
'DATABASE_URL is not set. Tests require a dedicated test database configured in .env.test ' +
'(e.g. postgresql://teqo:teqo@localhost:5432/teqo_test).',
)
}
let databaseName: string
try {
databaseName = new URL(databaseUrl).pathname.replace(/^\//, '')
} catch {
throw new Error('DATABASE_URL is not a valid PostgreSQL connection string.')
}
if (!/_test$/.test(databaseName)) {
throw new Error(
`Refusing to run tests against database "${databaseName || '(unknown)'}". ` +
'The test database name must end with "_test". ' +
'Configure DATABASE_URL in .env.test (e.g. postgresql://teqo:teqo@localhost:5432/teqo_test).',
)
}
}