"""Check upload errors through Nginx and exercise an actual S3 outage.""" from io import BytesIO from pathlib import Path import subprocess import sys import time from PIL import Image ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / 'tests')) from client import Client, Failure, arguments, check, run def main(): args = arguments(__doc__) client = Client(args.base_url, args.ca_file, timeout=45) alice, _, eve, chat = client.bootstrap() data = (ROOT / 'tests/fixtures/sample.png').read_bytes() path = f"/api/v1/chats/{chat['id']}/attachments" good = path + '?filename=sample.png' item, _ = client.attachment(alice, chat) content = f"/api/v1/attachments/{item['id']}/content" def upload(url, payload, expected, mime='image/png', actor=alice): return client.call('POST', url, expected, actor=actor, raw=payload, headers={'Content-Type': mime}) huge = BytesIO() Image.new('1', (8001, 5000)).save(huge, 'PNG') for payload, expected, mime in [ (b'x' * (10 * 1024 * 1024 + 1), 413, 'image/png'), (huge.getvalue(), 413, 'image/png'), (data[:30], 415, 'image/png'), (data, 415, 'image/jpeg'), ]: upload(good, payload, expected, mime) upload(path + '?filename=a%2Fb.png', data, 400) upload(good, data, 404, actor=eve) client.call('GET', content, 404, actor=eve) print('PASS: size, pixel count, corruption, MIME, filename and chat ACL over Nginx') def s3_command(action): subprocess.run(['docker', 'compose', action, 's3'], cwd=ROOT, check=True, timeout=30) try: s3_command('stop') upload(good, data, 503) client.call('GET', content, 503, actor=alice) client.message(alice, chat, 'Текст при недоступном S3') finally: s3_command('start') started = time.monotonic() for _ in range(40): try: downloaded = client.call('GET', content, actor=alice) break except Failure: time.sleep(.25) else: raise Failure('S3 download did not recover after restart') check(downloaded['bytes'] == data, 'original changed after S3 restart') print(f'PASS: S3 outage returned 503, text remained available, original recovered in {time.monotonic()-started:.2f}s') if __name__ == '__main__': run(main)