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"]