userver: /data/code/userver/testsuite/pytest_plugins/pytest_userver/utils/sync.py Source File
Loading...
Searching...
No Matches
sync.py
1import asyncio
2from collections.abc import Callable
3import datetime
4from typing import Any
5
6MAX_WAIT_TIME = datetime.timedelta(seconds=30)
7ITERATION_PERIOD_SECONDS = 0.5
8
9
10class NotReady(Exception):
11 pass
12
13
14async def wait_until(func: Callable) -> Any:
15 """
16 Waits for some external event for MAX_WAIT_TIME and
17 calls func every ITERATION_PERIOD_SECONDS.
18 If func raises NotReady exception, the waiting continues.
19 If func succesfully returns, wait_until() returns the same value.
20 After MAX_WAIT_TIME of unsuccesfull checks wait_until()
21 raises TimeoutError.
22
23 Example:
24
25 .. code-block:: python
26
27 async def try_to_connect_db():
28 if not db_conn_is_ok():
29 raise NotReady()
30
31 await wait_until(try_to_connect_db)
32
33 @throws TimeoutError after MAX_WAIT_TIME of unsuccesfull checks
34 @note If possible, use @ref testpoint instead. @ref testpoint is
35 an explicit message from the server "I'm ready", while wait_until()
36 uses an implicit idea "A condition is met, so I can continue".
37
38 @ingroup userver_testsuite
39 """
40 start = datetime.datetime.now()
41 while datetime.datetime.now() - start < MAX_WAIT_TIME:
42 try:
43 return await func()
44 except NotReady:
45 await asyncio.sleep(ITERATION_PERIOD_SECONDS)
46
47 raise TimeoutError()