File size: 9,003 Bytes
d086025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
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())