Repository navigation
Expand file tree
/
Copy pathtest_generators.py
More file actions
520 lines (424 loc) · 16.3 KB
/
Copy pathtest_generators.py
File metadata and controls
520 lines (424 loc) · 16.3 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
"""Tests for the batching helpers in ``python_utils.generators``."""
import asyncio
import datetime
import gc
import sys
import warnings
from types import SimpleNamespace
import pytest
import python_utils
from python_utils import types
@pytest.mark.asyncio
async def test_abatcher() -> None:
"""Group an async count into fixed-size batches."""
async for batch in python_utils.abatcher(python_utils.acount(stop=9), 3):
assert len(batch) == 3
async for batch in python_utils.abatcher(python_utils.acount(stop=2), 3):
assert len(batch) == 2
@pytest.mark.asyncio
@pytest.mark.parametrize(
('arrival_times', 'expected'),
[
(
(0, 8, 16, 24, 32, 40, 48, 56, 64, 72),
[[0, 1, 2], [3, 4], [5, 6], [7, 8], [9]],
),
(
(0, 10, 11, 21, 22, 32, 33, 43, 44, 54),
[[0, 1, 2], [3, 4], [5, 6], [7, 8], [9]],
),
],
)
async def test_abatcher_timed(
monkeypatch: pytest.MonkeyPatch,
arrival_times: tuple[int, ...],
expected: list[list[int]],
) -> None:
"""Group async items into batches by time interval."""
now: float = 0.0
monkeypatch.setattr(
python_utils.generators,
'time',
SimpleNamespace(perf_counter=lambda: now),
)
async def generator() -> types.AsyncIterator[int]:
nonlocal now
item: int
arrival: int
for item, arrival in enumerate(arrival_times):
now = float(arrival)
yield item
batches: types.List[types.List[int]] = []
async for batch in python_utils.abatcher(generator(), interval=10):
batches.append(batch)
assert batches == expected
assert len(batches) == 5
@pytest.mark.asyncio
async def test_abatcher_timed_with_timeout() -> None:
"""Respect timeouts and propagate errors while batching."""
async def generator() -> types.AsyncIterator[int]:
"""Yield items with sleeps to exercise batch timeouts."""
# Test if the timeout is respected
yield 0
yield 1
await asyncio.sleep(0.11)
# Test if the timeout is respected
yield 2
yield 3
await asyncio.sleep(0.11)
# Test if exceptions are handled correctly
await asyncio.wait_for(asyncio.sleep(1), timeout=0.05)
# Test if StopAsyncIteration is handled correctly
yield 4
batcher = python_utils.abatcher(generator(), interval=0.1)
assert await batcher.__anext__() == [0, 1]
assert await batcher.__anext__() == [2, 3]
with pytest.raises(asyncio.TimeoutError):
await batcher.__anext__()
with pytest.raises(StopAsyncIteration):
await batcher.__anext__()
@pytest.mark.asyncio
@pytest.mark.parametrize('batch_size', [None, 0, -1, 3])
@pytest.mark.parametrize('interval', [10, datetime.timedelta(seconds=10)])
@pytest.mark.parametrize('arrival', [8.0, 10.0])
async def test_abatcher_partial_batch_keeps_deadline(
monkeypatch: pytest.MonkeyPatch,
batch_size: int | None,
interval: int | datetime.timedelta,
arrival: float,
) -> None:
"""Flush a partial batch at its deadline, including an exact arrival."""
now: float = 0.0
monkeypatch.setattr(
python_utils.generators,
'time',
SimpleNamespace(perf_counter=lambda: now),
)
original_wait = asyncio.wait
async def wait(
pending: set[asyncio.Future[int]],
*,
timeout: float,
return_when: str,
) -> tuple[set[asyncio.Future[int]], set[asyncio.Future[int]]]:
"""Run ready items, or let the requested timeout elapse."""
nonlocal now
done, remaining = await original_wait(
pending, timeout=0, return_when=return_when
)
if not done:
now += timeout
return done, remaining
monkeypatch.setattr(asyncio, 'wait', wait)
async def generator() -> types.AsyncGenerator[int, None]:
"""Yield twice on the fake clock, then leave one item pending."""
nonlocal now
yield 0
now = arrival
yield 1
await asyncio.Event().wait()
batcher = python_utils.abatcher(
generator(), batch_size=batch_size, interval=interval
)
try:
first = await batcher.__anext__()
assert first == [0, 1]
assert now == 10.0
finally:
await batcher.aclose()
async def blocked_generator(
started: asyncio.Event, closed: types.List[str]
) -> types.AsyncIterator[int]:
"""Yield one item and then wait for an event that never comes."""
try:
yield 0
started.set()
await asyncio.Event().wait()
finally:
closed.append('closed')
@pytest.mark.asyncio
async def test_abatcher_cancels_pending_item_on_close() -> None:
"""Cancel the pending source item when the consumer stops early."""
closed: types.List[str] = []
before: types.Set[asyncio.Task[types.Any]] = asyncio.all_tasks()
# The source never yields a second item, so the interval always ends
# while that item is still pending. Sleep accuracy does not matter.
batcher: types.AsyncGenerator[types.List[int], None] = (
python_utils.abatcher(
blocked_generator(asyncio.Event(), closed), interval=0.01
)
)
first: types.List[int] = await batcher.__anext__()
await batcher.aclose()
assert first == [0]
assert asyncio.all_tasks() == before
assert closed == ['closed']
@pytest.mark.asyncio
async def test_abatcher_cancels_pending_item_on_cancellation() -> None:
"""Cancel the pending source item when the consumer is cancelled."""
started: asyncio.Event = asyncio.Event()
closed: types.List[str] = []
before: types.Set[asyncio.Task[types.Any]] = asyncio.all_tasks()
batcher: types.AsyncGenerator[types.List[int], None] = (
python_utils.abatcher(blocked_generator(started, closed), batch_size=2)
)
consumer: asyncio.Task[types.List[int]] = asyncio.create_task(
batcher.__anext__()
)
await started.wait()
consumer.cancel()
with pytest.raises(asyncio.CancelledError):
await consumer
assert asyncio.all_tasks() == before
assert closed == ['closed']
@pytest.mark.asyncio
async def test_abatcher_reports_source_error_during_cancellation() -> None:
"""Report an error that the source raises while it is cancelled."""
reported: types.List[types.Dict[str, types.Any]] = []
loop: asyncio.AbstractEventLoop = asyncio.get_running_loop()
loop.set_exception_handler(lambda _, context: reported.append(context))
async def generator() -> types.AsyncGenerator[int, None]:
"""Yield one item, then fail while the next one is cancelled."""
yield 0
try:
await asyncio.Event().wait()
finally:
raise RuntimeError('closing failed')
batcher: types.AsyncGenerator[types.List[int], None] = (
python_utils.abatcher(generator(), interval=0.01)
)
try:
first: types.List[int] = await batcher.__anext__()
await batcher.aclose()
finally:
loop.set_exception_handler(None)
assert first == [0]
assert [str(context['exception']) for context in reported] == [
'closing failed'
]
@pytest.mark.asyncio
async def test_abatcher_accepts_source_that_ends_on_cancellation() -> None:
"""Report nothing for a source that just stops when it is cancelled."""
reported: types.List[types.Dict[str, types.Any]] = []
loop: asyncio.AbstractEventLoop = asyncio.get_running_loop()
loop.set_exception_handler(lambda _, context: reported.append(context))
async def generator() -> types.AsyncGenerator[int, None]:
"""Yield one item, then end as soon as the wait is cancelled."""
yield 0
try:
await asyncio.Event().wait()
except asyncio.CancelledError:
return
batcher: types.AsyncGenerator[types.List[int], None] = (
python_utils.abatcher(generator(), interval=0.01)
)
try:
first: types.List[int] = await batcher.__anext__()
await batcher.aclose()
finally:
loop.set_exception_handler(None)
assert first == [0]
assert reported == []
def test_abatcher_collected_after_its_loop_closed(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Clean up without an event loop when nothing is on its way."""
unraisable: types.List[types.Any] = []
monkeypatch.setattr(sys, 'unraisablehook', unraisable.append)
async def generator() -> types.AsyncGenerator[int, None]:
"""Yield four items without waiting."""
i: int
for i in range(4):
yield i
loop: asyncio.AbstractEventLoop = asyncio.new_event_loop()
batcher: types.AsyncGenerator[types.List[int], None] = (
python_utils.abatcher(generator(), batch_size=2)
)
try:
first: types.List[int] = loop.run_until_complete(batcher.__anext__())
finally:
loop.close()
del batcher
gc.collect()
assert first == [0, 1]
assert unraisable == []
@pytest.mark.asyncio
async def test_abatcher_size_flush_restarts_interval(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Restart the interval after a batch that was flushed by its size."""
now: float = 0.0
monkeypatch.setattr(
python_utils.generators,
'time',
SimpleNamespace(perf_counter=lambda: now),
)
async def generator() -> types.AsyncIterator[int]:
"""Let one item arrive every 4 seconds on the fake clock."""
nonlocal now
item: int
for item in range(12):
now = 4.0 * (item + 1)
yield item
batches: types.List[types.List[int]] = [
batch
async for batch in python_utils.abatcher(
generator(), batch_size=3, interval=10
)
]
# Three items take 12 seconds, which is past the interval of 10. The size
# flush takes them and the next item has to start a fresh interval. It
# may not leave on its own because the old interval ran out.
assert batches == [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
class FutureIterator:
"""An async iterator that hands out futures instead of coroutines."""
def __init__(self, stop: int) -> None:
"""Count from zero up to ``stop``, which is excluded."""
self.current: int = 0
self.stop: int = stop
def __aiter__(self) -> 'FutureIterator':
"""Return the iterator itself."""
return self
def __anext__(self) -> 'asyncio.Future[int]':
"""Return a finished future with the next number."""
future: asyncio.Future[int] = (
asyncio.get_running_loop().create_future()
)
if self.current < self.stop:
future.set_result(self.current)
self.current += 1
else:
future.set_exception(StopAsyncIteration())
return future
@pytest.mark.asyncio
async def test_abatcher_with_future_returning_iterator() -> None:
"""Batch an iterator whose ``__anext__`` is not a coroutine."""
batches: types.List[types.List[int]] = [
batch async for batch in python_utils.abatcher(FutureIterator(5), 2)
]
assert batches == [[0, 1], [2, 3], [4]]
@pytest.mark.parametrize('batch_size', [0, -1])
@pytest.mark.parametrize('count', [0, 3])
def test_batcher_warns_for_nonpositive_size(
batch_size: int, count: int
) -> None:
"""Warn once while keeping the existing result and consumption order."""
consumed: list[int] = []
def source() -> types.Generator[int, None, None]:
for item in range(count):
consumed.append(item)
yield item
batcher = python_utils.batcher(source(), batch_size)
assert consumed == []
with pytest.warns(DeprecationWarning, match='ValueError.*5.0') as caught:
result = list(batcher)
assert result == ([list(range(count))] if count else [])
assert consumed == list(range(count))
assert len(caught) == 1
assert caught[0].filename == __file__
@pytest.mark.parametrize('batch_size', [0, -1])
def test_batcher_warning_as_error_does_not_consume(batch_size: int) -> None:
"""Let callers opt into failure before taking the first source item."""
source = iter(range(3))
batcher = python_utils.batcher(source, batch_size)
with warnings.catch_warnings():
warnings.simplefilter('error', DeprecationWarning)
with pytest.raises(DeprecationWarning, match='batch_size'):
next(batcher)
assert list(source) == [0, 1, 2]
@pytest.mark.asyncio
@pytest.mark.parametrize('batch_size', [0, -1])
@pytest.mark.parametrize('count', [0, 3])
@pytest.mark.parametrize('interval', [None, 0])
async def test_abatcher_warns_without_interval(
batch_size: int, count: int, interval: int | None
) -> None:
"""Keep the old zero-size error and negative-size result in 4.x."""
consumed: list[int] = []
async def source() -> types.AsyncGenerator[int, None]:
for item in range(count):
consumed.append(item)
yield item
batcher = python_utils.abatcher(source(), batch_size, interval)
assert consumed == []
with pytest.warns(DeprecationWarning, match='ValueError.*5.0') as caught:
if batch_size == 0:
with pytest.raises(AssertionError, match='Must specify either'):
await batcher.__anext__()
assert consumed == []
else:
result = [batch async for batch in batcher]
assert result == ([list(range(count))] if count else [])
assert consumed == list(range(count))
assert len(caught) == 1
assert caught[0].filename == __file__
@pytest.mark.asyncio
@pytest.mark.parametrize('batch_size', [0, -1])
async def test_abatcher_warning_as_error_does_not_consume(
batch_size: int,
) -> None:
"""Warn before scheduling even the first asynchronous source item."""
source = FutureIterator(3)
batcher = python_utils.abatcher(source, batch_size)
with warnings.catch_warnings():
warnings.simplefilter('error', DeprecationWarning)
with pytest.raises(DeprecationWarning, match='batch_size'):
await batcher.__anext__()
assert source.current == 0
@pytest.mark.asyncio
@pytest.mark.parametrize('batch_size', [None, 0, -1])
@pytest.mark.parametrize('count', [0, 3])
async def test_abatcher_interval_only_sizes(
batch_size: int | None, count: int
) -> None:
"""None and nonpositive sizes impose no limit and issue no warning."""
source = FutureIterator(count)
result = [
batch async for batch in python_utils.abatcher(source, batch_size, 10)
]
assert result == ([list(range(count))] if count else [])
assert source.current == count
def test_batcher_positive_size_is_lazy() -> None:
"""Positive sizes issue no warning and consume only the first batch."""
source = iter(range(3))
batcher = python_utils.batcher(source, 1)
assert next(batcher) == [0]
assert list(source) == [1, 2]
@pytest.mark.parametrize(
'batch_size,expected',
[('2', [[0, 1, 2, 3, 4]]), (2 + 0j, [[0, 1], [2, 3], [4]])],
)
def test_batcher_noncomparable_size(
batch_size: types.Any, expected: list[list[int]]
) -> None:
"""A size that does not compare with 1 keeps its 4.x result."""
with warnings.catch_warnings():
warnings.simplefilter('error', DeprecationWarning)
assert list(python_utils.batcher(range(5), batch_size)) == expected
@pytest.mark.asyncio
async def test_abatcher_noncomparable_size_with_interval() -> None:
"""A size that does not compare with 1 leaves the interval in charge."""
size: types.Any = '2'
source = FutureIterator(5)
result = [batch async for batch in python_utils.abatcher(source, size, 10)]
assert result == [[0, 1, 2, 3, 4]]
@pytest.mark.asyncio
async def test_abatcher_zero_size_with_interval_yields_empty_batch() -> None:
"""Keep the 4.x empty batch for an idle interval with a size of 0."""
async def generator() -> types.AsyncGenerator[int, None]:
"""Stay idle forever."""
await asyncio.Event().wait()
yield 0 # pragma: no cover
batcher = python_utils.abatcher(generator(), batch_size=0, interval=0.01)
try:
assert await asyncio.wait_for(batcher.__anext__(), 5) == []
finally:
await batcher.aclose()
def test_batcher() -> None:
"""Split an iterable into fixed-size batches."""
batch = []
for batch in python_utils.batcher(range(9), 3):
assert len(batch) == 3
for batch in python_utils.batcher(range(4), 3):
assert batch is not None
assert len(batch) == 1