Debian Codegraph @

tests/test_asyncio.py

raw symbols SCIP
1 import asyncio
2 import datetime
3 import time
4 from typing import Any
5
6 from freezegun import freeze_time
7
8
9 def test_datetime_in_coroutine() -> None:
10 @freeze_time('1970-01-01')
11 async def frozen_coroutine() -> Any:
12 assert datetime.date.today() == datetime.date(1970, 1, 1)
13
14 asyncio.run(frozen_coroutine()) # type: ignore
15
16
17 def test_freezing_time_in_coroutine() -> None:
18 """Test calling freeze_time while executing asyncio loop."""
19 async def coroutine() -> None:
20 with freeze_time('1970-01-02'):
21 assert time.time() == 86400
22 with freeze_time('1970-01-03'):
23 assert time.time() == 86400 * 2
24
25 asyncio.run(coroutine())
26
27
28 def test_freezing_time_before_running_coroutine() -> None:
29 """Test calling freeze_time before executing asyncio loop."""
30 async def coroutine() -> None:
31 assert time.time() == 86400
32 with freeze_time('1970-01-02'):
33 asyncio.run(coroutine())
34
35
36 def test_asyncio_sleeping_not_affected_by_freeze_time() -> None:
37 """Test that asyncio.sleep() is not affected by `freeze_time`.
38
39 This test ensures that despite freezing time using `freeze_time`,
40 the asyncio event loop can see real monotonic time, which is required
41 to make things like `asyncio.sleep()` work.
42 """
43
44 async def coroutine() -> None:
45 # Sleeping with time frozen should sleep the expected duration.
46 before_sleep = time.time()
47 with freeze_time('1970-01-02', real_asyncio=True):
48 await asyncio.sleep(0.05)
49 assert 0.02 <= time.time() - before_sleep < 0.3
50
51 # Exiting `freeze_time` the time should not break asyncio sleeping.
52 before_sleep = time.time()
53 await asyncio.sleep(0.05)
54 assert 0.02 <= time.time() - before_sleep < 0.3
55
56 asyncio.run(coroutine())
57
58
59 def test_asyncio_to_call_later_with_frozen_time() -> None:
60 """Test that asyncio `loop.call_later` works with frozen time."""
61 # `to_call_later` will be called by asyncio event loop and should add
62 # the Unix timestamp of 1970-01-02 00:00 to the `timestamps` list.
63 timestamps = []
64 def to_call_later() -> None:
65 timestamps.append(time.time())
66
67 async def coroutine() -> None:
68 # Schedule calling `to_call_later` in 100 ms.
69 asyncio.get_running_loop().call_later(0.1, to_call_later)
70
71 # Sleeping for 10 ms should not result in calling `to_call_later`.
72 await asyncio.sleep(0.01)
73 assert timestamps == []
74
75 # But sleeping more (150 ms in this case) should call `to_call_later`
76 # and we should see `timestamps` updated.
77 await asyncio.sleep(0.15)
78 assert timestamps == [86400]
79
80 with freeze_time('1970-01-02', real_asyncio=True):
81 asyncio.run(coroutine())