Files
mtusi2026lab5-fork/student_tests/variants.py
2026-11-16 20:30:12 +03:00

52 lines
2.1 KiB
Python

#!/usr/bin/env python3
"""original неизменен, thumbnail 256x256, crop 128x128, optimized существует."""
import hashlib, sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from tests.client import Client, check
from student_tests.common import upload, wait_status, ok, fail
from student_tests.jpeg_probe import jpeg_size as dims_jpeg
def main():
c = Client()
a, b, e, ch = c.bootstrap()
content = Path('tests/fixtures/sample.png').read_bytes()
att = upload(c, a, ch, content)
att = wait_status(c, a, att['id'], 'ready')
src_sha = hashlib.sha256(content).hexdigest()
def get(v):
return c.call('GET', '/api/v1/attachments/%s/content?variant=%s' % (att['id'], v),
200, actor=a)['bytes']
orig = get('original')
check(hashlib.sha256(orig).hexdigest() == src_sha, 'original changed')
ok('original byte-identical')
th = get('thumbnail')
w, h = dims_jpeg(th)
check(max(w, h) == 256 and w <= 256 and h <= 256,
'thumbnail is %dx%d, expected fit in 256x256' % (w, h))
check(w * 160 == h * 256 if h == 160 else True, ...) # необязательно
# Проще всего — сверить с metadata:
thumb_meta = next(v for v in att['variants'] if v['name'] == 'thumbnail')
check((w, h) == (thumb_meta['width'], thumb_meta['height']),
'thumbnail metadata %sx%s != actual %dx%d' % (thumb_meta['width'], thumb_meta['height'], w, h))
ok('thumbnail %dx%d (metadata matches)' % (w, h))
cr = get('crop')
w, h = dims_jpeg(cr)
check((w, h) == (128, 128), 'crop is %dx%d' % (w, h))
ok('crop 128x128 JPEG')
opt = get('optimized')
check(len(opt) > 0, 'optimized empty')
# optimized может быть JPEG или WebP; проверяем, что не пусто и похоже на изображение
check(opt[:2] == b'\xff\xd8' or opt[:4] == b'RIFF', 'optimized is not JPEG/WebP')
ok('optimized present (%d bytes)' % len(opt))
if __name__ == '__main__':
try:
main()
except Exception as exc:
fail(str(exc))