Debian Codegraph @

src/trio/_tests/test_timeouts.py

raw
1 from __future__ import annotations
2
3 import time
4 from typing import TYPE_CHECKING, Protocol, TypeVar
5
6 import outcome
7 import pytest
8
9 import trio
10
11 from .. import _core
12 from .._core._tests.tutil import slow
13 from .._timeouts import (
14 TooSlowError,
15 fail_after,
16 fail_at,
17 move_on_after,
18 move_on_at,
19 sleep,
20 sleep_forever,
21 sleep_until,
22 )
23 from ..testing import assert_checkpoints
24
25 if TYPE_CHECKING:
26 from collections.abc import Awaitable, Callable
27
28 T = TypeVar("T")
29
30
31 async def check_takes_about(f: Callable[[], Awaitable[T]], expected_dur: float) -> T:
32 start = time.perf_counter()
33 result = await outcome.acapture(f)
34 dur = time.perf_counter() - start
35 print(dur / expected_dur)
36 # 2.0 is an arbitrary fudge factor because there's always some delay
37 # between when we become eligible to wake up and when we actually do. We
38 # used to sleep for 0.05, and regularly observed overruns of 1.6x on
39 # Appveyor, and then started seeing overruns of 2.3x on Travis's macOS, so
40 # now we bumped up the sleep to 1 second, marked the tests as slow, and
41 # hopefully now the proportional error will be less huge.
42 #
43 # We also also for durations that are a hair shorter than expected. For
44 # example, here's a run on Windows where a 1.0 second sleep was measured
45 # to take 0.9999999999999858 seconds:
46 # https://ci.appveyor.com/project/njsmith/trio/build/1.0.768/job/3lbdyxl63q3h9s21
47 # I believe that what happened here is that Windows's low clock resolution
48 # meant that our calls to time.monotonic() returned exactly the same
49 # values as the calls inside the actual run loop, but the two subtractions
50 # returned slightly different values because the run loop's clock adds a
51 # random floating point offset to both times, which should cancel out, but
52 # lol floating point we got slightly different rounding errors. (That
53 # value above is exactly 128 ULPs below 1.0, which would make sense if it
54 # started as a 1 ULP error at a different dynamic range.)
55 assert (1 - 1e-8) <= (dur / expected_dur) < 2.0
56
57 return result.unwrap()
58
59
60 # How long to (attempt to) sleep for when testing. Smaller numbers make the
61 # test suite go faster.
62 TARGET = 1.0
63
64
65 @slow
66 async def test_sleep() -> None:
67 async def sleep_1() -> None:
68 await sleep_until(_core.current_time() + TARGET)
69
70 await check_takes_about(sleep_1, TARGET)
71
72 async def sleep_2() -> None:
73 await sleep(TARGET)
74
75 await check_takes_about(sleep_2, TARGET)
76
77 with assert_checkpoints():
78 await sleep(0)
79 # This also serves as a test of the trivial move_on_at
80 with move_on_at(_core.current_time()):
81 with pytest.raises(_core.Cancelled):
82 await sleep(0)
83
84
85 @slow
86 async def test_move_on_after() -> None:
87 async def sleep_3() -> None:
88 with move_on_after(TARGET):
89 await sleep(100)
90
91 await check_takes_about(sleep_3, TARGET)
92
93
94 async def test_cannot_wake_sleep_forever() -> None:
95 # Test an error occurs if you manually wake sleep_forever().
96 task = trio.lowlevel.current_task()
97
98 async def wake_task() -> None:
99 await trio.lowlevel.checkpoint()
100 trio.lowlevel.reschedule(task, outcome.Value(None))
101
102 async with trio.open_nursery() as nursery:
103 nursery.start_soon(wake_task)
104 with pytest.raises(RuntimeError):
105 await trio.sleep_forever()
106
107
108 class TimeoutScope(Protocol):
109 def __call__(self, seconds: float, *, shield: bool) -> trio.CancelScope: ...
110
111
112 @pytest.mark.parametrize("scope", [move_on_after, fail_after])
113 async def test_context_shields_from_outer(scope: TimeoutScope) -> None:
114 with _core.CancelScope() as outer, scope(TARGET, shield=True) as inner:
115 outer.cancel()
116 try:
117 await trio.lowlevel.checkpoint()
118 except trio.Cancelled: # pragma: no cover
119 pytest.fail("shield didn't work")
120 inner.shield = False
121 with pytest.raises(trio.Cancelled):
122 await trio.lowlevel.checkpoint()
123
124
125 @slow
126 async def test_move_on_after_moves_on_even_if_shielded() -> None:
127 async def task() -> None:
128 with _core.CancelScope() as outer, move_on_after(TARGET, shield=True):
129 outer.cancel()
130 # The outer scope is cancelled, but this task is protected by the
131 # shield, so it manages to get to sleep until deadline is met
132 await sleep_forever()
133
134 await check_takes_about(task, TARGET)
135
136
137 @slow
138 async def test_fail_after_fails_even_if_shielded() -> None:
139 async def task() -> None:
140 with (
141 pytest.raises(TooSlowError),
142 _core.CancelScope() as outer,
143 fail_after(
144 TARGET,
145 shield=True,
146 ),
147 ):
148 outer.cancel()
149 # The outer scope is cancelled, but this task is protected by the
150 # shield, so it manages to get to sleep until deadline is met
151 await sleep_forever()
152
153 await check_takes_about(task, TARGET)
154
155
156 @slow
157 async def test_fail() -> None:
158 async def sleep_4() -> None:
159 with fail_at(_core.current_time() + TARGET):
160 await sleep(100)
161
162 with pytest.raises(TooSlowError):
163 await check_takes_about(sleep_4, TARGET)
164
165 with fail_at(_core.current_time() + 100):
166 await sleep(0)
167
168 async def sleep_5() -> None:
169 with fail_after(TARGET):
170 await sleep(100)
171
172 with pytest.raises(TooSlowError):
173 await check_takes_about(sleep_5, TARGET)
174
175 with fail_after(100):
176 await sleep(0)
177
178
179 async def test_timeouts_raise_value_error() -> None:
180 # deadlines are allowed to be negative, but not delays.
181 # neither delays nor deadlines are allowed to be NaN
182
183 nan = float("nan")
184
185 for fun, val in (
186 (sleep, -1),
187 (sleep, nan),
188 (sleep_until, nan),
189 ):
190 with pytest.raises(
191 ValueError,
192 match=r"^(deadline|`seconds`) must (not )*be (non-negative|NaN)$",
193 ):
194 await fun(val)
195
196 for cm, val in (
197 (fail_after, -1),
198 (fail_after, nan),
199 (fail_at, nan),
200 (move_on_after, -1),
201 (move_on_after, nan),
202 (move_on_at, nan),
203 ):
204 with pytest.raises(
205 ValueError,
206 match=r"^(deadline|`seconds`) must (not )*be (non-negative|NaN)$",
207 ):
208 with cm(val):
209 pass # pragma: no cover
210
211
212 async def test_timeout_deadline_on_entry(mock_clock: _core.MockClock) -> None:
213 rcs = move_on_after(5)
214 assert rcs.relative_deadline == 5
215
216 mock_clock.jump(3)
217 start = _core.current_time()
218 with rcs as cs:
219 assert cs.is_relative is None
220
221 # This would previously be start+2
222 assert cs.deadline == start + 5
223 assert cs.relative_deadline == 5
224
225 cs.deadline = start + 3
226 assert cs.deadline == start + 3
227 assert cs.relative_deadline == 3
228
229 cs.relative_deadline = 4
230 assert cs.deadline == start + 4
231 assert cs.relative_deadline == 4
232
233 rcs = move_on_after(5)
234 assert rcs.shield is False
235 rcs.shield = True
236 assert rcs.shield is True
237
238 mock_clock.jump(3)
239 start = _core.current_time()
240 with rcs as cs:
241 assert cs.deadline == start + 5
242
243 assert rcs is cs
244
245
246 async def test_invalid_access_unentered() -> None:
247 cs = move_on_after(5)
248
249 match_str = "^Unentered relative cancel scope does not have an absolute deadline"
250 with pytest.raises(RuntimeError, match=match_str):
251 assert cs.deadline
252
253 with pytest.raises(RuntimeError, match=match_str):
254 cs.deadline = 7
255
256 # nothing happened!
257 assert cs.relative_deadline == 5
258 assert cs.is_relative
259
260 cs = move_on_at(5)
261
262 match_str = (
263 "^Unentered non-relative cancel scope does not have a relative deadline$"
264 )
265 with pytest.raises(RuntimeError, match=match_str):
266 assert cs.relative_deadline
267 with pytest.raises(RuntimeError, match=match_str):
268 cs.relative_deadline = 7
269
270
271 @pytest.mark.xfail(reason="not implemented")
272 async def test_fail_access_before_entering() -> None: # pragma: no cover
273 my_fail_at = fail_at(5)
274 assert my_fail_at.deadline # type: ignore[attr-defined]
275 my_fail_after = fail_after(5)
276 assert my_fail_after.relative_deadline # type: ignore[attr-defined]