|
| 1 | +from pathlib import Path |
| 2 | + |
| 3 | +import pytest |
| 4 | +from PIL.Image import open as pilopen |
| 5 | + |
| 6 | +from zimscraperlib.image.illustration import get_zim_illustration |
| 7 | + |
| 8 | +COMMONS_IMAGE_PATH = (Path(__file__) / "../../files/commons.png").resolve() |
| 9 | +COMMONS_48_IMAGE_PATH = (Path(__file__) / "../../files/commons48.png").resolve() |
| 10 | +NINJA_IMAGE_PATH = (Path(__file__) / "../../files/ninja.webp").resolve() |
| 11 | + |
| 12 | + |
| 13 | +@pytest.mark.parametrize( |
| 14 | + "user_illustration, expected_max_filesize", |
| 15 | + [ |
| 16 | + pytest.param(COMMONS_IMAGE_PATH, 5000, id="big_commons"), |
| 17 | + pytest.param(COMMONS_48_IMAGE_PATH, 4000, id="small_commons"), |
| 18 | + pytest.param(NINJA_IMAGE_PATH, 5000, id="ninja"), |
| 19 | + pytest.param( |
| 20 | + "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4a/Commons-logo.svg/250px-Commons-logo.svg.png", |
| 21 | + 4000, |
| 22 | + id="png_url", |
| 23 | + ), |
| 24 | + pytest.param( |
| 25 | + "https://upload.wikimedia.org/wikipedia/commons/4/4a/Commons-logo.svg", |
| 26 | + 4000, |
| 27 | + id="svg_url", |
| 28 | + ), |
| 29 | + ], |
| 30 | +) |
| 31 | +def test_get_zim_illustration( |
| 32 | + user_illustration: str | Path, |
| 33 | + expected_max_filesize: int, |
| 34 | +): |
| 35 | + image = get_zim_illustration(user_illustration) |
| 36 | + assert len(image.getvalue()) < expected_max_filesize |
| 37 | + with pilopen(image) as image_details: |
| 38 | + assert image_details.format == "PNG" |
| 39 | + assert image_details.size == (48, 48) |
| 40 | + |
| 41 | + |
| 42 | +def test_get_missing_user_zim_illustration(): |
| 43 | + with pytest.raises(Exception, match="missing.png could not be found"): |
| 44 | + get_zim_illustration("./missing.png") |
| 45 | + |
| 46 | + |
| 47 | +def test_get_missing_default_zim_illustration(): |
| 48 | + with pytest.raises(Exception, match="Illustration is missing"): |
| 49 | + get_zim_illustration("") |
| 50 | + |
| 51 | + |
| 52 | +def test_get_zim_illustration_custom_size(): |
| 53 | + image = get_zim_illustration(NINJA_IMAGE_PATH, 96, 120) |
| 54 | + assert len(image.getvalue()) < 21000 |
| 55 | + with pilopen(image) as image_details: |
| 56 | + assert image_details.format == "PNG" |
| 57 | + assert image_details.size == (96, 120) |
| 58 | + |
| 59 | + |
| 60 | +def test_get_zim_illustration_method(): |
| 61 | + image_cover = get_zim_illustration(NINJA_IMAGE_PATH, resize_method="cover") |
| 62 | + image_contain = get_zim_illustration(NINJA_IMAGE_PATH, resize_method="contain") |
| 63 | + # cover image is always bigger than contain image size more pixels are |
| 64 | + # "used/non-transparent" |
| 65 | + assert len(image_cover.getvalue()) > len(image_contain.getvalue()) |
| 66 | + for image in [image_cover, image_contain]: |
| 67 | + with pilopen(image) as image_details: |
| 68 | + assert image_details.format == "PNG" |
| 69 | + assert image_details.size == (48, 48) |
0 commit comments