Skip to content

Instantly share code, notes, and snippets.

@Homeopatch
Created July 13, 2023 14:55
Show Gist options
  • Save Homeopatch/29d0c63d3f676ead630eb9522b864631 to your computer and use it in GitHub Desktop.
Save Homeopatch/29d0c63d3f676ead630eb9522b864631 to your computer and use it in GitHub Desktop.
Blinker Signal connected to unittest.Mock and MagicMock does not work in Python 3.8 test case and workaround
import unittest
from unittest.mock import MagicMock, Mock
from blinker import Signal
def foo(sender, **kwargs):
"""Stub function for spec"""
pass
class FooStub:
"""Stub class for spec"""
def __call__(self, sender, **kwargs):
pass
class TestMocks(unittest.TestCase):
def setUp(self) -> None:
self.signal = Signal()
def test_magicmock_spec(self):
mock = MagicMock(spec=foo)
self.signal.connect(mock, sender=self)
self.signal.send(self) # RuntimeError: Cannot send to a coroutine function here
# see this for details: https://bugs.python.org/issue37251
mock.assert_called_once_with(self)
def test_magicmock(self):
mock = MagicMock()
self.signal.connect(mock, sender=self) # AttributeError: __self__
self.signal.send(self)
mock.assert_called_once_with(self)
def test_mock(self):
mock = Mock()
self.signal.connect(mock, sender=self) # AttributeError: __self__
self.signal.send(self)
mock.assert_called_once_with(self)
def test_mock_stub(self):
# This test passes
mock = Mock(spec=FooStub)
self.signal.connect(mock, sender=self)
self.signal.send(self)
mock.assert_called_once_with(self)
def test_magicmock_stub(self):
# This test passes
mock = MagicMock(spec=FooStub)
self.signal.connect(mock, sender=self)
self.signal.send(self)
mock.assert_called_once_with(self)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment