[英]How to mock a builtin method
我有一个对象,该对象定义仅在首先实例化时才可访问的方法:
>>> import select
>>> select.poll().poll
<built-in method poll of select.poll object at 0x7fcf2a94bd80>
>>> select.poll.poll
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'builtin_function_or_method' object has no attribute 'poll'
>>>
因此,我在嘲笑它时遇到了麻烦(“轮询”方法)。
>>> from unittest import mock
>>> import select
>>> with mock.patch('select.poll.poll') as m:
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.4/unittest/mock.py", line 1197, in __enter__
original, local = self.get_original()
File "/usr/local/lib/python3.4/unittest/mock.py", line 1171, in get_original
"%s does not have the attribute %r" % (target, name)
AttributeError: <built-in function poll> does not have the attribute 'poll'
有什么建议吗?
如评论中所述,最好还是嘲笑select.poll
。 您无需进一步研究该模块。 您正在测试外部模块的行为,该行为引发了一些事情,以了解您的代码将如何对此做出反应。 因此,请记住以下几点:
import unittest
import select
from mock import mock, Mock
def my_method():
select.poll()
class Testor(unittest.TestCase):
@mock.patch('select.poll', return_value=Mock())
def test_it(self, m_poll):
m_poll.side_effect = Exception
with self.assertRaises(Exception):
my_method()
if __name__ == '__main__':
unittest.main()
因此,您可以模拟补丁select.poll
,然后在调用poll()
设置了side_effect来引发异常。 使用self.assertRaises
来检查在调用my_method
时是否引发了异常。
另外,如果您想在模拟内部真正模拟其他方法,则可以执行以下操作:
import unittest
import select
from mock import mock, Mock
def my_method():
s = select.poll()
s.poll()
class Testor(unittest.TestCase):
@mock.patch('select.poll', return_value=Mock())
def test_it(self, m_poll):
m_poll.return_value.poll.side_effect = Exception
with self.assertRaises(Exception):
my_method()
if __name__ == '__main__':
unittest.main()
从m_poll.return_value
的返回值中,获取poll
的side_effect
以返回您的Exception
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.