#!/usr/bin/env python3 """Собственные интеграционные проверки вложений поверх неизменённого публичного API.""" import hashlib from pathlib import Path import sys from urllib.parse import quote import uuid ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / 'tests')) from client import Client, arguments, check, run def main(): args = arguments('Lab 4 student attachment checks') client = Client(args.base_url, args.ca_file) alice, bob, eve, chat = client.bootstrap() fixture = (ROOT / 'tests/fixtures/sample.png').read_bytes() uploaded = client.call( 'POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png', 201, actor=alice, raw=fixture, headers={'Content-Type': 'image/png'}, schema='Attachment', )['json'] check(uploaded['status'] == 'ready', 'upload was not ready') check(uploaded['variants'] == [] and uploaded['error_code'] is None, 'Lab 4 ready metadata must have no variants or error') check(uploaded['sha256'] == hashlib.sha256(fixture).hexdigest(), 'metadata checksum differs from fixture') check(uploaded['size_bytes'] == len(fixture), 'metadata size differs from fixture') metadata = client.call( 'GET', '/api/v1/attachments/' + uploaded['id'], actor=bob, schema='Attachment', )['json'] check(metadata == uploaded, 'another chat participant got different attachment metadata') downloaded = client.call( 'GET', '/api/v1/attachments/' + uploaded['id'] + '/content', actor=bob, ) check(downloaded['bytes'] == fixture, 'downloaded bytes are not identical') check(downloaded['headers'].get_content_type() == 'image/png', 'download Content-Type is not the detected image type') client.call('GET', '/api/v1/attachments/' + uploaded['id'], 404, actor=eve) client.call('GET', '/api/v1/attachments/' + uploaded['id'] + '/content', 404, actor=eve) # Нельзя привязать существующий файл чата к сообщению другого чата. other_chat = client.call( 'POST', '/api/v1/chats', 201, actor=alice, body={'title': 'Другой чат', 'member_ids': [alice['id'], bob['id']]}, schema='Chat', )['json'] client.call( 'POST', '/api/v1/chats/' + other_chat['id'] + '/messages', 404, actor=alice, body={'text': '', 'attachment_ids': [uploaded['id']]}, headers={'Idempotency-Key': uuid.uuid4().hex}, ) prefix = '/api/v1/chats/' + chat['id'] + '/attachments?filename=' client.call( 'POST', prefix + 'bad.png', 415, actor=alice, raw=b'not an image', headers={'Content-Type': 'image/png'}, ) client.call( 'POST', prefix + 'mismatch.jpg', 415, actor=alice, raw=fixture, headers={'Content-Type': 'image/jpeg'}, ) client.call( 'POST', prefix + quote('../sample.png', safe=''), 400, actor=alice, raw=fixture, headers={'Content-Type': 'image/png'}, ) client.call( 'POST', prefix + 'too-large.png', 413, actor=alice, raw=b'\x00' * (10 * 1024 * 1024 + 1), headers={'Content-Type': 'image/png'}, ) print('PASS: upload/checksum/download, chat ACL, message binding and upload limits') if __name__ == '__main__': run(main)