3

我正在重构现有代码以使用 blinker 库而不是传递回调函数。我有大量现有的测试,它们使用模拟来检查回调是否正确触发。但是,当我尝试针对使用 blinker 的新代码运行测试时,我从 Mock 中得到了一个异常。

该异常可以很容易地在 repl 上复制,并且是由于 blinker 试图访问__name__mock 的属性。

>>> from mock import Mock
>>> from blinker import signal
>>>
>>> test = signal('test')
>>> m = Mock()
>>>
>>> test.connect(m)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/ed/.virtualenvs/iws/lib/python2.7/site-packages/blinker/base.py", line 113, in connect
      receiver_ref = reference(receiver, self._cleanup_receiver)
  File "/Users/ed/.virtualenvs/iws/lib/python2.7/site-packages/blinker/_utilities.py", line 124, in reference
      weak = callable_reference(object, callback)
  File "/Users/ed/.virtualenvs/iws/lib/python2.7/site-packages/blinker/_utilities.py", line 135, in callable_reference
      return BoundMethodWeakref(target=object, on_delete=callback)
  File "/Users/ed/.virtualenvs/iws/lib/python2.7/site-packages/blinker/_saferef.py", line 143, in __new__
      base.__init__(target, on_delete, *arguments, **named)
  File "/Users/ed/.virtualenvs/iws/lib/python2.7/site-packages/blinker/_saferef.py", line 188, in __init__
      self.func_name = str(im_func.__name__)
  File "/Users/ed/.virtualenvs/iws/lib/python2.7/site-packages/mock.py", line 702, in __getattr__
      raise AttributeError(name)

MagicMock 引发了同样的异常。

我无法弄清楚如何准备模拟,以免引发异常。我可以用一个虚拟函数替换 mock 并在其中编写测试,但我有超过 1000 个测试。

4

2 回答 2

3

我找到了一个解决方案:

创建一个虚拟函数并将其作为规范传递给模拟成功。

>>> from blinker import signal
>>> from mock import Mock
>>>
>>> def foo():
...     pass
...
>>> t = signal('test')
>>> m = Mock(spec=foo)
>>> m.__name__
<Mock name='mock.__name__' id='4471403152'>
>>> t.connect(m)
<Mock spec='function' id='4471883984'>
>>> t.send()
[(<Mock spec='function' id='4471883984'>, <Mock name='mock()' id='4471404624'>)]
>>> m.called
True
于 2013-10-24T15:08:59.067 回答
2

速记

from mock import MagicMock    
mock_signal = MagicMock(spec={})
于 2016-12-16T08:42:48.683 回答