From a3ba7803db895b5e083c7f7d84fd3bb0e70bad25 Mon Sep 17 00:00:00 2001 From: epenet <6771947+epenet@users.noreply.github.com> Date: Thu, 7 Nov 2024 13:12:00 +0100 Subject: [PATCH] Add checks for translation placeholders (#129963) * Add checks for translation placeholders * Remove async * Apply suggestions from code review * Apply suggestions from code review * Apply suggestions from code review --- tests/components/conftest.py | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/tests/components/conftest.py b/tests/components/conftest.py index 1ec656d44c5a2e..00738cd252fc2e 100644 --- a/tests/components/conftest.py +++ b/tests/components/conftest.py @@ -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 @@ -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: @@ -610,6 +634,7 @@ async def _async_handle_step( category, component, f"error.{error}", + result["description_placeholders"], ) return result @@ -624,6 +649,7 @@ async def _async_handle_step( category, component, f"abort.{result["reason"]}", + result["description_placeholders"], ) return result