python - 在单个模拟变量中跨不同文件模拟相同的 Python 函数

标签 python mocking python-mock

假设我有以下 python 文件:

# source.py
def get_one():
    return 1

# file1.py
from source import get_one
def func1():
    return get_one()

# file2.py
from source import get_one
def func2():
    return get_one()

# script.py
from file1 import func1
from file2 import func2
def main(a, b):
    count = 0
    for _ in range(a):
        count += func1()
    for _ in range(b):
        count += func2()
    return count

我知道我可以使用以下设置在 main.py 中模拟 get_one():

def test_mock():
    with (
        patch("file1.get_one") as mock1,
        patch("file2.get_one") as mock2,
    ):
        main(2, 3)
    assert mock1.call_count + mock2.call_count == 5

但是,如果需要在许多文件中模拟 get_one() ,这会变得越来越冗长且难以阅读。我希望能够在一个模拟变量中模拟出它的所有位置。像这样的东西:

# this test fails, I'm just showing what this ideally would look like
def test_mock():
    with patch("file1.get_one", "file2.get_one") as mock:
        main(2, 3)
    assert mock.call_count == 5

有办法做到这一点还是我需要使用多个模拟?

注意,我知道我无法模拟函数的定义位置,例如补丁(“source.get_one”)

最佳答案

patch 接受 new 作为用于修补目标的对象:

def test_mock():
    with (
        patch("file1.get_one") as mock,
        patch("file2.get_one", new=mock),
    ):
        main(2, 3)
    assert mock.call_count == 5, mock.call_count

您可以编写一个辅助上下文管理器:

import contextlib
from unittest.mock import DEFAULT, patch


@contextlib.contextmanager
def patch_same(target, *targets, new=DEFAULT):
    with patch(target, new=new) as mock:
        if targets:
            with patch_same(*targets, new=mock):
                yield mock
        else:
            yield mock

用法:

def test_mock():
    with patch_same("file1.get_one", "file2.get_one") as mock:
        main(2, 3)
    assert mock.call_count == 5

关于python - 在单个模拟变量中跨不同文件模拟相同的 Python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73008751/

相关文章:

python - 如何在 Django Python 中的原始 SQL 中插入参数

python - Discord BOT与Python,如何让它在我们发送命令的 channel 中回复(完成)

c# - 假货比 Mocks 好吗?

ruby - 如何使用不同的参数模拟同一个数据库调用两次并将所有响应值与值数组进行匹配?

c# - 单元测试中的部分模拟/伪造

Python Mock - return_value - 获取 "real"返回值

Python测试: How do I mock outside of the testing scope?

python - 如何使用 Paramiko 访问远程主机?

python - 如何对目录中的所有 .dat 文件执行命令

python:将中间人注入(inject)方法调用