forked from mtusi2026/mtusi2026lab5
114 lines
3.9 KiB
Python
114 lines
3.9 KiB
Python
"""Реальные преобразования и OS-лимиты дочернего процесса worker."""
|
|
|
|
import asyncio
|
|
from io import BytesIO
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
from uuid import uuid4
|
|
|
|
from PIL import Image
|
|
import pytest
|
|
|
|
from app.core.image_processing import ImageSettings
|
|
from app.domain.image_pipeline import create_variants
|
|
from app.domain.job_files import render_variants
|
|
from app.storage.jobs import JobWork
|
|
from test_attachments import MemoryStorage
|
|
|
|
|
|
@pytest.mark.parametrize("size,transparent", [((1600, 800), False), ((24, 12), True)])
|
|
async def test_variant_geometry_metadata_and_alpha(tmp_path, size, transparent):
|
|
source = tmp_path / "source.png"
|
|
with Image.new("RGBA", size, (255, 0, 0, 0 if transparent else 255)) as image:
|
|
exif = Image.Exif()
|
|
exif[270] = "private description"
|
|
image.save(source, format="PNG", exif=exif)
|
|
result = create_variants(
|
|
source, tmp_path, "image/png", 40_000_000, ImageSettings(_env_file=None)
|
|
)
|
|
variants = {v.name: v for v in result.variants}
|
|
assert (variants["crop"].width, variants["crop"].height) == (128, 128)
|
|
assert (variants["thumbnail"].width, variants["thumbnail"].height) == (
|
|
(256, 128) if size[0] > 256 else size
|
|
)
|
|
assert (variants["optimized"].width, variants["optimized"].height) == (
|
|
(1280, 640) if size[0] > 1280 else size
|
|
)
|
|
for name in ("thumbnail.jpg", "crop.jpg", "optimized.webp"):
|
|
with Image.open(tmp_path / name) as image:
|
|
assert (
|
|
not image.getexif()
|
|
and not image.info.get("icc_profile")
|
|
and not image.info.get("xmp")
|
|
)
|
|
if transparent:
|
|
if name.endswith("webp"):
|
|
assert image.getpixel((0, 0))[3] == 0
|
|
else:
|
|
assert min(image.getpixel((0, 0))) >= 250
|
|
|
|
|
|
async def test_exif_orientation_applied(tmp_path):
|
|
source = tmp_path / "source.jpg"
|
|
with Image.new("RGB", (400, 200), "blue") as image:
|
|
exif = Image.Exif()
|
|
exif[274] = 6
|
|
image.save(source, exif=exif)
|
|
result = create_variants(
|
|
source, tmp_path, "image/jpeg", 40_000_000, ImageSettings(_env_file=None)
|
|
)
|
|
assert (result.variants[0].width, result.variants[0].height) == (128, 256)
|
|
|
|
|
|
@pytest.mark.parametrize("failure", ["memory", "cpu"])
|
|
async def test_worker_os_limits(failure, tmp_path):
|
|
body = (
|
|
"return bytearray(2 * 1024 ** 3)" if failure == "memory" else "while True: pass"
|
|
)
|
|
code = (
|
|
"from app.core import thumbnail_worker as w\ndef fail(*args):\n "
|
|
+ body
|
|
+ "\nw.create_variants=fail\nraise SystemExit(w.main())"
|
|
)
|
|
result = await asyncio.to_thread(
|
|
subprocess.run,
|
|
[
|
|
sys.executable,
|
|
"-c",
|
|
code,
|
|
"source",
|
|
str(tmp_path),
|
|
str(tmp_path / "metadata"),
|
|
"image/png",
|
|
"40000000",
|
|
],
|
|
env={**os.environ, "IMAGE_MEMORY_MIB": "256", "IMAGE_CPU_SECONDS": "1"},
|
|
capture_output=True,
|
|
timeout=15,
|
|
)
|
|
assert result.returncode == (3 if failure == "memory" else -9)
|
|
assert not (tmp_path / "metadata").exists()
|
|
|
|
|
|
async def test_render_timeout_kills_child(monkeypatch, tmp_path):
|
|
create = asyncio.create_subprocess_exec
|
|
children = []
|
|
|
|
async def slow_child(*args, **kwargs):
|
|
child = await create(
|
|
sys.executable, "-c", "import time;time.sleep(60)", **kwargs
|
|
)
|
|
children.append(child)
|
|
return child
|
|
|
|
monkeypatch.setattr(asyncio, "create_subprocess_exec", slow_child)
|
|
work = JobWork(
|
|
uuid4(), uuid4(), uuid4(), 1, "staging/test", "image/png", 1, "0" * 64
|
|
)
|
|
with pytest.raises(TimeoutError):
|
|
async with asyncio.timeout(0.2):
|
|
await render_variants(MemoryStorage(), work, tmp_path / "source", tmp_path)
|
|
assert len(children) == 1 and children[0].returncode is not None
|