R5 (Н5). `config account-add/transaction-add/recurring-add/asset-add/ liability-add` больше не роняют необработанный pydantic ValidationError: создание модели обёрнуто в try/except → `fail_validation`, поэтому пользователь видит русское сообщение и код 1 вместо traceback. R6 (Н6). `convert_value` ловит CurrencyError: `cf forecast --currency EUR` без курса печатает «Нет курса RUB → EUR — обновите курсы: cf config rate-refresh» и завершается с кодом 1, а не rich-трейсбеком. R7 (Н9). `JsonFileRepository.save` пишет во временный файл рядом, сбрасывает на диск и подменяет через `os.replace`; итоговый `model.json` получает права 0600. Обрыв записи больше не оставляет обрезанный файл. R8 (Н9). `save_model` хранит два поколения: `.bak` — состояние до текущей записи, `.bak.1` — поколение до него; оба с правами 0600. Тесты: +10 (5 команд/ошибок ввода, отсутствие курса, права файла, ротация бэкапов). Значения прогноза не менялись. Refs: review/2026-11-29-review.md §3 Н5, Н6, Н9, §6 R5–R8.
188 lines
8.4 KiB
Python
188 lines
8.4 KiB
Python
"""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
|
|
"cf config rate-refresh", # команда, которой пользователь обновляет курсы
|
|
)
|
|
|
|
_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
|