File size: 9,736 Bytes
065fee7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import asyncio
import sys
import time
from functools import wraps
from typing import Any, Callable, List, TypeVar

import pytest

from async_timeout import timeout, timeout_at


_Func = TypeVar("_Func", bound=Callable[..., Any])


def log_func(func: _Func, msg: str, call_order: List[str]) -> _Func:
    """Simple wrapper to add a log to call_order when the function is called."""

    @wraps(func)
    def wrapper(*args: Any, **kwargs: Any) -> Any:  # type: ignore[misc]
        call_order.append(msg)
        return func(*args, **kwargs)

    return wrapper  # type: ignore[return-value]


@pytest.mark.asyncio
async def test_timeout() -> None:
    canceled_raised = False

    async def long_running_task() -> None:
        try:
            await asyncio.sleep(10)
        except asyncio.CancelledError:
            nonlocal canceled_raised
            canceled_raised = True
            raise

    with pytest.raises(asyncio.TimeoutError):
        async with timeout(0.01) as t:
            await long_running_task()
            assert t._loop is asyncio.get_event_loop()
    assert canceled_raised, "CancelledError was not raised"
    if sys.version_info >= (3, 11):
        task = asyncio.current_task()
        assert task is not None
        assert not task.cancelling()


@pytest.mark.asyncio
async def test_timeout_finish_in_time() -> None:
    async def long_running_task() -> str:
        await asyncio.sleep(0.01)
        return "done"

    # timeout should be long enough to work even on slow bisy test boxes
    async with timeout(0.5):
        resp = await long_running_task()
    assert resp == "done"


@pytest.mark.asyncio
async def test_timeout_disable() -> None:
    async def long_running_task() -> str:
        await asyncio.sleep(0.1)
        return "done"

    loop = asyncio.get_event_loop()
    t0 = loop.time()
    async with timeout(None):
        resp = await long_running_task()
    assert resp == "done"
    dt = loop.time() - t0
    assert 0.09 < dt < 0.3, dt


@pytest.mark.asyncio
async def test_timeout_is_none_no_schedule() -> None:
    async with timeout(None) as cm:
        assert cm._timeout_handler is None
        assert cm.deadline is None


def test_timeout_no_loop() -> None:
    with pytest.raises(RuntimeError, match="no running event loop"):
        timeout(None)


@pytest.mark.asyncio
async def test_timeout_zero() -> None:
    with pytest.raises(asyncio.TimeoutError):
        async with timeout(0):
            await asyncio.sleep(10)


@pytest.mark.asyncio
async def test_timeout_not_relevant_exception() -> None:
    await asyncio.sleep(0)
    with pytest.raises(KeyError):
        async with timeout(0.1):
            raise KeyError


@pytest.mark.asyncio
async def test_timeout_canceled_error_is_not_converted_to_timeout() -> None:
    await asyncio.sleep(0)
    with pytest.raises(asyncio.CancelledError):
        async with timeout(0.001):
            raise asyncio.CancelledError


@pytest.mark.asyncio
async def test_timeout_blocking_loop() -> None:
    async def long_running_task() -> str:
        time.sleep(0.1)
        return "done"

    async with timeout(0.01):
        result = await long_running_task()
    assert result == "done"


@pytest.mark.asyncio
async def test_for_race_conditions() -> None:
    loop = asyncio.get_event_loop()
    fut = loop.create_future()
    loop.call_later(0.1, fut.set_result, "done")
    async with timeout(0.5):
        resp = await fut
    assert resp == "done"


@pytest.mark.asyncio
async def test_timeout_time() -> None:
    foo_running = None
    loop = asyncio.get_event_loop()
    start = loop.time()
    with pytest.raises(asyncio.TimeoutError):
        async with timeout(0.1):
            foo_running = True
            try:
                await asyncio.sleep(0.2)
            finally:
                foo_running = False

    dt = loop.time() - start
    assert 0.09 < dt < 0.3
    assert not foo_running


@pytest.mark.asyncio
async def test_outer_coro_is_not_cancelled() -> None:
    has_timeout = False

    async def outer() -> None:
        nonlocal has_timeout
        try:
            async with timeout(0.001):
                await asyncio.sleep(1)
        except asyncio.TimeoutError:
            has_timeout = True

    task = asyncio.ensure_future(outer())
    await task
    assert has_timeout
    assert not task.cancelled()
    if sys.version_info >= (3, 11):
        assert not task.cancelling()
    assert task.done()


@pytest.mark.asyncio
async def test_cancel_outer_coro() -> None:
    loop = asyncio.get_event_loop()
    fut = loop.create_future()

    async def outer() -> None:
        fut.set_result(None)
        await asyncio.sleep(1)

    task = asyncio.ensure_future(outer())
    await fut
    task.cancel()
    with pytest.raises(asyncio.CancelledError):
        await task
    assert task.cancelled()
    assert task.done()


@pytest.mark.asyncio
async def test_timeout_suppress_exception_chain() -> None:
    with pytest.raises(asyncio.TimeoutError) as ctx:
        async with timeout(0.01):
            await asyncio.sleep(10)
    assert not ctx.value.__suppress_context__


@pytest.mark.asyncio
async def test_timeout_expired() -> None:
    with pytest.raises(asyncio.TimeoutError):
        async with timeout(0.01) as cm:
            await asyncio.sleep(10)
    assert cm.expired


@pytest.mark.asyncio
async def test_timeout_inner_timeout_error() -> None:
    with pytest.raises(asyncio.TimeoutError):
        async with timeout(0.01) as cm:
            raise asyncio.TimeoutError
    assert not cm.expired


@pytest.mark.asyncio
async def test_timeout_inner_other_error() -> None:
    class MyError(RuntimeError):
        pass

    with pytest.raises(MyError):
        async with timeout(0.01) as cm:
            raise MyError
    assert not cm.expired


@pytest.mark.asyncio
async def test_timeout_at() -> None:
    loop = asyncio.get_event_loop()
    with pytest.raises(asyncio.TimeoutError):
        now = loop.time()
        async with timeout_at(now + 0.01) as cm:
            await asyncio.sleep(10)
    assert cm.expired


@pytest.mark.asyncio
async def test_timeout_at_not_fired() -> None:
    loop = asyncio.get_event_loop()
    now = loop.time()
    async with timeout_at(now + 1) as cm:
        await asyncio.sleep(0)
    assert not cm.expired


@pytest.mark.asyncio
async def test_expired_after_rejecting() -> None:
    t = timeout(10)
    assert not t.expired
    t.reject()
    assert not t.expired


@pytest.mark.asyncio
async def test_reject_finished() -> None:
    async with timeout(10) as t:
        await asyncio.sleep(0)

    assert not t.expired
    with pytest.raises(RuntimeError, match="invalid state EXIT"):
        t.reject()


@pytest.mark.asyncio
async def test_expired_after_timeout() -> None:
    with pytest.raises(asyncio.TimeoutError):
        async with timeout(0.01) as t:
            assert not t.expired
            await asyncio.sleep(10)
    assert t.expired


@pytest.mark.asyncio
async def test_deadline() -> None:
    loop = asyncio.get_event_loop()
    t0 = loop.time()
    async with timeout(1) as cm:
        t1 = loop.time()
        assert cm.deadline is not None
        assert t0 + 1 <= cm.deadline <= t1 + 1


@pytest.mark.asyncio
async def test_async_timeout() -> None:
    with pytest.raises(asyncio.TimeoutError):
        async with timeout(0.01) as cm:
            await asyncio.sleep(10)
    assert cm.expired


@pytest.mark.asyncio
async def test_async_no_timeout() -> None:
    async with timeout(1) as cm:
        await asyncio.sleep(0)
    assert not cm.expired


@pytest.mark.asyncio
async def test_shift() -> None:
    loop = asyncio.get_event_loop()
    t0 = loop.time()
    async with timeout(1) as cm:
        t1 = loop.time()
        assert cm.deadline is not None
        assert t0 + 1 <= cm.deadline <= t1 + 1
        cm.shift(1)
        assert t0 + 2 <= cm.deadline <= t0 + 2.1


@pytest.mark.asyncio
async def test_shift_nonscheduled() -> None:
    async with timeout(None) as cm:
        with pytest.raises(
            RuntimeError,
            match="cannot shift timeout if deadline is not scheduled",
        ):
            cm.shift(1)


@pytest.mark.asyncio
async def test_shift_negative_expired() -> None:
    async with timeout(1) as cm:
        with pytest.raises(asyncio.CancelledError):
            cm.shift(-1)
            await asyncio.sleep(10)


@pytest.mark.asyncio
async def test_shift_by_expired() -> None:
    async with timeout(0.001) as cm:
        with pytest.raises(asyncio.CancelledError):
            await asyncio.sleep(10)
        with pytest.raises(RuntimeError, match="cannot reschedule expired timeout"):
            cm.shift(10)


@pytest.mark.asyncio
async def test_shift_to_expired() -> None:
    loop = asyncio.get_event_loop()
    t0 = loop.time()
    async with timeout_at(t0 + 0.001) as cm:
        with pytest.raises(asyncio.CancelledError):
            await asyncio.sleep(10)
        with pytest.raises(RuntimeError, match="cannot reschedule expired timeout"):
            cm.update(t0 + 10)


@pytest.mark.asyncio
async def test_shift_by_after_cm_exit() -> None:
    async with timeout(1) as cm:
        await asyncio.sleep(0)
    with pytest.raises(
        RuntimeError, match="cannot reschedule after exit from context manager"
    ):
        cm.shift(1)


@pytest.mark.asyncio
async def test_enter_twice() -> None:
    async with timeout(10) as t:
        await asyncio.sleep(0)

    with pytest.raises(RuntimeError, match="invalid state EXIT"):
        async with t:
            await asyncio.sleep(0)


@pytest.mark.asyncio
async def test_deprecated_with() -> None:
    with pytest.warns(DeprecationWarning):
        with timeout(1):
            await asyncio.sleep(0)