146 lines
6.8 KiB
Python
146 lines
6.8 KiB
Python
import hashlib
|
|
import json
|
|
import tempfile
|
|
import unittest
|
|
from pathlib import Path
|
|
from unittest.mock import Mock
|
|
|
|
import production_cd as cd
|
|
|
|
|
|
SHA = 'a' * 40
|
|
TASK = 'd5abdf29-d0b5-4992-8073-0cb8fffd84ed'
|
|
IMAGES = {role: 'sha256:' + str(i) * 64 for i, role in enumerate(('api', 'web', 'worker'), 1)}
|
|
CTX = 'build / build (push)'
|
|
|
|
|
|
class ProductionCD(unittest.TestCase):
|
|
def setUp(self):
|
|
temp = tempfile.TemporaryDirectory()
|
|
self.addCleanup(temp.cleanup)
|
|
self.root = Path(temp.name)
|
|
self.request = dict(sha=SHA, task=TASK, bundle='b' * 64, confirm='deploy-production',
|
|
action='deploy', approval='signed', run_id='42')
|
|
self.manifest = dict(schema=1, target=cd.TARGET, sha=SHA, task=TASK, migrations=[1, 2], images={})
|
|
for role, image in IMAGES.items():
|
|
archive = self.root / (role + '.tar')
|
|
archive.write_text(role)
|
|
self.manifest['images'][role] = dict(id=image, sha256=hashlib.sha256(role.encode()).hexdigest())
|
|
data = json.dumps(self.manifest).encode()
|
|
(self.root / 'release.json').write_bytes(data)
|
|
for path in self.root.iterdir():
|
|
path.chmod(0o600)
|
|
self.request['bundle'] = hashlib.sha256(data).hexdigest()
|
|
self.acceptance = {'verdict': 'passed', 'sha': SHA, 'bundle': self.request['bundle'],
|
|
'evidence': 'https://example.test/result/42'}
|
|
self.host = Mock()
|
|
self.host.task.return_value = {'id': TASK, 'spaceId': cd.SPACE, 'status': {'id': cd.READY},
|
|
'metadata': {'cd_acceptance': json.dumps(self.acceptance)}}
|
|
self.host.baseline.return_value = {'before': 'baseline'}
|
|
self.host.pre_switch.return_value = None
|
|
self.host.verify.return_value = {'sha': SHA, 'images': IMAGES, 'health': 'ok'}
|
|
self.host.receipt_path = self.root / 'receipt.json'
|
|
self.host.bundle_path.return_value = self.root
|
|
|
|
def execute(self):
|
|
return cd.release(self.host, self.request)
|
|
|
|
def assert_no_deploy(self):
|
|
self.host.load.assert_not_called()
|
|
self.host.switch.assert_not_called()
|
|
self.host.callback.assert_not_called()
|
|
|
|
def test_no_confirmation_has_zero_side_effects(self):
|
|
self.request['confirm'] = ''
|
|
with self.assertRaisesRegex(cd.CDError, 'confirmation'):
|
|
self.execute()
|
|
self.host.assert_not_called()
|
|
self.assert_no_deploy()
|
|
|
|
def test_preconditions_prevent_loading_and_switching(self):
|
|
for mode in ('approval', 'ci', 'test', 'changed_bundle', 'tampered_archive', 'migration'):
|
|
with self.subTest(mode=mode):
|
|
self.setUp()
|
|
if mode in ('approval', 'ci', 'migration'):
|
|
step = {'approval': self.host.approve, 'ci': self.host.check_ci,
|
|
'migration': self.host.pre_switch}[mode]
|
|
step.side_effect = cd.CDError(mode)
|
|
elif mode == 'test':
|
|
self.host.task.return_value['metadata'].clear()
|
|
elif mode == 'changed_bundle':
|
|
self.request['bundle'] = 'f' * 64
|
|
else:
|
|
(self.root / 'web.tar').write_bytes(b'other image')
|
|
with self.assertRaises(cd.CDError):
|
|
self.execute()
|
|
self.assert_no_deploy()
|
|
|
|
def test_bare_ci_success_cannot_replace_required_context(self):
|
|
for statuses in ([], [{'context': 'different', 'status': 'success'}],
|
|
[{'context': CTX, 'status': 'failure'}, {'context': CTX, 'status': 'success'}]):
|
|
with self.assertRaises(cd.CDError):
|
|
cd.verify_contexts({'state': 'success', 'statuses': statuses}, [CTX])
|
|
cd.verify_contexts({'state': 'success', 'statuses': [{'context': CTX, 'status': 'success'}]}, [CTX])
|
|
|
|
def test_approval_and_acceptance_rechecked_before_switch(self):
|
|
self.host.approve.side_effect = [None, cd.CDError('revoked')]
|
|
with self.assertRaisesRegex(cd.CDError, 'revoked'):
|
|
self.execute()
|
|
self.host.switch.assert_not_called()
|
|
self.host.callback.assert_not_called()
|
|
|
|
def test_success_and_writeback_retry_do_not_switch_twice(self):
|
|
self.host.callback.side_effect = [cd.CDError('HiFox timeout'), None]
|
|
with self.assertRaisesRegex(cd.CDError, 'DEPLOYED_HIFOX_PENDING'):
|
|
self.execute()
|
|
self.assertEqual(cd.read_json(self.host.receipt_path)['state'], 'deployed_hifox_pending')
|
|
self.request.update(action='writeback', confirm='retry-writeback', approval='')
|
|
self.assertEqual(self.execute()['state'], 'published')
|
|
self.host.switch.assert_called_once()
|
|
self.host.load.assert_called_once()
|
|
self.assertEqual(self.host.verify.call_count, 2)
|
|
|
|
def test_writeback_without_receipt_refuses(self):
|
|
self.request.update(action='writeback', confirm='retry-writeback', approval='')
|
|
with self.assertRaisesRegex(cd.CDError, 'receipt'):
|
|
self.execute()
|
|
self.assert_no_deploy()
|
|
|
|
def test_failed_cutover_rolls_back_and_never_marks_published(self):
|
|
for result in ('rolled_back', 'rollback_failed'):
|
|
with self.subTest(result=result):
|
|
self.setUp()
|
|
self.host.verify.side_effect = cd.CDError('new unhealthy')
|
|
if result == 'rollback_failed':
|
|
self.host.rollback.side_effect = cd.CDError('old unhealthy')
|
|
with self.assertRaisesRegex(cd.CDError, result):
|
|
self.execute()
|
|
self.assertEqual(cd.read_json(self.host.receipt_path)['state'], result)
|
|
self.host.rollback.assert_called_once()
|
|
self.host.callback.assert_not_called()
|
|
with self.assertRaisesRegex(cd.CDError, 'receipt'):
|
|
self.execute()
|
|
self.host.switch.assert_called_once()
|
|
|
|
def test_target_lock_is_exclusive(self):
|
|
path = self.root / 'lock'
|
|
with cd.deploy_lock(path):
|
|
with self.assertRaisesRegex(cd.CDError, 'deployment lock'):
|
|
with cd.deploy_lock(path):
|
|
self.fail('lock was acquired twice')
|
|
|
|
def test_persisted_compose_changes_only_images(self):
|
|
original = {'services': {role: {'image': role + ':old', 'env_file': [{'path': '/kept', 'format': 'raw'}],
|
|
'volumes': ['/kept:/run/key:ro'], 'environment': {'GATE': 'true'}}
|
|
for role in IMAGES}, 'name': 'governance'}
|
|
changed = cd.with_images(original, IMAGES)
|
|
for role, new in changed['services'].items():
|
|
self.assertEqual(new.pop('image'), IMAGES[role])
|
|
old = original['services'][role].copy()
|
|
old.pop('image')
|
|
self.assertEqual(new, old)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|