#!/usr/bin/env bash # Start a disposable local PostgreSQL cluster on a private Unix socket only. # No production environment file, database or credentials are used. set -euo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" cd "$ROOT" PGBIN="$(pg_config --bindir)" for cmd in initdb pg_ctl createdb psql; do test -x "$PGBIN/$cmd" || { echo "PostgreSQL-Testwerkzeug fehlt: $cmd" >&2; exit 1; } done TMP="$(mktemp -d /var/tmp/landwelle-postgres-test.XXXXXX)" AS=() if [[ $EUID -eq 0 ]]; then id postgres >/dev/null chown postgres:postgres "$TMP" AS=(runuser -u postgres --) fi cleanup(){ "${AS[@]}" "$PGBIN/pg_ctl" -D "$TMP/db" -m fast -w stop >/dev/null 2>&1 || true rm -rf -- "$TMP" } trap cleanup EXIT "${AS[@]}" mkdir -m 700 "$TMP/socket" "${AS[@]}" "$PGBIN/initdb" -D "$TMP/db" -U postgres --auth=trust --no-locale -E UTF8 >/dev/null "${AS[@]}" "$PGBIN/pg_ctl" -D "$TMP/db" -l "$TMP/postgres.log" -o "-h '' -k $TMP/socket -p 5432" -w start >/dev/null unset PGPASSWORD PGSERVICE PGSERVICEFILE PGOPTIONS PGSSLROOTCERT PGSSLCERT PGSSLKEY PGHOSTADDR export PGHOST="$TMP/socket" PGPORT=5432 PGUSER=postgres PGDATABASE=landwelle_test PGSSLMODE=disable "$PGBIN/createdb" -h "$PGHOST" -p "$PGPORT" -U postgres landwelle_test export DATABASE_URL="postgresql://postgres@/landwelle_test?host=$PGHOST&sslmode=disable" export LANDWELLE_TEST_DATABASE_URL="$DATABASE_URL" touch "$TMP/test.env" # Apply all historical and current migrations without moving repository files. go run ./cmd/migrate --env-file "$TMP/test.env" --dir migrations --keep-files --lock-file "$TMP/migration.lock" go test -count=1 -p 1 ./internal/database ./internal/jobqueue go test -count=1 ./cmd/portal -run 'TestEditorialSchedulePostgres|TestHomepageRecentStoriesPostgres' # Optional authenticated HTTP smoke test against the same disposable database. if [[ "${LANDWELLE_HTTP_SMOKE:-0}" == 1 ]]; then "$PGBIN/psql" -X -v ON_ERROR_STOP=1 -c 'UPDATE landwelle.feed_sources SET enabled=false' >/dev/null go build -o "$TMP/portal" ./cmd/portal "${AS[@]}" env -i PATH=/usr/local/bin:/usr/bin:/bin HOME="$TMP" DATABASE_URL="$DATABASE_URL" python3 - "$TMP" <<'PY' import os,sys,subprocess,socket,time,urllib.request,urllib.parse,http.cookiejar,secrets,pathlib,json root=pathlib.Path(sys.argv[1]) with socket.socket() as sock: sock.bind(('127.0.0.1',0)) port=sock.getsockname()[1] password=secrets.token_urlsafe(24) env=dict(os.environ,ADDR=f'127.0.0.1:{port}',LANDWELLE_STATE_DIR=str(root/'state'),LANDWELLE_ADMIN_USER='integration-test-admin',LANDWELLE_ADMIN_PASSWORD=password,LANDWELLE_ADMIN_COOKIE_SECURE='false',LANDWELLE_AZURACAST_ENABLED='false',LANDWELLE_OPENAI_ENABLED='false',LANDWELLE_ELEVENLABS_ENABLED='false',LANDWELLE_FTP_ENABLED='false',LANDWELLE_SMTP_ENABLED='false') with (root/'portal.log').open('w+') as log: p=subprocess.Popen([str(root/'portal')],cwd=root,env=env,stdout=log,stderr=subprocess.STDOUT) try: base=f'http://127.0.0.1:{port}' for i in range(100): if p.poll() is not None:raise RuntimeError('Testportal vor dem Start beendet') try: with urllib.request.urlopen(base+'/ready',timeout=.5) as r: if json.load(r)['status']=='ready':break except Exception:time.sleep(.15) else:raise RuntimeError('Testportal nicht bereit') for path in ['/ready','/version','/','/player','/highlights','/assets/landwelle-ki-transparenz-preroll-v2.mp3','/api/info']: with urllib.request.urlopen(base+path,timeout=30) as r: assert r.status==200 and r.read() print('HTTP',r.status,path,flush=True) client=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())) data=urllib.parse.urlencode(dict(username='integration-test-admin',password=password)).encode() with client.open(base+'/admin/login',data=data,timeout=45) as r: html=r.read().decode() assert r.url.endswith('/admin') for phrase in ['Gitea · Landwelle','KI-Warteschlange','API-Monitoring','Datenbank & Cron','Verbunden','Repository öffnen']: assert phrase in html,phrase assert password not in html print('HTTP 200 authenticated admin dashboard with operational widgets',flush=True) with client.open(base+'/admin/media',timeout=30) as r: assert r.status==200 and r.read() print('HTTP 200 authenticated media gallery',flush=True) for tab in ('contents','create','categories'): with client.open(base+'/admin/editorial?tab='+tab,timeout=30) as r: page=r.read().decode() assert r.status==200 and 'Redaktionssystem' in page assert 'data-facebook-' not in page and 'name="post_to_facebook"' not in page and 'value="publish_facebook"' not in page if tab=='create': assert 'name="publication_date"' in page and 'name="ai_usage"' in page and 'name="media_asset_id"' in page import re csrf=re.search(r'name="csrf_token" value="([^"]+)"',page).group(1) print('HTTP 200 editorial '+tab+' without Facebook controls',flush=True) try: client.open(base+'/admin/editorial',data=urllib.parse.urlencode(dict(csrf_token=csrf,action='publish_facebook',id='1')).encode(),timeout=15) raise AssertionError('obsolete Facebook action accepted') except urllib.error.HTTPError as error: assert error.code==400,error.code print('HTTP 400 obsolete Facebook action rejected',flush=True) finally: p.terminate() try:p.wait(timeout=20) except subprocess.TimeoutExpired:p.kill();p.wait() if p.returncode not in (0,-15): log.seek(0) print(log.read()[-2000:]) PY fi