Files
nifodea/tests/test_rates.py
T
oqyude ebcc78be3a D37: обновление курсов валют из сети (ЦБ РФ)
- infrastructure/rates/cbr.py — загрузка ежедневных курсов ЦБ РФ
  (XML, windows-1251) и разбор их в пары X → RUB; разбор вынесен в
  чистую функцию, поэтому тестируется без сети;
- cf config rate-refresh [--dry-run] — обновляет курсы в модели: пары
  X → RUB обновляются, остальные (например, EUR → USD) не трогаются,
  неизменившиеся курсы перечисляются отдельно;
- нет сети или битый ответ — понятное сообщение, модель не меняется.

Тесты: 333 → 342 (tests/test_rates.py: разбор XML, применение курсов).
2026-11-15 06:15:21 +03:00

125 lines
4.6 KiB
Python

"""Тесты обновления курсов валют из сети (D37)."""
from decimal import Decimal
import pytest
from domain import ExchangeRate, FinancialModel
from infrastructure.rates import RatesError, RatesSnapshot, apply_rates, parse_cbr_xml
# Обрезанный ответ ЦБ РФ (в реальности — windows-1251).
_CBR_XML = """<?xml version="1.0" encoding="windows-1251"?>
<ValCurs Date="14.11.2026" name="Foreign Currency Market">
<Valute ID="R01235">
<NumCode>840</NumCode>
<CharCode>USD</CharCode>
<Nominal>1</Nominal>
<Name>Доллар США</Name>
<Value>82,1516</Value>
<VunitRate>82,1516</VunitRate>
</Valute>
<Valute ID="R01239">
<NumCode>978</NumCode>
<CharCode>EUR</CharCode>
<Nominal>1</Nominal>
<Name>Евро</Name>
<Value>91,0322</Value>
<VunitRate>91,0322</VunitRate>
</Valute>
<Valute ID="R01375">
<NumCode>156</NumCode>
<CharCode>CNY</CharCode>
<Nominal>10</Nominal>
<Name>Китайских юаней</Name>
<Value>112,6667</Value>
<VunitRate>11,26667</VunitRate>
</Valute>
<Valute ID="R01375">
<NumCode>810</NumCode>
<CharCode>RUB</CharCode>
<Nominal>1</Nominal>
<Name>Российский рубль</Name>
<Value>1</Value>
<VunitRate>1</VunitRate>
</Valute>
</ValCurs>
"""
class TestParseCbrXml:
def test_parses_rates(self):
snapshot = parse_cbr_xml(_CBR_XML.encode("windows-1251"))
assert snapshot.date == "14.11.2026"
codes = [rate.from_currency for rate in snapshot.rates]
assert codes == ["USD", "EUR", "CNY"]
def test_rate_is_per_unit(self):
snapshot = parse_cbr_xml(_CBR_XML.encode("windows-1251"))
cny = next(rate for rate in snapshot.rates if rate.from_currency == "CNY")
# CNY публикуется за 10 юаней, VunitRate — за единицу.
assert cny.rate == Decimal("11.26667")
assert cny.to_currency == "RUB"
def test_russian_rouble_is_skipped(self):
snapshot = parse_cbr_xml(_CBR_XML.encode("windows-1251"))
assert "RUB" not in [rate.from_currency for rate in snapshot.rates]
def test_broken_xml_raises(self):
with pytest.raises(RatesError):
parse_cbr_xml(b"<ValCurs><broken>")
def test_empty_list_raises(self):
payload = '<?xml version="1.0" encoding="windows-1251"?><ValCurs Date="14.11.2026"></ValCurs>'
with pytest.raises(RatesError):
parse_cbr_xml(payload.encode("windows-1251"))
class TestApplyRates:
def test_adds_new_rates(self):
model = FinancialModel()
snapshot = RatesSnapshot(
date="14.11.2026",
rates=(ExchangeRate(from_currency="EUR", to_currency="RUB", rate=Decimal("91.03")),),
)
report = apply_rates(model, snapshot)
assert len(report["added"]) == 1
assert any(rate.from_currency == "EUR" for rate in model.exchange_rates)
def test_updates_existing_rate(self):
model = FinancialModel(
exchange_rates=[ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("80"))]
)
snapshot = RatesSnapshot(
date="14.11.2026",
rates=(ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("82.15")),),
)
report = apply_rates(model, snapshot)
assert len(report["updated"]) == 1
assert model.exchange_rates[0].rate == Decimal("82.15")
def test_keeps_other_pairs(self):
model = FinancialModel(
exchange_rates=[ExchangeRate(from_currency="EUR", to_currency="USD", rate=Decimal("1.1"))]
)
snapshot = RatesSnapshot(
date="14.11.2026",
rates=(ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("82.15")),),
)
apply_rates(model, snapshot)
pairs = {(r.from_currency, r.to_currency) for r in model.exchange_rates}
assert ("EUR", "USD") in pairs
assert ("USD", "RUB") in pairs
def test_unchanged_rate_is_reported_separately(self):
model = FinancialModel(
exchange_rates=[ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("82.15"))]
)
snapshot = RatesSnapshot(
date="14.11.2026",
rates=(ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("82.15")),),
)
report = apply_rates(model, snapshot)
assert report["unchanged"] == ["USD → RUB"]
assert not report["updated"]
assert not report["added"]