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, применение курсов).
This commit is contained in:
1 parent
6b13a15408
commit
ebcc78be3a
6 files changed
+296
No files matched your search
@@ -11,6 +11,7 @@ from infrastructure.cli.commands.config._app import app
|
|||||||
from infrastructure.cli.commands.config._helpers import print_error, print_ok, print_warning
|
from infrastructure.cli.commands.config._helpers import print_error, print_ok, print_warning
|
||||||
from infrastructure.cli.services import console, fail_validation, load_model, save_model
|
from infrastructure.cli.services import console, fail_validation, load_model, save_model
|
||||||
from infrastructure.i18n import t
|
from infrastructure.i18n import t
|
||||||
|
from infrastructure.rates import RatesError, apply_rates, fetch_cbr_rates
|
||||||
|
|
||||||
|
|
||||||
@app.command()
|
@app.command()
|
||||||
@@ -77,3 +78,32 @@ def rate_remove(
|
|||||||
else:
|
else:
|
||||||
print_error(t("cmd.config.rate_remove.err", fc=fc, tc=tc))
|
print_error(t("cmd.config.rate_remove.err", fc=fc, tc=tc))
|
||||||
raise typer.Exit(1)
|
raise typer.Exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
@app.command(name="rate-refresh")
|
||||||
|
def rate_refresh(
|
||||||
|
dry_run: bool = typer.Option(False, "--dry-run", help=t("cmd.config.rate_refresh.opt.dry_run")),
|
||||||
|
) -> None:
|
||||||
|
"""Обновить курсы валют из сети (ЦБ РФ)"""
|
||||||
|
model = load_model()
|
||||||
|
try:
|
||||||
|
snapshot = fetch_cbr_rates()
|
||||||
|
except RatesError as e:
|
||||||
|
print_error(t("cmd.config.rate_refresh.err", error=str(e)))
|
||||||
|
raise typer.Exit(1)
|
||||||
|
|
||||||
|
report = apply_rates(model, snapshot)
|
||||||
|
console.print(t("cmd.config.rate_refresh.date", date=snapshot.date or "—"))
|
||||||
|
for line in report["added"]:
|
||||||
|
console.print(t("cmd.config.rate_refresh.added", pair=line))
|
||||||
|
for line in report["updated"]:
|
||||||
|
console.print(t("cmd.config.rate_refresh.updated", pair=line))
|
||||||
|
if report["unchanged"]:
|
||||||
|
console.print(t("cmd.config.rate_refresh.unchanged", count=len(report["unchanged"])))
|
||||||
|
|
||||||
|
if dry_run:
|
||||||
|
console.print(f"[yellow]{t('cmd.config.rate_refresh.dry_run')}[/yellow]")
|
||||||
|
return
|
||||||
|
|
||||||
|
save_model(model)
|
||||||
|
print_ok(t("cmd.config.rate_refresh.ok", count=len(snapshot.rates)))
|
||||||
@@ -142,6 +142,15 @@ MESSAGES: dict[str, str] = {
|
|||||||
"cmd.config.rate_remove.help": "Удалить курс валюты",
|
"cmd.config.rate_remove.help": "Удалить курс валюты",
|
||||||
"cmd.config.rate_remove.ok": "Курс {fc} → {tc} удалён",
|
"cmd.config.rate_remove.ok": "Курс {fc} → {tc} удалён",
|
||||||
"cmd.config.rate_remove.err": "Курс {fc} → {tc} не найден",
|
"cmd.config.rate_remove.err": "Курс {fc} → {tc} не найден",
|
||||||
|
"cmd.config.rate_refresh.help": "Обновить курсы валют из сети (ЦБ РФ)",
|
||||||
|
"cmd.config.rate_refresh.opt.dry_run": "Только показать, без записи в модель",
|
||||||
|
"cmd.config.rate_refresh.date": "Курсы ЦБ РФ на {date}",
|
||||||
|
"cmd.config.rate_refresh.added": "Добавлен курс: {pair}",
|
||||||
|
"cmd.config.rate_refresh.updated": "Обновлён курс: {pair}",
|
||||||
|
"cmd.config.rate_refresh.unchanged": "Без изменений: {count} курсов",
|
||||||
|
"cmd.config.rate_refresh.dry_run": "Курсы в модель не записаны (--dry-run)",
|
||||||
|
"cmd.config.rate_refresh.ok": "Курсов обновлено: {count}",
|
||||||
|
"cmd.config.rate_refresh.err": "Не удалось обновить курсы: {error}",
|
||||||
"cmd.config.account_add.help": "Добавить счёт",
|
"cmd.config.account_add.help": "Добавить счёт",
|
||||||
"cmd.config.account_add.opt.name": "Название счёта",
|
"cmd.config.account_add.opt.name": "Название счёта",
|
||||||
"cmd.config.account_add.opt.balance": "Начальный баланс",
|
"cmd.config.account_add.opt.balance": "Начальный баланс",
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
"""Источники курсов валют из сети."""
|
||||||
|
|
||||||
|
from infrastructure.rates.cbr import (
|
||||||
|
CBR_URL,
|
||||||
|
RatesError,
|
||||||
|
RatesSnapshot,
|
||||||
|
apply_rates,
|
||||||
|
fetch_cbr_rates,
|
||||||
|
parse_cbr_xml,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"CBR_URL",
|
||||||
|
"RatesError",
|
||||||
|
"RatesSnapshot",
|
||||||
|
"apply_rates",
|
||||||
|
"fetch_cbr_rates",
|
||||||
|
"parse_cbr_xml",
|
||||||
|
]
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
"""Загрузка курсов валют из сети ЦБ РФ (D37).
|
||||||
|
|
||||||
|
Источник — ежедневные курсы Центробанка:
|
||||||
|
https://www.cbr.ru/scripts/XML_daily.asp (XML в кодировке windows-1251).
|
||||||
|
|
||||||
|
Курсы, которые ЦБ публикует, — это «сколько рублей стоит единица валюты».
|
||||||
|
В модели они хранятся как пары ``X → RUB``, поэтому импорт обновляет именно
|
||||||
|
такие пары, а курсы между другими валютами (например, EUR → USD) не трогает.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from decimal import Decimal
|
||||||
|
from xml.etree import ElementTree
|
||||||
|
|
||||||
|
from domain import ExchangeRate
|
||||||
|
|
||||||
|
CBR_URL = "https://www.cbr.ru/scripts/XML_daily.asp"
|
||||||
|
CBR_ENCODING = "windows-1251"
|
||||||
|
DEFAULT_TIMEOUT = 15
|
||||||
|
|
||||||
|
|
||||||
|
class RatesError(Exception):
|
||||||
|
"""Курсы не удалось получить (нет сети, битый ответ, пустой список)."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class RatesSnapshot:
|
||||||
|
"""Набор курсов на одну дату."""
|
||||||
|
|
||||||
|
date: str
|
||||||
|
rates: tuple[ExchangeRate, ...]
|
||||||
|
|
||||||
|
|
||||||
|
def parse_cbr_xml(payload: bytes) -> RatesSnapshot:
|
||||||
|
"""Разобрать XML ЦБ РФ. Бросает ``RatesError`` при негодном ответе."""
|
||||||
|
try:
|
||||||
|
root = ElementTree.fromstring(payload.decode(CBR_ENCODING))
|
||||||
|
except (ElementTree.ParseError, UnicodeDecodeError) as exc:
|
||||||
|
raise RatesError(f"не удалось разобрать ответ ЦБ РФ: {exc}") from exc
|
||||||
|
|
||||||
|
date = root.get("Date", "")
|
||||||
|
rates: list[ExchangeRate] = []
|
||||||
|
for valute in root.findall("Valute"):
|
||||||
|
code = (valute.findtext("CharCode") or "").strip().upper()
|
||||||
|
unit_rate = (valute.findtext("VunitRate") or valute.findtext("Value") or "").strip()
|
||||||
|
if not code or not unit_rate:
|
||||||
|
continue
|
||||||
|
if code == "RUB":
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
# VunitRate — курс за единицу валюты; Nominal в нём уже учтён.
|
||||||
|
rate = Decimal(unit_rate.replace(",", "."))
|
||||||
|
except ArithmeticError as exc:
|
||||||
|
raise RatesError(f"некорректный курс для {code}: {unit_rate}") from exc
|
||||||
|
if rate <= 0:
|
||||||
|
continue
|
||||||
|
rates.append(ExchangeRate(from_currency=code, to_currency="RUB", rate=rate))
|
||||||
|
|
||||||
|
if not rates:
|
||||||
|
raise RatesError("ЦБ РФ вернул пустой список курсов")
|
||||||
|
return RatesSnapshot(date=date, rates=tuple(rates))
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_cbr_rates(url: str = CBR_URL, timeout: int = DEFAULT_TIMEOUT) -> RatesSnapshot:
|
||||||
|
"""Скачать и разобрать курсы ЦБ РФ."""
|
||||||
|
request = urllib.request.Request(url, headers={"User-Agent": "cashflow-forecast/1.0"})
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||||
|
payload = response.read()
|
||||||
|
except (urllib.error.URLError, OSError) as exc:
|
||||||
|
raise RatesError(f"не удалось получить курсы с {url}: {exc}") from exc
|
||||||
|
return parse_cbr_xml(payload)
|
||||||
|
|
||||||
|
|
||||||
|
def apply_rates(model, snapshot: RatesSnapshot) -> dict[str, list[str]]:
|
||||||
|
"""Обновить курсы модели по снимку. Возвращает отчёт об изменениях.
|
||||||
|
|
||||||
|
Курсы ``X → RUB`` заменяются, остальные пары (например, ``EUR → USD``)
|
||||||
|
остаются нетронутыми. Курс, который не изменился, в отчёт не попадает.
|
||||||
|
"""
|
||||||
|
updated: list[str] = []
|
||||||
|
added: list[str] = []
|
||||||
|
unchanged: list[str] = []
|
||||||
|
|
||||||
|
by_pair = {(r.from_currency, r.to_currency): r for r in model.exchange_rates}
|
||||||
|
for rate in snapshot.rates:
|
||||||
|
key = (rate.from_currency, rate.to_currency)
|
||||||
|
existing = by_pair.get(key)
|
||||||
|
if existing is None:
|
||||||
|
model.exchange_rates.append(rate)
|
||||||
|
added.append(f"{rate.from_currency} → {rate.to_currency} = {rate.rate}")
|
||||||
|
elif existing.rate != rate.rate:
|
||||||
|
existing.rate = rate.rate
|
||||||
|
updated.append(f"{rate.from_currency} → {rate.to_currency} = {rate.rate}")
|
||||||
|
else:
|
||||||
|
unchanged.append(f"{rate.from_currency} → {rate.to_currency}")
|
||||||
|
|
||||||
|
return {"added": added, "updated": updated, "unchanged": unchanged}
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"CBR_URL",
|
||||||
|
"RatesError",
|
||||||
|
"RatesSnapshot",
|
||||||
|
"apply_rates",
|
||||||
|
"fetch_cbr_rates",
|
||||||
|
"parse_cbr_xml",
|
||||||
|
]
|
||||||
@@ -40,6 +40,7 @@ EXPECTED_CONFIG_COMMANDS = {
|
|||||||
"rate-set",
|
"rate-set",
|
||||||
"rate-list",
|
"rate-list",
|
||||||
"rate-remove",
|
"rate-remove",
|
||||||
|
"rate-refresh",
|
||||||
"account-add",
|
"account-add",
|
||||||
"account-list",
|
"account-list",
|
||||||
"account-remove",
|
"account-remove",
|
||||||
@@ -104,6 +105,7 @@ EXPECTED_CONFIG_PARAMS = {
|
|||||||
("from_currency", ("from_currency",), None, True),
|
("from_currency", ("from_currency",), None, True),
|
||||||
("to_currency", ("to_currency",), None, True),
|
("to_currency", ("to_currency",), None, True),
|
||||||
],
|
],
|
||||||
|
"rate-refresh": [("dry_run", ("--dry-run",), False, False)],
|
||||||
"account-add": [
|
"account-add": [
|
||||||
("name", ("--name", "-n"), None, True),
|
("name", ("--name", "-n"), None, True),
|
||||||
("balance", ("--balance", "-b"), 0.0, False),
|
("balance", ("--balance", "-b"), 0.0, False),
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
"""Тесты обновления курсов валют из сети (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"]
|
||||||
Reference in new issue
Block a user