"""Runs deploy/thor_deploy.sh in a sandbox: a real git origin, fake systemctl/nginx/pip/curl.""" import os import shutil import stat import subprocess # nosec B404 - test runs our own script import time from pathlib import Path import pytest SCRIPT = Path(__file__).resolve().parent.parent / 'deploy' / 'thor_deploy.sh' pytestmark = pytest.mark.skipif(shutil.which('git') is None or shutil.which('flock') is None, reason='needs git and flock') def sh(*args, cwd=None): return subprocess.run(args, cwd=cwd, check=True, capture_output=True, text=True).stdout.strip() # nosec def shim(path: Path, body: str): path.write_text('#!/bin/bash\n' + body + '\n') path.chmod(path.stat().st_mode | stat.S_IEXEC) @pytest.fixture def sandbox(tmp_path): origin = tmp_path / 'origin' origin.mkdir() sh('git', 'init', '-q', '-b', 'main', cwd=origin) sh('git', 'config', 'user.email', 't@t', cwd=origin) sh('git', 'config', 'user.name', 't', cwd=origin) (origin / 'deploy' / 'systemd').mkdir(parents=True) (origin / 'deploy' / 'nginx').mkdir() for f in ('thor.service', 'thor-monitor.service'): (origin / 'deploy' / 'systemd' / f).write_text(f'[Unit]\nDescription={f}\n') (origin / 'deploy' / 'nginx' / 'thor').write_text('server {}\n') (origin / 'requirements.txt').write_text('flask\n') sh('git', 'add', '-A', cwd=origin) sh('git', 'commit', '-q', '-m', 'one', cwd=origin) first = sh('git', 'rev-parse', 'HEAD', cwd=origin) (origin / 'requirements.txt').write_text('flask\nrequests\n') sh('git', 'commit', '-qam', 'two', cwd=origin) second = sh('git', 'rev-parse', 'HEAD', cwd=origin) app = tmp_path / 'app' sh('git', 'clone', '-q', str(origin), str(app)) sh('git', 'checkout', '-q', '--detach', first, cwd=app) bin_dir = tmp_path / 'bin' bin_dir.mkdir() calls = tmp_path / 'calls.log' shim(bin_dir / 'systemctl', f'echo "systemctl $*" >> {calls}; exit 0') shim(bin_dir / 'nginx', f'echo "nginx $*" >> {calls}; exit 0') # /health reports whatever revision file says, unless HEALTH_BROKEN is set. revision = tmp_path / 'revision.env' shim(bin_dir / 'curl', f'[ -n "$HEALTH_BROKEN" ] && exit 7; . {revision} 2>/dev/null; ' 'echo "{\\"sha\\": \\"$THOR_SHA\\", \\"db\\": true}"') shim(bin_dir / 'install', 'src="${@: -2:1}"; dst="${@: -1}"; cp "$src" "$dst"') venv = tmp_path / 'venv' (venv / 'bin').mkdir(parents=True) shim(venv / 'bin' / 'pip', f'echo "pip $*" >> {calls}') (tmp_path / 'systemd').mkdir() (tmp_path / 'nginx').mkdir() env = dict(os.environ) env.update({ 'PATH': f'{bin_dir}:{env["PATH"]}', 'THOR_DEPLOY_APP_ROOT': str(app), 'THOR_DEPLOY_VENV': str(venv), 'THOR_DEPLOY_REVISION_FILE': str(revision), 'THOR_DEPLOY_STATE_DIR': str(tmp_path / 'state'), 'THOR_DEPLOY_LOG': str(tmp_path / 'deploy.log'), 'THOR_DEPLOY_LOCK': str(tmp_path / 'lock'), 'THOR_DEPLOY_SYSTEMD_DIR': str(tmp_path / 'systemd'), 'THOR_DEPLOY_NGINX_SITE': str(tmp_path / 'nginx' / 'thor'), 'THOR_DEPLOY_HEALTH_TRIES': '2', 'THOR_DEPLOY_HEALTH_SLEEP': '0', }) return {'env': env, 'app': app, 'first': first, 'second': second, 'calls': calls, 'revision': revision, 'tmp': tmp_path} def run(sb, sha, ts=None, **extra): env = dict(sb['env'], **extra) return subprocess.run(['bash', str(SCRIPT), sha, str(ts or int(time.time()))], env=env, # nosec capture_output=True, text=True) def test_deploys_exact_sha_installs_files_and_restarts(sandbox): r = run(sandbox, sandbox['second']) assert r.returncode == 0, r.stdout + r.stderr assert sh('git', 'rev-parse', 'HEAD', cwd=sandbox['app']) == sandbox['second'] assert sandbox['revision'].read_text() == f'THOR_SHA={sandbox["second"]}\n' calls = sandbox['calls'].read_text() assert 'pip install' in calls and 'systemctl daemon-reload' in calls assert 'nginx -t' in calls and 'systemctl restart thor thor-monitor' in calls assert (sandbox['tmp'] / 'systemd' / 'thor.service').exists() def test_refuses_bad_input_old_and_replayed_requests(sandbox): assert run(sandbox, 'not-a-sha').returncode == 1 assert run(sandbox, sandbox['second'], ts=int(time.time()) - 3600).returncode == 1 ts = int(time.time()) assert run(sandbox, sandbox['second'], ts=ts).returncode == 0 replay = run(sandbox, sandbox['second'], ts=ts) assert replay.returncode == 1 and 'not newer' in replay.stdout def test_refuses_commit_not_on_main(sandbox): r = run(sandbox, 'f' * 40) assert r.returncode == 1 and 'not found' in r.stdout def test_rolls_back_when_never_healthy(sandbox): r = run(sandbox, sandbox['second'], HEALTH_BROKEN='1') assert r.returncode == 1 assert 'rolling back' in r.stdout assert sh('git', 'rev-parse', 'HEAD', cwd=sandbox['app']) == sandbox['first'] assert sandbox['revision'].read_text() == f'THOR_SHA={sandbox["first"]}\n'