我有一个函数我试图测试它使用.endswith函数,但每次我尝试使用补丁模拟它我得到一个错误。
with patch("killme.endswith",MagicMock()) as mock_endswith
我尝试用以下内容替换killme.endswith
:
killme.UserString.endswith
killme.__builtin__.endswith
killme.__builtin__.str.endswith
killme.str.endswith
kill么.朋友
def foo(in_str):
if in_str.endswith("bob"):
return True
return False`
kill么_test.朋友
import killme
import unittest
from mock import MagicMock, patch
class tests(unittest.TestCase):
def test_foo(self):
with patch("killme.endswith", MagicMock()) as mock_endswith:
mock_endswith.return_value = True
result = killme.foo("xxx")
self.assertTrue(result)
错误:
Traceback (most recent call last):
File "C:\Python27\lib\unittest\case.py", line 329, in run
testMethod()
File "C:\Users\bisaacs\Desktop\gen2\tools\python\killme_test.py", line 8, in test_foo
with patch("killme.endswith", MagicMock()) as mock_endswith:
File "C:\Python27\lib\site-packages\mock\mock.py", line 1369, in __enter__
original, local = self.get_original()
File "C:\Python27\lib\site-packages\mock\mock.py", line 1343, in get_original
"%s does not have the attribute %r" % (target, name)
AttributeError: <module 'killme' from 'C:\Users\bisaacs\Desktop\gen2\tools\python\killme.py'> does not have the attribute 'endswith'
endswith
是一个内置的str方法,所以你不能简单地用killme.endswith
覆盖它。而不是这个你可以将模拟对象传递给foo
函数。这个对象将具有与str
相同的界面,但是模拟了startswith方法
mocked_str = Mock()
mocked_str.endswith.return_value = True # or something else you want
mocked_str.endswith('something') # True or something else
killme.foo(mocked_str)