"""Runs deploy/gandalf_deploy.sh in a sandbox (gandalf#55 part 2). A throwaway git origin and checkout, with fake systemctl, pip3 and curl on PATH. "Production" health is simulated by the fake curl: it reports whatever commit the fake systemctl last started, for both the web app and the monitor, and a commit containing a BROKEN file reports status "degraded" (an unhealthy build). Each test builds on the state the previous one left. """ import os import shutil import subprocess # nosec B404: runs the deploy script and git in a temporary sandbox import time import pytest SCRIPT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'deploy', 'gandalf_deploy.sh') pytestmark = pytest.mark.skipif(not (shutil.which('bash') and shutil.which('git') and shutil.which('flock')), reason='needs bash, git and flock') def _git(cwd, *args): return subprocess.run(['git', *args], cwd=cwd, check=True, capture_output=True, # nosec B603 B607 text=True).stdout.strip() def _commit(repo, name, files, remove=()): for f, content in files.items(): with open(os.path.join(repo, f), 'w') as fh: fh.write(content) for f in remove: os.unlink(os.path.join(repo, f)) _git(repo, 'add', '-A') _git(repo, '-c', 'user.name=t', '-c', 'user.email=t@example.invalid', 'commit', '-qm', name) return _git(repo, 'rev-parse', 'HEAD') @pytest.fixture(scope='module') def sandbox(tmp_path_factory): root = str(tmp_path_factory.mktemp('gandalf-deploy')) work, origin, app, bin_dir = (os.path.join(root, d) for d in ('work', 'origin.git', 'app', 'bin')) os.makedirs(work) os.makedirs(bin_dir) _git(root, 'init', '-q', '--bare', '-b', 'main', origin) _git(root, 'init', '-q', '-b', 'main', work) c = {'a': _commit(work, 'a', {'app.py': 'a', 'requirements.txt': ''})} _git(work, 'remote', 'add', 'origin', origin) _git(work, 'push', '-q', 'origin', 'main') _git(root, 'clone', '-q', origin, app) with open(os.path.join(app, 'config.json'), 'w') as fh: fh.write('{"secret": "keep-me"}') # untracked, must survive every checkout c['b'] = _commit(work, 'b', {'app.py': 'b'}) c['broken'] = _commit(work, 'broken', {'app.py': 'c', 'BROKEN': '1'}) c['fixed'] = _commit(work, 'fixed', {'app.py': 'd'}, remove=['BROKEN']) _git(work, 'push', '-q', 'origin', 'main') _git(work, 'checkout', '-q', '-b', 'side', c['a']) c['side'] = _commit(work, 'side', {'app.py': 'side'}) _git(work, 'push', '-q', 'origin', 'side') running = os.path.join(root, 'running') def fake(name, body): p = os.path.join(bin_dir, name) with open(p, 'w') as fh: fh.write('#!/bin/bash\n' + body + '\n') os.chmod(p, 0o755) # nosec B103: a test stub in a temporary directory fake('pip3', 'exit 0') fake('systemctl', f'git -C "{app}" rev-parse HEAD > "{running}"') fake('curl', f'''s=$(cat "{running}" 2>/dev/null) || exit 7 if [ -e "{app}/BROKEN" ]; then st=degraded; else st=ok; fi echo "{{\\"status\\":\\"$st\\",\\"sha\\":\\"$s\\",\\"monitor_sha\\":\\"$s\\"}}"''') with open(running, 'w') as fh: fh.write(c['a']) env = dict(os.environ, PATH=f'{bin_dir}:{os.environ["PATH"]}', GANDALF_DEPLOY_APP_ROOT=app, GANDALF_DEPLOY_STATE_DIR=os.path.join(root, 'state'), GANDALF_DEPLOY_LOG=os.path.join(root, 'deploy.log'), GANDALF_DEPLOY_LOCK=os.path.join(root, 'lock'), GANDALF_DEPLOY_HEALTH_TRIES='3', GANDALF_DEPLOY_HEALTH_SLEEP='0') def deploy(sha, ts=None): ts = int(time.time()) if ts is None else ts r = subprocess.run(['bash', SCRIPT, sha, str(ts)], env=env, # nosec B603 B607 capture_output=True, text=True) return r.returncode, r.stdout + r.stderr def head(): return _git(app, 'rev-parse', 'HEAD') def runs(): with open(running) as fh: return fh.read().strip() return {'c': c, 'deploy': deploy, 'head': head, 'running': runs, 'app': app} def test_deploys_exactly_the_requested_commit(sandbox): s = sandbox code, out = s['deploy'](s['c']['b']) assert code == 0, out assert s['head']() == s['c']['b'] and s['running']() == s['c']['b'] with open(os.path.join(s['app'], 'config.json')) as fh: assert fh.read() == '{"secret": "keep-me"}' def test_a_replayed_request_is_refused(sandbox): s = sandbox ts = int(time.time()) + 5 assert s['deploy'](s['c']['fixed'], ts)[0] == 0 code, out = s['deploy'](s['c']['b'], ts) assert code == 1 and 'replay or out of order' in out assert s['head']() == s['c']['fixed'] def test_a_stale_request_is_refused(sandbox): code, out = sandbox['deploy'](sandbox['c']['b'], int(time.time()) - 3600) assert code == 1 and 'old (limit 300s)' in out def test_a_commit_not_on_main_is_refused(sandbox): s = sandbox code, out = s['deploy'](s['c']['side'], int(time.time()) + 10) assert code == 1 and ('is not on main' in out or 'not found after fetch' in out) assert s['head']() == s['c']['fixed'] def test_malformed_input_is_refused(sandbox): s = sandbox assert 'invalid sha' in s['deploy']('abc', int(time.time()) + 11)[1] assert 'invalid timestamp' in s['deploy'](s['c']['b'], 'x')[1] def test_an_unhealthy_build_is_rolled_back(sandbox): s = sandbox code, out = s['deploy'](s['c']['broken'], int(time.time()) + 20) assert code == 1 assert 'rolling back' in out and 'healthy' in out.split('rolled back to', 1)[1] assert s['head']() == s['c']['fixed'] and s['running']() == s['c']['fixed'] def test_the_running_commit_is_a_no_op(sandbox): s = sandbox code, out = s['deploy'](s['c']['fixed'], int(time.time()) + 30) assert code == 0 and 'nothing to do' in out