Files
mtusi2026lab2/student-tests/unit/test_png_memory.py
T

111 lines
3.9 KiB
Python

import json
import subprocess
import sys
import weakref
from pathlib import Path
import pytest
from PIL import Image, ImageFile
from PIL._util import DeferredError
from messenger.attachments.infrastructure.images import RenderLimits, render_variants
from png_trns_fixtures import boundary_png, png_with_trns
CASES = [(2, (1,)), (4, (5,)), (16, (12345,)), (16, (12345, 23456, 34567))]
LIMITS = RenderLimits(10_485_760, 40_000_000)
SAMPLE = Path(__file__).parents[2] / "tests/fixtures/sample.png"
@pytest.mark.parametrize("depth,key", CASES)
def test_live_pixel_buffers_are_bounded(
monkeypatch: pytest.MonkeyPatch, depth: int, key: tuple[int, ...]
) -> None:
size = (1025, 769)
data, reference = png_with_trns(depth, key, size=size)
expected = render_variants(reference, LIMITS)
references: dict[int, weakref.ReferenceType[Image.Image]] = {}
peak = 0
original_new = Image.Image._new
original_load = ImageFile.ImageFile.load_prepare
def record(image: Image.Image) -> None:
nonlocal peak
references[id(image)] = weakref.ref(image)
buffers = {}
for ref in references.values():
current = ref()
if current is None or current._im is None or isinstance(current._im, DeferredError):
continue
stride = 1 if current.mode in {"1", "L", "P"} else 4
if current.mode.startswith("I;16"):
stride = 2
buffers[id(current.im)] = current.width * current.height * stride
peak = max(peak, sum(buffers.values()))
def allocated(image: Image.Image, core: Image.core.ImagingCore) -> Image.Image:
result = original_new(image, core)
record(result)
return result
def loaded(image: ImageFile.ImageFile) -> None:
original_load(image)
record(image)
monkeypatch.setattr(Image.Image, "_new", allocated)
monkeypatch.setattr(ImageFile.ImageFile, "load_prepare", loaded)
assert render_variants(data, LIMITS) == expected
assert peak < size[0] * size[1] * 8 + 2**20, peak
print(json.dumps({"depth": depth, "key": key, "pixel_buffer_peak_bytes": peak}))
@pytest.mark.skipif(sys.platform != "linux", reason="RLIMIT_AS проверяется в Linux")
def test_boundary_pngs_fit_worker_address_space(tmp_path: Path) -> None:
script = """
import json
from io import BytesIO
from pathlib import Path
import resource
import signal
import sys
import messenger.worker
from PIL import Image
from messenger.attachments.infrastructure.images import RenderLimits, render_variants
resource.setrlimit(resource.RLIMIT_AS, (448 << 20, 448 << 20))
limits = RenderLimits(10_485_760, 40_000_000)
for version in (1, 2):
signal.alarm(30)
variants = render_variants(Path(sys.argv[1]).read_bytes(), limits, version)
signal.alarm(0)
assert [(v.name, v.width, v.height) for v in variants] == [
("thumbnail", 256, 160), ("crop", 128, 128), ("optimized", 1280, 800)
]
for variant in variants:
with Image.open(BytesIO(variant.data)) as image:
assert image.getpixel((5, image.height // 2)) == (255, 255, 255)
assert image.getpixel((image.width - 6, image.height // 2)) != (255, 255, 255)
assert len(render_variants(Path(sys.argv[2]).read_bytes(), limits)) == 3
print(json.dumps({
"versions": [1, 2], "max_rss_kib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
}))
"""
for name, (depth, key) in zip(("gray2", "gray4", "gray16", "rgb16"), CASES, strict=True):
fixture = tmp_path / f"{name}-40mp.png"
fixture.write_bytes(boundary_png(depth, key))
result = subprocess.run(
[
sys.executable,
"-c",
script,
str(fixture),
str(SAMPLE),
],
capture_output=True,
text=True,
timeout=65,
check=True,
)
assert json.loads(result.stdout)["versions"] == [1, 2]
print(name, result.stdout.strip())