Created
May 20, 2020 07:46
-
-
Save melvinkcx/928e094d1c22c71dc3af98493f57b864 to your computer and use it in GitHub Desktop.
Testing Django Signals Emission
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
from collections import Mapping | |
from dataclasses import dataclass | |
from typing import Any, Tuple | |
@dataclass() | |
class SignalHandlerContext: | |
sender: Any | |
args: Tuple[Any] | |
kwargs: Mapping | |
class InterceptSignal: | |
def __init__(self, signal): | |
self._signal = signal | |
self._call_args = [] | |
def __enter__(self): | |
self._signal.connect(self._signal_handler) | |
return self | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
self._signal.disconnect(self._signal_handler) | |
def _signal_handler(self, sender, *args, **kwargs): | |
self._call_args.append(SignalHandlerContext(sender=sender, args=args, kwargs=kwargs)) | |
@property | |
def call_args(self): | |
return self._call_args | |
@property | |
def call_count(self): | |
return len(self._call_args) |
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
from django.test import TestCase | |
class SomeTestCase(TestCase): | |
def test_something(self): | |
with InterceptSignal(signal=my_custom_signal) as signal_data: | |
# Invoke functions that will emit the signal specified | |
self.assertEqual(signal_data.call_count, 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment