Files
chrnx-dev-wp/tests/assets/test_alter_ego_assets.py
T

313 lines
11 KiB
Python

import json
import shutil
import subprocess
import sys
from pathlib import Path
import pytest
from PIL import Image
PROJECT_ROOT = Path(__file__).resolve().parents[2]
ASSET_DIRECTORY = PROJECT_ROOT / "assets" / "images"
GENERATED_DIRECTORY = ASSET_DIRECTORY / "generated"
ALTER_EGO_ASSETS = (
"alter-ego-code.png",
"alter-ego-literature.png",
"alter-ego-research.png",
"alter-ego-podcasts.png",
"alter-ego-life.png",
"alter-ego-gaming.png",
)
ALTER_EGO_SOURCE_ASSETS = (*ALTER_EGO_ASSETS, "alter-ego-gaming-half-body.png")
BACKGROUND_ASSETS = ("podcast-frequency-grunge.png",)
PODCAST_DERIVATIVES = tuple(
f"podcast-frequency-grunge-{width}.{extension}"
for width in (384, 768, 1536)
for extension in ("avif", "webp")
)
PODCAST_MANIFEST = "podcast-frequency-grunge.json"
CONTACT_SHEET_SCRIPT = PROJECT_ROOT / "scripts" / "build-alter-ego-contact-sheet.py"
def _opaque_coverage(alpha: Image.Image) -> float:
return sum(alpha.histogram()[250:]) / (alpha.width * alpha.height)
def _load_verified_image(path: Path) -> Image.Image:
with Image.open(path) as image:
image.verify()
image = Image.open(path)
try:
image.load()
except Exception:
image.close()
raise
return image
def test_opaque_coverage_counts_near_opaque_alpha() -> None:
alpha = Image.new("L", (4, 1))
try:
alpha.putdata((0, 250, 255, 255))
assert _opaque_coverage(alpha) == 0.75
finally:
alpha.close()
def test_alter_ego_asset_inventory_and_image_contract() -> None:
expected = set(ALTER_EGO_SOURCE_ASSETS)
actual = {path.name for path in ASSET_DIRECTORY.glob("alter-ego-*.png")}
missing = [name for name in ALTER_EGO_SOURCE_ASSETS if name not in actual]
unexpected = sorted(actual - expected)
inventory_violations = [
*(f"missing assets/images/{name}" for name in missing),
*(f"unexpected assets/images/{name}" for name in unexpected),
]
assert not inventory_violations, "Alter ego asset inventory mismatch:\n" + "\n".join(
f"- {violation}" for violation in inventory_violations
)
violations: list[str] = []
for name in ALTER_EGO_SOURCE_ASSETS:
path = ASSET_DIRECTORY / name
with Image.open(path) as image:
if image.format != "PNG":
violations.append(f"{name}: expected PNG, got {image.format!r}")
if image.mode != "RGBA":
violations.append(f"{name}: expected RGBA, got {image.mode!r}")
width, height = image.size
if width < 1000 or height < 1200:
violations.append(
f"{name}: expected at least 1000x1200, got {width}x{height}"
)
if image.mode != "RGBA":
continue
with image.getchannel("A") as alpha:
alpha_extrema = alpha.getextrema()
if alpha_extrema != (0, 255):
violations.append(
f"{name}: expected alpha extrema (0, 255), got {alpha_extrema}"
)
corners = (
alpha.getpixel((0, 0)),
alpha.getpixel((width - 1, 0)),
alpha.getpixel((0, height - 1)),
alpha.getpixel((width - 1, height - 1)),
)
if corners != (0, 0, 0, 0):
violations.append(
f"{name}: expected four transparent corners, got {corners}"
)
opaque_coverage = _opaque_coverage(alpha)
if not 0.18 <= opaque_coverage <= 0.80:
violations.append(
f"{name}: opaque coverage {opaque_coverage:.4f} outside 0.18..0.80"
)
assert not violations, "Alter ego asset contract violations:\n" + "\n".join(
f"- {violation}" for violation in violations
)
def test_background_asset_inventory_and_image_contract() -> None:
assert BACKGROUND_ASSETS == ("podcast-frequency-grunge.png",)
missing = [
name for name in BACKGROUND_ASSETS if not (ASSET_DIRECTORY / name).is_file()
]
assert not missing, "Background asset inventory mismatch:\n" + "\n".join(
f"- missing assets/images/{name}" for name in missing
)
violations: list[str] = []
for name in BACKGROUND_ASSETS:
path = ASSET_DIRECTORY / name
with _load_verified_image(path) as image:
if image.format != "PNG":
violations.append(f"{name}: expected PNG, got {image.format!r}")
if image.mode not in {"RGB", "RGBA"}:
violations.append(f"{name}: expected RGB or RGBA, got {image.mode!r}")
width, height = image.size
if width < 1536 or height < 960:
violations.append(
f"{name}: expected at least 1536x960, got {width}x{height}"
)
aspect_ratio = width / height
if not 1.35 <= aspect_ratio <= 1.7:
violations.append(
f"{name}: aspect ratio {aspect_ratio:.4f} outside 1.35..1.7"
)
assert not violations, "Background asset contract violations:\n" + "\n".join(
f"- {violation}" for violation in violations
)
def test_podcast_responsive_derivative_inventory_manifest_and_budgets() -> None:
generated_names = sorted(path.name for path in GENERATED_DIRECTORY.iterdir())
assert len(generated_names) == 52, (
f"generated inventory expected 52 files, got {len(generated_names)}"
)
for name in (*PODCAST_DERIVATIVES, PODCAST_MANIFEST):
assert name in generated_names, f"missing {name}"
manifest = json.loads((GENERATED_DIRECTORY / PODCAST_MANIFEST).read_text())
assert manifest == {
"source": "podcast-frequency-grunge.png",
"formats": ["avif", "webp"],
"widths": [384, 768, 1536],
}
family_total = 0
for name in PODCAST_DERIVATIVES:
size = (GENERATED_DIRECTORY / name).stat().st_size
width = int(name.rsplit("-", 1)[1].split(".", 1)[0])
limit = 260 * 1024 if width == 1536 else 160 * 1024
assert size <= limit, f"{name} exceeds {limit} bytes: {size} bytes"
family_total += size
assert family_total <= 620 * 1024, (
"podcast-frequency-grunge family exceeds 620 KiB: "
f"{family_total} total bytes"
)
binary_total = sum(
path.stat().st_size
for path in GENERATED_DIRECTORY.iterdir()
if path.suffix in {".avif", ".webp"}
)
assert binary_total <= 2.75 * 1024 * 1024, (
f"generated binary payload exceeds 2.75 MiB: {binary_total} total bytes"
)
def test_background_contract_rejects_corrupt_idat_data(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
path = tmp_path / BACKGROUND_ASSETS[0]
image = Image.new("RGB", (1536, 960), (13, 17, 23))
try:
image.save(path)
finally:
image.close()
corrupt_png = bytearray(path.read_bytes())
idat_type_offset = corrupt_png.index(b"IDAT")
idat_length = int.from_bytes(
corrupt_png[idat_type_offset - 4 : idat_type_offset], "big"
)
assert idat_length > 0
corrupt_png[idat_type_offset + 4 + (idat_length // 2)] ^= 0x01
path.write_bytes(corrupt_png)
monkeypatch.setattr(sys.modules[__name__], "ASSET_DIRECTORY", tmp_path)
with pytest.raises((OSError, SyntaxError)):
test_background_asset_inventory_and_image_contract()
def test_gaming_half_body_preserves_original_and_has_prominent_visible_alpha() -> None:
original = ASSET_DIRECTORY / "alter-ego-gaming.png"
half_body = ASSET_DIRECTORY / "alter-ego-gaming-half-body.png"
assert original.read_bytes() != half_body.read_bytes()
with Image.open(original) as original_image, Image.open(half_body) as half_body_image:
assert original_image.size == half_body_image.size == (1024, 1536)
original_box = original_image.getchannel("A").point(
lambda value: 255 if value >= 16 else 0
).getbbox()
half_body_box = half_body_image.getchannel("A").point(
lambda value: 255 if value >= 16 else 0
).getbbox()
assert original_box == (170, 54, 882, 1475)
assert half_body_box == (15, 79, 948, 1536)
assert (half_body_box[2] - half_body_box[0]) / 1024 >= 0.90
def _install_contact_sheet_script(project_root: Path) -> Path:
assert CONTACT_SHEET_SCRIPT.is_file(), (
f"Missing contact-sheet script: {CONTACT_SHEET_SCRIPT}"
)
script = project_root / "scripts" / CONTACT_SHEET_SCRIPT.name
script.parent.mkdir(parents=True)
shutil.copyfile(CONTACT_SHEET_SCRIPT, script)
return script
def test_contact_sheet_cli_reports_every_missing_input(tmp_path: Path) -> None:
script = _install_contact_sheet_script(tmp_path)
result = subprocess.run(
[sys.executable, str(script)],
cwd=tmp_path,
capture_output=True,
text=True,
check=False,
)
assert result.returncode != 0
for name in ALTER_EGO_ASSETS:
assert f"assets/images/{name}" in result.stderr
assert not (tmp_path / "docs/visual-reviews/alter-ego-v1.png").exists()
def test_contact_sheet_cli_uses_fixed_order_and_deterministic_layout(
tmp_path: Path,
) -> None:
script = _install_contact_sheet_script(tmp_path)
asset_directory = tmp_path / "assets" / "images"
asset_directory.mkdir(parents=True)
colors = (
(210, 45, 45, 255),
(45, 180, 75, 255),
(55, 95, 220, 255),
(220, 150, 40, 255),
(155, 65, 205, 255),
(40, 185, 195, 255),
)
for name, color in zip(ALTER_EGO_ASSETS, colors, strict=True):
image = Image.new("RGBA", (1000, 1200), (0, 0, 0, 0))
try:
image.paste(color, (200, 200, 800, 1000))
image.save(asset_directory / name)
finally:
image.close()
first = subprocess.run(
[sys.executable, str(script)],
cwd=tmp_path,
capture_output=True,
text=True,
check=False,
)
assert first.returncode == 0, first.stderr
output = tmp_path / "docs" / "visual-reviews" / "alter-ego-v1.png"
first_bytes = output.read_bytes()
second = subprocess.run(
[sys.executable, str(script)],
cwd=tmp_path,
capture_output=True,
text=True,
check=False,
)
assert second.returncode == 0, second.stderr
assert output.read_bytes() == first_bytes
with Image.open(output) as sheet:
assert sheet.mode == "RGB"
assert sheet.size == (704, 2664)
for row, color in enumerate(colors):
center_y = 248 + (row * 440)
assert sheet.getpixel((184, center_y)) == color[:3]
assert sheet.getpixel((520, center_y)) == color[:3]
assert sheet.getpixel((40, 72)) == (13, 17, 23)
assert sheet.getpixel((376, 72)) == (246, 242, 233)