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): # D15: конверсия больше не квантует, поэтому обратный курс (1/90) — # бесконечная десятичная дробь, и результат НЕ ровно 10. # До D15 quantize("0.01") скрывал это и давал ровно 10.00. rate = ExchangeRate(from_currency="EUR", to_currency="RUB", rate=90.0) converter = CurrencyConverter([rate]) result = converter.convert(900, "RUB", "EUR") assert result == Decimal("9.999999999999999999999999999") assert str(result) == "9.999999999999999999999999999" # На отображении округление по знакам валюты даёт те же 10.00. assert converter.format_money(result, "EUR") == "€10.00" def test_cross_rate_through_rub(self): # Н3: прямых пар между не-рублёвыми валютами нет, но обе известны к RUB. converter = CurrencyConverter( [ ExchangeRate(from_currency="USD", to_currency="RUB", rate=80), ExchangeRate(from_currency="EUR", to_currency="RUB", rate=90), ] ) assert converter.convert(100, "EUR", "USD") == Decimal("112.5") # Обратный кросс-курс — бесконечная дробь; сравниваем после округления. assert converter.convert(112.5, "USD", "EUR").quantize(Decimal("0.01")) == Decimal("100.00") def test_direct_rate_wins_over_cross_rate(self): converter = CurrencyConverter( [ ExchangeRate(from_currency="USD", to_currency="RUB", rate=80), ExchangeRate(from_currency="EUR", to_currency="RUB", rate=90), ExchangeRate(from_currency="EUR", to_currency="USD", rate=Decimal("1.2")), ] ) assert converter.get_rate("EUR", "USD") == Decimal("1.2") def test_no_path_raises(self): converter = CurrencyConverter([ExchangeRate(from_currency="USD", to_currency="RUB", rate=80)]) with pytest.raises(CurrencyError): converter.convert(100, "EUR", "GBP") 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 # D15: обратный курс EUR→RUB (1/90) даёт 9.999999999999999999999999999 # вместо прежних ровно 10.0 (раньше квантование скрывало погрешность). assert converter.convert(900, "RUB", "EUR") == Decimal("9.999999999999999999999999999") 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", "expected_str"), [ # USD→RUB, курс 80: точное умножение, БЕЗ quantize (D15). (Decimal("0.005"), Decimal("0.4000"), "0.4000"), (Decimal("0.015"), Decimal("1.2000"), "1.2000"), (Decimal("0.125"), Decimal("10.0000"), "10.0000"), (Decimal("2.675"), Decimal("214.0000"), "214.0000"), (Decimal("1"), Decimal("80.0"), "80.0"), ], ) def test_convert_keeps_full_precision(self, sample_converter, amount, expected, expected_str): # D15: convert() больше не квантует результат — внутри остаётся полная # точность Decimal. Значение равно прежнему, но представление другое: # раньше было quantize("0.01"), теперь результат сохраняет точность # произведения (0.005 * 80.0 = 0.4000, а не «0.40»). result = sample_converter.convert(amount, "USD", "RUB") assert result == expected assert str(result) == expected_str def test_convert_does_not_round_away_precision(self, sample_converter): """D15: конверсия не округляет результат до 2 знаков. До D15 `convert()` квантовал до `Decimal("0.01")` и терял точность: 0.0001 USD → 0.01 вместо 0.00800. """ result = sample_converter.convert(Decimal("0.0001"), "USD", "RUB") assert result == Decimal("0.00800") assert str(result) == "0.00800" # Курс с тремя знаками: 90.125 раньше превращался в 90.13. precise = CurrencyConverter([ExchangeRate(from_currency="EUR", to_currency="RUB", rate=Decimal("90.125"))]) assert precise.convert(Decimal("1"), "EUR", "RUB") == Decimal("90.125") def test_convert_to_jpy_has_no_intermediate_rounding(self): """D15: 0.1 USD → JPY = amount × rate без промежуточного округления.""" converter = CurrencyConverter([ExchangeRate(from_currency="USD", to_currency="JPY", rate=Decimal("80"))]) result = converter.convert(Decimal("0.1"), "USD", "JPY") assert result == Decimal("8.0") assert str(result) == "8.0" # Курс 78.6: 0.1 * 78.6 = 7.86 — тоже без промежуточного округления. by_786 = CurrencyConverter([ExchangeRate(from_currency="USD", to_currency="JPY", rate=Decimal("78.6"))]) assert by_786.convert(Decimal("0.1"), "USD", "JPY") == Decimal("7.86") def test_format_money_rounds_after_conversion(self, sample_converter): """D15: округление — только при отображении, по знакам ISO 4217. `convert()` даёт полную точность, `format_money()` округляет по числу знаков целевой валюты. """ converted = sample_converter.convert(Decimal("0.0001"), "USD", "RUB") assert str(converted) == "0.00800" assert sample_converter.format_money(converted, "RUB") == "₽0.01" # JPY — 0 знаков: 8.0 → «¥8». jpy = CurrencyConverter([ExchangeRate(from_currency="USD", to_currency="JPY", rate=Decimal("80"))]) assert jpy.format_money(jpy.convert(Decimal("0.1"), "USD", "JPY"), "JPY") == "¥8"