Conghao97's picture tcftrees's picture
ProgramGen release
d086025
Raw History Blame Contribute Delete
9 kB
diff --git a/tests/test_callbacks.py b/tests/test_callbacks.py
new file mode 100644
--- /dev/null
+++ b/tests/test_callbacks.py
@@ -0,0 +1,57 @@
+import asyncio
+
+import pytest
+
+from cafeteria.asyncio.callbacks import (
+ Callback,
+ SimpleTriggerCallback,
+ trigger_callback,
+)
+
+
+@pytest.mark.asyncio
+async def test_trigger_callback_blocking(mocker):
+ m = mocker.Mock()
+
+ result = trigger_callback(m, "foo", bar="baz")
+ assert isinstance(result, asyncio.Future)
+
+ await result
+ m.assert_called_once_with("foo", bar="baz")
+
+
+@pytest.mark.asyncio
+async def test_trigger_callback_coroutine():
+ call_args = []
+
+ # using a real corouting here as mocking will fail iscoroutine checks
+ async def coroutine(*_, **__):
+ call_args.append((_, __))
+
+ result = trigger_callback(coroutine, "foo", bar="baz")
+ assert isinstance(result, asyncio.Task)
+
+ await result
+ assert call_args == [(("foo",), dict(bar="baz"))]
+
+
+@pytest.mark.asyncio
+async def test_trigger_callback_callback(mocker):
+ m = mocker.Mock()
+ cb = Callback(m, "foo", bar="baz")
+ result = trigger_callback(cb, not_ignored=True)
+ assert isinstance(result, asyncio.Future)
+
+ await result
+ m.assert_called_once_with(*cb.args, **cb.kwargs, not_ignored=True)
+
+
+@pytest.mark.asyncio
+async def test_trigger_callback_simple_trigger_callback(mocker):
+ m = mocker.Mock()
+ cb = SimpleTriggerCallback(m, "foo", bar="baz")
+ result = trigger_callback(cb, ignored=True)
+ assert isinstance(result, asyncio.Future)
+
+ await result
+ m.assert_called_once_with(*cb.args, **cb.kwargs)
diff --git a/tests/test_callbacks_registry.py b/tests/test_callbacks_registry.py
new file mode 100644
--- /dev/null
+++ b/tests/test_callbacks_registry.py
@@ -0,0 +1,140 @@
+import pytest
+
+from cafeteria.asyncio.callbacks import Callback, CallbackRegistry
+
+
+def test_callback_registry_simple(mocker):
+ callback_one = mocker.Mock()
+ callback_two = mocker.Mock()
+ registry = CallbackRegistry(callbacks={"one": callback_one, "two": callback_two})
+ registry.dispatch("one", "one")
+ registry.dispatch("two", "two")
+ registry.dispatch(None, "None")
+
+ callback_one.assert_called_once()
+ callback_one.assert_called_once_with("one")
+
+ callback_two.assert_called_once()
+ callback_two.assert_called_once_with("two")
+
+ callback_one.reset_mock()
+ registry.deregister("one", callback_one)
+ registry.dispatch("one", "one")
+
+ callback_one.assert_not_called()
+
+
+def test_callback_registry_multiple(mocker):
+ callback_one = mocker.Mock()
+ callback_two = mocker.Mock()
+ registry = CallbackRegistry(callbacks={"event": [callback_one, callback_two]})
+
+ assert len(registry.callbacks("event")) == 2
+
+ registry.dispatch("event", "event")
+
+ callback_one.assert_called_once()
+ callback_one.assert_called_once_with("event")
+
+ callback_two.assert_called_once()
+ callback_two.assert_called_once_with("event")
+
+ callback_one.reset_mock()
+ callback_two.reset_mock()
+
+ registry.deregister("event", callback_two)
+ registry.dispatch("event", "event")
+
+ callback_one.assert_called_once()
+ callback_one.assert_called_once_with("event")
+
+ callback_two.assert_not_called()
+
+
+def test_callback_registry_coro_without_loop(caplog):
+ async def hello():
+ pass
+
+ registry = CallbackRegistry(callbacks={"hello": hello})
+
+ with pytest.warns(RuntimeWarning):
+ registry.dispatch("hello")
+ assert "Callback triggered without a running loop" in caplog.text
+ assert f"skipping {str(hello)}" in caplog.text
+
+
+def test_callback_registry_callbacks(mocker):
+ callback_one = mocker.Mock()
+ callback_two = mocker.Mock()
+ callback_default = mocker.Mock()
+
+ registry = CallbackRegistry()
+ registry.register("one", callback_one)
+ registry.register("two", callback_two)
+ registry.register(None, callback_default)
+
+ assert registry.callbacks() == [Callback(callback_default)]
+ assert registry.callbacks("one") == [Callback(callback_one)]
+ assert registry.callbacks("two") == [Callback(callback_two)]
+
+
+def test_callback_registry_exists(mocker):
+ callback = mocker.Mock()
+
+ registry = CallbackRegistry()
+ registry.register("one", callback)
+
+ assert registry.exists("one", callback)
+ assert registry.exists("one", Callback(callback))
+ assert not registry.exists(None, callback)
+ assert not registry.exists("two", callback)
+
+
+def test_callback_registry_callbacks_default(mocker):
+ callback = mocker.Mock()
+ registry = CallbackRegistry()
+
+ assert registry.callbacks() == []
+
+ registry.register(None, callback)
+ assert registry.callbacks() == [Callback(callback)]
+
+
+def test_callback_registry_default(mocker):
+ callback = mocker.Mock()
+ registry = CallbackRegistry()
+ registry.register(None, callback)
+
+ registry.dispatch("doesnotexist", "one")
+
+ callback.assert_called_once()
+ callback.assert_called_once_with("one")
+
+ callback.reset_mock()
+ registry.dispatch(None, "one")
+
+ callback.assert_called_once()
+ callback.assert_called_once_with("one")
+
+ callback.reset_mock()
+ registry.deregister(None, callback)
+ registry.dispatch("doesnotexist", "two")
+ registry.dispatch(None, "two")
+
+ callback.assert_not_called()
+
+
+def test_callback_registry_deregister_non_existing():
+ # noinspection PyBroadException
+ try:
+ CallbackRegistry().deregister("one", lambda x: None)
+ except Exception:
+ pytest.fail("Unexpected exception")
+
+
+@pytest.mark.asyncio
+async def test_callback_registry_handle_event(mocker):
+ callback = mocker.Mock()
+ with pytest.warns(DeprecationWarning):
+ await CallbackRegistry(callbacks={"one": callback}).handle_event("one", "one")
+ callback.assert_called_once_with("one")
diff --git a/tests/test_commons.py b/tests/test_commons.py
new file mode 100644
--- /dev/null
+++ b/tests/test_commons.py
@@ -0,0 +1,93 @@
+import asyncio
+import signal
+
+import pytest
+
+from cafeteria.asyncio.commons import cancel_all_tasks, cancel_tasks_on_termination
+
+
+# noinspection PyUnresolvedReferences,PyProtectedMember
+def ensure_signal_handlers_registered(
+ loop: asyncio.AbstractEventLoop, *args: signal.Signals
+) -> None:
+ assert len(loop._signal_handlers) == 2 + len(args)
+
+ # ensure default signal handlers registered added
+ assert signal.SIGINT in loop._signal_handlers
+ assert signal.SIGTERM in loop._signal_handlers
+
+ for arg in args:
+ assert arg in loop._signal_handlers
+
+
+def test_handle_signals(recwarn):
+ # noinspection PyDeprecation
+ from cafeteria.asyncio.commons import handle_signals
+
+ loop = asyncio.get_event_loop()
+ handle_signals(event_loop=loop)
+ ensure_signal_handlers_registered(loop)
+
+ # ensure a deprecation warning was issued
+ assert len(recwarn) == 1
+ w = recwarn.pop(DeprecationWarning)
+ assert issubclass(w.category, DeprecationWarning)
+ assert str(w.message) == "Use cancel_tasks_on_termination instead"
+
+
+def test_cancel_tasks_on_termination_default():
+ loop = asyncio.get_event_loop()
+ cancel_tasks_on_termination(loop, signal.SIGABRT)
+ ensure_signal_handlers_registered(loop, signal.SIGABRT)
+
+
+def test_cancel_tasks_on_termination_int():
+ loop = asyncio.get_event_loop()
+ cancel_tasks_on_termination(loop, 6)
+ ensure_signal_handlers_registered(loop, signal.SIGABRT)
+
+
+def test_cancel_tasks_on_termination_str():
+ loop = asyncio.get_event_loop()
+ cancel_tasks_on_termination(loop, "SIGABRT")
+ ensure_signal_handlers_registered(loop, signal.SIGABRT)
+
+
+def test_cancel_tasks_on_termination_invalid_type(mocker):
+ with pytest.raises(ValueError):
+ # noinspection PyTypeChecker
+ cancel_tasks_on_termination(asyncio.get_event_loop(), mocker.Mock())
+
+
+def test_cancel_tasks_on_termination_invalid_int():
+ with pytest.raises(ValueError):
+ # noinspection PyTypeChecker
+ cancel_tasks_on_termination(asyncio.get_event_loop(), 9999)
+
+
+def test_cancel_tasks_on_termination_invalid_str():
+ with pytest.raises(ValueError):
+ # noinspection PyTypeChecker
+ cancel_tasks_on_termination(asyncio.get_event_loop(), "FOOBAR")
+
+
+@pytest.mark.asyncio
+async def test_cancel_all_tasks():
+ async def infinity():
+ try:
+ while True:
+ await asyncio.sleep(2)
+ except asyncio.CancelledError:
+ pass
+
+ test_task = asyncio.current_task()
+ task = asyncio.ensure_future(infinity())
+
+ # ensure task is running
+ assert not (task.done() or task.cancelled())
+
+ await cancel_all_tasks(None, test_task)
+ assert task.cancelled()
+
+ # current task was ignored
+ assert not (test_task.done() or test_task.cancelled())