|
| 1 | +"""Tests for the sync CircuitBreaker middleware (mirror of AsyncCircuitBreaker).""" |
| 2 | + |
| 3 | +import logging |
| 4 | +import threading |
| 5 | +from collections.abc import Callable |
| 6 | +from http import HTTPStatus |
| 7 | + |
| 8 | +import httpx2 |
| 9 | +import pytest |
| 10 | + |
| 11 | +from httpware import ( |
| 12 | + CircuitOpenError, |
| 13 | + Client, |
| 14 | + InternalServerError, |
| 15 | + NetworkError, |
| 16 | + NotFoundError, |
| 17 | + RateLimitedError, |
| 18 | + ServiceUnavailableError, |
| 19 | +) |
| 20 | +from httpware.middleware.resilience.circuit_breaker import CircuitBreaker |
| 21 | + |
| 22 | + |
| 23 | +class _Clock: |
| 24 | + def __init__(self) -> None: |
| 25 | + self.t = 0.0 |
| 26 | + |
| 27 | + def __call__(self) -> float: |
| 28 | + return self.t |
| 29 | + |
| 30 | + def advance(self, seconds: float) -> None: |
| 31 | + self.t += seconds |
| 32 | + |
| 33 | + |
| 34 | +class _StatusSequence: |
| 35 | + def __init__(self, statuses: list[int]) -> None: |
| 36 | + self._statuses = list(statuses) |
| 37 | + self.calls = 0 |
| 38 | + |
| 39 | + def __call__(self, request: httpx2.Request) -> httpx2.Response: |
| 40 | + self.calls += 1 |
| 41 | + status = self._statuses.pop(0) if self._statuses else HTTPStatus.OK |
| 42 | + return httpx2.Response(status, request=request) |
| 43 | + |
| 44 | + |
| 45 | +def _client(handler: Callable[[httpx2.Request], httpx2.Response], *, breaker: CircuitBreaker) -> Client: |
| 46 | + return Client( |
| 47 | + httpx2_client=httpx2.Client(transport=httpx2.MockTransport(handler)), |
| 48 | + middleware=[breaker], |
| 49 | + ) |
| 50 | + |
| 51 | + |
| 52 | +def test_failure_threshold_below_one_rejected() -> None: |
| 53 | + with pytest.raises(ValueError, match="failure_threshold must be >= 1"): |
| 54 | + CircuitBreaker(failure_threshold=0) |
| 55 | + |
| 56 | + |
| 57 | +def test_negative_reset_timeout_rejected() -> None: |
| 58 | + with pytest.raises(ValueError, match="reset_timeout must be >= 0"): |
| 59 | + CircuitBreaker(reset_timeout=-1.0) |
| 60 | + |
| 61 | + |
| 62 | +def test_success_threshold_below_one_rejected() -> None: |
| 63 | + with pytest.raises(ValueError, match="success_threshold must be >= 1"): |
| 64 | + CircuitBreaker(success_threshold=0) |
| 65 | + |
| 66 | + |
| 67 | +def test_closed_passes_through() -> None: |
| 68 | + handler = _StatusSequence([HTTPStatus.OK]) |
| 69 | + breaker = CircuitBreaker(failure_threshold=3, _now=_Clock()) |
| 70 | + with _client(handler, breaker=breaker) as client: |
| 71 | + response = client.get("https://example.test/x") |
| 72 | + assert response.status_code == HTTPStatus.OK |
| 73 | + |
| 74 | + |
| 75 | +def test_open_emits_opened_event_and_rejects(caplog: pytest.LogCaptureFixture) -> None: |
| 76 | + handler = _StatusSequence([500, 500]) |
| 77 | + breaker = CircuitBreaker(failure_threshold=2, _now=_Clock()) |
| 78 | + with ( |
| 79 | + _client(handler, breaker=breaker) as client, |
| 80 | + caplog.at_level(logging.WARNING, logger="httpware.circuit_breaker"), |
| 81 | + ): |
| 82 | + for _ in range(2): |
| 83 | + with pytest.raises(InternalServerError): |
| 84 | + client.get("https://example.test/x") |
| 85 | + with pytest.raises(CircuitOpenError) as info: |
| 86 | + client.get("https://example.test/y") |
| 87 | + assert info.value.retry_after is not None |
| 88 | + assert handler.calls == 2 # noqa: PLR2004 |
| 89 | + records = [r for r in caplog.records if r.name == "httpware.circuit_breaker"] |
| 90 | + assert any("opened" in r.message for r in records) |
| 91 | + assert any("rejecting" in r.message for r in records) |
| 92 | + |
| 93 | + |
| 94 | +def test_success_resets_failure_streak() -> None: |
| 95 | + handler = _StatusSequence([500, 500, 200, 500, 500]) |
| 96 | + breaker = CircuitBreaker(failure_threshold=3, _now=_Clock()) |
| 97 | + with _client(handler, breaker=breaker) as client: |
| 98 | + for _ in range(2): |
| 99 | + with pytest.raises(InternalServerError): |
| 100 | + client.get("https://example.test/x") |
| 101 | + client.get("https://example.test/x") |
| 102 | + for _ in range(2): |
| 103 | + with pytest.raises(InternalServerError): |
| 104 | + client.get("https://example.test/x") |
| 105 | + response = client.get("https://example.test/x") |
| 106 | + assert response.status_code == HTTPStatus.OK |
| 107 | + assert handler.calls == 6 # noqa: PLR2004 — 2 failures + 1 success + 2 failures + 1 success |
| 108 | + |
| 109 | + |
| 110 | +def test_404_and_429_do_not_count_as_failures() -> None: |
| 111 | + handler = _StatusSequence([404, 429, 404, 429, 404]) |
| 112 | + breaker = CircuitBreaker(failure_threshold=2, _now=_Clock()) |
| 113 | + with _client(handler, breaker=breaker) as client: |
| 114 | + for _ in range(5): |
| 115 | + with pytest.raises((NotFoundError, RateLimitedError)): |
| 116 | + client.get("https://example.test/x") |
| 117 | + assert handler.calls == 5 # noqa: PLR2004 — never opened, all five reached the transport |
| 118 | + |
| 119 | + |
| 120 | +def test_network_error_counts_as_failure() -> None: |
| 121 | + def _raise(request: httpx2.Request) -> httpx2.Response: # noqa: ARG001 |
| 122 | + msg = "connect failed" |
| 123 | + raise httpx2.ConnectError(msg) |
| 124 | + |
| 125 | + breaker = CircuitBreaker(failure_threshold=2, _now=_Clock()) |
| 126 | + with _client(_raise, breaker=breaker) as client: |
| 127 | + for _ in range(2): |
| 128 | + with pytest.raises(NetworkError): |
| 129 | + client.get("https://example.test/x") |
| 130 | + with pytest.raises(CircuitOpenError): |
| 131 | + client.get("https://example.test/x") |
| 132 | + |
| 133 | + |
| 134 | +def test_custom_failure_status_codes_trips_on_member() -> None: |
| 135 | + handler = _StatusSequence([503, 503]) |
| 136 | + breaker = CircuitBreaker(failure_threshold=2, failure_status_codes=frozenset({503}), _now=_Clock()) |
| 137 | + with _client(handler, breaker=breaker) as client: |
| 138 | + for _ in range(2): |
| 139 | + with pytest.raises(ServiceUnavailableError): |
| 140 | + client.get("https://example.test/x") |
| 141 | + with pytest.raises(CircuitOpenError): |
| 142 | + client.get("https://example.test/x") |
| 143 | + assert handler.calls == 2 # noqa: PLR2004 |
| 144 | + |
| 145 | + |
| 146 | +def test_custom_failure_status_codes_excludes_other_5xx() -> None: |
| 147 | + handler = _StatusSequence([500, 500, 500, 500]) |
| 148 | + breaker = CircuitBreaker(failure_threshold=2, failure_status_codes=frozenset({503}), _now=_Clock()) |
| 149 | + with _client(handler, breaker=breaker) as client: |
| 150 | + for _ in range(4): |
| 151 | + with pytest.raises(InternalServerError): |
| 152 | + client.get("https://example.test/x") |
| 153 | + assert handler.calls == 4 # noqa: PLR2004 # 500 not in custom set -> never opened |
| 154 | + |
| 155 | + |
| 156 | +def test_non_counted_exception_propagates_without_state_change() -> None: |
| 157 | + class _Boom: |
| 158 | + def __call__(self, request: httpx2.Request, next: object) -> httpx2.Response: # noqa: A002,ARG002 |
| 159 | + msg = "boom" |
| 160 | + raise ValueError(msg) |
| 161 | + |
| 162 | + handler = _StatusSequence([200]) |
| 163 | + breaker = CircuitBreaker(failure_threshold=1, _now=_Clock()) |
| 164 | + client = Client( |
| 165 | + httpx2_client=httpx2.Client(transport=httpx2.MockTransport(handler)), |
| 166 | + middleware=[breaker, _Boom()], |
| 167 | + ) |
| 168 | + with client: |
| 169 | + for _ in range(3): |
| 170 | + with pytest.raises(ValueError, match="boom"): |
| 171 | + client.get("https://example.test/x") |
| 172 | + |
| 173 | + |
| 174 | +def test_reset_timeout_admits_probe_then_closes(caplog: pytest.LogCaptureFixture) -> None: |
| 175 | + clock = _Clock() |
| 176 | + handler = _StatusSequence([500, 500, 200]) |
| 177 | + breaker = CircuitBreaker(failure_threshold=2, reset_timeout=30.0, success_threshold=1, _now=clock) |
| 178 | + with _client(handler, breaker=breaker) as client: |
| 179 | + for _ in range(2): |
| 180 | + with pytest.raises(InternalServerError): |
| 181 | + client.get("https://example.test/x") |
| 182 | + with pytest.raises(CircuitOpenError): |
| 183 | + client.get("https://example.test/x") |
| 184 | + assert handler.calls == 2 # noqa: PLR2004 |
| 185 | + clock.advance(30.0) |
| 186 | + with caplog.at_level(logging.INFO, logger="httpware.circuit_breaker"): |
| 187 | + response = client.get("https://example.test/x") |
| 188 | + assert response.status_code == HTTPStatus.OK |
| 189 | + assert handler.calls == 3 # noqa: PLR2004 |
| 190 | + messages = [r.message for r in caplog.records if r.name == "httpware.circuit_breaker"] |
| 191 | + assert any("half-open" in m for m in messages) |
| 192 | + assert any("closed" in m for m in messages) |
| 193 | + |
| 194 | + |
| 195 | +def test_probe_failure_reopens_circuit() -> None: |
| 196 | + clock = _Clock() |
| 197 | + handler = _StatusSequence([500, 500, 500]) |
| 198 | + breaker = CircuitBreaker(failure_threshold=2, reset_timeout=10.0, _now=clock) |
| 199 | + with _client(handler, breaker=breaker) as client: |
| 200 | + for _ in range(2): |
| 201 | + with pytest.raises(InternalServerError): |
| 202 | + client.get("https://example.test/x") |
| 203 | + clock.advance(10.0) |
| 204 | + with pytest.raises(InternalServerError): |
| 205 | + client.get("https://example.test/x") |
| 206 | + with pytest.raises(CircuitOpenError): |
| 207 | + client.get("https://example.test/x") |
| 208 | + assert handler.calls == 3 # noqa: PLR2004 |
| 209 | + |
| 210 | + |
| 211 | +def test_success_threshold_requires_multiple_probes() -> None: |
| 212 | + clock = _Clock() |
| 213 | + handler = _StatusSequence([500, 500, 200, 200]) |
| 214 | + breaker = CircuitBreaker(failure_threshold=2, reset_timeout=5.0, success_threshold=2, _now=clock) |
| 215 | + with _client(handler, breaker=breaker) as client: |
| 216 | + for _ in range(2): |
| 217 | + with pytest.raises(InternalServerError): |
| 218 | + client.get("https://example.test/x") |
| 219 | + clock.advance(5.0) |
| 220 | + client.get("https://example.test/x") # probe 1 -> 200 (HALF_OPEN 1/2) |
| 221 | + client.get("https://example.test/x") # probe 2 -> 200 -> CLOSED |
| 222 | + response = client.get("https://example.test/x") # default 200, CLOSED |
| 223 | + assert response.status_code == HTTPStatus.OK |
| 224 | + assert handler.calls == 5 # noqa: PLR2004 — 2 failures + 2 probes + 1 CLOSED |
| 225 | + |
| 226 | + |
| 227 | +def test_half_open_second_concurrent_request_rejected_with_none_retry_after() -> None: |
| 228 | + """Two threads hit a half-open breaker; exactly one is the probe, the other is rejected.""" |
| 229 | + clock = _Clock() |
| 230 | + probe_started = threading.Event() |
| 231 | + release_probe = threading.Event() |
| 232 | + |
| 233 | + def _handler(request: httpx2.Request) -> httpx2.Response: |
| 234 | + probe_started.set() |
| 235 | + release_probe.wait(timeout=5.0) |
| 236 | + return httpx2.Response(HTTPStatus.OK, request=request) |
| 237 | + |
| 238 | + breaker = CircuitBreaker(failure_threshold=1, reset_timeout=1.0, _now=clock) |
| 239 | + open_handler = _StatusSequence([500]) |
| 240 | + with _client(open_handler, breaker=breaker) as opener, pytest.raises(InternalServerError): |
| 241 | + opener.get("https://example.test/x") |
| 242 | + clock.advance(1.0) |
| 243 | + |
| 244 | + client = Client( |
| 245 | + httpx2_client=httpx2.Client(transport=httpx2.MockTransport(_handler)), |
| 246 | + middleware=[breaker], |
| 247 | + ) |
| 248 | + rejected: list[CircuitOpenError] = [] |
| 249 | + |
| 250 | + def _probe() -> None: |
| 251 | + client.get("https://example.test/probe") |
| 252 | + |
| 253 | + with client: |
| 254 | + thread = threading.Thread(target=_probe) |
| 255 | + thread.start() |
| 256 | + assert probe_started.wait(timeout=5.0) |
| 257 | + with pytest.raises(CircuitOpenError) as info: |
| 258 | + client.get("https://example.test/concurrent") |
| 259 | + rejected.append(info.value) |
| 260 | + release_probe.set() |
| 261 | + thread.join(timeout=5.0) |
| 262 | + |
| 263 | + assert rejected[0].retry_after is None |
0 commit comments