File size: 22,550 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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
diff --git a/src/cafeteria/asyncio/callbacks.py b/src/cafeteria/asyncio/callbacks.py
new file mode 100644
index 0000000000000000000000000000000000000000..8031062063b018e23ae2026fe66218ea3adead34
--- /dev/null
+++ b/src/cafeteria/asyncio/callbacks.py
@@ -0,0 +1,214 @@
+import asyncio
+import logging
+import warnings
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import (
+    Any,
+    Callable,
+    Coroutine,
+    Dict,
+    Generator,
+    Hashable,
+    List,
+    Optional,
+    Tuple,
+    Union,
+)
+
+from cafeteria.logging import LoggedObject
+
+CallbackType = Union[Callable, Coroutine, "Callback"]
+CallbackResultType = Union[asyncio.Task, Generator, Coroutine]
+EventType = Optional[Union[Enum, Hashable, None]]
+
+logger = logging.getLogger()
+
+
+@dataclass
+class Callback:
+    function: CallbackType
+    args: Tuple[Any] = field(default_factory=list)
+    kwargs: Dict[str, Any] = field(default_factory=dict)
+
+    def __init__(self, function, *args: Any, **kwargs: Any) -> None:
+        super().__init__()
+        self.function = function
+        self.args = args
+        self.kwargs = kwargs
+
+    def trigger(self, *args: Any, **kwargs) -> CallbackResultType:
+        """
+        Trigger this callback by prepending given positional arguments and merging
+        given keyword arguments updating default keyword arguments.
+
+        :param args: Positional arguments to prepend.
+        :param kwargs: Keyword arguments to update defaults with.
+        :return: An awaitable result.
+        """
+        kwargz = dict(**self.kwargs)
+        kwargz.update(kwargs)
+        argz = args + self.args
+        return trigger_callback(self.function, *argz, **kwargz)
+
+
+@dataclass
+class SimpleTriggerCallback(Callback):
+    """
+    A callback dataclass implementation that allows for ignoring any additional
+    arguments provided at the time of trigger.
+    """
+
+    def __init__(self, function, *args: Any, **kwargs: Any) -> None:
+        super().__init__(function, *args, **kwargs)
+
+    def trigger(self, *_, **__) -> CallbackResultType:
+        """
+        Trigger callback ignoring provided arguments.
+        """
+        return super().trigger()
+
+
+def trigger_callback(callback: CallbackType, *args, **kwargs) -> CallbackResultType:
+    """
+    Helper function to trigger a callback (coroutine or callable) with the provided
+    positional/keyword arguments. This will return an awaitable callback result.
+
+    :param callback: The callback to use for this trigger. This could be a `Coroutine`,
+        `Callable` or a instance of :class:`cafeteria.asyncio.callbacks.Callback`.
+    :param args: The positional arguments to use when triggering a callback.
+    :param kwargs: The keyword arguments to use when triggering a callback.
+    :return: An awaitable result.
+    """
+    if isinstance(callback, Callback):
+        return callback.trigger(*args, **kwargs)
+
+    if asyncio.iscoroutinefunction(callback):
+        try:
+            return asyncio.create_task(callback(*args, **kwargs))
+        except RuntimeError:
+            logger.warning(
+                "Callback triggered without a running loop, skipping %s", callback
+            )
+    else:
+        try:
+            return asyncio.get_running_loop().run_in_executor(
+                None, lambda: callback(*args, **kwargs)
+            )
+        except RuntimeError:
+            callback(*args, **kwargs)
+
+
+class CallbackRegistry(LoggedObject):
+    def __init__(
+        self,
+        callbacks: Optional[
+            Dict[EventType, Union[CallbackType, List[CallbackType]]]
+        ] = None,
+    ) -> None:
+        self._callbacks: Dict[EventType, List[Callback]] = dict()
+        if callbacks is not None:
+            for event_type, callback in callbacks.items():
+                if not isinstance(callback, list):
+                    callback = [callback]
+                for c in callback:
+                    self.register(event_type, c)
+
+    def callbacks(self, event_type: EventType = None) -> List[Callback]:
+        """
+        Retrieve all callbacks registered for a particular *event_type*. If *event_type*
+        is `None` or does not have any callbacks already registered, the default
+        callbacks are returned.
+
+        :param event_type: Event type to retrieve callbacks for.
+        :return: Registered callbacks or default callbacks if none registered for the
+            event type.
+        """
+        return self._callbacks.get(event_type, self._callbacks.get(None, []))
+
+    def register(self, event_type: EventType, callback: CallbackType) -> None:
+        """
+        This method allows for a handler to be registered for a specified event type. If
+        the *event_type* is `None` this is registered as a default callback triggered
+        only when explicitly dispatched or no other event type matched the specified
+        event type when dispatching.
+
+        :param event_type: The type of event to associate the callback handler with.
+        :param callback: The callback handler to associate with this event.
+        """
+        if not isinstance(callback, Callback):
+            callback = Callback(function=callback)
+
+        if event_type not in self._callbacks:
+            self._callbacks[event_type] = list()
+        self._callbacks[event_type].append(callback)
+        self.logger.debug("Registered %s to %s", event_type, callback)
+
+    def deregister(self, event_type: EventType, callback: CallbackType) -> None:
+        """
+        This method allows for a handler to be de-registered for a specified event type
+        if it has already been registered. If *event_type* is set to `None`, *callback*
+        is removed (if exists) from the default callbacks.
+
+        :param event_type: The type of event the callback handler is associated with.
+        :param callback: The callback handler to de-register.
+        """
+        if not isinstance(callback, Callback):
+            callback = Callback(function=callback)
+
+        try:
+            self._callbacks.get(event_type, []).remove(callback)
+        except ValueError:
+            pass
+
+    def exists(self, event_type: EventType, callback: CallbackType) -> bool:
+        """
+        Check if callback exists for the specified *event_type*
+
+        :param event_type: The type of event to check the callback for.
+        :param callback: The callback handler to de-register.
+        :return: `True` if *callback* exists for the specified *event_type*.
+        """
+        if not isinstance(callback, Callback):
+            callback = Callback(function=callback)
+        return callback in self.callbacks(event_type)
+
+    def dispatch(self, event_type: EventType, *args: Any, **kwargs: Any):
+        """
+        Dispatch callbacks registered for an *event_type*. This arguments expects
+        any additional positional/keyword arguments required when triggering the
+        callback. If *event_type* is `None` or does not have any callbacks already
+         registered, the default callbacks (if any) are triggered.
+
+        :param event_type: Event type to dispatch
+        :param args: Positional arguments to be passed into the callback before any
+            pre-configured positional arguments.
+        :param kwargs: Keyword arguments to be passed when triggering the callback.
+            These override any pre-configured arguments.
+        """
+        self.logger.debug("Received event: %s", event_type)
+        for callback in self.callbacks(event_type):
+            self.logger.debug("Executing callback %s", callback)
+            _ = callback.trigger(*args, **kwargs)
+
+    async def handle_event(
+        self, event_type: EventType, *args: Any, **kwargs: Any
+    ) -> None:
+        """
+        Method called when an event is to be dispatched/handled. This arguments expects
+        any additional positional/keyword arguments required when triggering the
+        callback.
+
+        :param event_type: Event type to dispatch
+        :param args: Positional arguments to be passed into the callback before any
+            pre-configured positional arguments.
+        :param kwargs: Keyword arguments to be passed when triggering the callback.
+            These override any pre-configured arguments.
+        """
+        warnings.warn(
+            "CallbackRegistry.handle_event() is deprecated in favour of "
+            "CallbackRegistry.dispatch() and will be removed in a future version",
+            category=DeprecationWarning,
+            stacklevel=2,
+        )
+        return self.dispatch(event_type, *args, **kwargs)
diff --git a/src/cafeteria/asyncio/commons.py b/src/cafeteria/asyncio/commons.py
new file mode 100644
index 0000000000000000000000000000000000000000..2aff1de8c1440c5d5942bfdc65cadb368e1fad94
--- /dev/null
+++ b/src/cafeteria/asyncio/commons.py
@@ -0,0 +1,67 @@
+import asyncio
+import signal
+import warnings
+from asyncio import AbstractEventLoop
+from typing import Optional, Union
+
+
+async def cancel_all_tasks(
+    loop: Optional[AbstractEventLoop] = None, *ignore: asyncio.Task
+):
+    """
+    Cancel and wait for all running tasks in the specified or current event loop.
+
+    :param loop: Optional `AbstractEventLoop` to add signal handlers for, if not
+        provided, running loop is used.
+    :param ignore: If specified, these tasks are ignored even when running.
+    """
+    for task in asyncio.all_tasks(loop):
+        if task is asyncio.current_task() or task in ignore:
+            continue
+        if not (task.done() or task.cancelled()):
+            task.cancel()
+            try:
+                await task
+            except asyncio.CancelledError:
+                pass
+
+
+def cancel_tasks_on_termination(
+    loop: Optional[AbstractEventLoop] = None, *args: Union[signal.Signals, int, str]
+) -> None:
+    """
+    Helper method to add a signal handlers for specified or current event loop. Handlers
+    are registered for SIGINT, SIGTERM and any additional signals passed in.
+
+    :param loop: Optional `AbstractEventLoop` to add signal handlers for, if not
+        provided, running loop is used.
+    :param args: Additional signals to register cancellation for.
+    """
+    if loop is None:
+        loop = asyncio.get_running_loop()
+
+    for sig in {signal.SIGINT, signal.SIGTERM, *args}:
+        if not isinstance(sig, signal.Signals):
+            if isinstance(sig, int):
+                sig = signal.Signals(sig)
+            elif isinstance(sig, str):
+                try:
+                    sig = getattr(signal, sig)
+                except AttributeError:
+                    raise ValueError(f"Invalid signal name {sig}")
+            else:
+                raise ValueError(
+                    f"Signal should be one of signal.Signals, int or str, got {type(sig)}"
+                )
+        loop.add_signal_handler(
+            sig, lambda: asyncio.ensure_future(cancel_all_tasks(loop=loop), loop=loop)
+        )
+
+
+def handle_signals(event_loop: AbstractEventLoop, *signames: str) -> None:
+    warnings.warn(
+        f"Use {cancel_tasks_on_termination.__name__} instead",
+        category=DeprecationWarning,
+        stacklevel=2,
+    )
+    return cancel_tasks_on_termination(loop=event_loop, *signames)
diff --git a/src/cafeteria/asyncio/patterns/application.py b/src/cafeteria/asyncio/patterns/application.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a4c63ce94ede97bc6909ece06e26b0b62975cdb
--- /dev/null
+++ b/src/cafeteria/asyncio/patterns/application.py
@@ -0,0 +1,27 @@
+import asyncio
+from abc import abstractmethod
+from typing import Any
+
+from cafeteria.asyncio.commons import cancel_tasks_on_termination
+from cafeteria.logging import LoggedObject
+
+
+class AsyncioGracefulApplication(LoggedObject):
+    @abstractmethod
+    async def main(self) -> Any:
+        """
+        The main method to execute for the application. The application runs until this
+        completes or errors out.
+        """
+        raise NotImplementedError
+
+    async def __main(self) -> Any:
+        cancel_tasks_on_termination()
+        return await self.main()
+
+    def run(self, debug: bool = False):
+        try:
+            self.logger.debug("Starting application")
+            return asyncio.run(self.__main(), debug=debug)
+        except (asyncio.CancelledError, KeyboardInterrupt):
+            self.logger.debug("Application halted")
diff --git a/src/cafeteria/asyncio/synchronous.py b/src/cafeteria/asyncio/synchronous.py
new file mode 100644
index 0000000000000000000000000000000000000000..820c31f17f27df3f04fc56a0f1772958d1b9552c
--- /dev/null
+++ b/src/cafeteria/asyncio/synchronous.py
@@ -0,0 +1,15 @@
+import asyncio
+from asyncio import Task
+from typing import Any, Coroutine, Union
+
+
+def execute_async_method(coroutine: Coroutine) -> Union[Any, Task]:
+    try:
+        loop = asyncio.get_event_loop()
+    except RuntimeError:
+        loop = asyncio.new_event_loop()
+
+    if loop.is_running():
+        return loop.create_task(coroutine)
+    else:
+        return loop.run_until_complete(coroutine)
diff --git a/tests/test_callbacks.py b/tests/test_callbacks.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c884912ada7e9a9c0fabc8ebefffdd65480a137
--- /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
index 0000000000000000000000000000000000000000..8515f783b9430809a8518368c43d8884ef72793e
--- /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
index 0000000000000000000000000000000000000000..3ec1f495701436dd8071b9f9fa026cc3c38d3e83
--- /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())