gpt4 book ai didi

python - 由于 AttributeError PyTest-Mock 不工作

转载 作者:太空宇宙 更新时间:2023-11-03 14:43:12 25 4
gpt4 key购买 nike

我正在尝试使用 PyTest_Mock 在我的 Python 项目中进行一些测试。我创建了一个非常简单的测试来尝试它,但我收到了一个 AttributeError 并且我不知道为什么。

模型.py

def square(x):
return x * x

if __name__ == '__main__':
res = square(5)
print("result: {}".format(res))

test_model.py

import pytest
from pytest_mock import mocker

import model

def test_model():
mocker.patch(square(5))

assert model.square(5) == 25

运行 python -m pytest 后我遇到了失败并出现以下错误:

    def test_model():
> mocker.patch(square(5))
E AttributeError: 'function' object has no attribute 'patch'

test_model.py:7: AttributeError

最佳答案

  1. 您不需要导入 mocker,它可以作为 fixture 使用,因此您只需将它作为参数传递到测试函数中即可:

    def test_model(mocker):
    mocker.patch(...)
  2. square(5) 的计算结果为 25,因此 mocker.patch(square(5)) 将有效地尝试修补数字 25。相反,通过作为参数的函数名称:要么

    mocker.patch('model.square')

    mocker.patch.object(model, 'square')
  3. 修补后,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'

关于python - 由于 AttributeError PyTest-Mock 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51713849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com