Skip to content

Commit

Permalink
Added coverage tests for the "shutdown" method
Browse files Browse the repository at this point in the history
  • Loading branch information
cjrh committed Dec 1, 2019
1 parent bb93b44 commit e3b245f
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 4 deletions.
7 changes: 3 additions & 4 deletions coroexecutor.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,9 @@ async def map(self, fn, *iterables, timeout=None):
yield await f

async def shutdown(self, wait=True):
self._cancel_all_tasks()
coro = self.__aexit__(None, None, None)
if wait:
await coro
if not wait:
self._cancel_all_tasks()
await self.__aexit__(None, None, None)

def _cancel_all_tasks(self):
for t in self.tasks:
Expand Down
53 changes: 53 additions & 0 deletions tests/test_coroexecutor.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from contextlib import suppress
import asyncio
from asyncio import run
import pytest
Expand Down Expand Up @@ -354,3 +355,55 @@ async def main():
else:
run(main())
assert len(returned) == 9


def test_shutdown():
results = []

async def f(dt):
await asyncio.sleep(dt)
results.append(1)

async def main():
exe = CoroutineExecutor()
t1 = exe.submit(f, 0.01)
t2 = exe.submit(f, 0.05)
await exe.shutdown(wait=True) # default

assert t1.done() and not t1.cancelled()
assert t2.done() and not t2.cancelled()

run(main())
assert results == [1, 1]


@pytest.mark.parametrize('with_interruption', [False, True])
def test_shutdown_nowait(with_interruption):
results = []

async def f(dt):
with suppress(asyncio.CancelledError):
await asyncio.sleep(dt)
results.append(1)

async def main():
exe = CoroutineExecutor()
t1 = exe.submit(f, 0.1)
t2 = exe.submit(f, 0.5)
if with_interruption:
await asyncio.sleep(0)
await exe.shutdown(wait=False)

# "not cancelled" because CancelledError was handled inside f
assert t1.done() and not t1.cancelled()
assert t2.done() and not t2.cancelled()

if with_interruption:
run(main())
else:
# If a task is cancelled before it even starts running, the function
# being wrapped by the task doesn't get a chance to handle the
# CancelledError!
with pytest.raises(asyncio.CancelledError):
run(main())
assert results == []

0 comments on commit e3b245f

Please sign in to comment.