Skip to content

Instantly share code, notes, and snippets.

@seddonym
Last active September 9, 2020 17:05
Show Gist options
  • Save seddonym/8571321a77237812a05771f119fbe56d to your computer and use it in GitHub Desktop.
Save seddonym/8571321a77237812a05771f119fbe56d to your computer and use it in GitHub Desktop.
Django test class for asserting the connection of a receiver to a given signal
from django.test import TestCase
class ReceiverConnectionTestCase(TestCase):
"""TestCase that allows asserting that a given receiver is connected to a signal.
Important: this will work correctly providing you:
1. Do not import or patch anything in the module containing the receiver in any django.test.TestCase.
2. Do not import (except in the context of a method) the module containing the receiver in any test module.
This is because as soon as you import/patch, the receiver will be connected by your test and will be connected
for the entire test suite run.
If you want to test the behaviour of the receiver, you may do this providing it is a unittest.TestCase, and there
is no import from the receiver module in that test module.
Usage:
# myapp/receivers.py
from django.dispatch import receiver
from apples.signals import apple_eaten
from apples.models import Apple
@receiver(apple_eaten, sender=Apple)
def my_receiver(sender, **kwargs):
pass
# tests/integration_tests.py
from apples.signals import apple_eaten
from apples.models import Apple
class TestMyReceiverConnection(ReceiverConnectionTestCase):
def test_connection(self):
self.assert_receiver_is_connected('myapp.receivers.my_receiver', signal=apple_eaten, sender=Apple)
"""
def assert_receiver_is_connected(self, receiver_string, signal, sender):
receivers = signal._live_receivers(sender)
receiver_strings = ["{}.{}".format(r.__module__, r.__name__) for r in receivers]
if receiver_string not in receiver_strings:
raise AssertionError('{} is not connected to signal.'.format(receiver_string))
@seddonym
Copy link
Author

seddonym commented Mar 2, 2017

For more details see my talk slides: http://slides.com/davidseddon/signals

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment