Skip to content

Commit

Permalink
Fix middleware traceback fetching on Python 3.8+, fix ResourceWarning…
Browse files Browse the repository at this point in the history
…s in TestClient, fix CI build (#1132)

* Add __init__ file for tests.middleware so Mypy 0.800 is happy

* testclient: Tie loop lifetime to thread

* ServerErrorMiddleware: Don't use undocumented TracebackException.exc_traceback attribute
  • Loading branch information
JayH5 committed Jan 31, 2021
1 parent e430706 commit 62e95b8
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 8 deletions.
12 changes: 6 additions & 6 deletions starlette/middleware/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,15 +217,15 @@ def generate_html(self, exc: Exception, limit: int = 7) -> str:
traceback_obj = traceback.TracebackException.from_exception(
exc, capture_locals=True
)
frames = inspect.getinnerframes(
traceback_obj.exc_traceback, limit # type: ignore
)

exc_html = ""
is_collapsed = False
for frame in reversed(frames):
exc_html += self.generate_frame_html(frame, is_collapsed)
is_collapsed = True
exc_traceback = exc.__traceback__
if exc_traceback is not None:
frames = inspect.getinnerframes(exc_traceback, limit)
for frame in reversed(frames):
exc_html += self.generate_frame_html(frame, is_collapsed)
is_collapsed = True

# escape error class and text
error = (
Expand Down
6 changes: 4 additions & 2 deletions starlette/testclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,6 @@ def __init__(self, app: ASGI3App, scope: Scope) -> None:
self.app = app
self.scope = scope
self.accepted_subprotocol = None
self._loop = asyncio.new_event_loop()
self._receive_queue = queue.Queue() # type: queue.Queue
self._send_queue = queue.Queue() # type: queue.Queue
self._thread = threading.Thread(target=self._run)
Expand All @@ -293,13 +292,16 @@ def _run(self) -> None:
"""
The sub-thread in which the websocket session runs.
"""
loop = asyncio.new_event_loop()
scope = self.scope
receive = self._asgi_receive
send = self._asgi_send
try:
self._loop.run_until_complete(self.app(scope, receive, send))
loop.run_until_complete(self.app(scope, receive, send))
except BaseException as exc:
self._send_queue.put(exc)
finally:
loop.close()

async def _asgi_receive(self) -> Message:
while self._receive_queue.empty():
Expand Down
Empty file added tests/middleware/__init__.py
Empty file.

0 comments on commit 62e95b8

Please sign in to comment.