-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Background Tasks Start & Stop
- Loading branch information
Showing
4 changed files
with
189 additions
and
59 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
import asyncio | ||
import logging | ||
from typing import Optional, Coroutine, Any, Callable | ||
|
||
from pyobs.utils.exceptions import SevereError | ||
|
||
log = logging.getLogger(__name__) | ||
|
||
|
||
class BackgroundTask: | ||
def __init__(self, func: Callable[..., Coroutine[Any, Any, None]], restart: bool) -> None: | ||
self._func: Callable[..., Coroutine[Any, Any, None]] = func | ||
self._restart: bool = restart | ||
self._task: Optional[asyncio.Future] = None | ||
|
||
def start(self) -> None: | ||
self._task = asyncio.create_task(self._func()) | ||
self._task.add_done_callback(self._callback_function) | ||
|
||
def _callback_function(self, args=None) -> None: | ||
try: | ||
exception = self._task.exception() | ||
except asyncio.CancelledError: | ||
return | ||
|
||
if isinstance(exception, SevereError): | ||
raise exception | ||
elif exception is not None: | ||
log.error("Exception %s in task %s.", exception, self._func.__name__) | ||
|
||
if self._restart: | ||
log.error("Background task for %s has died, restarting...", self._func.__name__) | ||
self.start() | ||
else: | ||
log.error("Background task for %s has died, quitting...", self._func.__name__) | ||
|
||
def stop(self) -> None: | ||
if self._task is not None: | ||
self._task.cancel() |
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,76 @@ | ||
import asyncio | ||
import logging | ||
from unittest.mock import AsyncMock, Mock | ||
|
||
import pytest | ||
import pyobs.utils.exceptions as exc | ||
from pyobs.background_task import BackgroundTask | ||
|
||
|
||
@pytest.mark.asyncio | ||
async def test_callback_canceled(caplog): | ||
test_function = AsyncMock() | ||
task = asyncio.create_task(test_function()) | ||
task.exception = Mock(side_effect=asyncio.CancelledError()) | ||
|
||
bg_task = BackgroundTask(test_function, False) | ||
bg_task._task = task | ||
|
||
with caplog.at_level(logging.ERROR): | ||
bg_task._callback_function() | ||
|
||
assert len(caplog.messages) == 0 | ||
|
||
|
||
@pytest.mark.asyncio | ||
async def test_callback_exception(caplog): | ||
test_function = AsyncMock() | ||
test_function.__name__ = "test_function" | ||
|
||
task = asyncio.create_task(test_function()) | ||
task.exception = Mock(return_value=Exception("TestError")) | ||
|
||
bg_task = BackgroundTask(test_function, False) | ||
bg_task._task = task | ||
|
||
with caplog.at_level(logging.ERROR): | ||
bg_task._callback_function() | ||
|
||
assert caplog.messages[0] == "Exception TestError in task test_function." | ||
assert caplog.messages[1] == "Background task for test_function has died, quitting..." | ||
|
||
|
||
@pytest.mark.asyncio | ||
async def test_callback_pyobs_error(): | ||
test_function = AsyncMock() | ||
test_function.__name__ = "test_function" | ||
|
||
task = asyncio.create_task(test_function()) | ||
task.exception = Mock(return_value=exc.SevereError(exc.ImageError("TestError"))) | ||
|
||
bg_task = BackgroundTask(test_function, False) | ||
bg_task._task = task | ||
|
||
with pytest.raises(exc.SevereError): | ||
bg_task._callback_function() | ||
|
||
|
||
@pytest.mark.asyncio | ||
async def test_callback_restart(caplog): | ||
test_function = AsyncMock() | ||
test_function.__name__ = "test_function" | ||
|
||
task = asyncio.create_task(test_function()) | ||
task.exception = Mock(return_value=None) | ||
|
||
bg_task = BackgroundTask(test_function, True) | ||
bg_task._task = task | ||
|
||
bg_task.start = Mock() | ||
|
||
with caplog.at_level(logging.ERROR): | ||
bg_task._callback_function() | ||
|
||
assert caplog.messages[0] == "Background task for test_function has died, restarting..." | ||
bg_task.start.assert_called_once() | ||
|
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,53 @@ | ||
from unittest.mock import AsyncMock | ||
|
||
import pyobs | ||
from pyobs.background_task import BackgroundTask | ||
from pyobs.object import Object | ||
|
||
|
||
def test_add_background_task(): | ||
obj = Object() | ||
test_function = AsyncMock() | ||
|
||
task = obj.add_background_task(test_function, False, False) | ||
|
||
assert task._func == test_function | ||
assert task._restart is False | ||
|
||
assert obj._background_tasks[0] == (task, False) | ||
|
||
|
||
def test_perform_background_task_autostart(mocker): | ||
mocker.patch("pyobs.background_task.BackgroundTask.start") | ||
|
||
obj = Object() | ||
test_function = AsyncMock() | ||
|
||
obj.add_background_task(test_function, False, True) | ||
obj._perform_background_task_autostart() | ||
|
||
pyobs.background_task.BackgroundTask.start.assert_called_once() | ||
|
||
|
||
def test_perform_background_task_no_autostart(mocker): | ||
mocker.patch("pyobs.background_task.BackgroundTask.start") | ||
|
||
obj = Object() | ||
test_function = AsyncMock() | ||
|
||
obj.add_background_task(test_function, False, False) | ||
obj._perform_background_task_autostart() | ||
|
||
pyobs.background_task.BackgroundTask.start.assert_not_called() | ||
|
||
|
||
def test_stop_background_task(mocker): | ||
mocker.patch("pyobs.background_task.BackgroundTask.stop") | ||
|
||
obj = Object() | ||
test_function = AsyncMock() | ||
|
||
obj.add_background_task(test_function, False, False) | ||
obj._stop_background_tasks() | ||
|
||
pyobs.background_task.BackgroundTask.stop.assert_called_once() |