pytest-mock - 模拟模块中的函数
pytest-mock - Mock a function from a module
我的模块 engine.py
中有一个实用程序,它是从另一个文件导入的:
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
的情况下实现模拟部分?
我把mocker.patch('main.utils.string.get_random_string', return_value='123456')
改成mocker.patch('engine.get_random_string', return_value='123456')
成功了。
可以找到详细信息here。
尝试使用
修补模块函数时
@patch('utils.collection_utils.min_object', return_value='mocked_min_object_result')
我不得不从
更改我使用 class 的导入
from utils.collection_utils import min_object
...
min_object(...)
至
from utils import collection_utils
...
collection_utils.min_object(...)
另请注意,使用补丁可能会更改测试方法的参数顺序。而不是
@patch('utils.collection_utils.min_object', return_value='mocked_min_object')
def test_process_with_min_production_cost(sut):
然后
@patch('utils.collection_utils.min_object', return_value='mocked_min_object')
def test_process_with_min_production_cost(patched_min_object, sut):
我的模块 engine.py
中有一个实用程序,它是从另一个文件导入的:
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
的情况下实现模拟部分?
我把mocker.patch('main.utils.string.get_random_string', return_value='123456')
改成mocker.patch('engine.get_random_string', return_value='123456')
成功了。
可以找到详细信息here。
尝试使用
修补模块函数时@patch('utils.collection_utils.min_object', return_value='mocked_min_object_result')
我不得不从
更改我使用 class 的导入from utils.collection_utils import min_object
...
min_object(...)
至
from utils import collection_utils
...
collection_utils.min_object(...)
另请注意,使用补丁可能会更改测试方法的参数顺序。而不是
@patch('utils.collection_utils.min_object', return_value='mocked_min_object')
def test_process_with_min_production_cost(sut):
然后
@patch('utils.collection_utils.min_object', return_value='mocked_min_object')
def test_process_with_min_production_cost(patched_min_object, sut):