Files

79 lines
3.4 KiB
Python

"""Exercise deployment control flow without touching Docker or the real host."""
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
class DeployTests(unittest.TestCase):
def run_deploy(self, failure=''):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / 'scripts').mkdir()
(root / 'state').mkdir()
(root / 'state/metrics.env').write_text('METRICS_TOKEN=test\n')
source = Path('scripts/deploy.sh').read_text().replace(
'state_dir=/home/koden/.local/state/oktp-deploy', f'state_dir={root}/state')
(root / 'scripts/deploy.sh').write_text(source)
binary = root / 'bin'
binary.mkdir()
fake = '''#!/usr/bin/env python3
import os, sys
from pathlib import Path
name = Path(sys.argv[0]).name
args = sys.argv[1:]
with open(os.environ['TEST_LOG'], 'a') as log:
log.write(name + ' ' + ' '.join(args) + '\\n')
failure = os.environ.get('TEST_FAILURE')
if name == 'git':
if failure == 'auth' and args[0] == 'ls-remote': sys.exit(128)
print('a' * 40)
elif name == 'docker':
if args[0] == 'inspect': print('false')
if failure == 'build' and args[0] == 'build': sys.exit(1)
if failure == 'candidate' and args[0] == 'exec': sys.exit(1)
if failure == 'start' and args[:2] == ['start', 'oktp-docs'] and not Path(os.environ['TEST_MARKER']).exists():
Path(os.environ['TEST_MARKER']).touch()
sys.exit(1)
elif name == 'curl' and failure == 'health':
sys.exit(1)
'''
for command in ('git', 'docker', 'curl'):
file = binary / command
file.write_text(fake)
file.chmod(0o755)
log = root / 'calls'
env = dict(os.environ, PATH=f'{binary}:' + os.environ['PATH'],
TEST_LOG=str(log), TEST_MARKER=str(root / 'marker'), TEST_FAILURE=failure)
result = subprocess.run(['bash', str(root / 'scripts/deploy.sh')],
env=env, capture_output=True, text=True)
return result, log.read_text()
def test_success_replaces_container(self):
result, calls = self.run_deploy()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('docker create --name oktp-docs', calls)
self.assertIn('--retry-all-errors', calls)
self.assertIn('docker rm oktp-docs-backup-', calls)
def test_build_or_candidate_failure_keeps_current_container(self):
for failure in ('build', 'candidate'):
result, calls = self.run_deploy(failure)
self.assertNotEqual(result.returncode, 0)
self.assertNotIn('docker stop ', calls)
def test_new_container_failure_restores_previous(self):
for failure in ('start', 'health'):
result, calls = self.run_deploy(failure)
self.assertNotEqual(result.returncode, 0)
self.assertIn('docker rm -f oktp-docs\n', calls)
self.assertIn('docker rename oktp-docs-backup-', calls)
self.assertIn('Previous container restored.', result.stderr)
def test_auth_failure_is_not_reported_as_success(self):
result, calls = self.run_deploy('auth')
self.assertNotEqual(result.returncode, 0)
self.assertIn('Cannot read main from Gitea', result.stderr)
self.assertNotIn('docker build', calls)