-
Notifications
You must be signed in to change notification settings - Fork 107
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add
background_tasks
for canceling tasks
This contextmanager makes it simpler to ensure that infinitely-running tasks get canceled when appropriate, even when an exception occurs.
- Loading branch information
Showing
5 changed files
with
93 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import asyncio | ||
|
||
import pytest | ||
|
||
from ert.async_utils import background_tasks | ||
|
||
|
||
@pytest.mark.timeout(1) | ||
async def test_background_tasks(caplog): | ||
current_task_future = asyncio.Future() | ||
|
||
async def task(): | ||
current_task_future.set_result(asyncio.current_task()) | ||
await asyncio.sleep(100) | ||
|
||
async with background_tasks() as bt: | ||
bt(task()) | ||
current_task = await current_task_future | ||
assert not current_task.done() | ||
|
||
assert current_task.done() | ||
assert caplog.records == [] | ||
|
||
|
||
@pytest.mark.timeout(1) | ||
async def test_background_tasks_with_exception(caplog): | ||
started = asyncio.Event() | ||
|
||
async def task(): | ||
started.set() | ||
raise ValueError("Uh-oh!") | ||
|
||
async with background_tasks() as bt: | ||
bt(task()) | ||
await started.wait() | ||
|
||
assert len(caplog.records) == 1 | ||
assert caplog.records[0].message == "Uh-oh!" |