starlette/tests/middleware/test_base.py

161 lines
4.3 KiB
Python
Raw Normal View History

import pytest
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import PlainTextResponse
from starlette.routing import Route
from starlette.testclient import TestClient
2019-06-17 14:29:49 +00:00
class CustomMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
response = await call_next(request)
response.headers["Custom-Header"] = "Example"
return response
app = Starlette()
app.add_middleware(CustomMiddleware)
2019-06-17 14:29:49 +00:00
@app.route("/")
def homepage(request):
return PlainTextResponse("Homepage")
2019-06-17 14:29:49 +00:00
@app.route("/exc")
def exc(request):
raise Exception()
2019-06-17 14:29:49 +00:00
@app.route("/no-response")
class NoResponse:
def __init__(self, scope, receive, send):
pass
2019-06-17 14:29:49 +00:00
def __await__(self):
return self.dispatch().__await__()
2019-06-17 14:29:49 +00:00
async def dispatch(self):
pass
2019-06-17 14:29:49 +00:00
@app.websocket_route("/ws")
async def websocket_endpoint(session):
await session.accept()
await session.send_text("Hello, world!")
await session.close()
def test_custom_middleware():
client = TestClient(app)
response = client.get("/")
assert response.headers["Custom-Header"] == "Example"
with pytest.raises(Exception):
response = client.get("/exc")
with pytest.raises(RuntimeError):
response = client.get("/no-response")
with client.websocket_connect("/ws") as session:
text = session.receive_text()
assert text == "Hello, world!"
def test_middleware_decorator():
app = Starlette()
@app.route("/homepage")
def homepage(request):
return PlainTextResponse("Homepage")
@app.middleware("http")
async def plaintext(request, call_next):
if request.url.path == "/":
return PlainTextResponse("OK")
response = await call_next(request)
response.headers["Custom"] = "Example"
return response
client = TestClient(app)
response = client.get("/")
assert response.text == "OK"
response = client.get("/homepage")
assert response.text == "Homepage"
assert response.headers["Custom"] == "Example"
2019-06-17 12:56:29 +00:00
def test_state_data_across_multiple_middlewares():
2019-06-17 12:56:29 +00:00
expected_value1 = "foo"
expected_value2 = "bar"
class aMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
2019-06-16 16:18:38 +00:00
request.state.foo = expected_value1
response = await call_next(request)
return response
class bMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
2019-06-16 16:18:38 +00:00
request.state.bar = expected_value2
response = await call_next(request)
2019-06-16 16:18:38 +00:00
response.headers["X-State-Foo"] = request.state.foo
return response
class cMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
response = await call_next(request)
response.headers["X-State-Bar"] = request.state.bar
return response
app = Starlette()
app.add_middleware(aMiddleware)
app.add_middleware(bMiddleware)
2019-06-16 16:18:38 +00:00
app.add_middleware(cMiddleware)
@app.route("/")
def homepage(request):
return PlainTextResponse("OK")
client = TestClient(app)
response = client.get("/")
assert response.text == "OK"
2019-06-16 16:18:38 +00:00
assert response.headers["X-State-Foo"] == expected_value1
assert response.headers["X-State-Bar"] == expected_value2
def test_app_middleware_argument():
def homepage(request):
return PlainTextResponse("Homepage")
app = Starlette(
routes=[Route("/", homepage)], middleware=[Middleware(CustomMiddleware)]
)
client = TestClient(app)
response = client.get("/")
assert response.headers["Custom-Header"] == "Example"
def test_middleware_repr():
middleware = Middleware(CustomMiddleware)
assert repr(middleware) == "Middleware(CustomMiddleware)"
anyio integration (#1157) * First whack at anyio integration * Fix formatting * Remove debug messages * mypy fixes * Update README.md Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com> * Fix install_requires typo * move_on_after blocks if deadline is too small * Linter fixes * Improve WSGI structured concurrency * Tests use anyio * Checkin progress on testclient * Prep for anyio 3 * Remove debug backend option * Use anyio 3.0.0rc1 * Remove old style executor from GraphQLApp * Fix extra import * Don't cancel task scope early * Wait for wsgi sender to finish before exiting * Use memory object streams in websocket tests * Test on asyncio, asyncio+uvloop, and trio * Formatting fixes * run_until_first_complete doesn't need a return * Fix middleware app call * Simplify middleware exceptions * Use anyio for websocket test * Set STARLETTE_TESTCLIENT_ASYNC_BACKEND in tests * Pass async backend to portal * Formatting fixes * Bump anyio * Cleanup portals and add TestClient.async_backend * Use anyio.run_async_from_thread to send from worker thread * Use websocket_connect as context manager * Document changes in TestClient * Formatting fix * Fix websocket raises coverage * Update to anyio 3.0.0rc3 and replace aiofiles * Apply suggestions from code review Co-authored-by: Alex Grönholm <alex.gronholm@nextday.fi> * Bump to require anyio 3.0.0 final * Remove mention of aiofiles in README.md * Pin jinja2 to releases before 3 due to DeprecationWarnings * Add task_group as application attribute * Remove run_until_first_complete * Undo jinja pin * Refactor anyio.sleep into an event * Use one less task in test_websocket_concurrency_pattern * Apply review suggestions * Rename argument * fix start_task_soon type * fix BaseHTTPMiddleware when used without Starlette * Testclient receive() is a non-trapping function if the response is already complete This allows for a zero deadline when waiting for a disconnect message * Use variable annotation for async_backend * Update docs regarding dependency on anyio * Use CancelScope instead of move_on_after in request.is_disconnected * Cancel task group after returning middleware response Add test for https://github.com/encode/starlette/issues/1022 * Add link to anyio backend options in testclient docs * Add types-dataclasses * Re-implement starlette.concurrency.run_until_first_complete and add a test * Fix type on handler callable * Apply review comments to clarify run_until_first_complete scope Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com> Co-authored-by: Alex Grönholm <alex.gronholm@nextday.fi> Co-authored-by: Thomas Grainger <tagrain@gmail.com>
2021-06-18 14:48:43 +00:00
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"