Validate brand images of integrations in hassfest (#187957)

This commit is contained in:
Evan Severson
2026-11-03 22:22:37 +00:00
committed by GitHub
parent 8fc92d145b
commit f62cea6480
6 changed files with 395 additions and 3 deletions
+156
View File
@@ -0,0 +1,156 @@
"""Validate the brand images an integration ships in its brand folder."""
from pathlib import Path
import struct
from .model import Config, Integration
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
# Signature, then the IHDR chunk: length, type, 13 bytes of data and its CRC.
PNG_HEADER_SIZE = 33
IHDR_START = b"\x00\x00\x00\x0dIHDR"
# Mirrors homeassistant.components.brands.const; the package can't import Core, and a
# Core test keeps both in sync.
ALLOWED_IMAGES = frozenset(
{
"icon.png",
"logo.png",
"icon@2x.png",
"logo@2x.png",
"dark_icon.png",
"dark_logo.png",
"dark_icon@2x.png",
"dark_logo@2x.png",
}
)
IMAGE_FALLBACKS = {
"logo.png": ["icon.png"],
"icon@2x.png": ["icon.png"],
"logo@2x.png": ["logo.png", "icon.png"],
"dark_icon.png": ["icon.png"],
"dark_logo.png": ["dark_icon.png", "logo.png", "icon.png"],
"dark_icon@2x.png": ["icon@2x.png", "icon.png"],
"dark_logo@2x.png": ["dark_icon@2x.png", "logo@2x.png", "logo.png", "icon.png"],
}
# Same size rules as the home-assistant/brands repository; dark_ variants share them.
ICON_SIZE = {"icon.png": 256, "icon@2x.png": 512}
LOGO_SHORTEST_SIDE = {"logo.png": (128, 256), "logo@2x.png": (256, 512)}
def _report(integration: Integration, message: str) -> None:
"""Report a problem: an error for core, a warning for custom integrations.
Custom integrations get warnings so existing repositories don't start failing.
"""
integration.add_warning_or_error(not integration.core, "brand_images", message)
def _png_size(path: Path) -> tuple[int, int] | None:
"""Return the width and height from a PNG header, or None if it is no PNG."""
with path.open("rb") as file:
header = file.read(PNG_HEADER_SIZE)
if (
len(header) < PNG_HEADER_SIZE
or header[:8] != PNG_SIGNATURE
or header[8:16] != IHDR_START
):
return None
width, height = struct.unpack(">II", header[16:24])
return width, height
def _validate_size(integration: Integration, image: str, size: tuple[int, int]) -> None:
"""Validate the dimensions of a brand image."""
base = image.removeprefix("dark_")
width, height = size
if base in ICON_SIZE:
expected = ICON_SIZE[base]
if size != (expected, expected):
_report(
integration,
f"brand/{image} is {width}x{height}, but must be {expected}x{expected}",
)
return
low, high = LOGO_SHORTEST_SIDE[base]
if not low <= min(size) <= high:
_report(
integration,
f"brand/{image} is {width}x{height}, but its shortest side must be"
f" between {low} and {high} pixels",
)
def _served(images: dict[str, Path], image: str) -> Path | None:
"""Return the file the brands integration serves for an image, if any."""
return next(
(
images[name]
for name in (image, *IMAGE_FALLBACKS.get(image, ()))
if name in images
),
None,
)
def _redundant_fallback(images: dict[str, Path], image: str) -> str | None:
"""Return the fallback an image duplicates, if removing it changes nothing."""
fallback = next(
(name for name in IMAGE_FALLBACKS.get(image, ()) if name in images), None
)
if fallback is None or images[fallback].read_bytes() != images[image].read_bytes():
return None
# An @2x image requires its normal-resolution companion.
if image.replace(".png", "@2x.png") in images:
return None
remaining = {name: path for name, path in images.items() if name != image}
for other in sorted(ALLOWED_IMAGES):
before, after = _served(images, other), _served(remaining, other)
if before and after and before.read_bytes() != after.read_bytes():
return None
return fallback
def _validate_brand_folder(integration: Integration, brand_dir: Path) -> None:
"""Validate the brand folder of an integration."""
images: dict[str, Path] = {}
for path in sorted(brand_dir.iterdir()):
if path.is_file():
images[path.name] = path
else:
_report(integration, f"brand/{path.name} is not a file")
for name in sorted(images.keys() - ALLOWED_IMAGES):
_report(
integration,
f"brand/{name} is not a brand image Home Assistant uses, allowed are:"
f" {', '.join(sorted(ALLOWED_IMAGES))}",
)
for image in sorted(images.keys() & ALLOWED_IMAGES):
if (size := _png_size(images[image])) is None:
_report(integration, f"brand/{image} is not a PNG image")
continue
_validate_size(integration, image, size)
if "@2x" in image and image.replace("@2x", "") not in images:
_report(
integration,
f"brand/{image} is provided, but brand/{image.replace('@2x', '')}"
" is missing",
)
if (fallback := _redundant_fallback(images, image)) is not None:
_report(
integration,
f"brand/{image} is identical to brand/{fallback}, which is used"
f" when brand/{image} is missing, remove brand/{image}",
)
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Validate the brand folders of all integrations."""
for integration in integrations.values():
if (brand_dir := integration.path / "brand").is_dir():
_validate_brand_folder(integration, brand_dir)
+1 -1
View File
@@ -5,7 +5,7 @@ from types import ModuleType
from .model import Config
INTEGRATION_PLUGINS = ["codeowners", "json"]
INTEGRATION_PLUGINS = ["brand_images", "codeowners", "json"]
def load_plugins(config: Config) -> list[ModuleType]:
+10 -1
View File
@@ -1,8 +1,10 @@
"""Fixtures for the shared hassfest package."""
from collections.abc import Generator
from pathlib import Path
from unittest.mock import patch
from hassfest.model import Config
from hassfest.model import Config, Integration
import pytest
@@ -15,3 +17,10 @@ def config(tmp_path: Path) -> Config:
action="validate",
requirements=False,
)
@pytest.fixture
def mock_core_integration() -> Generator[None]:
"""Mock Integration to be a core one."""
with patch.object(Integration, "core", return_value=True):
yield
@@ -0,0 +1,213 @@
"""Tests for hassfest brand_images."""
from pathlib import Path
import struct
import zlib
from hassfest import brand_images
from hassfest.model import Config, Integration
import pytest
def _png(width: int, height: int, content: bytes = b"") -> bytes:
"""Return a PNG header with the given size, followed by some content."""
ihdr = b"IHDR" + struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)
return (
brand_images.PNG_SIGNATURE
+ struct.pack(">I", 13)
+ ihdr
+ struct.pack(">I", zlib.crc32(ihdr))
+ content
)
def _validate(tmp_path: Path, config: Config, files: dict[str, bytes]) -> Integration:
"""Write a brand folder and validate it."""
brand_dir = tmp_path / "test" / "brand"
brand_dir.mkdir(parents=True)
for name, data in files.items():
(brand_dir / name).write_bytes(data)
integration = Integration(
tmp_path / "test",
_config=config,
_manifest={"domain": "test", "name": "Test"},
)
brand_images.validate({"test": integration}, config)
return integration
@pytest.mark.parametrize(
"files",
[
pytest.param({"icon.png": _png(256, 256)}, id="icon_only"),
pytest.param(
{
"icon.png": _png(256, 256),
"icon@2x.png": _png(512, 512),
"logo.png": _png(400, 128),
"logo@2x.png": _png(800, 256),
"dark_icon.png": _png(256, 256, b"dark"),
"dark_logo.png": _png(400, 128, b"dark"),
},
id="full_set",
),
pytest.param({"logo.png": _png(256, 600)}, id="tall_logo"),
pytest.param(
{
"icon.png": _png(256, 256),
"dark_icon.png": _png(256, 256, b"dark"),
"dark_logo.png": _png(256, 256),
},
# dark_icon.png is served when dark_logo.png is missing, not icon.png.
id="identical_to_later_fallback",
),
pytest.param(
{
"icon.png": _png(256, 256),
"dark_icon.png": _png(256, 256),
"logo.png": _png(400, 128),
},
# Removing dark_icon.png would serve logo.png as the dark logo.
id="duplicate_serves_other_fallback",
),
pytest.param(
{
"icon.png": _png(256, 256),
"dark_icon.png": _png(256, 256),
"dark_icon@2x.png": _png(512, 512),
},
# dark_icon@2x.png requires dark_icon.png.
id="duplicate_has_2x_companion",
),
],
)
def test_valid_brand_folder(
tmp_path: Path, config: Config, files: dict[str, bytes]
) -> None:
"""Test valid brand folders."""
integration = _validate(tmp_path, config, files)
assert integration.errors == []
assert integration.warnings == []
def test_no_brand_folder(tmp_path: Path, config: Config) -> None:
"""Test an integration without a brand folder."""
(tmp_path / "test").mkdir()
integration = Integration(
tmp_path / "test",
_config=config,
_manifest={"domain": "test", "name": "Test"},
)
brand_images.validate({"test": integration}, config)
assert integration.errors == []
@pytest.mark.parametrize(
("files", "error"),
[
pytest.param(
{"icon.png": _png(512, 512)},
"brand/icon.png is 512x512, but must be 256x256",
id="icon_size",
),
pytest.param(
{"icon.png": _png(256, 256), "icon@2x.png": _png(256, 256, b"other")},
"brand/icon@2x.png is 256x256, but must be 512x512",
id="hdpi_icon_size",
),
pytest.param(
{"icon.png": _png(256, 256), "logo.png": _png(600, 100)},
"brand/logo.png is 600x100, but its shortest side must be between 128"
" and 256 pixels",
id="logo_too_small",
),
pytest.param(
{"logo.png": _png(400, 128), "logo@2x.png": _png(1200, 600)},
"brand/logo@2x.png is 1200x600, but its shortest side must be between 256"
" and 512 pixels",
id="hdpi_logo_too_large",
),
pytest.param(
{"icon@2x.png": _png(512, 512)},
"brand/icon@2x.png is provided, but brand/icon.png is missing",
id="hdpi_without_normal",
),
pytest.param(
{"icon.png": _png(256, 256), "dark_icon.png": _png(256, 256)},
"brand/dark_icon.png is identical to brand/icon.png, which is used when"
" brand/dark_icon.png is missing, remove brand/dark_icon.png",
id="dark_identical_to_light",
),
pytest.param(
{"icon.png": _png(256, 256), "logo.png": _png(256, 256)},
"brand/logo.png is identical to brand/icon.png, which is used when"
" brand/logo.png is missing, remove brand/logo.png",
id="logo_identical_to_icon",
),
pytest.param(
{"icon.png": b"<svg></svg>"},
"brand/icon.png is not a PNG image",
id="not_png",
),
pytest.param(
{"icon.png": _png(256, 256)[:18]},
"brand/icon.png is not a PNG image",
id="truncated_png",
),
pytest.param(
{"icon.png": _png(256, 256)[:24]},
"brand/icon.png is not a PNG image",
id="truncated_ihdr",
),
pytest.param(
{
"icon.png": brand_images.PNG_SIGNATURE
+ struct.pack(">I", 12)
+ _png(256, 256)[12:]
},
"brand/icon.png is not a PNG image",
id="malformed_ihdr_length",
),
pytest.param(
{"icon.png": _png(256, 256), "icon.svg": b"<svg></svg>"},
"brand/icon.svg is not a brand image Home Assistant uses, allowed are:"
" dark_icon.png, dark_icon@2x.png, dark_logo.png, dark_logo@2x.png,"
" icon.png, icon@2x.png, logo.png, logo@2x.png",
id="unknown_file",
),
],
)
def test_invalid_brand_folder(
tmp_path: Path, config: Config, files: dict[str, bytes], error: str
) -> None:
"""Test invalid brand folders of custom integrations only warn."""
integration = _validate(tmp_path, config, files)
assert integration.errors == []
assert [warning.error for warning in integration.warnings] == [error]
@pytest.mark.usefixtures("mock_core_integration")
def test_invalid_brand_folder_core(tmp_path: Path, config: Config) -> None:
"""Test invalid brand folders of core integrations are errors."""
integration = _validate(tmp_path, config, {"icon.png": _png(512, 512)})
assert integration.warnings == []
assert [error.error for error in integration.errors] == [
"brand/icon.png is 512x512, but must be 256x256"
]
def test_directory_in_brand_folder(tmp_path: Path, config: Config) -> None:
"""Test a directory in the brand folder is reported instead of read."""
brand_dir = tmp_path / "test" / "brand"
(brand_dir / "icon.png").mkdir(parents=True)
(brand_dir / "logo.png").write_bytes(_png(400, 128))
integration = Integration(
tmp_path / "test",
_config=config,
_manifest={"domain": "test", "name": "Test"},
)
brand_images.validate({"test": integration}, config)
assert integration.errors == []
assert [warning.error for warning in integration.warnings] == [
"brand/icon.png is not a file"
]
+4 -1
View File
@@ -8,6 +8,7 @@ from hassfest.model import Config
INTEGRATION_PLUGINS = [
"application_credentials",
"bluetooth",
"brand_images",
"codeowners",
"conditions",
"config_schema",
@@ -46,7 +47,9 @@ CORE_PLUGINS = [
ALL_PLUGIN_NAMES = [*INTEGRATION_PLUGINS, *CORE_PLUGINS]
LOCAL_PLUGINS = {
name: f"{__package__}.{name}" for name in ALL_PLUGIN_NAMES if name != "json"
name: f"{__package__}.{name}"
for name in ALL_PLUGIN_NAMES
if name not in ("brand_images", "json")
}
@@ -0,0 +1,11 @@
"""Tests for the brand image validation in Core."""
from hassfest import brand_images
from homeassistant.components.brands import ALLOWED_IMAGES, IMAGE_FALLBACKS
def test_constants_match_brands_integration() -> None:
"""Test the package validates the same images and fallbacks as the brands view."""
assert brand_images.ALLOWED_IMAGES == ALLOWED_IMAGES
assert brand_images.IMAGE_FALLBACKS == IMAGE_FALLBACKS