Separate ASGI request and lifespan callables (#2646)

This commit is contained in:
Adam Hopkins
2023-03-17 09:05:33 +02:00
committed by GitHub
parent 08a81c81be
commit 5ee36fd933
3 changed files with 130 additions and 115 deletions

View File

@@ -2,13 +2,14 @@ import asyncio
import logging
from collections import deque, namedtuple
from unittest.mock import call
import pytest
import uvicorn
from sanic import Sanic
from sanic.application.state import Mode
from sanic.asgi import ASGIApp, MockTransport
from sanic.asgi import ASGIApp, Lifespan, MockTransport
from sanic.exceptions import BadRequest, Forbidden, ServiceUnavailable
from sanic.request import Request
from sanic.response import json, text
@@ -116,10 +117,6 @@ def test_listeners_triggered(caplog):
stop_message,
) not in caplog.record_tuples
all_tasks = asyncio.all_tasks(asyncio.get_event_loop())
for task in all_tasks:
task.cancel()
assert before_server_start
assert after_server_start
assert before_server_stop
@@ -218,10 +215,6 @@ def test_listeners_triggered_async(app, caplog):
stop_message,
) not in caplog.record_tuples
all_tasks = asyncio.all_tasks(asyncio.get_event_loop())
for task in all_tasks:
task.cancel()
assert before_server_start
assert after_server_start
assert before_server_stop
@@ -272,10 +265,6 @@ def test_non_default_uvloop_config_raises_warning(app):
with pytest.warns(UserWarning) as records:
server.run()
all_tasks = asyncio.all_tasks(asyncio.get_event_loop())
for task in all_tasks:
task.cancel()
msg = ""
for record in records:
_msg = str(record.message)
@@ -583,15 +572,28 @@ async def test_error_on_lifespan_exception_start(app, caplog):
async def before_server_start(_):
1 / 0
recv = AsyncMock(return_value={"type": "lifespan.startup"})
recv = AsyncMock(
side_effect=[
{"type": "lifespan.startup"},
{"type": "lifespan.shutdown"},
]
)
send = AsyncMock()
app.asgi = True
lifespan = Lifespan(app, {"type": "lifespan"}, recv, send)
with caplog.at_level(logging.ERROR):
await ASGIApp.create(app, {"type": "lifespan"}, recv, send)
await lifespan()
send.assert_awaited_once_with(
{"type": "lifespan.startup.failed", "message": "division by zero"}
send.assert_has_calls(
[
call(
{
"type": "lifespan.startup.failed",
"message": "division by zero",
}
)
]
)
@@ -601,13 +603,26 @@ async def test_error_on_lifespan_exception_stop(app: Sanic):
async def before_server_stop(_):
1 / 0
recv = AsyncMock(return_value={"type": "lifespan.shutdown"})
recv = AsyncMock(
side_effect=[
{"type": "lifespan.startup"},
{"type": "lifespan.shutdown"},
]
)
send = AsyncMock()
app.asgi = True
await app._startup()
await ASGIApp.create(app, {"type": "lifespan"}, recv, send)
lifespan = Lifespan(app, {"type": "lifespan"}, recv, send)
await lifespan()
send.assert_awaited_once_with(
{"type": "lifespan.shutdown.failed", "message": "division by zero"}
send.assert_has_calls(
[
call(
{
"type": "lifespan.shutdown.failed",
"message": "division by zero",
}
)
]
)