Files
mtusi2026lab4-fork/student-tests/test_attachments.py
T

106 lines
4.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
import sys
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, arguments, check, run # noqa: E402
SAMPLE = (ROOT / 'tests/fixtures/sample.png').read_bytes()
MAX_UPLOAD = 10485760
def upload(c, actor, chat, content, content_type, filename='x.png', expected=201):
return c.call(
'POST',
f'/api/v1/chats/{chat["id"]}/attachments?filename={filename}',
expected,
actor=actor,
raw=content,
headers={'Content-Type': content_type},
schema='Attachment',
)
def main():
args = arguments('Негативные сценарии вложений')
c = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = c.bootstrap()
# 1. Слишком большой файл (11 MiB) -> 413
oversized = b'\x89PNG\r\n\x1a\n' + b'\x00' * (MAX_UPLOAD + 1024)
r = upload(c, alice, chat, oversized, 'image/png', expected=413)
check(r['json']['error']['code'] == 'payload_too_large',
'11 MiB: ожидался payload_too_large')
# 2. Битый PNG (обрезанный header) -> 415
broken = b'\x89PNG\r\n\x1a\n' + b'\x00' * 32
r = upload(c, alice, chat, broken, 'image/png', expected=415)
check(r['json']['error']['code'] == 'unsupported_media_type',
'битый PNG (нет IHDR): ожидался unsupported_media_type')
# 3. MIME-подмена: PNG-байты с Content-Type image/jpeg -> 201, но content_type image/png
r = upload(c, alice, chat, SAMPLE, 'image/jpeg')
check(r['json']['content_type'] == 'image/png',
'MIME-подмена: content_type должен определяться по содержимому')
# 4. Чужой attachment_id (не member чата) -> 404
att, _ = c.attachment(alice, chat)
c.call('GET', f'/api/v1/attachments/{att["id"]}', 404, actor=eve)
c.call('GET', f'/api/v1/attachments/{att["id"]}/content', 404, actor=eve)
# 5. attachment_id из другого чата -> 404 при попытке привязать
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Другой чат', 'member_ids': [alice['id'], bob['id']]},
schema='Chat')['json']
key = uuid.uuid4().hex
r = c.call('POST', f'/api/v1/chats/{other["id"]}/messages', 404,
actor=alice,
body={'text': '', 'attachment_ids': [att['id']]},
headers={'Idempotency-Key': key})
check(r['json']['error']['code'] == 'not_found',
'чужой attachment_id в message: ожидался not_found')
# 6. 11 вложений в одном message -> 400 (binding max=10)
att_ids = [str(uuid.uuid4()) for _ in range(11)]
r = c.call('POST', f'/api/v1/chats/{chat["id"]}/messages', 400,
actor=alice,
body={'text': '', 'attachment_ids': att_ids},
headers={'Idempotency-Key': uuid.uuid4().hex})
check(r['json']['error']['code'] == 'invalid_request',
'11 вложений: ожидался invalid_request')
# 7. Дубликаты attachment_ids в одном message -> 400
r = c.call('POST', f'/api/v1/chats/{chat["id"]}/messages', 400,
actor=alice,
body={'text': '', 'attachment_ids': [att['id'], att['id']]},
headers={'Idempotency-Key': uuid.uuid4().hex})
check(r['json']['error']['code'] == 'invalid_request',
'дубликаты attachment_ids: ожидался invalid_request')
# 8. Пустое имя файла -> 400
r = c.call('POST', f'/api/v1/chats/{chat["id"]}/attachments?filename=',
400, actor=alice, raw=SAMPLE, headers={'Content-Type': 'image/png'})
check(r['json']['error']['code'] == 'invalid_request',
'пустой filename: ожидался invalid_request')
# 9. Опасный filename -> 400
for bad in ('../etc/passwd.png', 'a\\b.png', 'x\x00.png'):
q = bad.replace('\\', '%5C').replace('/', '%2F').replace('\x00', '%00')
r = c.call('POST', f'/api/v1/chats/{chat["id"]}/attachments?filename={q}',
400, actor=alice, raw=SAMPLE, headers={'Content-Type': 'image/png'})
check(r['json']['error']['code'] == 'invalid_request',
f'опасный filename {bad!r}: ожидался invalid_request')
# 10. Failed-вложение нельзя прикрепить -> 409
# (симулируем прямо в БД — только для этого стенда)
c.call('GET', '/health/ready', schema='Health')
print('PASS: негативные сценарии вложений (413/415/404/400) прошли без 500')
if __name__ == '__main__':
run(main)