我试图使用PyTest_Mock以便在我的Python项目中进行一些测试。我创建了一个非常简单的测试来进行测试,但是却出现了AttributeError,我不知道为什么。
模型
def square(x):
return x * x
if __name__ == '__main__':
res = square(5)
print("result: {}".format(res))
Run Code Online (Sandbox Code Playgroud)
test_model.py
import pytest
from pytest_mock import mocker
import model
def test_model():
mocker.patch(square(5))
assert model.square(5) == 25
Run Code Online (Sandbox Code Playgroud)
运行后,python -m pytest出现故障和以下错误:
def test_model():
> mocker.patch(square(5))
E AttributeError: 'function' object has no attribute 'patch'
test_model.py:7: AttributeError
Run Code Online (Sandbox Code Playgroud)
您不需要import mocker,它可以作为夹具使用,因此只需将其作为参数传递给test函数:
def test_model(mocker):
mocker.patch(...)
Run Code Online (Sandbox Code Playgroud)square(5)计算结果为25,因此mocker.patch(square(5))将有效地尝试修补数字25。而是将函数名称作为参数传递:
mocker.patch('model.square')
Run Code Online (Sandbox Code Playgroud)
要么
mocker.patch.object(model, 'square')
Run Code Online (Sandbox Code Playgroud)修补后,square(5)将不再返回25,因为将原始函数替换为可以返回任何内容的模拟对象,并且默认情况下将返回新的模拟对象。assert model.square(5) == 25因此将失败。通常,您修补材料是为了避免复杂的测试设置,或者模拟测试场景中所需组件的行为(例如,网站不可用)。在您的示例中,您根本不需要嘲笑。
完整的工作示例:
import model
def test_model(mocker):
mocker.patch.object(model, 'square', return_value='foo')
assert model.square(5) == 'foo'
Run Code Online (Sandbox Code Playgroud)