Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Add mock signal receiver. #2

Merged
merged 1 commit into from

2 participants

@tkaemming

Tested on Python 2.6.7 with installed packages:

Django==1.2
mock==0.8.0
nose==1.1.2
unittest2==0.5.1

Test Plan: touch tests/settings.py && DJANGO_SETTINGS_MODULE=tests.settings nosetests tests/mock_django/signals

@dcramer dcramer merged commit 5127e2c into dcramer:master
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on May 30, 2012
  1. @tkaemming
This page is out of date. Refresh to see the latest.
View
1  mock_django/__init__.py
@@ -9,3 +9,4 @@
from .http import *
from .managers import *
from .models import *
+from .signals import *
View
35 mock_django/signals.py
@@ -0,0 +1,35 @@
+"""
+mock_django.signals
+~~~~~~~~~~~~~~~~
+
+:copyright: (c) 2012 DISQUS.
+:license: Apache License 2.0, see LICENSE for more details.
+"""
+import contextlib
+import mock
+
+
+@contextlib.contextmanager
+def mock_signal_receiver(signal, wraps=None, **kwargs):
+ """
+ Temporarily attaches a receiver to the provided ``signal`` within the scope
+ of the context manager.
+
+ The mocked receiver is returned as the ``as`` target of the ``with``
+ statement.
+
+ To have the mocked receiver wrap a callable, pass the callable as the
+ ``wraps`` keyword argument. All other keyword arguments provided are passed
+ through to the signal's ``connect`` method.
+
+ >>> with mock_signal_receiver(post_save, sender=Model) as receiver:
+ >>> Model.objects.create()
+ >>> assert receiver.call_count = 1
+ """
+ if wraps is None:
+ wraps = lambda *args, **kwargs: None
+
+ receiver = mock.Mock(wraps=wraps)
+ signal.connect(receiver, **kwargs)
+ yield receiver
+ signal.disconnect(receiver)
View
0  tests/mock_django/signals/__init__.py
No changes.
View
22 tests/mock_django/signals/tests.py
@@ -0,0 +1,22 @@
+from django.dispatch import Signal
+from mock_django.signals import mock_signal_receiver
+from unittest2 import TestCase
+
+
+class MockSignalTestCase(TestCase):
+ def test_mock_receiver(self):
+ signal = Signal()
+ with mock_signal_receiver(signal) as receiver:
+ signal.send(sender=None)
+ self.assertEqual(receiver.call_count, 1)
+
+ sentinel = {}
+ def side_effect(*args, **kwargs):
+ return sentinel
+
+ with mock_signal_receiver(signal, wraps=side_effect) as receiver:
+ responses = signal.send(sender=None)
+ self.assertEqual(receiver.call_count, 1)
+
+ # Signals respond with a list of tuple pairs [(receiver, response), ...]
+ self.assertIs(responses[0][1], sentinel)
Something went wrong with that request. Please try again.