test_api.py — сквозные сценарии на живой БД (auth, сессии, чаты, идемпотентность, миграции, доступ к чужим чатам). test_images.py — валидация PNG/JPEG: MIME, лимиты bytes/pixels, повреждённые файлы, доступ только для участников чата. Указано 3 применённые миграции.
40 lines
1.6 KiB
Python
40 lines
1.6 KiB
Python
"""Offline negative checks of image admission; execute: python -m unittest discover -s student-tests -p test_images.py."""
|
|
import io
|
|
import unittest
|
|
from pathlib import Path
|
|
from PIL import Image
|
|
from messenger.images import validate_image, MAX_BYTES
|
|
from messenger.domain import ApiError
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
class ImageAdmissionTests(unittest.TestCase):
|
|
def test_fixture_and_byte_preservation(self):
|
|
blob = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
|
self.assertIsNone(validate_image(blob, 'image/png'))
|
|
|
|
def test_mismatch_or_invalid(self):
|
|
data = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
|
for blob, mime in [(data, 'image/jpeg'), (b'not-an-image', 'image/png'),
|
|
(b'\xff\xd8broken', 'image/jpeg'), (data, 'application/octet-stream')]:
|
|
with self.subTest(mime=mime):
|
|
with self.assertRaises(ApiError) as error:
|
|
validate_image(blob, mime)
|
|
self.assertEqual(error.exception.status, 415)
|
|
|
|
def test_byte_limit(self):
|
|
with self.assertRaises(ApiError) as error:
|
|
validate_image(b'0' * (MAX_BYTES + 1), 'image/png')
|
|
self.assertEqual(error.exception.status, 413)
|
|
|
|
def test_pixel_limit_before_decompression(self):
|
|
img = Image.new('RGB', (8000, 5001))
|
|
stream = io.BytesIO()
|
|
img.save(stream, format='PNG')
|
|
with self.assertRaises(ApiError) as error:
|
|
validate_image(stream.getvalue(), 'image/png')
|
|
self.assertEqual(error.exception.status, 413)
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|