Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何模拟/修补.endswith()?_Python_Python 2.7_Mocking_Patch - Fatal编程技术网

Python 如何模拟/修补.endswith()?

Python 如何模拟/修补.endswith()?,python,python-2.7,mocking,patch,Python,Python 2.7,Mocking,Patch,我有一个函数要测试,它使用了.endswith函数,但每次我尝试使用补丁模拟它时,我都会得到一个错误 将补丁(“killme.endswith”,MagicMock())作为mock_endswith 我尝试用以下内容替换killme.endswith: killme.UserString.endswith killme.\uuuuuuuuuuuuuuuuuuuu.endswith killme.\uuuuuuuuuuuuuuuuuuuu.str.endswith killme.str.end

我有一个函数要测试,它使用了.endswith函数,但每次我尝试使用补丁模拟它时,我都会得到一个错误

将补丁(“killme.endswith”,MagicMock())作为mock_endswith

我尝试用以下内容替换
killme.endswith

  • killme.UserString.endswith
  • killme.\uuuuuuuuuuuuuuuuuuuu.endswith
  • killme.\uuuuuuuuuuuuuuuuuuuu.str.endswith
  • killme.str.endswith
killme.py

def foo(in_str):
 if in_str.endswith("bob"):
     return True
 return False`
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)
killme\u test.py

def foo(in_str):
 if in_str.endswith("bob"):
     return True
 return False`
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)
错误:

回溯(最近一次呼叫最后一次):
文件“C:\Python27\lib\unittest\case.py”,第329行,正在运行
testMethod()
文件“C:\Users\bisaacs\Desktop\gen2\tools\python\killme\u test.py”,第8行,在test\u foo中
使用补丁(“killme.endswith”,MagicMock())作为mock_endswith:
文件“C:\Python27\lib\site packages\mock\mock.py”,第1369行,输入__
原始的,本地的=self.get_original()
文件“C:\Python27\lib\site packages\mock\mock.py”,第1343行,原始版本
“%s没有属性%r”%(目标,名称)
AttributeError:没有“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)
.endswith()
对于给定的输入有一个非常明确的输出,为什么要模拟它?顺便说一句,您用一个
if
和一个函数包装了一个表达式。两者都添加了代码,但没有价值。