|
1 | 1 | """Tests for the Middleware protocol and chain composition.""" |
2 | 2 |
|
| 3 | +import asyncio |
3 | 4 | from collections.abc import Awaitable, Callable |
4 | 5 | from contextlib import AbstractAsyncContextManager |
5 | 6 | from typing import get_type_hints |
6 | 7 |
|
| 8 | +import pytest |
| 9 | + |
7 | 10 | from httpware._internal.chain import compose |
8 | 11 | from httpware.middleware import Middleware, Next |
9 | 12 | from httpware.request import Request |
@@ -155,3 +158,108 @@ async def __call__(self, request: Request, next: Next) -> Response: # noqa: A00 |
155 | 158 |
|
156 | 159 | assert response.headers["x-trace"] == "abc123" |
157 | 160 | 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