Skip to content

Commit a929686

Browse files
lesnik512claude
andcommitted
test(story-2.1): short-circuit, exception propagation, cancellation, reusability
Adds five tests covering the remaining acceptance criteria: - short-circuit middleware bypasses inner layers and the transport - exceptions raised inside middleware bubble through unchanged - exceptions raised by the transport pass through middleware unchanged - asyncio.CancelledError propagates (NFR15) - the Next returned by compose can be reused across sequential requests No production code changes; compose's no-try/except design carries the cancellation guarantee. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent e2ebade commit a929686

1 file changed

Lines changed: 108 additions & 0 deletions

File tree

‎tests/test_middleware.py‎

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
"""Tests for the Middleware protocol and chain composition."""
22

3+
import asyncio
34
from collections.abc import Awaitable, Callable
45
from contextlib import AbstractAsyncContextManager
56
from typing import get_type_hints
67

8+
import pytest
9+
710
from httpware._internal.chain import compose
811
from httpware.middleware import Middleware, Next
912
from httpware.request import Request
@@ -155,3 +158,108 @@ async def __call__(self, request: Request, next: Next) -> Response: # noqa: A00
155158

156159
assert response.headers["x-trace"] == "abc123"
157160
assert response.headers["x-from"] == "transport" # original still present
161+
162+
163+
async def test_short_circuit_returns_synthesized_response() -> None:
164+
"""A middleware that does NOT call next returns a synthesized Response; transport never runs."""
165+
transport_calls = 0
166+
167+
class CountingTransport(_OkTransport):
168+
async def __call__(self, request: Request) -> Response:
169+
nonlocal transport_calls
170+
transport_calls += 1
171+
return await super().__call__(request)
172+
173+
class ShortCircuit:
174+
async def __call__(self, request: Request, next: Next) -> Response: # noqa: A002, ARG002
175+
return Response(
176+
status=418,
177+
headers={},
178+
content=b"teapot",
179+
url=request.url,
180+
elapsed=0.0,
181+
)
182+
183+
class NeverReached:
184+
async def __call__(self, request: Request, next: Next) -> Response: # noqa: A002, ARG002
185+
msg = "inner middleware should not be invoked"
186+
raise AssertionError(msg)
187+
188+
response = await compose([ShortCircuit(), NeverReached()], CountingTransport())(_make_request())
189+
190+
assert response.status == 418 # noqa: PLR2004
191+
assert response.content == b"teapot"
192+
assert transport_calls == 0
193+
194+
195+
async def test_exception_in_middleware_propagates() -> None:
196+
"""A custom exception raised inside a middleware bubbles through the chain unchanged."""
197+
198+
class CustomError(Exception):
199+
pass
200+
201+
class Boom:
202+
async def __call__(self, request: Request, next: Next) -> Response: # noqa: A002, ARG002
203+
msg = "boom"
204+
raise CustomError(msg)
205+
206+
with pytest.raises(CustomError, match="boom"):
207+
await compose([Boom()], _OkTransport())(_make_request())
208+
209+
210+
async def test_exception_in_transport_propagates_through_chain() -> None:
211+
"""An exception raised by the transport passes through every middleware unmodified."""
212+
213+
class TransportFail:
214+
async def __call__(self, request: Request) -> Response: # noqa: ARG002
215+
msg = "transport failed"
216+
raise RuntimeError(msg)
217+
218+
def stream( # pragma: no cover - not exercised
219+
self, request: Request
220+
) -> AbstractAsyncContextManager[StreamResponse]:
221+
raise NotImplementedError
222+
223+
async def aclose(self) -> None: # pragma: no cover - not exercised
224+
return None
225+
226+
class Passthrough:
227+
async def __call__(self, request: Request, next: Next) -> Response: # noqa: A002
228+
return await next(request)
229+
230+
with pytest.raises(RuntimeError, match="transport failed"):
231+
await compose([Passthrough(), Passthrough()], TransportFail())(_make_request())
232+
233+
234+
async def test_cancelled_error_propagates_through_chain() -> None:
235+
"""asyncio.CancelledError raised mid-chain propagates to the caller (NFR15)."""
236+
237+
class Cancel:
238+
async def __call__(self, request: Request, next: Next) -> Response: # noqa: A002, ARG002
239+
raise asyncio.CancelledError
240+
241+
class Passthrough:
242+
async def __call__(self, request: Request, next: Next) -> Response: # noqa: A002
243+
return await next(request)
244+
245+
with pytest.raises(asyncio.CancelledError):
246+
await compose([Passthrough(), Cancel()], _OkTransport())(_make_request())
247+
248+
249+
async def test_compose_returned_callable_is_reusable() -> None:
250+
"""The Next returned by compose can be awaited sequentially across multiple requests."""
251+
count = 0
252+
253+
class Counter:
254+
async def __call__(self, request: Request, next: Next) -> Response: # noqa: A002
255+
nonlocal count
256+
count += 1
257+
return await next(request)
258+
259+
dispatch = compose([Counter()], _OkTransport())
260+
261+
for _ in range(3):
262+
response = await dispatch(_make_request())
263+
assert response.status == 200 # noqa: PLR2004
264+
265+
assert count == 3 # noqa: PLR2004

0 commit comments

Comments
 (0)