81 lines
2.6 KiB
Python
81 lines
2.6 KiB
Python
import io
|
||
|
||
import pytest
|
||
from PIL import Image
|
||
|
||
from app.exceptions.invalid_image_exception import InvalidImageException
|
||
from app.moderation.image.loader import CorruptImageError, load_image
|
||
from app.moderation.image.validator import ImageValidator
|
||
from tests.conftest import image_bytes, png_header_only
|
||
|
||
validator = ImageValidator()
|
||
|
||
|
||
@pytest.mark.parametrize("fmt", ["JPEG", "PNG", "WEBP"])
|
||
def test_loads_allowed_formats_as_rgb(fmt):
|
||
image = load_image(image_bytes(fmt=fmt), validator)
|
||
assert image.mode == "RGB"
|
||
assert image.size == (200, 150)
|
||
|
||
|
||
def test_large_photo_is_downscaled_to_max_side():
|
||
image = load_image(image_bytes(size=(4000, 3000)), validator, max_side=1280)
|
||
assert max(image.size) == 1280
|
||
assert image.size == (1280, 960)
|
||
|
||
|
||
def test_exif_rotation_is_applied():
|
||
exif = Image.Exif()
|
||
exif[0x0112] = 6 # Orientation: повернуть на 90°
|
||
data = image_bytes(size=(200, 100), exif=exif.tobytes())
|
||
assert load_image(data, validator).size == (100, 200)
|
||
|
||
|
||
def test_transparent_pixels_become_white_not_hidden_rgb():
|
||
data = image_bytes(fmt="PNG", mode="RGBA", color=(255, 0, 0, 0))
|
||
image = load_image(data, validator)
|
||
assert image.getpixel((10, 10)) == (255, 255, 255)
|
||
|
||
|
||
def test_garbage_is_rejected():
|
||
with pytest.raises(CorruptImageError):
|
||
load_image(b"definitely not an image", validator)
|
||
|
||
|
||
def test_disallowed_format_is_rejected_even_if_valid():
|
||
with pytest.raises(CorruptImageError):
|
||
load_image(image_bytes(fmt="GIF", mode="P", color=1), validator)
|
||
|
||
|
||
def test_truncated_jpeg_is_client_error_not_500():
|
||
data = image_bytes(size=(800, 600))
|
||
with pytest.raises(CorruptImageError):
|
||
load_image(data[: len(data) // 2], validator)
|
||
|
||
|
||
def test_too_small_image_is_rejected():
|
||
with pytest.raises(InvalidImageException):
|
||
load_image(image_bytes(size=(10, 10)), validator)
|
||
|
||
|
||
def test_extreme_aspect_ratio_is_rejected():
|
||
with pytest.raises(InvalidImageException):
|
||
load_image(image_bytes(size=(60, 3000), fmt="PNG"), validator)
|
||
|
||
|
||
def test_pixel_bomb_over_limit_rejected_before_decoding():
|
||
# 9000×9000 = 81 Мп: в пределах MAX_WIDTH/HEIGHT, но больше MAX_IMAGE_PIXELS
|
||
with pytest.raises(InvalidImageException):
|
||
load_image(png_header_only(9000, 9000), validator)
|
||
|
||
|
||
def test_huge_pixel_bomb_rejected_by_pillow_guard():
|
||
with pytest.raises((CorruptImageError, InvalidImageException)):
|
||
load_image(png_header_only(60000, 60000), validator)
|
||
|
||
|
||
def test_validator_works_on_lazy_image_without_decoding():
|
||
image = Image.open(io.BytesIO(png_header_only(9000, 9000)))
|
||
with pytest.raises(InvalidImageException):
|
||
validator.validate(image)
|