115 lines
5.6 KiB
Python
115 lines
5.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Run backend tests against freshly initialized, disposable PostgreSQL only.
|
|
|
|
Requires Python 3, installed backend dependencies, and PostgreSQL 16+ binaries
|
|
(initdb, pg_ctl, postgres) on PATH or in PG_BIN. Never reuses a running database.
|
|
Stage-principal /app + Redis integration tests remain separately opt-in.
|
|
"""
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import signal
|
|
import socket
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
|
|
BACKEND = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def run(args, env=None):
|
|
subprocess.run([str(a) for a in args], cwd=BACKEND, env=env, check=True)
|
|
|
|
|
|
def binary(name):
|
|
candidate = str(Path(os.environ['PG_BIN']) / name) if os.environ.get('PG_BIN') else shutil.which(name)
|
|
if not candidate or not os.access(candidate, os.X_OK):
|
|
raise RuntimeError(f'{name} unavailable: install PostgreSQL binaries or set PG_BIN; integration tests cannot be skipped')
|
|
return candidate
|
|
|
|
|
|
def interrupted(signum, _frame):
|
|
raise SystemExit(128 + signum)
|
|
|
|
|
|
def main():
|
|
initdb, pg_ctl = binary('initdb'), binary('pg_ctl')
|
|
binary('postgres')
|
|
if os.geteuid() == 0:
|
|
raise RuntimeError('Run disposable PostgreSQL tests as a non-root user')
|
|
for sig in (signal.SIGTERM, signal.SIGINT):
|
|
signal.signal(sig, interrupted)
|
|
env = os.environ.copy()
|
|
# Do not propagate operational database URLs to Prisma schema setup or tests.
|
|
for key in list(env):
|
|
if key.endswith('DATABASE_URL'):
|
|
del env[key]
|
|
env.pop('STAGE_PRINCIPAL_DISPOSABLE_TEST', None)
|
|
env['DATABASE_URL'] = 'postgresql://disabled@127.0.0.1:1/disabled'
|
|
definitions = [
|
|
('SEO_TEST_DATABASE_URL', 'seo_test', 55439, 'postgres', ''),
|
|
# Keep the existing publication fixture's literal URL allowlist intact.
|
|
('PUBLICATION_TEST_DATABASE_URL', 'publication_test', 55447, 'publication_test', None),
|
|
('CORPORATE_TEST_DATABASE_URL', 'corporate_test', 55449, 'corporate_test', ''),
|
|
]
|
|
# Refuse occupied dedicated ports before creating any cluster. PostgreSQL's
|
|
# own bind still protects against races; no existing server is ever stopped.
|
|
for _, _, port, _, _ in definitions:
|
|
with socket.socket() as probe:
|
|
probe.bind(('127.0.0.1', port))
|
|
started = []
|
|
with tempfile.TemporaryDirectory(prefix='backend-pg-', dir=os.environ.get('TMPDIR', '/opt/data/cache/scratch')) as root:
|
|
try:
|
|
for key, user, port, database, password in definitions:
|
|
data = Path(root) / str(port)
|
|
unix_socket = Path(root) / f's{port}'
|
|
unix_socket.mkdir(mode=0o700)
|
|
run([initdb, '-D', data, '-U', user, '--auth=trust', '--no-locale', '--encoding=UTF8'])
|
|
# Track our initialized directory before startup, so even an
|
|
# interrupted pg_ctl start is cleaned up, never another server.
|
|
started.append(data)
|
|
run([pg_ctl, '-D', data, '-l', Path(root) / f'{port}.log', '-w', '-t', '30',
|
|
'-o', f'-h 127.0.0.1 -p {port} -k {unix_socket}', 'start'])
|
|
if password is None:
|
|
# The fixture owns its dedicated test-only credential prefix;
|
|
# read that literal rather than duplicate or log it here.
|
|
import re
|
|
fixture = (BACKEND / 'src/seo-tracking/publication.postgres.spec.ts').read_text()
|
|
match = re.search(r"url\.startsWith\('([^']+)'\)", fixture)
|
|
if not match:
|
|
raise RuntimeError('Publication disposable URL allowlist not found')
|
|
from urllib.parse import urlsplit
|
|
prefix = match.group(1)
|
|
parsed = urlsplit(prefix)
|
|
if parsed.hostname != '127.0.0.1' or parsed.port != port or parsed.username != user or parsed.path != '/':
|
|
raise RuntimeError('Publication allowlist is not the dedicated disposable endpoint')
|
|
url = prefix + database
|
|
else:
|
|
url = f'postgresql://{user}{password}@127.0.0.1:{port}/{database}'
|
|
if database != 'postgres':
|
|
setup = {**env, 'DATABASE_URL': url.rsplit('/', 1)[0] + '/postgres'}
|
|
run(['node', '-e', 'const {PrismaClient}=require("@prisma/client"); const p=new PrismaClient(); '
|
|
f'p.$executeRawUnsafe(\'CREATE DATABASE "{database}"\')'
|
|
'.finally(()=>p.$disconnect()).catch(e=>{console.error(e);process.exitCode=1})'], setup)
|
|
run([BACKEND / 'node_modules/.bin/prisma', 'db', 'push', '--skip-generate'], {**env, 'DATABASE_URL': url})
|
|
env[key] = url
|
|
print('Disposable PostgreSQL ready: SEO, publication and corporate integration enabled; '
|
|
'Stage-principal Redis+/app suites remain explicitly out of scope.', flush=True)
|
|
run([BACKEND / 'node_modules/.bin/jest', '--runInBand', *sys.argv[1:]], env)
|
|
finally:
|
|
failures = []
|
|
for data in reversed(started):
|
|
result = subprocess.run([pg_ctl, '-D', str(data), '-m', 'immediate', '-w', '-t', '30', 'stop'], cwd=BACKEND)
|
|
if result.returncode and (data / 'postmaster.pid').exists():
|
|
failures.append(str(data))
|
|
if failures:
|
|
raise RuntimeError(f'Failed to stop disposable clusters: {failures}')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
main()
|
|
except (RuntimeError, OSError, subprocess.CalledProcessError) as error:
|
|
print(f'Backend PostgreSQL test gate failed: {error}', file=sys.stderr)
|
|
sys.exit(1)
|