+71 тест (81 → 160). Характеристики фиксируют существующее поведение как есть; их правка — вместе с изменением поведения (Tier 2, D14–D16). - tests/test_forecast.py: TestForecastCharacterization — точные 24 строки forecast_cashflow(12), summary(6)/summary(12), неидемпотентность повторного прогноза (Tier 2, D14), расхождение summary после прогноза, влияние горизонта - tests/test_scenarios.py: TestScenarioCharacterization — числа baseline/ optimistic/pessimistic на 6 и 12 мес., what_if, совпадение compare() с apply() - tests/test_ai.py: TestAssistantCompareScenarios — точный текст промпта compare_scenarios (251 символ), display_currency, подстановка JSON - tests/test_model.py: TestPydanticValidators — все 7 валидаторов домена (balance, amount×2, frequency, interest/payment, множители×3, rate) с проверкой текста ошибки; TestDecimalCoercionAndIds - tests/test_currency.py: TestRoundingBoundaries — 18 границ .5 для format_money (USD/JPY/BHD/CHF/RUB, отрицательные) и 5 для convert() - tests/test_excel_sync.py: TestExcelRoundTripByValues — round-trip по значениям всех 6 листов + ModelInfo, 7 листов в файле Проверено мутацией: смена режима округления роняет 11 тестов test_currency.py.
189 lines
8.0 KiB
Python
189 lines
8.0 KiB
Python
from decimal import Decimal
|
||
|
||
import pytest
|
||
|
||
from domain import CurrencyConverter, CurrencyError, ExchangeRate
|
||
|
||
|
||
class TestExchangeRate:
|
||
def test_to_dict_roundtrip(self):
|
||
rate = ExchangeRate(from_currency="USD", to_currency="RUB", rate=80.0)
|
||
d = rate.model_dump(mode="json")
|
||
r2 = ExchangeRate.model_validate(d)
|
||
assert r2.from_currency == "USD"
|
||
assert r2.to_currency == "RUB"
|
||
assert r2.rate == 80.0
|
||
|
||
def test_defaults(self):
|
||
r = ExchangeRate()
|
||
assert r.from_currency == "USD"
|
||
assert r.to_currency == "RUB"
|
||
assert r.rate == 80.0
|
||
|
||
|
||
class TestCurrencyConverter:
|
||
def test_convert_usd_to_rub(self, sample_converter):
|
||
result = sample_converter.convert(100, "USD", "RUB")
|
||
assert result == 8000.0
|
||
|
||
def test_convert_rub_to_usd(self, sample_converter):
|
||
result = sample_converter.convert(8000, "RUB", "USD")
|
||
assert result == 100.0
|
||
|
||
def test_same_currency(self, sample_converter):
|
||
result = sample_converter.convert(500, "USD", "USD")
|
||
assert result == 500.0
|
||
|
||
def test_unknown_pair(self):
|
||
converter = CurrencyConverter()
|
||
with pytest.raises(CurrencyError):
|
||
converter.convert(100, "USD", "RUB")
|
||
|
||
def test_negative_rate(self):
|
||
converter = CurrencyConverter()
|
||
with pytest.raises(CurrencyError):
|
||
converter.set_rate("USD", "RUB", -1)
|
||
|
||
def test_zero_rate(self):
|
||
converter = CurrencyConverter()
|
||
with pytest.raises(CurrencyError):
|
||
converter.set_rate("USD", "RUB", 0)
|
||
|
||
def test_inverse_auto(self):
|
||
rate = ExchangeRate(from_currency="EUR", to_currency="RUB", rate=90.0)
|
||
converter = CurrencyConverter([rate])
|
||
assert converter.convert(900, "RUB", "EUR") == 10.0
|
||
|
||
def test_get_symbol(self, sample_converter):
|
||
assert sample_converter.get_symbol("USD") == "$"
|
||
assert sample_converter.get_symbol("RUB") == "₽"
|
||
assert sample_converter.get_symbol("XYZ") == "XYZ"
|
||
|
||
def test_with_defaults(self):
|
||
converter = CurrencyConverter.with_defaults()
|
||
assert converter.convert(10, "USD", "RUB") == 800.0
|
||
|
||
def test_multiple_rates(self):
|
||
rates = [
|
||
ExchangeRate(from_currency="USD", to_currency="RUB", rate=80.0),
|
||
ExchangeRate(from_currency="EUR", to_currency="RUB", rate=90.0),
|
||
]
|
||
converter = CurrencyConverter(rates)
|
||
assert converter.convert(10, "USD", "RUB") == 800.0
|
||
assert converter.convert(10, "EUR", "RUB") == 900.0
|
||
assert converter.convert(900, "RUB", "EUR") == 10.0
|
||
|
||
|
||
class TestFormatMoney:
|
||
"""ISO 4217-aware display formatting. Rounding mode: ROUND_HALF_UP."""
|
||
|
||
def test_jpy_zero_decimals(self):
|
||
c = CurrencyConverter()
|
||
assert c.format_money(Decimal("1234.567"), "JPY") == "¥1,235"
|
||
|
||
def test_usd_two_decimals(self, sample_converter):
|
||
assert sample_converter.format_money(Decimal("1234.567"), "USD") == "$1,234.57"
|
||
|
||
def test_bhd_three_decimals(self):
|
||
# BHD has 3 minor units and is NOT in CURRENCY_SYMBOLS — code prefix with space.
|
||
c = CurrencyConverter()
|
||
assert c.format_money(Decimal("1.234"), "BHD") == "BHD 1.234"
|
||
|
||
def test_chf_unknown_code_two_decimals(self):
|
||
# Unknown code falls back to DEFAULT_CURRENCY_DECIMALS=2, layout is code prefix.
|
||
c = CurrencyConverter()
|
||
assert c.format_money(Decimal("1.234"), "CHF") == "CHF 1.23"
|
||
|
||
def test_negative_amount(self, sample_converter):
|
||
# Sign must be rendered before the symbol, not embedded in the number.
|
||
assert sample_converter.format_money(Decimal("-1200.00"), "RUB") == "-₽1,200.00"
|
||
|
||
def test_zero_amount(self, sample_converter):
|
||
assert sample_converter.format_money(Decimal("0"), "JPY") == "¥0"
|
||
assert sample_converter.format_money(Decimal("0"), "USD") == "$0.00"
|
||
|
||
def test_accepts_float_and_int(self, sample_converter):
|
||
# Defensive: callers from CLI pass float — format_money must coerce.
|
||
assert sample_converter.format_money(1500.5, "USD") == "$1,500.50"
|
||
assert sample_converter.format_money(1500, "JPY") == "¥1,500"
|
||
|
||
def test_case_insensitive_currency_code(self, sample_converter):
|
||
# Defensive: lower-case codes are accepted; storage stays upper-case.
|
||
assert sample_converter.format_money(Decimal("100"), "usd") == "$100.00"
|
||
|
||
|
||
class TestRoundingBoundaries:
|
||
"""Границы округления `.5` — текущее поведение (D11).
|
||
|
||
Режим округления — ROUND_HALF_UP (0.5 → 1, а не «к чётному»).
|
||
|
||
* `format_money` квантизует по числу знаков ISO 4217:
|
||
JPY — 0 знаков, BHD/KWD/OMR — 3 знака, остальные — 2;
|
||
неизвестный код → 2 знака (`DEFAULT_CURRENCY_DECIMALS`).
|
||
* `convert()` квантует результат до 2 знаков ROUND_HALF_UP
|
||
независимо от числа знаков целевой валюты (см. Tier 2 (D15) ниже).
|
||
"""
|
||
|
||
@pytest.mark.parametrize(
|
||
("amount", "currency", "expected"),
|
||
[
|
||
# USD — 2 знака, ROUND_HALF_UP
|
||
(Decimal("0.005"), "USD", "$0.01"),
|
||
(Decimal("0.015"), "USD", "$0.02"),
|
||
(Decimal("0.025"), "USD", "$0.03"),
|
||
(Decimal("1.005"), "USD", "$1.01"),
|
||
(Decimal("2.675"), "USD", "$2.68"),
|
||
(Decimal("100.999"), "USD", "$101.00"),
|
||
(Decimal("100.995"), "USD", "$101.00"),
|
||
# JPY — 0 знаков
|
||
(Decimal("0.5"), "JPY", "¥1"),
|
||
(Decimal("1.5"), "JPY", "¥2"),
|
||
(Decimal("2.5"), "JPY", "¥3"),
|
||
(Decimal("-0.5"), "JPY", "-¥1"),
|
||
# BHD — 3 знака, символа нет → префикс с пробелом
|
||
(Decimal("0.0005"), "BHD", "BHD 0.001"),
|
||
(Decimal("1.2345"), "BHD", "BHD 1.235"),
|
||
# Неизвестный код (CHF) — 2 знака по умолчанию
|
||
(Decimal("0.125"), "CHF", "CHF 0.13"),
|
||
# Знак минуса — перед символом
|
||
(Decimal("-0.005"), "USD", "-$0.01"),
|
||
(Decimal("-1.005"), "USD", "-$1.01"),
|
||
# RUB — 2 знака
|
||
(Decimal("0.5"), "RUB", "₽0.50"),
|
||
(Decimal("0.05"), "RUB", "₽0.05"),
|
||
],
|
||
)
|
||
def test_format_money_half_up_boundaries(self, amount, currency, expected):
|
||
assert CurrencyConverter.format_money(amount, currency) == expected
|
||
|
||
@pytest.mark.parametrize(
|
||
("amount", "expected"),
|
||
[
|
||
(Decimal("0.005"), Decimal("0.40")),
|
||
(Decimal("0.015"), Decimal("1.20")),
|
||
(Decimal("0.125"), Decimal("10.00")),
|
||
(Decimal("2.675"), Decimal("214.00")),
|
||
(Decimal("1"), Decimal("80.00")),
|
||
],
|
||
)
|
||
def test_convert_half_up_boundaries(self, sample_converter, amount, expected):
|
||
# USD→RUB, курс 80: multiply, затем quantize(0.01, ROUND_HALF_UP).
|
||
assert sample_converter.convert(amount, "USD", "RUB") == expected
|
||
|
||
def test_convert_always_quantizes_to_two_decimals(self, sample_converter):
|
||
"""Текущее поведение: convert() квантует до 2 знаков независимо от валюты.
|
||
|
||
Изменение — Tier 2 (D15): результат должен учитывать число знаков
|
||
ISO 4217 целевой валюты (для JPY — 0 знаков).
|
||
"""
|
||
assert sample_converter.convert(Decimal("100"), "USD", "RUB") == Decimal("8000.00")
|
||
|
||
def test_convert_to_jpy_keeps_two_decimals(self):
|
||
"""Текущее поведение: USD→JPY квантуется до 2 знаков.
|
||
|
||
0.1 USD по курсу 80 → 8.00 (а не «8» — как было бы при 0 знаках JPY).
|
||
Изменение — Tier 2 (D15).
|
||
"""
|
||
converter = CurrencyConverter([ExchangeRate(from_currency="USD", to_currency="JPY", rate=Decimal("80"))])
|
||
assert converter.convert(Decimal("0.1"), "USD", "JPY") == Decimal("8.00")
|