Debian Codegraph @

docs/examples/testing/test_with_portal.py

raw
1 from concurrent.futures import Future, wait
2
3 import anyio
4
5 from litestar.testing import create_test_client
6
7
8 def test_with_portal() -> None:
9 """This example shows how to manage asynchronous tasks using a portal.
10
11 The test function itself is not async. Asynchronous functions are executed and awaited using the portal.
12 """
13
14 async def get_float(value: float) -> float:
15 await anyio.sleep(value)
16 return value
17
18 with create_test_client(route_handlers=[]) as test_client, test_client.portal() as portal:
19 # start a background task with the portal
20 future: Future[float] = portal.start_task_soon(get_float, 0.25)
21 # do other work
22 assert portal.call(get_float, 0.1) == 0.1
23 # wait for the background task to complete
24 wait([future])
25 assert future.done()
26 assert future.result() == 0.25