gpt4 book ai didi

python - 将 Mock() 传递到 blinker signal.connect() 引发 "AttributeError: __name__"

转载 作者:行者123 更新时间:2023-12-04 02:42:34 27 4
gpt4 key购买 nike

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

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

>>> 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 引发了同样的异常。

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

最佳答案

我找到了一个解决方案:

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

>>> 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

关于python - 将 Mock() 传递到 blinker signal.connect() 引发 "AttributeError: __name__",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19569164/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com