| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from contextlib import AbstractAsyncContextManager |
| 4 |
from types import TracebackType |
| 5 |
|
| 6 |
import trio |
| 7 |
from quart.app import Quart |
| 8 |
from quart.testing.app import DEFAULT_TIMEOUT, LifespanError |
| 9 |
from quart.typing import TestClientProtocol |
| 10 |
|
| 11 |
|
| 12 |
class TrioTestApp: |
| 13 |
def __init__( |
| 14 |
self, |
| 15 |
app: "Quart", |
| 16 |
startup_timeout: int = DEFAULT_TIMEOUT, |
| 17 |
shutdown_timeout: int = DEFAULT_TIMEOUT, |
| 18 |
) -> None: |
| 19 |
self.app = app |
| 20 |
self.startup_timeout = startup_timeout |
| 21 |
self.shutdown_timeout = shutdown_timeout |
| 22 |
self._startup = trio.Event() |
| 23 |
self._shutdown = trio.Event() |
| 24 |
self._app_send_channel, self._app_receive_channel = trio.open_memory_channel[dict](10) |
| 25 |
self._nursery_manager: AbstractAsyncContextManager[trio.Nursery] |
| 26 |
self._nursery: trio.Nursery |
| 27 |
|
| 28 |
def test_client(self) -> TestClientProtocol: |
| 29 |
return self.app.test_client() |
| 30 |
|
| 31 |
async def startup(self) -> None: |
| 32 |
scope = {"type": "lifespan", "asgi": {"spec_version": "2.0"}} |
| 33 |
self._nursery.start_soon(self.app, scope, self._asgi_receive, self._asgi_send) # type: ignore # noqa: E501 |
| 34 |
await self._app_send_channel.send({"type": "lifespan.startup"}) |
| 35 |
with trio.fail_after(self.startup_timeout): |
| 36 |
await self._startup.wait() |
| 37 |
|
| 38 |
async def shutdown(self) -> None: |
| 39 |
await self._app_send_channel.send({"type": "lifespan.shutdown"}) |
| 40 |
with trio.fail_after(self.shutdown_timeout): |
| 41 |
await self._shutdown.wait() |
| 42 |
|
| 43 |
async def __aenter__(self) -> "TrioTestApp": |
| 44 |
self._nursery_manager = trio.open_nursery() |
| 45 |
self._nursery = await self._nursery_manager.__aenter__() |
| 46 |
await self.startup() |
| 47 |
return self |
| 48 |
|
| 49 |
async def __aexit__(self, exc_type: type, exc_value: BaseException, tb: TracebackType) -> None: |
| 50 |
await self.shutdown() |
| 51 |
await self._nursery_manager.__aexit__(exc_type, exc_value, tb) |
| 52 |
|
| 53 |
async def _asgi_receive(self) -> dict: |
| 54 |
return await self._app_receive_channel.receive() |
| 55 |
|
| 56 |
async def _asgi_send(self, message: dict) -> None: |
| 57 |
if message["type"] == "lifespan.startup.complete": |
| 58 |
self._startup.set() |
| 59 |
elif message["type"] == "lifespan.shutdown.complete": |
| 60 |
self._shutdown.set() |
| 61 |
elif message["type"] == "lifespan.startup.failed": |
| 62 |
self._startup.set() |
| 63 |
raise LifespanError(f"Error during startup {message['message']}") |
| 64 |
elif message["type"] == "lifespan.shutdown.failed": |
| 65 |
self._shutdown.set() |
| 66 |
raise LifespanError(f"Error during shutdown {message['message']}") |