Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: as_completed with return_exceptions=True #104

Merged
merged 1 commit into from
Jan 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified .coverage
Binary file not shown.
13 changes: 10 additions & 3 deletions a_sync/utils/as_completed.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,12 @@ def as_completed(fs, *, timeout: Optional[float] = None, return_exceptions: bool
...
```
"""
if isinstance(fs, Mapping):
return as_completed_mapping(fs, timeout=timeout, return_exceptions=return_exceptions, aiter=aiter, tqdm=tqdm, **tqdm_kwargs)
if return_exceptions:
raise NotImplementedError
fs = [__exc_wrap(f) for f in fs]
return (
as_completed_mapping(fs, timeout=timeout, return_exceptions=return_exceptions, aiter=aiter, tqdm=tqdm, **tqdm_kwargs) if isinstance(fs, Mapping)
else ASyncIterator.wrap(__yield_as_completed(fs, tqdm=tqdm, **tqdm_kwargs)) if aiter
ASyncIterator.wrap(__yield_as_completed(fs, timeout=timeout, tqdm=tqdm, **tqdm_kwargs)) if aiter
else tqdm_asyncio.as_completed(fs, timeout=timeout, **tqdm_kwargs) if tqdm
else asyncio.as_completed(fs, timeout=timeout)
)
Expand Down Expand Up @@ -128,3 +129,9 @@ async def __yield_as_completed(futs: Iterable[Awaitable[T]], *, timeout: Optiona

async def __mapping_wrap(k: KT, v: Awaitable[VT]) -> VT:
return k, await v

async def __exc_wrap(awaitable: Awaitable[T]) -> Union[T, Exception]:
try:
return await awaitable
except Exception as e:
return e
11 changes: 11 additions & 0 deletions tests/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,3 +135,14 @@ def _test_kwargs(fn, default: Literal['sync','async',None]):
assert fn() == 2
elif default == 'async':
assert asyncio.get_event_loop().run_until_complete(fn()) == 2

async def sample_task(n):
await asyncio.sleep(0.01)
return n

async def timeout_task(n):
await asyncio.sleep(0.1)
return n

async def sample_exc(n):
raise ValueError("Sample error")
79 changes: 79 additions & 0 deletions tests/test_as_completed.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@

import asyncio

import a_sync
import pytest

from tests.fixtures import sample_exc, sample_task, timeout_task


@pytest.mark.asyncio_cooperative
async def test_as_completed_with_awaitables():
tasks = [sample_task(i) for i in range(5)]
results = [await result for result in a_sync.as_completed(tasks, aiter=False)]
assert sorted(results) == list(range(5)), "Results should be in ascending order from 0 to 4"

@pytest.mark.asyncio_cooperative
async def test_as_completed_with_awaitables_aiter():
tasks = [sample_task(i) for i in range(5)]
results = []
async for result in a_sync.as_completed(tasks, aiter=True):
results.append(result)
assert sorted(results) == list(range(5)), "Results should be in ascending order from 0 to 4"

@pytest.mark.asyncio_cooperative
async def test_as_completed_with_mapping():
tasks = {'task1': sample_task(1), 'task2': sample_task(2)}
results = {}
for result in a_sync.as_completed(tasks, aiter=False):
key, value = await result
results[key] = value
assert results == {'task1': 1, 'task2': 2}, "Results should match the input mapping"

@pytest.mark.asyncio_cooperative
async def test_as_completed_with_mapping_aiter():
tasks = {'task1': sample_task(1), 'task2': sample_task(2)}
results = {}
async for key, result in a_sync.as_completed(tasks, aiter=True):
results[key] = result
assert results == {'task1': 1, 'task2': 2}, "Results should match the input mapping"

@pytest.mark.asyncio_cooperative
async def test_as_completed_with_timeout():
tasks = [timeout_task(i) for i in range(2)]
with pytest.raises(asyncio.TimeoutError):
[await result for result in a_sync.as_completed(tasks, aiter=False, timeout=0.05)]

@pytest.mark.asyncio_cooperative
async def test_as_completed_with_timeout_aiter():
tasks = [timeout_task(i) for i in range(2)]
with pytest.raises(asyncio.TimeoutError):
[result async for result in a_sync.as_completed(tasks, aiter=True, timeout=0.05)]

@pytest.mark.asyncio_cooperative
async def test_as_completed_return_exceptions():
tasks = {i: sample_exc(i) for i in range(1)}
results = [await result for result in a_sync.as_completed(tasks, aiter=False, return_exceptions=True)]
assert isinstance(results[0], ValueError), "The result should be an exception"

@pytest.mark.asyncio_cooperative
async def test_as_completed_return_exceptions_aiter():
tasks = [sample_exc(i) for i in range(1)]
results = []
async for result in a_sync.as_completed(tasks, aiter=True, return_exceptions=True):
results.append(result)
assert isinstance(results[0], ValueError), "The result should be an exception"

@pytest.mark.asyncio_cooperative
async def test_as_completed_with_tqdm_disabled():
tasks = [sample_task(i) for i in range(5)]
results = [await result for result in a_sync.as_completed(tasks, aiter=False, tqdm=False)]
assert sorted(results) == list(range(5)), "Results should be in ascending order from 0 to 4"

@pytest.mark.asyncio_cooperative
async def test_as_completed_with_tqdm_disabled_aiter():
tasks = [sample_task(i) for i in range(5)]
results = []
async for result in a_sync.as_completed(tasks, aiter=True, tqdm=False):
results.append(result)
assert sorted(results) == list(range(5)), "Results should be in ascending order from 0 to 4"
32 changes: 32 additions & 0 deletions tests/test_gather.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import asyncio

import pytest

from a_sync import gather
from tests.fixtures import sample_exc


async def sample_task(number):
await asyncio.sleep(0.1)
return number * 2

@pytest.mark.asyncio_cooperative
async def test_gather_with_awaitables():
results = await gather(sample_task(1), sample_task(2), sample_task(3))
assert results == [2, 4, 6]

@pytest.mark.asyncio_cooperative
async def test_gather_with_mapping():
tasks = {'a': sample_task(1), 'b': sample_task(2), 'c': sample_task(3)}
results = await gather(tasks)
assert results == {'a': 2, 'b': 4, 'c': 6}

@pytest.mark.asyncio_cooperative
async def test_gather_with_exceptions():
with pytest.raises(ValueError):
await gather(sample_exc(None))

@pytest.mark.asyncio_cooperative
async def test_gather_with_return_exceptions():
results = await gather(sample_exc(None), return_exceptions=True)
assert isinstance(results[0], ValueError)
Loading