From f9218ae59ec50abeddcd2195bf119e3ec08b8dcd Mon Sep 17 00:00:00 2001 From: matejcik Date: Tue, 19 Nov 2024 11:27:48 +0100 Subject: [PATCH] feat(tests): raise a warning for a translation not found in language we need to propagate stacklevel so that the warning is emitted at the usage line instead of deep in translations.py i mean we don't _need_ need to it's just nicer --- tests/translations.py | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/tests/translations.py b/tests/translations.py index 2bf3489894..a1ab531294 100644 --- a/tests/translations.py +++ b/tests/translations.py @@ -1,6 +1,7 @@ import json import re import threading +import warnings import typing as t from hashlib import sha256 from pathlib import Path @@ -93,20 +94,24 @@ class Translation: def translations(self) -> dict[str, str]: return self.lang_json["translations"] - def _translate_raw(self, key: str) -> str: + def _translate_raw(self, key: str, _stacklevel: int = 0) -> str: tr = self.translations.get(key) if tr is not None: return tr if self.lang != "en": + warnings.warn( + f"Translation key '{key}' not found in '{self.lang}' translation file", + stacklevel=_stacklevel + 2, + ) return TRANSLATIONS["en"]._translate_raw(key) raise KeyError(key) - def translate(self, key: str) -> str: - tr = self._translate_raw(key) + def translate(self, key: str, _stacklevel: int = 0) -> str: + tr = self._translate_raw(key, _stacklevel=_stacklevel + 1) return tr.replace("\xa0", " ").strip() - def as_regexp(self, key: str) -> re.Pattern: - tr = self.translate(key) + def as_regexp(self, key: str, _stacklevel: int = 0) -> re.Pattern: + tr = self.translate(key, _stacklevel=_stacklevel + 1) re_safe = re.escape(tr) return re.compile(self.FORMAT_STR_RE.sub(r".*?", re_safe)) @@ -114,13 +119,13 @@ class Translation: TRANSLATIONS = {lang: Translation(lang) for lang in LANGUAGES} -def translate(key: str) -> str: - return _CURRENT_TRANSLATION.TR.translate(key) +def translate(key: str, _stacklevel: int = 0) -> str: + return _CURRENT_TRANSLATION.TR.translate(key, _stacklevel=_stacklevel + 1) def regexp(key: str) -> re.Pattern: - return _CURRENT_TRANSLATION.TR.as_regexp(key) + return _CURRENT_TRANSLATION.TR.as_regexp(key, _stacklevel=1) def __getattr__(key: str) -> str: - return translate(key) + return translate(key, _stacklevel=1)