Skip to content

Commit

Permalink
Cancel task group after returning middleware response
Browse files Browse the repository at this point in the history
Add test for encode#1022
  • Loading branch information
uSpike committed Jun 13, 2021
1 parent a1ceb35 commit 63cfcb9
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
1 change: 1 addition & 0 deletions starlette/middleware/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ async def body_stream() -> typing.AsyncGenerator[bytes, None]:
request = Request(scope, receive=receive)
response = await self.dispatch_func(request, call_next)
await response(scope, receive, send)
task_group.cancel_scope.cancel()

async def dispatch(
self, request: Request, call_next: RequestResponseEndpoint
Expand Down
15 changes: 15 additions & 0 deletions tests/middleware/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,3 +143,18 @@ def homepage(request):
def test_middleware_repr():
middleware = Middleware(CustomMiddleware)
assert repr(middleware) == "Middleware(CustomMiddleware)"


def test_fully_evaluated_response():
# Test for https://github.com/encode/starlette/issues/1022
class CustomMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
await call_next(request)
return PlainTextResponse("Custom")

app = Starlette()
app.add_middleware(CustomMiddleware)

client = TestClient(app)
response = client.get("/does_not_exist")
assert response.text == "Custom"

0 comments on commit 63cfcb9

Please sign in to comment.