Python 在函数中模拟函数
我试图模拟一个函数中的几个函数调用,以便测试它们的行为 我已经尝试了两种不同的方法,如代码所示,但它应该被模拟,因为函数永远不会被模拟。我使用python3,PyCharm,测试框架设置为pytest test.pyPython 在函数中模拟函数,python,mocking,pytest,monkeypatching,Python,Mocking,Pytest,Monkeypatching,我试图模拟一个函数中的几个函数调用,以便测试它们的行为 我已经尝试了两种不同的方法,如代码所示,但它应该被模拟,因为函数永远不会被模拟。我使用python3,PyCharm,测试框架设置为pytest test.py 来自unittest导入模拟,TestCase 从unittest.mock导入修补程序 从路径导入应该被模拟 从其他路径导入流 def测试_流量(monkeypatch): def ret_val(): 返回应该被嘲笑(“hi”) setattr('path',“应该被模仿”,r
来自unittest导入模拟,TestCase
从unittest.mock导入修补程序
从路径导入应该被模拟
从其他路径导入流
def测试_流量(monkeypatch):
def ret_val():
返回应该被嘲笑(“hi”)
setattr('path',“应该被模仿”,ret\u val())
断言流()=“hi”
def测试流程2(monkeypatch):
monkeypatch.setattr('path.should_mock',lambda x:“hi”)
断言流()=“hi”
@补丁('path.should\u mock')
def测试流程3(模拟机):
mocker.return\u value=“hello returned”
流量()
mocker.test.assert_使用(“hello”)调用_
类TestStuff(TestCase):
@补丁('path.should\u mock')
def测试流程4(自模拟):
mocker.return\u value=“hello returned”
流量()
mocker.test.assert_使用(“hello”)调用_
路径
def应该被嘲笑(你好):
打招呼
其他路径
def flow():
#这里的业务逻辑
返回应该被嘲笑(“你好”)
所有测试都失败,并从实函数返回值。我哪里出错了
添加信息
尝试将路径更改为其他路径会导致
E AttributeError: 'other_path' has no attribute 'should_be_mocked'
我在这里回答我自己的问题。多亏了@hoefling,我才发现这条路走错了。但是我无法运行第一个测试用例。其他的都是这样返工的
def test_flow2(monkeypatch):
monkeypatch.setattr('other_path', lambda x: "hi")
assert flow() == "hi"
@patch('other_path.should_be_mocked')
def test_flow3(mocker):
flow()
mocker.assert_called_with("hello")
class TestStuff(TestCase):
@patch('other_path.should_be_mocked')
def test_flow4(self, mocker):
flow()
mocker.assert_called_with("hello")
第一个不起作用,第二个在改变路径后起作用。第三个和第四个需要从assert语句中删除.test您应该模拟
其他路径。应该模拟而不是路径。应该模拟。有关详细信息,请参阅。