Skip to content

Commit

Permalink
Add checks for translation placeholders (home-assistant#129963)
Browse files Browse the repository at this point in the history
* Add checks for translation placeholders

* Remove async

* Apply suggestions from code review

* Apply suggestions from code review

* Apply suggestions from code review
  • Loading branch information
epenet authored Nov 7, 2024
1 parent 49bf5db commit a3ba780
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion tests/components/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from collections.abc import Callable, Generator
from importlib.util import find_spec
from pathlib import Path
import string
from typing import TYPE_CHECKING, Any
from unittest.mock import AsyncMock, MagicMock, patch

Expand Down Expand Up @@ -542,17 +543,40 @@ def supervisor_client() -> Generator[AsyncMock]:
yield supervisor_client


def _validate_translation_placeholders(
full_key: str,
translation: str,
description_placeholders: dict[str, str] | None,
) -> str | None:
"""Raise if translation exists with missing placeholders."""
tuples = list(string.Formatter().parse(translation))
for _, placeholder, _, _ in tuples:
if placeholder is None:
continue
if (
description_placeholders is None
or placeholder not in description_placeholders
):
pytest.fail(
f"Description not found for placeholder `{placeholder}` in {full_key}"
)


async def _ensure_translation_exists(
hass: HomeAssistant,
ignore_translations: dict[str, StoreInfo],
category: str,
component: str,
key: str,
description_placeholders: dict[str, str] | None,
) -> None:
"""Raise if translation doesn't exist."""
full_key = f"component.{component}.{category}.{key}"
translations = await async_get_translations(hass, "en", category, [component])
if full_key in translations:
if (translation := translations.get(full_key)) is not None:
_validate_translation_placeholders(
full_key, translation, description_placeholders
)
return

if full_key in ignore_translations:
Expand Down Expand Up @@ -610,6 +634,7 @@ async def _async_handle_step(
category,
component,
f"error.{error}",
result["description_placeholders"],
)
return result

Expand All @@ -624,6 +649,7 @@ async def _async_handle_step(
category,
component,
f"abort.{result["reason"]}",
result["description_placeholders"],
)

return result
Expand Down

0 comments on commit a3ba780

Please sign in to comment.