pytest-mock - 从模块中模拟一个函数

问题描述 投票:2回答:1

我的模块engine.py中有一个util,它是从另一个文件导入的:

from main.utils.string import get_random_string

def generate_random_string():
    return get_random_string()

在我的测试文件中:

def test_generate_random_string(mocker):
    mocker.patch('main.utils.string.get_random_string', return_value='123456')

然而,它仍然试图使用string.get_random_string的真实实现而不是我创建的模拟,除非我将我的engine.py更改为:

from main.utils import string

def generate_random_string():
    return string.get_random_string()

如何在不将整个string模块导入engine.py的情况下实现模拟部分?

python pytest
1个回答
2
投票

我通过将mocker.patch('main.utils.string.get_random_string', return_value='123456')改为mocker.patch('engine.get_random_string', return_value='123456')成功实现了它。

细节可以找到here

© www.soinside.com 2019 - 2024. All rights reserved.