"""Lab4: файлы, ACL, привязка к чату и идемпотентность. Публичный контракт не изменяется.""" import hashlib from pathlib import Path import struct import sys import unittest from urllib.parse import quote import uuid import zlib sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) from client import Client, ROOT class AttachmentsTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.c = Client('http://127.0.0.1:8080' if not __import__('os').environ.get('BASE_URL') else __import__('os').environ['BASE_URL']) cls.a, cls.b, cls.eve, cls.chat = cls.c.bootstrap() cls.png = (ROOT / 'tests/fixtures/sample.png').read_bytes() cls.path = '/api/v1/chats/' + cls.chat['id'] + '/attachments' def upload(self, raw=None, mime='image/png', filename='photo.png', status=201, actor=None, headers=None): return self.c.call('POST', self.path + '?filename=' + quote(filename, safe=''), status, actor=actor or self.a, raw=self.png if raw is None else raw, headers={'Content-Type': mime, **(headers or {})}, schema='Attachment' if status == 201 else None) def test_original_and_metadata_and_acl(self): a = self.upload(filename='фото 👋.png')['json'] self.assertEqual(a['sha256'], hashlib.sha256(self.png).hexdigest()) self.assertEqual(a['size_bytes'], len(self.png)) self.assertEqual((a['status'], a['variants'], a['error_code']), ('ready', [], None)) path = '/api/v1/attachments/' + a['id'] self.assertEqual(self.c.call('GET', path, actor=self.b, schema='Attachment')['json'], a) result = self.c.call('GET', path + '/content?variant=original', actor=self.b) self.assertEqual(result['bytes'], self.png) self.assertEqual(result['headers'].get_content_type(), 'image/png') for suffix in ('', '/content'): self.c.call('GET', path + suffix, 404, actor=self.eve) self.c.call('GET', path + suffix, 401) self.c.call('GET', path + '/content?variant=thumbnail', 404, actor=self.a) def test_jpeg_original(self): jpeg = (ROOT / 'student-tests/fixtures/sample.jpg').read_bytes() a = self.upload(raw=jpeg, mime='image/jpeg', filename='photo.jpg')['json'] got = self.c.call('GET', '/api/v1/attachments/' + a['id'] + '/content', actor=self.b) self.assertEqual(got['bytes'], jpeg) self.assertEqual(got['headers'].get_content_type(), 'image/jpeg') def test_corrupt_and_wrong_mime(self): for raw, mime in ((b'not an image', 'image/png'), (self.png[:40], 'image/png'), (self.png, 'image/jpeg'), (self.png, 'text/plain'), (b'', 'image/png')): with self.subTest(mime=mime, size=len(raw)): self.upload(raw=raw, mime=mime, status=415) def test_filename(self): for name in ('', ' ', '../x.png', 'a/b.png', 'a\\b.png', 'a\x00.png', 'a\n.png', 'a\x7f.png', 'я' * 256): with self.subTest(name=repr(name)): self.upload(filename=name, status=400) def test_byte_limit_before_body(self): # Большой Content-Length с одним байтом: сервер отклоняет до чтения/выделения памяти. self.upload(raw=b'x', status=413, headers={'Content-Length': '10485761'}) def test_pixel_limit_before_decode(self): ihdr = struct.pack('>IIBBBBB', 10000, 5000, 8, 2, 0, 0, 0) chunk = b'IHDR' + ihdr png = (b'\x89PNG\r\n\x1a\n' + struct.pack('>I', len(ihdr)) + chunk + struct.pack('>I', zlib.crc32(chunk)) + self.png[33:]) self.upload(raw=png, status=413) def test_foreign_chat_upload(self): self.upload(actor=self.eve, status=404) def test_attachment_only_and_idempotency(self): aid = self.upload()['json']['id'] key = uuid.uuid4().hex first = self.c.message(self.b, self.chat, '', key=key, attachments=[aid])['json'] self.assertEqual(first['attachment_ids'], [aid]) self.assertEqual(self.c.message(self.b, self.chat, '', key=key, attachments=[aid])['json'], first) path = '/api/v1/chats/' + self.chat['id'] + '/messages' self.c.call('POST', path, 409, actor=self.b, body={'text': 'другое', 'attachment_ids': [aid]}, headers={'Idempotency-Key': key}) key = uuid.uuid4().hex first = self.c.message(self.a, self.chat, 'text', key=key)['json'] self.assertEqual(self.c.message(self.a, self.chat, 'text', key=key, attachments=[])['json'], first) def test_unknown_foreign_and_duplicate_ids(self): aid = self.upload()['json']['id'] other = self.c.call('POST', '/api/v1/chats', 201, actor=self.a, body={'title': 'другой', 'member_ids': [self.a['id']]}, schema='Chat')['json'] for chat, ids, status in ((other, [aid], 404), (self.chat, [str(uuid.uuid4())], 404), (self.chat, [aid, aid], 400), (self.chat, [aid] * 11, 400), (self.chat, ['bad'], 400)): self.c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', status, actor=self.a, body={'text': '', 'attachment_ids': ids}, headers={'Idempotency-Key': uuid.uuid4().hex}) if __name__ == '__main__': unittest.main()