From 12d55a321a293bec2b9c86d45ac920e449321eb5 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 18 Jul 2018 15:34:13 +0100 Subject: [PATCH] Show exceptions that occur during app init. Ignore non-http scopes. --- starlette/debug.py | 7 +++++-- tests/test_debug.py | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/starlette/debug.py b/starlette/debug.py index d40c6d3f..eb1455a0 100644 --- a/starlette/debug.py +++ b/starlette/debug.py @@ -9,19 +9,22 @@ class DebugMiddleware: self.app = app def __call__(self, scope): + if scope["type"] != "http": + return self.app(scope) return _DebugResponder(self.app, scope) class _DebugResponder: def __init__(self, app, scope): + self.app = app self.scope = scope - self.asgi_instance = app(scope) self.response_started = False async def __call__(self, receive, send): self.raw_send = send try: - await self.asgi_instance(receive, self.send) + asgi = self.app(self.scope) + await asgi(receive, self.send) except: if self.response_started: raise diff --git a/tests/test_debug.py b/tests/test_debug.py index 8694bb09..fffeec93 100644 --- a/tests/test_debug.py +++ b/tests/test_debug.py @@ -43,3 +43,25 @@ def test_debug_after_response_sent(): client = TestClient(DebugMiddleware(app)) with pytest.raises(RuntimeError): response = client.get("/") + + +def test_debug_error_during_scope(): + def app(scope): + raise RuntimeError("Something went wrong") + + app = DebugMiddleware(app) + client = TestClient(DebugMiddleware(app)) + response = client.get("/", headers={"Accept": "text/html, */*"}) + assert response.status_code == 500 + assert response.headers["content-type"].startswith("text/html") + assert "RuntimeError" in response.text + + +def test_debug_not_http(): + def app(scope): + raise RuntimeError("Something went wrong") + + app = DebugMiddleware(app) + + with pytest.raises(RuntimeError): + app({"type": "websocket"}) -- 2.47.2