diff --git a/application/forecast.py b/application/forecast.py index 2227b26..3d2e1dc 100644 --- a/application/forecast.py +++ b/application/forecast.py @@ -57,7 +57,7 @@ class ForecastService: def forecast_cashflow(self, months: int = 12) -> list[dict]: if months < 1: - raise ForecastError("months must be >= 1") + raise ForecastError("Число месяцев должно быть не меньше 1") # Локальное состояние расчёта — вместо мутации модели (D14). # `liability_balances` — текущий остаток по каждому обязательству, diff --git a/application/scenarios.py b/application/scenarios.py index fd33099..7e8c006 100644 --- a/application/scenarios.py +++ b/application/scenarios.py @@ -83,6 +83,6 @@ class ScenarioService: income_multiplier=to_d(income_mult), expense_multiplier=to_d(expense_mult), growth_multiplier=to_d(growth_mult), - description=(f"What-if: income x{income_mult}, expense x{expense_mult}, growth x{growth_mult}"), + description=(f"What-if: доход x{income_mult}, расход x{expense_mult}, рост x{growth_mult}"), ) return self.apply(scenario, months) diff --git a/domain/account.py b/domain/account.py index 9f3f0ad..6f9f7ce 100644 --- a/domain/account.py +++ b/domain/account.py @@ -19,5 +19,5 @@ class Account(BaseModel): @classmethod def _balance_non_negative(cls, v: Decimal) -> Decimal: if v < 0: - raise ValueError("balance must be non-negative") + raise ValueError("баланс не может быть отрицательным") return v diff --git a/domain/currency.py b/domain/currency.py index baef893..58a0584 100644 --- a/domain/currency.py +++ b/domain/currency.py @@ -55,7 +55,7 @@ class ExchangeRate(BaseModel): @classmethod def _rate_positive(cls, v: Decimal) -> Decimal: if v <= 0: - raise ValueError("rate must be positive") + raise ValueError("курс должен быть положительным") return v @@ -83,7 +83,7 @@ class CurrencyConverter: ) -> None: d = Decimal(str(rate)) if not isinstance(rate, Decimal) else rate if d <= 0: - raise CurrencyError(f"Rate must be positive: {d}") + raise CurrencyError(f"Курс должен быть положительным: {d}") self._rates[(from_currency, to_currency)] = d self._rates[(to_currency, from_currency)] = Decimal("1") / d @@ -93,7 +93,7 @@ class CurrencyConverter: try: return self._rates[(from_currency, to_currency)] except KeyError: - raise CurrencyError(f"No exchange rate: {from_currency} → {to_currency}") + raise CurrencyError(f"Нет курса: {from_currency} → {to_currency}") def convert( self, diff --git a/domain/liability.py b/domain/liability.py index 13377f7..3d495ab 100644 --- a/domain/liability.py +++ b/domain/liability.py @@ -20,5 +20,5 @@ class Liability(BaseModel): @classmethod def _non_negative(cls, v: Decimal) -> Decimal: if v < 0: - raise ValueError("must be non-negative") + raise ValueError("значение не может быть отрицательным") return v diff --git a/domain/model.py b/domain/model.py index 981f34f..4dc2f7f 100644 --- a/domain/model.py +++ b/domain/model.py @@ -59,7 +59,7 @@ class FinancialModel(BaseModel): return cls._from_legacy(data) if version == 1: return cls._from_v1(data) - raise ValueError(f"Unsupported FinancialModel version: {version}") + raise ValueError(f"Неподдерживаемая версия финансовой модели: {version}") @classmethod def _from_v1(cls, data: dict) -> "FinancialModel": diff --git a/domain/recurring.py b/domain/recurring.py index c4515e5..0806dfe 100644 --- a/domain/recurring.py +++ b/domain/recurring.py @@ -39,14 +39,14 @@ class RecurringCashflow(BaseModel): @classmethod def _frequency_known(cls, v: str) -> str: if v not in {"daily", "weekly", "monthly", "yearly"}: - raise ValueError(f"unknown frequency: {v}") + raise ValueError(f"неизвестная периодичность: {v}") return v @field_validator("amount") @classmethod def _amount_nonzero(cls, v: Decimal) -> Decimal: if v == 0: - raise ValueError("amount must be non-zero") + raise ValueError("сумма не может быть нулевой") return v def monthly_amount(self) -> Decimal: diff --git a/domain/scenario.py b/domain/scenario.py index e3a9ff8..ef0a3e1 100644 --- a/domain/scenario.py +++ b/domain/scenario.py @@ -21,5 +21,5 @@ class ForecastScenario(BaseModel): @classmethod def _non_negative(cls, v: Decimal) -> Decimal: if v < 0: - raise ValueError("multiplier must be non-negative") + raise ValueError("множитель не может быть отрицательным") return v diff --git a/domain/transaction.py b/domain/transaction.py index ddd3602..e970832 100644 --- a/domain/transaction.py +++ b/domain/transaction.py @@ -21,5 +21,5 @@ class Transaction(BaseModel): @classmethod def _amount_nonzero(cls, v: Decimal) -> Decimal: if v == 0: - raise ValueError("amount must be non-zero") + raise ValueError("сумма не может быть нулевой") return v diff --git a/infrastructure/cli/services.py b/infrastructure/cli/services.py index c3d0401..8edc458 100644 --- a/infrastructure/cli/services.py +++ b/infrastructure/cli/services.py @@ -22,6 +22,15 @@ console = Console() _json_repo = JsonFileRepository() +def _validation_message(error: dict) -> str: + """Текст одной ошибки pydantic без английского префикса. + + pydantic добавляет к тексту исключения валидатора префикс + «Value error, » — пользователю он не нужен, поэтому срезается (D19). + """ + return str(error["msg"]).removeprefix("Value error, ") + + def fail_validation(exc: ValidationError) -> NoReturn: """Показать ошибку валидации понятным сообщением и завершить команду. @@ -31,7 +40,8 @@ def fail_validation(exc: ValidationError) -> NoReturn: вместо traceback. """ details = "; ".join( - f"{'.'.join(str(part) for part in error['loc']) or 'значение'}: {error['msg']}" for error in exc.errors() + f"{'.'.join(str(part) for part in error['loc']) or t('global.value')}: {_validation_message(error)}" + for error in exc.errors() ) console.print(f"[red]{t('global.validation_error', error=details)}[/red]") raise typer.Exit(1) diff --git a/infrastructure/i18n/ru.py b/infrastructure/i18n/ru.py index 02a7003..8f6d03d 100644 --- a/infrastructure/i18n/ru.py +++ b/infrastructure/i18n/ru.py @@ -179,6 +179,7 @@ MESSAGES: dict[str, str] = { "cmd.config.liability_remove.ok": "Обязательство '{id}' удалено", "cmd.config.liability_remove.err": "Обязательство '{id}' не найдено", "global.ok": "OK", + "global.value": "значение", "global.validation_error": "Ошибка валидации данных: {error}", "prompt.analyze": "Ты — финансовый AI-ассистент. Проанализируй финансовую модель пользователя.\n" "\n" diff --git a/infrastructure/repositories/excel_repository.py b/infrastructure/repositories/excel_repository.py index a1b1845..057adef 100644 --- a/infrastructure/repositories/excel_repository.py +++ b/infrastructure/repositories/excel_repository.py @@ -146,14 +146,14 @@ def _parse_row(sheet_name: str, cls: type[BaseModel], data: dict[str, Any]) -> B try: return cls.model_validate(data) except Exception as e: - raise ExcelRepositoryError(f"Failed to parse row in {sheet_name}: {e}") from e + raise ExcelRepositoryError(f"Не удалось разобрать строку листа {sheet_name}: {e}") from e class ExcelRepository(ModelRepository): def load(self, path: str | Path) -> FinancialModel: p = Path(path) if not p.exists(): - raise ExcelRepositoryError(f"File not found: {p}") + raise ExcelRepositoryError(f"Файл не найден: {p}") wb = load_workbook(p, read_only=True, data_only=True) try: diff --git a/tests/test_cli.py b/tests/test_cli.py index c6ec6b1..ce9a68b 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -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) diff --git a/tests/test_language.py b/tests/test_language.py new file mode 100644 index 0000000..783fc8c --- /dev/null +++ b/tests/test_language.py @@ -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 diff --git a/tests/test_model.py b/tests/test_model.py index a4d7f4f..e94d3dd 100644 --- a/tests/test_model.py +++ b/tests/test_model.py @@ -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") diff --git a/tests/test_scenarios.py b/tests/test_scenarios.py index e5a2efd..efeb6c7 100644 --- a/tests/test_scenarios.py +++ b/tests/test_scenarios.py @@ -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