Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trigger http.lifecycle.request signal in ASGI mode #2451

Merged
merged 2 commits into from Jun 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions sanic/asgi.py
Expand Up @@ -163,6 +163,13 @@ async def create(
instance.request_body = True
instance.request.conn_info = ConnInfo(instance.transport)

await sanic_app.dispatch(
"http.lifecycle.request",
inline=True,
context={"request": instance.request},
fail_not_found=False,
)

return instance

async def read(self) -> Optional[bytes]:
Expand Down
32 changes: 32 additions & 0 deletions tests/test_asgi.py
Expand Up @@ -13,6 +13,7 @@
from sanic.request import Request
from sanic.response import json, text
from sanic.server.websockets.connection import WebSocketConnection
from sanic.signals import RESERVED_NAMESPACES


@pytest.fixture
Expand Down Expand Up @@ -513,3 +514,34 @@ def forbidden(request):

_, response = await app.asgi_client.get("/error-prone")
assert response.status_code == 403


@pytest.mark.asyncio
async def test_signals_triggered(app):
@app.get("/test_signals_triggered")
async def _request(request):
return text("test_signals_triggered")

signals_triggered = []
signals_expected = [
# "http.lifecycle.begin",
# "http.lifecycle.read_head",
"http.lifecycle.request",
"http.lifecycle.handle",
"http.routing.before",
"http.routing.after",
"http.lifecycle.response",
# "http.lifecycle.send",
# "http.lifecycle.complete",
]

def signal_handler(signal):
return lambda *a, **kw: signals_triggered.append(signal)

for signal in RESERVED_NAMESPACES["http"]:
app.signal(signal)(signal_handler(signal))

_, response = await app.asgi_client.get("/test_signals_triggered")
assert response.status_code == 200
assert response.text == "test_signals_triggered"
assert signals_triggered == signals_expected