|
| 1 | +"""Tests for the Retry middleware. |
| 2 | +
|
| 3 | +Mocks the transport via httpx2.MockTransport; injects a recording `_sleep` |
| 4 | +callable so the suite runs instantly without freezegun. |
| 5 | +""" |
| 6 | + |
| 7 | +from collections.abc import Callable |
| 8 | +from http import HTTPStatus |
| 9 | + |
| 10 | +import httpx2 |
| 11 | +import pytest |
| 12 | + |
| 13 | +from httpware import AsyncClient, NotFoundError, ServiceUnavailableError |
| 14 | +from httpware.errors import RetryBudgetExhaustedError |
| 15 | +from httpware.middleware.resilience.budget import RetryBudget |
| 16 | +from httpware.middleware.resilience.retry import ( |
| 17 | + DEFAULT_IDEMPOTENT_METHODS, |
| 18 | + DEFAULT_RETRY_STATUS_CODES, |
| 19 | + Retry, |
| 20 | +) |
| 21 | + |
| 22 | + |
| 23 | +class _SleepRecorder: |
| 24 | + def __init__(self) -> None: |
| 25 | + self.calls: list[float] = [] |
| 26 | + |
| 27 | + async def __call__(self, delay: float) -> None: |
| 28 | + self.calls.append(delay) |
| 29 | + |
| 30 | + |
| 31 | +class _ResponseSequence: |
| 32 | + """Mock-transport handler that returns a fixed sequence of responses.""" |
| 33 | + |
| 34 | + def __init__(self, statuses: list[int]) -> None: |
| 35 | + self._statuses = list(statuses) |
| 36 | + self.calls: int = 0 |
| 37 | + |
| 38 | + def __call__(self, request: httpx2.Request) -> httpx2.Response: |
| 39 | + self.calls += 1 |
| 40 | + status = self._statuses.pop(0) if self._statuses else HTTPStatus.OK |
| 41 | + return httpx2.Response(status, request=request) |
| 42 | + |
| 43 | + |
| 44 | +def _client(handler: Callable[[httpx2.Request], httpx2.Response], *, retry: Retry) -> AsyncClient: |
| 45 | + transport = httpx2.MockTransport(handler) |
| 46 | + return AsyncClient( |
| 47 | + httpx2_client=httpx2.AsyncClient(transport=transport), |
| 48 | + middleware=[retry], |
| 49 | + ) |
| 50 | + |
| 51 | + |
| 52 | +def test_default_retry_status_codes_match_spec() -> None: |
| 53 | + assert frozenset({408, 429, 502, 503, 504}) == DEFAULT_RETRY_STATUS_CODES |
| 54 | + |
| 55 | + |
| 56 | +def test_default_idempotent_methods_match_spec() -> None: |
| 57 | + assert frozenset({"GET", "HEAD", "OPTIONS", "PUT", "DELETE"}) == DEFAULT_IDEMPOTENT_METHODS |
| 58 | + |
| 59 | + |
| 60 | +async def test_succeeds_first_try_no_sleep() -> None: |
| 61 | + sleeper = _SleepRecorder() |
| 62 | + handler = _ResponseSequence([HTTPStatus.OK]) |
| 63 | + client = _client(handler, retry=Retry(_sleep=sleeper)) |
| 64 | + response = await client.get("https://example.test/x") |
| 65 | + assert response.status_code == HTTPStatus.OK |
| 66 | + assert handler.calls == 1 |
| 67 | + assert sleeper.calls == [] |
| 68 | + |
| 69 | + |
| 70 | +async def test_retries_503_then_succeeds() -> None: |
| 71 | + sleeper = _SleepRecorder() |
| 72 | + handler = _ResponseSequence([HTTPStatus.SERVICE_UNAVAILABLE, HTTPStatus.OK]) |
| 73 | + client = _client(handler, retry=Retry(_sleep=sleeper, base_delay=0.01, max_delay=0.02)) |
| 74 | + response = await client.get("https://example.test/x") |
| 75 | + assert response.status_code == HTTPStatus.OK |
| 76 | + assert handler.calls == 2 # noqa: PLR2004 — "2" is intentional literal in test assertion |
| 77 | + assert len(sleeper.calls) == 1 |
| 78 | + assert 0.0 <= sleeper.calls[0] <= 0.02 # noqa: PLR2004 — 0.02 matches max_delay literal above |
| 79 | + |
| 80 | + |
| 81 | +async def test_gives_up_after_max_attempts_and_reraises_status_error() -> None: |
| 82 | + sleeper = _SleepRecorder() |
| 83 | + handler = _ResponseSequence([HTTPStatus.SERVICE_UNAVAILABLE] * 3) |
| 84 | + client = _client(handler, retry=Retry(_sleep=sleeper, base_delay=0.01, max_delay=0.02, max_attempts=3)) |
| 85 | + with pytest.raises(ServiceUnavailableError) as info: |
| 86 | + await client.get("https://example.test/x") |
| 87 | + assert handler.calls == 3 # noqa: PLR2004 — "3" is intentional literal in test assertion |
| 88 | + assert len(sleeper.calls) == 2 # noqa: PLR2004 — max_attempts=3 → 2 sleeps between 3 attempts |
| 89 | + notes = getattr(info.value, "__notes__", []) |
| 90 | + assert any("gave up after 3 attempts" in note for note in notes) |
| 91 | + |
| 92 | + |
| 93 | +async def test_does_not_retry_non_retryable_status() -> None: |
| 94 | + sleeper = _SleepRecorder() |
| 95 | + handler = _ResponseSequence([HTTPStatus.NOT_FOUND]) |
| 96 | + client = _client(handler, retry=Retry(_sleep=sleeper)) |
| 97 | + with pytest.raises(NotFoundError): |
| 98 | + await client.get("https://example.test/x") |
| 99 | + assert handler.calls == 1 |
| 100 | + assert sleeper.calls == [] |
| 101 | + |
| 102 | + |
| 103 | +async def test_does_not_retry_non_idempotent_methods_by_default() -> None: |
| 104 | + sleeper = _SleepRecorder() |
| 105 | + handler = _ResponseSequence([HTTPStatus.SERVICE_UNAVAILABLE]) |
| 106 | + client = _client(handler, retry=Retry(_sleep=sleeper)) |
| 107 | + with pytest.raises(ServiceUnavailableError): |
| 108 | + await client.post("https://example.test/x", json={"x": 1}) |
| 109 | + assert handler.calls == 1 |
| 110 | + assert sleeper.calls == [] |
| 111 | + |
| 112 | + |
| 113 | +async def test_retries_post_when_method_explicitly_included() -> None: |
| 114 | + sleeper = _SleepRecorder() |
| 115 | + handler = _ResponseSequence([HTTPStatus.SERVICE_UNAVAILABLE, HTTPStatus.OK]) |
| 116 | + methods = frozenset(DEFAULT_IDEMPOTENT_METHODS | {"POST"}) |
| 117 | + client = _client( |
| 118 | + handler, |
| 119 | + retry=Retry(_sleep=sleeper, retry_methods=methods, base_delay=0.01, max_delay=0.02), |
| 120 | + ) |
| 121 | + response = await client.post("https://example.test/x", json={"x": 1}) |
| 122 | + assert response.status_code == HTTPStatus.OK |
| 123 | + assert handler.calls == 2 # noqa: PLR2004 — "2" is intentional literal in test assertion |
| 124 | + |
| 125 | + |
| 126 | +async def test_max_attempts_one_means_no_retries() -> None: |
| 127 | + sleeper = _SleepRecorder() |
| 128 | + handler = _ResponseSequence([HTTPStatus.SERVICE_UNAVAILABLE]) |
| 129 | + client = _client(handler, retry=Retry(_sleep=sleeper, max_attempts=1)) |
| 130 | + with pytest.raises(ServiceUnavailableError): |
| 131 | + await client.get("https://example.test/x") |
| 132 | + assert handler.calls == 1 |
| 133 | + assert sleeper.calls == [] |
| 134 | + |
| 135 | + |
| 136 | +def test_max_attempts_zero_rejected() -> None: |
| 137 | + with pytest.raises(ValueError, match="max_attempts must be >= 1"): |
| 138 | + Retry(max_attempts=0) |
| 139 | + |
| 140 | + |
| 141 | +async def test_budget_exhausted_raises_retry_budget_exhausted_error() -> None: |
| 142 | + sleeper = _SleepRecorder() |
| 143 | + handler = _ResponseSequence([HTTPStatus.SERVICE_UNAVAILABLE, HTTPStatus.SERVICE_UNAVAILABLE]) |
| 144 | + # Budget with zero tolerance: percent_can_retry=0.0, min_retries_per_sec=0.0 → ceiling=0 |
| 145 | + stingy_budget = RetryBudget(percent_can_retry=0.0, min_retries_per_sec=0.0) |
| 146 | + client = _client( |
| 147 | + handler, |
| 148 | + retry=Retry(_sleep=sleeper, budget=stingy_budget, max_attempts=3, base_delay=0.01), |
| 149 | + ) |
| 150 | + with pytest.raises(RetryBudgetExhaustedError) as info: |
| 151 | + await client.get("https://example.test/x") |
| 152 | + assert handler.calls == 1 |
| 153 | + assert info.value.attempts == 1 |
| 154 | + assert sleeper.calls == [] |
0 commit comments