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

+1 -1
View File
@@ -212,7 +212,7 @@ class TestValidationErrors:
result = runner.invoke(app, ["config", "rate-set", "USD", "RUB", "--", "-5"])
assert result.exit_code == 1
assert "Ошибка валидации" in result.stdout
assert "rate must be positive" in result.stdout
assert "курс должен быть положительным" in result.stdout
assert "Traceback" not in result.stdout
assert result.exception is None or isinstance(result.exception, SystemExit)
+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
+16 -16
View File
@@ -133,7 +133,7 @@ class TestValidateAssignment:
rate = ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("80"))
with pytest.raises(ValidationError) as exc_info:
rate.rate = Decimal("-5")
assert "rate must be positive" in str(exc_info.value)
assert "курс должен быть положительным" in str(exc_info.value)
# Значение не изменилось — невалидное присваивание отклонено целиком.
assert rate.rate == Decimal("80")
@@ -156,14 +156,14 @@ class TestValidateAssignment:
account = Account(name="A", balance=Decimal("100"))
with pytest.raises(ValidationError) as exc_info:
account.balance = Decimal("-1")
assert "balance must be non-negative" in str(exc_info.value)
assert "баланс не может быть отрицательным" in str(exc_info.value)
assert account.balance == Decimal("100")
def test_transaction_amount_rejected_on_assignment(self):
txn = Transaction(amount=Decimal("100"))
with pytest.raises(ValidationError) as exc_info:
txn.amount = Decimal("0")
assert "amount must be non-zero" in str(exc_info.value)
assert "сумма не может быть нулевой" in str(exc_info.value)
assert txn.amount == Decimal("100")
def test_recurring_amount_and_frequency_rejected_on_assignment(self):
@@ -277,7 +277,7 @@ class TestPydanticValidators:
def test_account_balance_rejects_negative(self):
with pytest.raises(ValidationError) as exc_info:
Account(balance=Decimal("-1"))
assert "balance must be non-negative" in str(exc_info.value)
assert "баланс не может быть отрицательным" in str(exc_info.value)
def test_account_balance_allows_zero(self):
assert Account(balance=Decimal("0")).balance == Decimal("0")
@@ -285,14 +285,14 @@ class TestPydanticValidators:
def test_account_balance_rejects_small_negative(self):
with pytest.raises(ValidationError) as exc_info:
Account(balance=Decimal("-0.01"))
assert "balance must be non-negative" in str(exc_info.value)
assert "баланс не может быть отрицательным" in str(exc_info.value)
# --- 2. Transaction.amount — ненулевой (отрицательные разрешены) ---
def test_transaction_amount_rejects_zero(self):
with pytest.raises(ValidationError) as exc_info:
Transaction(amount=Decimal("0"))
assert "amount must be non-zero" in str(exc_info.value)
assert "сумма не может быть нулевой" in str(exc_info.value)
def test_transaction_amount_allows_negative(self):
# Расходы записываются отрицательными суммами — это валидное значение.
@@ -306,19 +306,19 @@ class TestPydanticValidators:
def test_recurring_frequency_rejects_unknown_value(self):
with pytest.raises(ValidationError) as exc_info:
RecurringCashflow(frequency="hourly")
assert "unknown frequency: hourly" in str(exc_info.value)
assert "неизвестная периодичность: hourly" in str(exc_info.value)
def test_recurring_frequency_rejects_empty_string(self):
with pytest.raises(ValidationError) as exc_info:
RecurringCashflow(frequency="")
assert "unknown frequency:" in str(exc_info.value)
assert "неизвестная периодичность:" in str(exc_info.value)
# --- 4. RecurringCashflow.amount — ненулевой ---
def test_recurring_amount_rejects_zero(self):
with pytest.raises(ValidationError) as exc_info:
RecurringCashflow(amount=Decimal("0"))
assert "amount must be non-zero" in str(exc_info.value)
assert "сумма не может быть нулевой" in str(exc_info.value)
def test_recurring_amount_allows_non_zero(self):
assert RecurringCashflow(amount=Decimal("1")).amount == Decimal("1")
@@ -329,14 +329,14 @@ class TestPydanticValidators:
with pytest.raises(ValidationError) as exc_info:
Liability(interest=Decimal("-1"))
text = str(exc_info.value)
assert "must be non-negative" in text
assert "значение не может быть отрицательным" in text
assert "interest" in text
def test_liability_payment_rejects_negative(self):
with pytest.raises(ValidationError) as exc_info:
Liability(payment=Decimal("-1"))
text = str(exc_info.value)
assert "must be non-negative" in text
assert "значение не может быть отрицательным" in text
assert "payment" in text
def test_liability_allows_zero_interest_and_payment(self):
@@ -350,21 +350,21 @@ class TestPydanticValidators:
with pytest.raises(ValidationError) as exc_info:
ForecastScenario(income_multiplier=Decimal("-1"))
text = str(exc_info.value)
assert "multiplier must be non-negative" in text
assert "множитель не может быть отрицательным" in text
assert "income_multiplier" in text
def test_scenario_expense_multiplier_rejects_negative(self):
with pytest.raises(ValidationError) as exc_info:
ForecastScenario(expense_multiplier=Decimal("-1"))
text = str(exc_info.value)
assert "multiplier must be non-negative" in text
assert "множитель не может быть отрицательным" in text
assert "expense_multiplier" in text
def test_scenario_growth_multiplier_rejects_negative(self):
with pytest.raises(ValidationError) as exc_info:
ForecastScenario(growth_multiplier=Decimal("-1"))
text = str(exc_info.value)
assert "multiplier must be non-negative" in text
assert "множитель не может быть отрицательным" in text
assert "growth_multiplier" in text
def test_scenario_allows_zero_multipliers(self):
@@ -382,12 +382,12 @@ class TestPydanticValidators:
def test_exchange_rate_rejects_zero(self):
with pytest.raises(ValidationError) as exc_info:
ExchangeRate(rate=Decimal("0"))
assert "rate must be positive" in str(exc_info.value)
assert "курс должен быть положительным" in str(exc_info.value)
def test_exchange_rate_rejects_negative(self):
with pytest.raises(ValidationError) as exc_info:
ExchangeRate(rate=Decimal("-1"))
assert "rate must be positive" in str(exc_info.value)
assert "курс должен быть положительным" in str(exc_info.value)
def test_exchange_rate_allows_small_positive(self):
assert ExchangeRate(rate=Decimal("0.01")).rate == Decimal("0.01")
+1 -1
View File
@@ -124,7 +124,7 @@ class TestScenarioCharacterization:
) == expected[name]
def test_what_if_numbers(self, sample_model):
description = "What-if: income x1.2, expense x0.9, growth x1.0"
description = "What-if: доход x1.2, расход x0.9, рост x1.0"
six = ScenarioService(sample_model, start_month=_GRID_START).what_if(
income_mult=1.2, expense_mult=0.9, months=6