I had a similar issue and wasn't able to successfully disconnect my signal using signals.post_save.disconnect()
. Found this alternative approach that creates a decorator to override the SUSPEND_SIGNALS
setting on specified tests and signals. Might be useful for anyone in the same boat.
First, create the decorator:
import functools
from django.conf import settings
from django.dispatch import receiver
def suspendingreceiver(signal, **decorator_kwargs):
def our_wrapper(func):
@receiver(signal, **decorator_kwargs)
@functools.wraps(func)
def fake_receiver(sender, **kwargs):
if settings.SUSPEND_SIGNALS:
return
return func(sender, **kwargs)
return fake_receiver
return our_wrapper
Replace the usual @receiver
decorator on your signal with the new one:
@suspendingreceiver(post_save, sender=MyModel)
def mymodel_post_save(sender, **kwargs):
work()
Use Django's override_settings()
on your TestCase:
@override_settings(SUSPEND_SIGNALS=True)
class MyTestCase(TestCase):
def test_method(self):
Model.objects.create() # post_save_receiver won't execute
Thanks to Josh Smeaton, who wrote the blog.