"""GDELT DOC 2.0 quota handling: no http retry on 429, backoff, prose bodies. GDELT answers ``429`` with a plain-text "Please limit requests to one every 5 seconds" body and no Retry-After header. The ingester must not spend a second request from the same IP on a status error, and must stop calling until the backoff window expires instead of raising a traceback every cycle. """ from __future__ import annotations import asyncio import httpx import pytest @pytest.fixture(autouse=True) def _reset_backoff(monkeypatch): import sources sources._gdelt_clear_backoff() monkeypatch.setattr(sources, "GDELT_BACKOFF_BASE", 300) monkeypatch.setattr(sources, "GDELT_BACKOFF_MAX", 1800) yield sources._gdelt_clear_backoff() class _FakeClient: """Stands in for httpx.AsyncClient; records every GET it is asked for.""" def __init__(self, responses, calls): self._responses = list(responses) self._calls = calls async def __aenter__(self): return self async def __aexit__(self, *exc): return False async def get(self, url, params=None): self._calls.append(url) resp = self._responses.pop(0) resp.request = httpx.Request("GET", url) return resp def _install(monkeypatch, responses): import sources calls: list[str] = [] monkeypatch.setattr( sources.httpx, "AsyncClient", lambda **kw: _FakeClient(responses, calls) ) return calls def _no_publish(monkeypatch): import sources published: list[str] = [] async def _fake(subject, event): published.append(subject) monkeypatch.setattr(sources, "publish_event", _fake) return published def test_429_does_not_retry_http_and_starts_backoff(monkeypatch): import sources calls = _install( monkeypatch, [httpx.Response(429, text="Please limit requests to one every 5 seconds")], ) n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5)) assert n == 0 assert calls == [sources.GDELT_API] # exactly one request, no http fallback assert sources.gdelt_backoff_remaining() > 250 def test_cycle_skipped_while_backing_off(monkeypatch): import sources calls = _install( monkeypatch, [httpx.Response(429, text="Please limit requests to one every 5 seconds")] ) asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5)) assert len(calls) == 1 # A second cycle inside the window must not touch the network at all. n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5)) assert n == 0 assert len(calls) == 1 def test_backoff_doubles_then_caps(monkeypatch): import sources sources._gdelt_start_backoff() first = sources._gdelt_backoff_secs sources._gdelt_start_backoff() second = sources._gdelt_backoff_secs for _ in range(6): sources._gdelt_start_backoff() assert first == 300 assert second == 600 assert sources._gdelt_backoff_secs == 1800 def test_retry_after_header_is_honoured(monkeypatch): import sources _install(monkeypatch, [httpx.Response(429, headers={"Retry-After": "45"}, text="busy")]) asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5)) assert 40 <= sources.gdelt_backoff_remaining() <= 45 def test_200_prose_body_treated_as_throttle(monkeypatch): import sources calls = _install( monkeypatch, [httpx.Response(200, text="Please limit requests to one every 5 seconds")], ) n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5)) assert n == 0 assert len(calls) == 1 assert sources.gdelt_backoff_remaining() > 250 def test_success_publishes_and_clears_backoff(monkeypatch): import sources sources._gdelt_start_backoff() sources._gdelt_clear_backoff() published = _no_publish(monkeypatch) _install( monkeypatch, [ httpx.Response( 200, json={ "articles": [ { "url": "https://example.com/a", "title": "Protest", "domain": "example.com", "seendate": "20261121T120000Z", "language": "English", "sourcecountry": "United States", } ] }, ) ], ) n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5)) assert n == 1 assert published == ["events.gdelt"] assert sources.gdelt_backoff_remaining() == 0 def test_transport_error_still_falls_back_to_http(monkeypatch): import sources class _BoomClient(_FakeClient): async def get(self, url, params=None): self._calls.append(url) if url.startswith("https://"): raise httpx.ConnectError("tls handshake failed") resp = self._responses.pop(0) resp.request = httpx.Request("GET", url) return resp calls: list[str] = [] responses = [httpx.Response(200, json={"articles": []})] monkeypatch.setattr( sources.httpx, "AsyncClient", lambda **kw: _BoomClient(responses, calls) ) _no_publish(monkeypatch) n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5)) assert n == 0 assert calls == [sources.GDELT_API, sources.GDELT_API.replace("https://", "http://", 1)] assert sources.gdelt_backoff_remaining() == 0