【问题标题】:Different monkey patch scripts for the same method相同方法的不同猴子补丁脚本
【发布时间】:2023-01-03 22:03:07
【问题描述】:

我们可以对在 python 函数内的不同行调用的同一方法使用两个不同的猴子补丁脚本吗?

# abc.py
def add(a,b):
sum=a+b
return sum


# file1.py
def xyz():
        ...
        sum = add(i,j)
        ...
        ...
        addition = add(v,u)
        ...
        ...

# test_file1.py
def test_xyz():
        ..... # ---> I need to add two different monkey patch scripts for
              # add() with different results within pytest

谁能帮我打猴子补丁?

【问题讨论】:

  • 你能提供更多细节吗?如果只是添加,为什么还要打补丁?如果需要,请在伪代码中显示预期结果

标签: python unit-testing mocking pytest monkeypatching


【解决方案1】:

Side effect 就是为了这个目的——它可以用来在同一个模拟中返回不同的值。此示例取自文档 - 对模拟的 3 次连续调用将产生不同的结果,如 side_effect 中指定的那样:

>>> mock = MagicMock()
>>> mock.side_effect = [5, 4, 3, 2, 1]
>>> mock(), mock(), mock()
(5, 4, 3)

为了使其适用于您的示例和pytest mock,我将您的源文件放在q72959276 模块中,这样您的abc.py 就不会覆盖built-in python ABC module。我还让 xyz 方法返回模拟值,因此很容易断言一切正常:

# q72959276/abc.py
def add(a, b):
    sum = a + b
    return sum


# q72959276/file1.py
from .abc import add


def xyz():
    sum = add(1, 2)
    addition = add(3, 4)

    return sum, addition


# tests/test_file1.py
from q72959276.file1 import xyz


def test_xyz(mocker):
    mocker.patch("q72959276.file1.add", side_effect=[20, 42])
    assert 20, 42 == xyz()

【讨论】:

    猜你喜欢
    • 2012-08-19
    • 1970-01-01
    • 2010-09-29
    • 1970-01-01
    • 2012-07-26
    • 1970-01-01
    • 2016-09-01
    • 2012-09-16
    • 2012-12-18
    相关资源
    最近更新 更多