Files
mtusi2026lab5/scripts/attachment-interrupt.py
T
2026-11-16 19:54:38 +03:00

40 lines
1.8 KiB
Python

#!/usr/bin/env python3
"""Abort a binary request mid-body and verify temporary files and metadata are absent."""
import os
from pathlib import Path
import socket
import subprocess
import sys
import time
import urllib.parse
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, check
c = Client()
alice, bob, eve, chat = c.bootstrap()
name = 'interrupted-' + uuid.uuid4().hex + '.png'
base = urllib.parse.urlsplit(c.base)
body = (ROOT / 'tests/fixtures/sample.png').read_bytes()
headers = ('POST /api/v1/chats/' + chat['id'] + '/attachments?filename=' + name + ' HTTP/1.1\r\n'
'Host: localhost\r\nAuthorization: Bearer ' + alice['token'] + '\r\n'
'Content-Type: image/png\r\nContent-Length: 1048576\r\n\r\n')
with socket.create_connection((base.hostname, base.port or 80)) as connection:
connection.sendall(headers.encode() + body[:len(body)//2])
time.sleep(0.5)
# Let the server observe EOF, or the bounded receive timeout.
ids = subprocess.check_output(['docker', 'compose', 'ps', '-q', 'api'], cwd=ROOT, text=True).split()
deadline = time.monotonic() + 20
while True:
files = [subprocess.check_output(['docker', 'exec', cid, 'find', '/tmp', '-name', 'messenger-upload-*'], text=True).strip() for cid in ids]
if not any(files):
break
check(time.monotonic() < deadline, 'temporary upload file survived interruption/timeout')
time.sleep(0.2)
count = subprocess.check_output(['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-Atc',
"SELECT count(*) FROM attachments WHERE filename = '" + name + "'"], cwd=ROOT, text=True).strip()
check(count == '0', 'interrupted upload published metadata')
print('PASS: connection closed mid-body; temporary files removed on both replicas; metadata absent')