Repository navigation
Expand file tree
/
Copy pathtest_time.py
More file actions
587 lines (479 loc) · 17.5 KB
/
Copy pathtest_time.py
File metadata and controls
587 lines (479 loc) · 17.5 KB
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
"""Tests for the timeout generators in ``python_utils.time``."""
import asyncio
import datetime
import itertools
import time
import pytest
import python_utils
from _python_utils_tests import clock
from python_utils import types
#: Far longer than every timeout in this module, so a generator that sleeps
#: this long is always interrupted first.
STALL: float = 10.0
@pytest.mark.parametrize(
'timeout,interval,interval_multiplier,maximum_interval,iterable,result',
[
(0.2, 0.1, 0.4, 0.2, python_utils.acount, 2),
(0.3, 0.1, 0.4, 0.2, python_utils.acount(), 3),
(0.3, 0.06, 1.0, None, python_utils.acount, 5),
(
datetime.timedelta(seconds=0.1),
datetime.timedelta(seconds=0.06),
2.0,
datetime.timedelta(seconds=0.1),
python_utils.acount,
2,
),
],
)
@pytest.mark.asyncio
async def test_aio_timeout_generator(
fake_clock: clock.FakeClock,
monkeypatch: pytest.MonkeyPatch,
timeout: float,
interval: float,
interval_multiplier: float,
maximum_interval: float,
iterable: types.AsyncIterable[types.Any],
result: int,
) -> None:
"""Stop the async generator near the configured timeout."""
async def sleep(delay: float) -> None:
"""Let the fake clock pass the delay without waiting for it."""
fake_clock.sleep(delay)
monkeypatch.setattr(asyncio, 'sleep', sleep)
i = None
async for i in python_utils.aio_timeout_generator(
timeout, interval, iterable, maximum_interval=maximum_interval
):
pass
assert i == result
@pytest.mark.parametrize(
'timeout,interval,interval_multiplier,maximum_interval,iterable,result,'
'sleeps',
[
(0.1, 0.06, 0.5, 0.1, 'abc', 'c', [0.06, 0.03, 0.015]),
(0.1, 0.07, 0.5, 0.1, itertools.count, 2, [0.07, 0.035]),
(0.1, 0.07, 0.5, 0.1, itertools.count(), 2, [0.07, 0.035]),
(0.1, 0.06, 1.0, None, 'abc', 'c', [0.06, 0.06]),
(
datetime.timedelta(seconds=0.1),
datetime.timedelta(seconds=0.06),
2.0,
datetime.timedelta(seconds=0.1),
itertools.count,
2,
[0.06, 0.1],
),
],
)
def test_timeout_generator(
fake_clock: clock.FakeClock,
timeout: float,
interval: float,
interval_multiplier: float,
maximum_interval: float,
iterable: types.Union[
str,
types.Iterable[types.Any],
types.Callable[..., types.Iterable[types.Any]],
],
result: int,
sleeps: types.List[float],
) -> None:
"""Stop the sync generator at the timeout and scale the interval."""
i = None
for i in python_utils.timeout_generator(
timeout=timeout,
interval=interval,
interval_multiplier=interval_multiplier,
iterable=iterable,
maximum_interval=maximum_interval,
):
assert i is not None
assert i == result
assert fake_clock.sleeps == pytest.approx(sleeps)
def test_timeout_generator_real_clock() -> None:
"""Keep yielding on the real clock until the timeout has passed."""
timeout: float = 0.05
interval: float = 0.01
start: float = time.perf_counter()
items: types.List[int] = list(
python_utils.timeout_generator(timeout, interval, itertools.count())
)
elapsed: float = time.perf_counter() - start
# A sleep can take longer than requested but never shorter, so these
# hold on any machine. The exact number of items does not.
assert items == list(range(len(items)))
assert len(items) <= timeout / interval + 2
assert elapsed >= timeout
async def stalling_generator() -> types.AsyncGenerator[int, None]:
"""Yield 0-4 without waiting, then stall before the next item."""
for i in range(10):
if i == 5:
await asyncio.sleep(STALL)
yield i
def ticking_generator(
fake_clock: clock.FakeClock,
) -> types.AsyncGenerator[int, None]:
"""Yield 0-9 and let 0.1 seconds pass on the fake clock for each item."""
async def generator() -> types.AsyncGenerator[int, None]:
"""Advance the fake clock before every item."""
for i in range(10):
fake_clock.sleep(0.1)
yield i
return generator()
@pytest.mark.asyncio
async def test_aio_generator_timeout_detector(
fake_clock: clock.FakeClock,
) -> None:
"""Raise or exit on per-item and total timeouts."""
# Make pyright happy
i = None
detector = python_utils.aio_generator_timeout_detector
# Test regular timeout with reraise
with pytest.raises(asyncio.TimeoutError):
async for i in detector(stalling_generator(), 0.05):
pass
# Test regular timeout with clean exit
async for i in detector(stalling_generator(), 0.05, on_timeout=None):
pass
assert i == 4
# Test total timeout with reraise
with pytest.raises(asyncio.TimeoutError):
async for i in detector(
ticking_generator(fake_clock), total_timeout=0.45
):
pass
# Test total timeout with clean exit
async for i in detector(
ticking_generator(fake_clock), total_timeout=0.45, on_timeout=None
):
pass
assert i == 4
# Test stop iteration
async for i in detector(ticking_generator(fake_clock), on_timeout=None):
pass
assert i == 9
@pytest.mark.asyncio
async def test_aio_generator_timeout_detector_decorator_reraise() -> None:
"""Reraise ``TimeoutError`` on a per-item timeout."""
# Test regular timeout with reraise
generator_timeout = python_utils.aio_generator_timeout_detector_decorator(
timeout=0.05
)(stalling_generator)
with pytest.raises(asyncio.TimeoutError):
async for _ in generator_timeout():
pass
@pytest.mark.asyncio
async def test_aio_generator_timeout_detector_decorator_clean_exit() -> None:
"""Exit cleanly when ``on_timeout`` is ``None``."""
# Make pyright happy
i = None
# Test regular timeout with clean exit
generator_clean = python_utils.aio_generator_timeout_detector_decorator(
timeout=0.05, on_timeout=None
)(stalling_generator)
async for i in generator_clean():
pass
assert i == 4
@pytest.mark.asyncio
async def test_aio_generator_timeout_detector_decorator_reraise_total(
fake_clock: clock.FakeClock,
) -> None:
"""Reraise ``TimeoutError`` on a total timeout."""
# Test total timeout with reraise
@python_utils.aio_generator_timeout_detector_decorator(total_timeout=0.45)
async def generator_reraise() -> types.AsyncGenerator[int, None]:
"""Let the fake clock pass the total timeout while yielding."""
async for i in ticking_generator(fake_clock):
yield i
with pytest.raises(asyncio.TimeoutError):
async for _ in generator_reraise():
pass
@pytest.mark.asyncio
async def test_aio_generator_timeout_detector_decorator_clean_total(
fake_clock: clock.FakeClock,
) -> None:
"""Exit cleanly on total timeout when ``on_timeout`` is ``None``."""
# Make pyright happy
i = None
# Test total timeout with clean exit
@python_utils.aio_generator_timeout_detector_decorator(
total_timeout=0.45, on_timeout=None
)
async def generator_clean_total() -> types.AsyncGenerator[int, None]:
"""Let the fake clock pass the total timeout while yielding."""
async for i in ticking_generator(fake_clock):
yield i
async for i in generator_clean_total():
pass
assert i == 4
@pytest.mark.asyncio
async def test_aio_generator_timeout_detector_sync_callback(
fake_clock: clock.FakeClock,
) -> None:
"""Accept an ``on_timeout`` callback that is a plain function."""
exceptions: types.List[BaseException] = []
def on_timeout(
generator: types.AsyncGenerator[int, None],
timeout: types.Optional[types.delta_type],
total_timeout: types.Optional[types.delta_type],
exception: BaseException,
) -> None:
"""Record the timeout and return nothing to await."""
exceptions.append(exception)
items: types.List[int] = [
i
async for i in python_utils.aio_generator_timeout_detector(
ticking_generator(fake_clock),
total_timeout=0.45,
on_timeout=on_timeout,
)
]
assert items == [0, 1, 2, 3, 4]
assert len(exceptions) == 1
assert isinstance(exceptions[0], asyncio.TimeoutError)
@pytest.mark.asyncio
async def test_aio_generator_timeout_detector_async_callback(
fake_clock: clock.FakeClock,
) -> None:
"""Await an ``on_timeout`` callback that is a coroutine function."""
calls: types.List[types.Mapping[str, types.Any]] = []
async def on_timeout(
generator: types.AsyncGenerator[int, None],
timeout: types.Optional[types.delta_type],
total_timeout: types.Optional[types.delta_type],
exception: BaseException,
**kwargs: types.Mapping[str, types.Any],
) -> None:
"""Record the extra keyword arguments after a real await."""
await asyncio.sleep(0)
calls.append(kwargs)
items: types.List[int] = [
i
async for i in python_utils.aio_generator_timeout_detector(
ticking_generator(fake_clock),
total_timeout=0.45,
on_timeout=on_timeout,
context={'attempt': 1},
)
]
assert items == [0, 1, 2, 3, 4]
assert calls == [{'context': {'attempt': 1}}]
async def collect_before_stall(
generator: types.AsyncGenerator[int, None],
) -> types.List[int]:
"""Collect the items of a detector that has to stop at the stall."""
items: types.List[int] = []
async def collect() -> None:
"""Gather every item the detector lets through."""
item: int
async for item in generator:
items.append(item)
try:
# Without the guard a detector that waits out the stall would keep
# the test busy for `STALL` seconds before it fails.
await asyncio.wait_for(collect(), STALL / 10)
finally:
await generator.aclose()
return items
@pytest.mark.asyncio
async def test_aio_generator_timeout_detector_item_before_total() -> None:
"""Let the item timeout win when it ends before the total timeout."""
detector: types.AsyncGenerator[int, None] = (
python_utils.aio_generator_timeout_detector(
stalling_generator(), timeout=STALL / 500, total_timeout=STALL
)
)
with pytest.raises(asyncio.TimeoutError) as exc_info:
await collect_before_stall(detector)
assert 'Total timeout reached' not in str(exc_info.value)
@pytest.mark.asyncio
async def test_aio_generator_timeout_detector_total_timeout_finishes() -> None:
"""Finish as normal when the generator ends within the total timeout."""
async def generator() -> types.AsyncGenerator[int, None]:
"""Yield three items without waiting."""
i: int
for i in range(3):
yield i
items: types.List[int] = [
i
async for i in python_utils.aio_generator_timeout_detector(
generator(), total_timeout=STALL
)
]
assert items == [0, 1, 2]
@pytest.mark.asyncio
async def test_aio_generator_timeout_detector_generator_timeout() -> None:
"""Hand a timeout raised by the generator itself over unchanged."""
exceptions: types.List[BaseException] = []
async def generator() -> types.AsyncGenerator[int, None]:
"""Yield one item and then fail with a timeout of its own."""
yield 0
raise asyncio.TimeoutError('raised by the generator')
def on_timeout(
generator: types.AsyncGenerator[int, None],
timeout: types.Optional[types.delta_type],
total_timeout: types.Optional[types.delta_type],
exception: BaseException,
) -> None:
"""Record the exception the detector reports."""
exceptions.append(exception)
items: types.List[int] = [
i
async for i in python_utils.aio_generator_timeout_detector(
generator(), total_timeout=STALL, on_timeout=on_timeout
)
]
assert items == [0]
assert [str(exception) for exception in exceptions] == [
'raised by the generator'
]
@pytest.mark.parametrize(
'timestamp,precision,expected',
[
(1, datetime.timedelta(milliseconds=100), '0:00:01'),
(60, datetime.timedelta(milliseconds=100), '0:01:00'),
(0.3, datetime.timedelta(milliseconds=100), '0:00:00.300000'),
(1.234, datetime.timedelta(milliseconds=1), '0:00:01.234000'),
(1.239, datetime.timedelta(milliseconds=10), '0:00:01.230000'),
(
datetime.timedelta(seconds=2),
datetime.timedelta(milliseconds=100),
'0:00:02',
),
(
datetime.datetime(2000, 1, 2, 3, 4, 5),
datetime.timedelta(milliseconds=100),
'2000-01-02 03:04:05',
),
(
datetime.datetime(2000, 1, 2, 3, 4, 5, 678901),
datetime.timedelta(milliseconds=10),
'2000-01-02 03:04:05.670000',
),
],
)
def test_format_time_sub_second_precision(
timestamp: types.timestamp_type,
precision: datetime.timedelta,
expected: str,
) -> None:
"""Keep a value that is on the precision grid where it is."""
assert python_utils.format_time(timestamp, precision) == expected
@pytest.mark.parametrize(
'timestamp',
[float('nan'), 'nan', float('inf'), float('-inf'), 1e20, 10**30],
)
def test_format_time_placeholder_for_impossible_numbers(
timestamp: types.timestamp_type,
) -> None:
"""Print the placeholder for a number that is not a duration."""
assert python_utils.format_time(timestamp) == '--:--:--'
def test_format_time_extreme_timedeltas() -> None:
"""Format the largest and the smallest timedelta without overflow."""
largest: str = python_utils.format_time(datetime.timedelta.max)
smallest: str = python_utils.format_time(datetime.timedelta.min)
assert largest == '999999999 days, 23:59:59'
assert smallest == '-999999999 days, 0:00:00'
@pytest.mark.parametrize(
'delta',
[
datetime.timedelta(microseconds=1),
datetime.timedelta(microseconds=-1),
datetime.timedelta(seconds=437, microseconds=579262),
datetime.timedelta(days=-5, microseconds=1),
datetime.timedelta(days=1000000, microseconds=999999),
datetime.timedelta.max,
],
)
def test_timedelta_to_seconds_fraction_precision(
delta: datetime.timedelta,
) -> None:
"""Keep the precision of ``total_seconds`` for a fraction of a second."""
seconds: types.Number = python_utils.timedelta_to_seconds(delta)
assert isinstance(seconds, float)
assert seconds == delta.total_seconds()
@pytest.mark.parametrize(
'delta,expected',
[
(datetime.timedelta(0), 0),
(datetime.timedelta(seconds=1), 1),
(datetime.timedelta(seconds=-1), -1),
(datetime.timedelta(days=1), 86400),
(datetime.timedelta(days=999999999, seconds=86399), 86399999999999),
(datetime.timedelta.min, -86399999913600),
],
)
def test_timedelta_to_seconds_whole_seconds_stay_int(
delta: datetime.timedelta, expected: int
) -> None:
"""Return whole seconds as the exact ``int`` they have always been."""
seconds: types.Number = python_utils.timedelta_to_seconds(delta)
assert isinstance(seconds, int)
assert seconds == expected
def test_timeout_generator_maximum_interval_first_sleep(
fake_clock: clock.FakeClock,
) -> None:
"""Hold the first sleep to ``maximum_interval`` as well."""
items: types.List[str] = list(
python_utils.timeout_generator(
timeout=100, interval=10, iterable='abc', maximum_interval=1
)
)
assert items == ['a', 'b', 'c']
assert fake_clock.sleeps == [1, 1, 1]
def test_timeout_generator_maximum_interval_keeps_progression(
fake_clock: clock.FakeClock,
) -> None:
"""Shorten the first sleep only, the later ones stay as they were."""
items: types.List[str] = list(
python_utils.timeout_generator(
timeout=100,
interval=3,
iterable='abcd',
interval_multiplier=0.5,
maximum_interval=2,
)
)
assert items == ['a', 'b', 'c', 'd']
assert fake_clock.sleeps == [2, 1.5, 0.75, 0.375]
def test_timeout_generator_maximum_interval_zero(
fake_clock: clock.FakeClock,
) -> None:
"""Read a ``maximum_interval`` of zero as no maximum at all."""
items: types.List[str] = list(
python_utils.timeout_generator(
timeout=100,
interval=1,
iterable='abc',
interval_multiplier=2,
maximum_interval=0,
)
)
assert items == ['a', 'b', 'c']
assert fake_clock.sleeps == [1, 2, 4]
@pytest.mark.asyncio
async def test_aio_timeout_generator_maximum_interval_first_sleep(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Hold the first async sleep to ``maximum_interval`` as well."""
sleeps: types.List[float] = []
async def mock_sleep(delay: float) -> None:
"""Record each requested delay instead of sleeping."""
sleeps.append(delay)
monkeypatch.setattr(asyncio, 'sleep', mock_sleep)
async def letters() -> types.AsyncGenerator[str, None]:
"""Yield three letters without waiting."""
letter: str
for letter in 'abc':
yield letter
items: types.List[str] = [
item
async for item in python_utils.aio_timeout_generator(
timeout=100, interval=10, iterable=letters, maximum_interval=1
)
]
assert items == ['a', 'b', 'c']
assert sleeps == [1, 1, 1]