[英]pytest-mock - Mock a function from a module
I have an util in my module engine.py
, which is imported from another file:我的模块
engine.py
中有一个实用程序,它是从另一个文件导入的:
from main.utils.string import get_random_string
def generate_random_string():
return get_random_string()
In my test file:在我的测试文件中:
def test_generate_random_string(mocker):
mocker.patch('main.utils.string.get_random_string', return_value='123456')
However, it's still trying to use the real implementation of string.get_random_string
instead of the mock that I've created, unless I change my engine.py
to:但是,它仍在尝试使用
string.get_random_string
的实际实现而不是我创建的模拟,除非我将engine.py
更改为:
from main.utils import string
def generate_random_string():
return string.get_random_string()
How can I achieve the mocking part without importing the whole string
module to engine.py
?如何在不将整个
string
模块导入 engine.py 的情况下实现engine.py
部分?
I have successfully achieved it by changing mocker.patch('main.utils.string.get_random_string', return_value='123456')
to mocker.patch('engine.get_random_string', return_value='123456')
. 我已经成功地通过改变实现它
mocker.patch('main.utils.string.get_random_string', return_value='123456')
到mocker.patch('engine.get_random_string', return_value='123456')
While trying to patch a module function with在尝试修补模块 function 时
@patch('utils.collection_utils.min_object', return_value='mocked_min_object_result')
I had to change the import for my using class from我不得不更改我使用 class 的导入
from utils.collection_utils import min_object
...
min_object(...)
to到
from utils import collection_utils
...
collection_utils.min_object(...)
Also note that using a patch might change the order of arguments for the test method.另请注意,使用补丁可能会更改测试方法的 arguments 的顺序。 Instead of
代替
@patch('utils.collection_utils.min_object', return_value='mocked_min_object')
def test_process_with_min_production_cost(sut):
then然后
@patch('utils.collection_utils.min_object', return_value='mocked_min_object')
def test_process_with_min_production_cost(patched_min_object, sut):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.