-
-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathtest_parallel_async.py
More file actions
402 lines (307 loc) · 12.3 KB
/
Copy pathtest_parallel_async.py
File metadata and controls
402 lines (307 loc) · 12.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
"""The asyncio engine: `amap` and its call-strategy handling."""
from __future__ import annotations
import asyncio
import io
import operator
import typing
import pytest
from progressbar._parallel import _async
async def _async_double(value: int) -> int:
return value * 2
def _sync_double(value: int) -> int:
return value * 2
def _returns_awaitable(value: int) -> typing.Awaitable[int]:
return _async_double(value)
async def _boom_on_two(value: int) -> int:
if value == 2:
raise ValueError('boom')
return value
class TestAmap:
def test_async_fn_ordered(self) -> None:
async def _run() -> list[int]:
return await _async.amap(_async_double, range(10), bar=False)
assert asyncio.run(_run()) == [value * 2 for value in range(10)]
@pytest.mark.no_freezegun
def test_ordered_despite_scrambled_completion(self) -> None:
async def _staggered(value: int) -> int:
await asyncio.sleep((5 - value) * 0.02)
return value
async def _run() -> list[int]:
return await _async.amap(_staggered, range(5), bar=False)
assert asyncio.run(_run()) == list(range(5))
@pytest.mark.no_freezegun
def test_sync_fn_wrapped_in_thread(self) -> None:
async def _run() -> list[int]:
return await _async.amap(_sync_double, range(5), bar=False)
assert asyncio.run(_run()) == [0, 2, 4, 6, 8]
@pytest.mark.no_freezegun
def test_sync_fn_returning_awaitable_is_awaited(self) -> None:
async def _run() -> list[int]:
return await _async.amap(_returns_awaitable, range(4), bar=False)
assert asyncio.run(_run()) == [0, 2, 4, 6]
def test_multiple_iterables_zip(self) -> None:
async def _add(left: int, right: int) -> int:
return left + right
async def _run() -> list[int]:
return await _async.amap(_add, [1, 2], [10, 20], bar=False)
assert asyncio.run(_run()) == [11, 22]
def test_empty(self) -> None:
async def _run() -> list[int]:
return await _async.amap(_async_double, [], bar=False)
assert asyncio.run(_run()) == []
@pytest.mark.no_freezegun
def test_concurrency_capped(self) -> None:
running: list[int] = [0]
seen_max: list[int] = [0]
async def _tracked(value: int) -> int:
running[0] += 1
seen_max[0] = max(seen_max[0], running[0])
await asyncio.sleep(0.02)
running[0] -= 1
return value
async def _run() -> list[int]:
return await _async.amap(
_tracked, range(10), concurrency=2, bar=False
)
assert asyncio.run(_run()) == list(range(10))
assert seen_max[0] <= 2
def test_workers_alias(self) -> None:
async def _run() -> list[int]:
return await _async.amap(
_async_double, range(4), workers=2, bar=False
)
assert asyncio.run(_run()) == [0, 2, 4, 6]
class TestAmapErrors:
def test_fail_fast(self) -> None:
async def _run() -> list[int]:
return await _async.amap(
_boom_on_two, range(10), concurrency=1, bar=False
)
with pytest.raises(ValueError, match='boom'):
asyncio.run(_run())
def test_on_error_return(self) -> None:
async def _run() -> list[typing.Any]:
return await _async.amap(
_boom_on_two, range(5), on_error='return', bar=False
)
results: list[typing.Any] = asyncio.run(_run())
assert results[1] == 1
assert isinstance(results[2], ValueError)
assert results[4] == 4
@pytest.mark.no_freezegun
def test_timeout_cancels_cleanly(self) -> None:
async def _slow(value: int) -> int:
await asyncio.sleep(30)
return value # pragma: no cover - always cancelled
async def _run() -> list[int]:
return await _async.amap(
_slow,
range(4),
timeout=0.2,
poll_interval=0.05,
bar=False,
)
with pytest.raises(asyncio.TimeoutError):
asyncio.run(_run())
# asyncio.run closing the loop without warnings proves the
# outstanding tasks were cancelled and awaited.
def test_invalid_on_error(self) -> None:
async def _run() -> list[int]:
return await _async.amap(
_async_double, range(3), on_error='ignore', bar=False
)
with pytest.raises(ValueError, match='on_error'):
asyncio.run(_run())
class TestKeepAlive:
@pytest.mark.no_freezegun
def test_bar_ticks_during_long_task(self) -> None:
stream = io.StringIO()
async def _slow(value: int) -> int:
await asyncio.sleep(0.4)
return value
async def _run() -> list[int]:
return await _async.amap(
_slow, range(2), poll_interval=0.05, fd=stream
)
assert asyncio.run(_run()) == [0, 1]
# Multiple renders happened while the tasks slept: the output
# contains far more than the start + finish frames. Count
# rendered frames by their timer text -- the line separator
# depends on stream/tty detection.
assert stream.getvalue().count('Elapsed Time') > 3
class TestAimap:
@pytest.mark.no_freezegun
def test_ordered_despite_scrambled_completion(self) -> None:
async def _staggered(value: int) -> int:
await asyncio.sleep((5 - value) * 0.02)
return value
async def _run() -> list[int]:
return [
value
async for value in _async.aimap(
_staggered, range(5), bar=False
)
]
assert asyncio.run(_run()) == list(range(5))
@pytest.mark.no_freezegun
def test_early_break_with_aclosing(self) -> None:
import contextlib
async def _run() -> list[int]:
collected: list[int] = []
async with contextlib.aclosing(
_async.aimap(
_async_double, range(10), concurrency=2, bar=False
)
) as iterator:
async for value in iterator:
collected.append(value)
if len(collected) == 2:
break
return collected
assert asyncio.run(_run()) == [0, 2]
class TestAimapUnordered:
@pytest.mark.no_freezegun
def test_yields_pairs_in_completion_order(self) -> None:
async def _staggered(value: int) -> int:
await asyncio.sleep((5 - value) * 0.02)
return value
async def _run() -> list[tuple[int, int]]:
return [
pair
async for pair in _async.aimap_unordered(
_staggered, range(5), bar=False
)
]
pairs: list[tuple[int, int]] = asyncio.run(_run())
assert sorted(pairs) == [(value, value) for value in range(5)]
assert pairs[0] == (4, 4)
def test_multi_iterable_pairs_use_args_tuple(self) -> None:
async def _add(left: int, right: int) -> int:
return left + right
async def _run() -> list[tuple[typing.Any, int]]:
return [
pair
async for pair in _async.aimap_unordered(
_add, [1, 2], [10, 20], bar=False
)
]
assert sorted(asyncio.run(_run())) == [
((1, 10), 11),
((2, 20), 22),
]
class TestGather:
def test_ordered_results(self) -> None:
async def _run() -> list[int]:
return await _async.gather(
_async_double(1),
_async_double(2),
_async_double(3),
bar=False,
)
assert asyncio.run(_run()) == [2, 4, 6]
def test_empty_returns_empty_list(self) -> None:
async def _run() -> list[typing.Any]:
return await _async.gather()
assert asyncio.run(_run()) == []
def test_return_exceptions(self) -> None:
async def _run() -> list[typing.Any]:
return await _async.gather(
_async_double(1),
_boom_on_two(2),
_async_double(3),
return_exceptions=True,
bar=False,
)
results: list[typing.Any] = asyncio.run(_run())
assert results[0] == 2
assert isinstance(results[1], ValueError)
assert results[2] == 6
def test_fail_fast_by_default(self) -> None:
async def _run() -> list[typing.Any]:
return await _async.gather(
_async_double(1), _boom_on_two(2), bar=False
)
with pytest.raises(ValueError, match='boom'):
asyncio.run(_run())
class TestAsyncPool:
@pytest.mark.no_freezegun
def test_bounds_concurrency(self) -> None:
running: list[int] = [0]
seen_max: list[int] = [0]
async def _tracked(value: int) -> int:
running[0] += 1
seen_max[0] = max(seen_max[0], running[0])
await asyncio.sleep(0.02)
running[0] -= 1
return value
async def _run() -> list[int]:
async with _async.AsyncPool(2, bar=False) as pool:
return await pool.map(_tracked, range(8))
assert asyncio.run(_run()) == list(range(8))
assert seen_max[0] <= 2
def test_defaults_merge_and_override(self) -> None:
async def _run() -> list[typing.Any]:
async with _async.AsyncPool(2, bar=False) as pool:
return await pool.map(
_boom_on_two, range(4), on_error='return'
)
results: list[typing.Any] = asyncio.run(_run())
assert isinstance(results[2], ValueError)
def test_imap_methods(self) -> None:
async def _run() -> tuple[list[int], list[tuple[int, int]]]:
async with _async.AsyncPool(2, bar=False) as pool:
ordered: list[int] = [
value async for value in pool.imap(_async_double, range(3))
]
pairs: list[tuple[int, int]] = sorted(
[
pair
async for pair in pool.imap_unordered(
_async_double, range(3)
)
]
)
return ordered, pairs
ordered, pairs = asyncio.run(_run())
assert ordered == [0, 2, 4]
assert pairs == [(0, 0), (1, 2), (2, 4)]
class TestMultiBarMode:
def test_async_workers_see_their_task_bar(self) -> None:
from progressbar._parallel import _common
seen: list[bool] = []
async def _check(value: int) -> int:
seen.append(_common.current_task_bar() is not None)
return value
async def _run() -> list[int]:
return await _async.amap(
_check, range(3), bar='multi', fd=io.StringIO()
)
assert asyncio.run(_run()) == [0, 1, 2]
assert seen == [True, True, True]
class TestExternalCancellation:
def test_self_cancelling_task_surfaces(self) -> None:
async def _self_cancel(value: int) -> int:
if value == 1:
task = asyncio.current_task()
assert task is not None
task.cancel()
await asyncio.sleep(1)
return value
async def _run() -> list[int]:
return await _async.amap(
_self_cancel, range(3), concurrency=1, bar=False
)
# A cancellation this run did not initiate must surface, never
# silently drop the item.
with pytest.raises(asyncio.CancelledError):
asyncio.run(_run())
class TestCallStrategy:
def test_detects_coroutine_function(self) -> None:
assert _async._call_strategy(_async_double) == 'async'
def test_detects_partial_of_coroutine_function(self) -> None:
import functools
partial = functools.partial(_async_double)
assert _async._call_strategy(partial) == 'async'
def test_sync_fallback(self) -> None:
assert _async._call_strategy(_sync_double) == 'sync'
assert _async._call_strategy(operator.add) == 'sync'