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]