Skip to content

Commit

Permalink
Trigger http.lifecycle.request signal in ASGI mode (#2451)
Browse files Browse the repository at this point in the history
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
  • Loading branch information
zozzz and ahopkins committed Jun 16, 2022
1 parent 65b53a5 commit b879827
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
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

0 comments on commit b879827

Please sign in to comment.