gpt4 book ai didi

python - 使用 mocker 与 pytest 打补丁

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

我安装了 pytest-mock并使用模拟程序我试图像补丁一样运行,但我得到“类型错误:需要一个有效的目标来打补丁。你提供了'return a + b'”

# test_capitalize.py
import time


def sum(a, b):
time.sleep(10)
return a + b

def test_sum(mocker):
mocker.patch('return a + b');
assertEqual(sum(2, 3), 9)

最佳答案

patch 需要被修补函数的路径。你可以这样做:

import pytest


def sum(a, b):
return a + b


def test_sum1(mocker):
mocker.patch(__name__ + ".sum", return_value=9)
assert sum(2, 3) == 9


def test_sum2(mocker):
def crazy_sum(a, b):
return b + b

mocker.patch(__name__ + ".sum", side_effect=crazy_sum)
assert sum(2, 3) == 6

结果:

$ pytest -v patch_test.py
============= test session starts ==============
platform cygwin -- Python 3.6.4, pytest-3.10.1, py-1.7.0, pluggy-0.8.0 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: /home/xyz/temp, inifile:
plugins: mock-1.10.0, cov-2.6.0
collected 2 items

patch_test.py::test_sum1 PASSED [ 50%]
patch_test.py::test_sum2 PASSED [100%]

=========== 2 passed in 0.02 seconds ===========

关于python - 使用 mocker 与 pytest 打补丁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53434986/

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