Dalsi banky, prehled ve Swaggeru, /status a prazdne promenne
- zdroje rb, unicredit a air - nahore ve Swaggeru prehled nabizenych a nenabizenych bank s duvody - GET /status s prehledem vypadku stahovani u jednotlivych bank - prazdna promenna prostredi znamena vychozi hodnotu - popis stahovani v documentation/stahovani.md
This commit is contained in:
@@ -45,6 +45,15 @@ def test_health_answers_without_any_data(client: TestClient) -> None:
|
||||
assert response.json() == {"status": "ok"}
|
||||
|
||||
|
||||
def test_documentation_lists_offered_and_not_offered_banks(client: TestClient) -> None:
|
||||
description = client.get("/openapi.json").json()["info"]["description"]
|
||||
|
||||
assert "`/cnb`" in description
|
||||
assert "`/moneta`" in description
|
||||
assert "Revolut" in description
|
||||
assert "Česká spořitelna" in description
|
||||
|
||||
|
||||
def test_unknown_source_is_not_found(client: TestClient) -> None:
|
||||
assert client.get("/nonexistent").status_code == 404
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app import refresh
|
||||
from app.config import load_settings
|
||||
|
||||
INTERVAL = "REFRESH_INTERVAL_MINUTES"
|
||||
SECONDS_PER_MINUTE = 60
|
||||
|
||||
|
||||
class StopLoop(Exception):
|
||||
"""Ends the otherwise endless refresh loop in a test."""
|
||||
|
||||
|
||||
def test_defaults_apply_when_variables_are_not_set(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
for name in (INTERVAL, "DATA_DIR", "APP_NAME", "APP_VERSION", "ROOT_PATH"):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
|
||||
settings = load_settings()
|
||||
|
||||
assert settings.refresh_interval_minutes == 60
|
||||
assert settings.data_dir == Path("data")
|
||||
assert settings.app_name == "Exchange rates"
|
||||
assert settings.app_version == "1.0.0"
|
||||
assert settings.root_path == ""
|
||||
|
||||
|
||||
@pytest.mark.parametrize("empty", ["", " "])
|
||||
def test_empty_variables_mean_defaults(monkeypatch: pytest.MonkeyPatch, empty: str) -> None:
|
||||
monkeypatch.setenv(INTERVAL, empty)
|
||||
monkeypatch.setenv("DATA_DIR", empty)
|
||||
|
||||
settings = load_settings()
|
||||
|
||||
assert settings.refresh_interval_minutes == 60
|
||||
assert settings.data_dir == Path("data")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("minutes", [60, 360])
|
||||
def test_filled_interval_is_used(monkeypatch: pytest.MonkeyPatch, minutes: int) -> None:
|
||||
monkeypatch.setenv(INTERVAL, str(minutes))
|
||||
|
||||
assert load_settings().refresh_interval_minutes == minutes
|
||||
|
||||
|
||||
@pytest.mark.parametrize("invalid", ["abc", "0", "-5", "1.5"])
|
||||
def test_invalid_interval_stops_the_start(monkeypatch: pytest.MonkeyPatch, invalid: str) -> None:
|
||||
monkeypatch.setenv(INTERVAL, invalid)
|
||||
|
||||
with pytest.raises(ValueError, match=INTERVAL):
|
||||
load_settings()
|
||||
|
||||
|
||||
def test_refresh_loop_waits_for_the_configured_interval(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
refresh_calls = []
|
||||
sleep_calls = []
|
||||
|
||||
async def fake_refresh_all(_client: object, data_dir: Path, _history: object) -> None:
|
||||
refresh_calls.append(data_dir)
|
||||
|
||||
async def fake_sleep(seconds: float) -> None:
|
||||
sleep_calls.append(seconds)
|
||||
raise StopLoop
|
||||
|
||||
monkeypatch.setattr(refresh, "refresh_all", fake_refresh_all)
|
||||
monkeypatch.setattr(refresh.asyncio, "sleep", fake_sleep)
|
||||
|
||||
with pytest.raises(StopLoop):
|
||||
asyncio.run(refresh.refresh_forever(tmp_path, interval_minutes=360, history={}))
|
||||
|
||||
assert refresh_calls == [tmp_path]
|
||||
assert sleep_calls == [360 * SECONDS_PER_MINUTE]
|
||||
+68
-1
@@ -5,7 +5,21 @@ from datetime import date
|
||||
import pytest
|
||||
|
||||
from app.models import Origin, Rate
|
||||
from app.sources import cnb, creditas, csob, fio, jt, kb, mbank, moneta, ppf, trinity
|
||||
from app.sources import (
|
||||
air,
|
||||
cnb,
|
||||
creditas,
|
||||
csob,
|
||||
fio,
|
||||
jt,
|
||||
kb,
|
||||
mbank,
|
||||
moneta,
|
||||
ppf,
|
||||
rb,
|
||||
trinity,
|
||||
unicredit,
|
||||
)
|
||||
|
||||
|
||||
def rate(
|
||||
@@ -201,6 +215,56 @@ def test_creditas_skips_row_without_price() -> None:
|
||||
assert parsed.rates == [rate("EUR", 23.853, 24.827, 24.34, middle_origin="computed")]
|
||||
|
||||
|
||||
def test_rb_uses_only_the_last_list_and_noncash_rates() -> None:
|
||||
document = """{"exchangeRateLists":[
|
||||
{"effectiveDateFrom":"2026-11-04T09:00:00Z","lastRates":true,"exchangeRates":[
|
||||
{"currencyFrom":"JPY","unitsFrom":100,"exchangeRateBuy":13.0,"exchangeRateSell":14.0,
|
||||
"exchangeRateCenter":13.5,"exchangeRateBuyCash":12.0}]},
|
||||
{"effectiveDateFrom":"2026-11-03T23:00:00Z","lastRates":false,"exchangeRates":[
|
||||
{"currencyFrom":"USD","unitsFrom":1,"exchangeRateBuy":20.0,"exchangeRateSell":22.0,
|
||||
"exchangeRateCenter":21.0}]}
|
||||
]}"""
|
||||
|
||||
parsed = rb.parse(document)
|
||||
|
||||
assert parsed.valid_date == date(2026, 11, 4)
|
||||
assert parsed.rates == [rate("JPY", 0.13, 0.14, 0.135)]
|
||||
|
||||
|
||||
def test_air_uses_latest_revision_date_and_converts_to_one_unit() -> None:
|
||||
document = """{"data":{"exchangeRates":{"rates":[
|
||||
{"code":"EUR","buy":23.512,"sell":25.116,"quantity":1,"lastRevisionDate":"2026-11-03 16:00:00"},
|
||||
{"code":"VND","buy":0.812,"sell":0.868,"quantity":1000,"lastRevisionDate":null}
|
||||
]}}}"""
|
||||
|
||||
parsed = air.parse(document)
|
||||
|
||||
assert parsed.valid_date == date(2026, 11, 3)
|
||||
assert parsed.rates == [
|
||||
rate("EUR", 23.512, 25.116, 24.314, middle_origin="computed"),
|
||||
rate("VND", 0.000812, 0.000868, 0.00084, middle_origin="computed"),
|
||||
]
|
||||
|
||||
|
||||
def test_unicredit_uses_card_rates_and_units_from_the_page() -> None:
|
||||
document = """[
|
||||
{"CurrencyCode":"JPY","CardsPurchaseRate":13.255,"CardsSaleRate":14.217,"CardsMiddleRate":13.736,
|
||||
"CashPurchaseRate":13.046,"CashSaleRate":14.42,"MiddleRate":13.755,
|
||||
"ExchangeRateUpdatedTimestamp":"2026-11-04T04:25:06Z"},
|
||||
{"CurrencyCode":"TRY","CardsPurchaseRate":0.418,"CardsSaleRate":0.448,"CardsMiddleRate":0.433,
|
||||
"CashPurchaseRate":0,"CashSaleRate":0,"MiddleRate":0.431,
|
||||
"ExchangeRateUpdatedTimestamp":"2026-11-04T04:25:06Z"}
|
||||
]"""
|
||||
|
||||
parsed = unicredit.parse(document)
|
||||
|
||||
assert parsed.valid_date == date(2026, 11, 4)
|
||||
assert parsed.rates == [
|
||||
rate("JPY", 0.13255, 0.14217, 0.13736),
|
||||
rate("TRY", 0.418, 0.448, 0.433),
|
||||
]
|
||||
|
||||
|
||||
def test_csob_uses_noncash_columns_and_converts_to_one_unit() -> None:
|
||||
parsed = csob.parse(CSOB_SAMPLE)
|
||||
|
||||
@@ -275,6 +339,9 @@ def test_ppf_converts_to_one_unit_and_ignores_card_transaction_tab() -> None:
|
||||
creditas.parse,
|
||||
csob.parse,
|
||||
moneta.parse,
|
||||
rb.parse,
|
||||
air.parse,
|
||||
unicredit.parse,
|
||||
],
|
||||
)
|
||||
def test_changed_page_format_is_an_error(parser) -> None:
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import asyncio
|
||||
from dataclasses import replace
|
||||
from datetime import UTC, date, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import main, refresh
|
||||
from app.models import ParsedRates, Rate, RateSheet
|
||||
from app.sources import SOURCES
|
||||
from app.sources.base import Source
|
||||
from app.status import RefreshAttempt, build_status
|
||||
from app.storage import read_sheet, write_sheet
|
||||
|
||||
NOW = datetime(2026, 11, 4, 12, 0, tzinfo=UTC)
|
||||
INTERVAL_MINUTES = 60
|
||||
RATE = Rate(
|
||||
currency="USD",
|
||||
buy=20,
|
||||
sell=22,
|
||||
middle=21,
|
||||
buy_sell_origin="fetched",
|
||||
middle_origin="computed",
|
||||
)
|
||||
|
||||
|
||||
def store_sheet(data_dir: Path, source_id: str, fetched_at: datetime) -> None:
|
||||
write_sheet(
|
||||
data_dir,
|
||||
RateSheet(
|
||||
source=source_id,
|
||||
source_name=source_id,
|
||||
source_url="https://example.test",
|
||||
fetched_at=fetched_at,
|
||||
valid_date=date(2026, 11, 4),
|
||||
rates=[RATE],
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def succeeded_history() -> dict[str, RefreshAttempt]:
|
||||
return {source_id: RefreshAttempt(attempted_at=NOW, error=None) for source_id in SOURCES}
|
||||
|
||||
|
||||
def test_all_sources_ok(tmp_path: Path) -> None:
|
||||
for source_id in SOURCES:
|
||||
store_sheet(tmp_path, source_id, NOW)
|
||||
|
||||
result = build_status(succeeded_history(), tmp_path, NOW, INTERVAL_MINUTES)
|
||||
|
||||
assert result.status == "ok"
|
||||
assert result.problems == []
|
||||
assert all(item.state == "ok" and not item.stale for item in result.sources)
|
||||
|
||||
|
||||
def test_failed_source_is_reported_with_its_error_and_last_success(tmp_path: Path) -> None:
|
||||
for source_id in SOURCES:
|
||||
store_sheet(tmp_path, source_id, NOW)
|
||||
old_success = NOW - timedelta(hours=4)
|
||||
store_sheet(tmp_path, "kb", old_success)
|
||||
history = succeeded_history()
|
||||
history["kb"] = RefreshAttempt(attempted_at=NOW, error="HTTPStatusError: 403")
|
||||
|
||||
result = build_status(history, tmp_path, NOW, INTERVAL_MINUTES)
|
||||
|
||||
assert result.status == "degraded"
|
||||
assert result.problems == ["kb"]
|
||||
kb_status = next(item for item in result.sources if item.source == "kb")
|
||||
assert kb_status.state == "failing"
|
||||
assert kb_status.stale is True
|
||||
assert kb_status.last_success_at == old_success
|
||||
assert kb_status.last_error == "HTTPStatusError: 403"
|
||||
|
||||
|
||||
def test_source_without_attempt_or_data_is_pending_and_stale(tmp_path: Path) -> None:
|
||||
result = build_status({}, tmp_path, NOW, INTERVAL_MINUTES)
|
||||
|
||||
assert result.status == "degraded"
|
||||
assert set(result.problems) == set(SOURCES)
|
||||
assert all(item.state == "pending" and item.stale for item in result.sources)
|
||||
assert all(item.last_success_at is None for item in result.sources)
|
||||
|
||||
|
||||
def test_refresh_records_failure_and_success_and_keeps_good_file(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
async def fetch_ok(_client: object) -> str:
|
||||
return "ok"
|
||||
|
||||
async def fetch_failing(_client: object) -> str:
|
||||
raise RuntimeError("bank is down\nsecond line")
|
||||
|
||||
def parse(_document: str) -> ParsedRates:
|
||||
return ParsedRates(valid_date=date(2026, 11, 4), rates=[RATE])
|
||||
|
||||
sources = {
|
||||
"good": Source(id="good", name="Good", url="https://x.test", parse=parse, fetch=fetch_ok),
|
||||
"bad": Source(id="bad", name="Bad", url="https://x.test", parse=parse, fetch=fetch_failing),
|
||||
}
|
||||
monkeypatch.setattr(refresh, "SOURCES", sources)
|
||||
store_sheet(tmp_path, "bad", NOW)
|
||||
history: dict[str, RefreshAttempt] = {}
|
||||
|
||||
asyncio.run(refresh.refresh_all(None, tmp_path, history))
|
||||
|
||||
assert history["good"].error is None
|
||||
assert history["bad"].error == "RuntimeError: bank is down"
|
||||
assert read_sheet(tmp_path, "good") is not None
|
||||
kept = read_sheet(tmp_path, "bad")
|
||||
assert kept is not None and kept.fetched_at == NOW
|
||||
|
||||
|
||||
def test_status_endpoint_and_health_stay_available_during_outage(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setattr(main, "settings", replace(main.settings, data_dir=tmp_path))
|
||||
monkeypatch.setattr(main, "refresh_history", {})
|
||||
client = TestClient(main.app)
|
||||
|
||||
response = client.get("/status")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "degraded"
|
||||
assert client.get("/health").status_code == 200
|
||||
assert "/status" in client.get("/openapi.json").json()["paths"]
|
||||
Reference in New Issue
Block a user