import asyncio import time import httpx import pytest from config.settings import settings from services.external import data_go_kr, guard, open_meteo from services.external.data_go_kr import DataGoKrRequestFailed, get_body from services.external.open_meteo import OpenMeteoRequestFailed, fetch_clouds URL = "https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst" @pytest.fixture def fast(monkeypatch): monkeypatch.setattr(settings, "data_go_kr_service_key", "fake-key") monkeypatch.setattr(data_go_kr, "_BACKOFF_SEC", 0) monkeypatch.setattr(guard, "BUDGET_SEC", 0.3) def _client(handler) -> httpx.AsyncClient: return httpx.AsyncClient(transport=httpx.MockTransport(handler)) def _ok(_req: httpx.Request) -> httpx.Response: return httpx.Response(200, json={"response": {"header": {"resultCode": "00"}, "body": {"items": []}}}) @pytest.mark.anyio async def test_hanging_api_gives_up_within_budget_then_is_skipped(fast): calls = [] async def hang(req: httpx.Request) -> httpx.Response: calls.append(1) await asyncio.sleep(5) return _ok(req) async with _client(hang) as client: start = time.perf_counter() with pytest.raises(DataGoKrRequestFailed, match="no answer within"): await get_body(client, URL, {}) assert time.perf_counter() - start < 1 start = time.perf_counter() with pytest.raises(DataGoKrRequestFailed, match="skipped"): await get_body(client, URL, {}) assert time.perf_counter() - start < 0.1 assert len(calls) == 1 @pytest.mark.anyio async def test_refused_connection_is_skipped_but_other_apis_still_called(fast): def handler(req: httpx.Request) -> httpx.Response: if req.url.path.endswith("getVilageFcst"): raise httpx.ConnectError("refused") return _ok(req) async with _client(handler) as client: with pytest.raises(DataGoKrRequestFailed, match="failed after 3 attempts: ConnectError"): await get_body(client, URL, {}) with pytest.raises(DataGoKrRequestFailed, match="skipped"): await get_body(client, URL, {}) assert await get_body(client, URL.replace("getVilageFcst", "getUltraSrtFcst"), {}) == {"items": []} @pytest.mark.anyio async def test_error_code_from_api_does_not_pause_it(fast): calls = [] def handler(req: httpx.Request) -> httpx.Response: calls.append(1) return httpx.Response(200, json={"response": {"header": {"resultCode": "03", "resultMsg": "NO_DATA"}}}) async with _client(handler) as client: for _ in range(2): with pytest.raises(DataGoKrRequestFailed, match="03 NO_DATA"): await get_body(client, URL, {}) assert len(calls) == 2 @pytest.mark.anyio async def test_open_meteo_down_is_skipped(monkeypatch): monkeypatch.setattr(open_meteo, "_BUDGET_SEC", 0.3) calls = [] async def hang(req: httpx.Request) -> httpx.Response: calls.append(1) await asyncio.sleep(5) return httpx.Response(200, json=[]) async with _client(hang) as client: for _ in range(2): with pytest.raises(OpenMeteoRequestFailed): await fetch_clouds(client, [(37.5, 127.0)]) assert len(calls) == 1