[英]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.