From 2ded04c8fe9dd5bf2a905b6b0be38f99ac3fff24 Mon Sep 17 00:00:00 2001 From: Chris Withers Date: Wed, 15 Apr 2020 10:46:46 +0200 Subject: [PATCH] allow exceptions in middleware to surface when using TestClient (#888) --- starlette/testclient.py | 2 ++ tests/test_testclient.py | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/starlette/testclient.py b/starlette/testclient.py index 03506998..a4c7dffc 100644 --- a/starlette/testclient.py +++ b/starlette/testclient.py @@ -471,6 +471,8 @@ class TestClient(requests.Session): async def wait_startup(self) -> None: await self.receive_queue.put({"type": "lifespan.startup"}) message = await self.send_queue.get() + if message is None: + self.task.result() assert message["type"] in ( "lifespan.startup.complete", "lifespan.startup.failed", diff --git a/tests/test_testclient.py b/tests/test_testclient.py index 504034b6..25bb4b9d 100644 --- a/tests/test_testclient.py +++ b/tests/test_testclient.py @@ -3,6 +3,7 @@ import asyncio import pytest from starlette.applications import Starlette +from starlette.middleware import Middleware from starlette.responses import JSONResponse from starlette.testclient import TestClient from starlette.websockets import WebSocket, WebSocketDisconnect @@ -56,6 +57,25 @@ def test_error_on_startup(): pass # pragma: no cover +def test_exception_in_middleware(): + + class MiddlewareException(Exception): + pass + + class BrokenMiddleware: + def __init__(self, app): + self.app = app + + async def __call__(self, scope, receive, send): + raise MiddlewareException() + + broken_middleware = Starlette(middleware=[Middleware(BrokenMiddleware)]) + + with pytest.raises(MiddlewareException): + with TestClient(broken_middleware): + pass # pragma: no cover + + def test_testclient_asgi2(): def app(scope): async def inner(receive, send):