Files
mtusi2026lab4/student-tests/attachment_failover.py
T

43 lines
2.1 KiB
Python

"""Stop exactly the replica that accepted the upload; repeat for both replicas."""
import os
import subprocess
import sys
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, Failure, arguments
args = arguments('Upload replica failover')
c = Client(args.base_url, args.ca_file)
a, b, eve, chat = c.bootstrap()
data = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
ids = subprocess.check_output(['docker', 'compose', 'ps', '-q', 'api'], text=True).split()
assert len(ids) == 2
for container in ids:
target = subprocess.check_output(['docker', 'inspect', '--format', '{{.Config.Hostname}}', container], text=True).strip()
try:
for attempt in range(30):
result = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=failover.png', 201,
actor=a, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')
if result['headers']['X-Instance-Id'] == target:
break
else:
raise AssertionError('Upload did not reach target replica')
subprocess.run(['scripts/stop-one.sh'], env={**os.environ, 'TARGET_INSTANCE_ID': target}, check=True, stdout=subprocess.DEVNULL)
deadline = time.monotonic() + 10
while True:
try:
download = c.call('GET', '/api/v1/attachments/' + result['json']['id'] + '/content', actor=b)
break
except Failure:
if time.monotonic() >= deadline:
raise
time.sleep(0.2)
assert download['headers']['X-Instance-Id'] != target
assert download['bytes'] == data
state = subprocess.check_output(['docker', 'inspect', '--format', '{{.State.Running}}', container], text=True).strip()
assert state == 'false'
print('PASS: upload on ' + target + ', stopped that container, identical download on ' + download['headers']['X-Instance-Id'])
finally:
subprocess.run(['docker', 'compose', 'up', '-d', '--wait'], check=True)