D19: единый язык пользовательских сообщений — русский

Переведены все английские тексты, которые видит пользователь:
13 сообщений исключений (ExcelRepositoryError, CurrencyError,
ForecastError, ValueError в domain/ и from_dict) и 7 сообщений
pydantic-валидаторов. What-if описание сценария — по-русски.

fail_validation() срезает английский префикс pydantic «Value error, »
и берёт запасную подпись поля из нового ключа global.value (ключи
i18n не переименованы, en.py не тронут).

Инвариант tests/test_language.py: словарь ru, тексты raise(...) и
прямые строковые литералы console.print не содержат английских
маркеров; end-to-end проверки ошибок export/import/валидации.
This commit is contained in:
oqyude committed 2026-10-25 19:50:31 +03:00
1 parent d2d301f8c4
commit 7aed61f21b
16 files changed
+230 -33

No files matched your search

+186
View File
@@ -0,0 +1,186 @@
"""D19: пользовательские сообщения — только на русском.
Инвариант проверяет три источника пользовательского текста:
1. словарь `infrastructure/i18n/ru.py` — всё, что CLI печатает через `t()`;
2. тексты исключений в `application/`, `domain/`, `infrastructure/` — их
пользователь видит в выводе команд (`cmd.export.err`, `cmd.import.err`,
`global.validation_error`);
3. строковые литералы, которые печатаются напрямую (`console.print`,
`typer.echo`, `print_ok`/`print_error`/`print_warning`).
Технические тексты (docstring'и, комментарии, имена в тестах) вне охвата D19.
"""
import ast
import re
from pathlib import Path
from infrastructure.i18n.ru import MESSAGES as RU_MESSAGES
REPO_ROOT = Path(__file__).resolve().parent.parent
SOURCE_DIRS = ("application", "domain", "infrastructure")
# Типичные маркеры английского сообщения (D19).
ENGLISH_MARKERS = ("not found", "error", "invalid", "failed", "cannot", "must be")
# Плейсхолдеры шаблонов — это имена подстановок, а не английский текст.
# `{error}` содержит слово «error», но пользователь видит вместо него
# сообщение исключения.
ALLOWED_PLACEHOLDERS = ("{error}",)
# Английские вкрапления, которым разрешено оставаться: имя продукта и
# технические идентификаторы (коды валют, имена сценариев, пути, имена
# листов Excel, коды выхода). Сравниваются как подстроки.
ALLOWED_LATIN_RUNS = (
"CashFlow Forecast", # имя продукта в app.help
)
_PRINT_FUNCS = {"print", "console.print", "typer.echo", "print_ok", "print_error", "print_warning"}
_MARKER_RE = re.compile(r"\b(?:" + "|".join(re.escape(m) for m in ENGLISH_MARKERS) + r")\b")
_LATIN_RUN_RE = re.compile(r"\b[A-Za-z]{2,}(?:[ \t]+[A-Za-z]{2,})+\b")
def _source_files() -> list[Path]:
return sorted(path for directory in SOURCE_DIRS for path in (REPO_ROOT / directory).rglob("*.py"))
def _constant_parts(node: ast.AST) -> list[str]:
"""Строковые литералы выражения: `Constant` и константные части f-строки."""
if isinstance(node, ast.Constant) and isinstance(node.value, str):
return [node.value]
if isinstance(node, ast.JoinedStr):
return [part.value for part in node.values if isinstance(part, ast.Constant) and isinstance(part.value, str)]
return []
def _exception_messages() -> list[tuple[str, str]]:
"""(файл:строка, текст) для каждого `raise ...("...")` в исходниках."""
found = []
for path in _source_files():
tree = ast.parse(path.read_text(encoding="utf-8"))
for node in ast.walk(tree):
if not isinstance(node, ast.Raise) or not isinstance(node.exc, ast.Call):
continue
for arg in node.exc.args:
for text in _constant_parts(arg):
found.append((f"{path.relative_to(REPO_ROOT)}:{node.lineno}", text))
return found
def _printed_literals() -> list[tuple[str, str]]:
"""(файл:строка, текст) для строковых литералов, печатаемых напрямую."""
found = []
for path in _source_files():
tree = ast.parse(path.read_text(encoding="utf-8"))
for node in ast.walk(tree):
if not isinstance(node, ast.Call):
continue
if ast.unparse(node.func) not in _PRINT_FUNCS:
continue
for arg in node.args:
for text in _constant_parts(arg):
found.append((f"{path.relative_to(REPO_ROOT)}:{node.lineno}", text))
return found
def _strip_allowed(text: str) -> str:
for placeholder in ALLOWED_PLACEHOLDERS:
text = text.replace(placeholder, "")
return text
def _english_markers(text: str) -> list[str]:
return _MARKER_RE.findall(_strip_allowed(text).lower())
def _unexpected_latin_runs(text: str) -> list[str]:
"""Последовательности из двух и более латинских слов — признак английской фразы."""
cleaned = _strip_allowed(text)
for allowed in ALLOWED_LATIN_RUNS:
cleaned = cleaned.replace(allowed, "")
return _LATIN_RUN_RE.findall(cleaned)
def _assert_russian(messages: list[tuple[str, str]]) -> None:
bad = [f"{where}: {text!r} (маркеры: {markers})" for where, text in messages if (markers := _english_markers(text))]
assert not bad, "Английские маркеры в пользовательских сообщениях:\n" + "\n".join(bad)
runs = [
f"{where}: {text!r} (английская фраза: {found})"
for where, text in messages
if (found := _unexpected_latin_runs(text))
]
assert not runs, "Английские фразы в пользовательских сообщениях:\n" + "\n".join(runs)
def _is_english(text: str) -> bool:
return bool(_english_markers(text) or _unexpected_latin_runs(text))
class TestUserFacingMessagesAreRussian:
def test_i18n_dictionary_is_russian(self):
_assert_russian([(f"ru.py:{key}", text) for key, text in RU_MESSAGES.items()])
def test_exception_messages_are_russian(self):
messages = _exception_messages()
assert len(messages) >= 15, "Список исключений опустел — проверьте сборщик AST"
_assert_russian(messages)
def test_directly_printed_literals_are_russian(self):
_assert_russian(_printed_literals())
def test_invariant_catches_old_english_messages(self):
"""Самопроверка: прежние английские тексты инвариант бы отклонил."""
old = [
("excel_repository.py:156", "File not found: {p}"),
("domain/currency.py:96", "No exchange rate: USD → RUB"),
("domain/account.py:22", "balance must be non-negative"),
("application/forecast.py:60", "months must be >= 1"),
]
for where, text in old:
assert _is_english(text), f"инвариант не видит английский текст: {where}"
class TestCliLanguageEndToEnd:
"""Приёмка D19: ошибки, которые видит пользователь, — русские."""
def test_export_error_is_russian(self, tmp_path: Path):
from typer.testing import CliRunner
from infrastructure.cli.app import app
blocker = tmp_path / "blocker"
blocker.write_text("not a directory", encoding="utf-8")
result = CliRunner().invoke(app, ["export-xlsx", str(blocker / "out.xlsx")])
assert result.exit_code == 1
assert "Ошибка экспорта" in result.stdout
assert "Не удалось создать каталог" in result.stdout
assert "Traceback" not in result.stdout
def test_import_missing_file_error_is_russian(self, tmp_path: Path):
from typer.testing import CliRunner
from infrastructure.cli.app import app
result = CliRunner().invoke(app, ["import-xlsx", str(tmp_path / "nope.xlsx")])
assert result.exit_code == 1
assert "Ошибка импорта" in result.stdout
assert "Файл не найден" in result.stdout
assert "Traceback" not in result.stdout
def test_validation_error_is_russian_without_pydantic_prefix(self):
from typer.testing import CliRunner
from infrastructure.cli.app import app
result = CliRunner().invoke(app, ["config", "rate-set", "USD", "RUB", "--", "-5"])
assert result.exit_code == 1
assert "Ошибка валидации данных" in result.stdout
assert "курс должен быть положительным" in result.stdout
assert "Value error" not in result.stdout
assert "Traceback" not in result.stdout