Monkey为单元测试模块中的函数打补丁

2024-04-27 17:33:52 发布

您现在位置:Python中文网/ 问答频道 /正文

在调用从另一个模块导入的另一个方法的模块中,我有以下方法:

def imported_function():
    do_unnecessary_things_for_unittest()

实际需要测试的方法,导入并使用上述函数:

from somewhere import imported_function

def function_to_be_tested():
    imported_function()
    do_something_more()
    return 42

导入的函数中的内部调用和相关计算并不重要,它们不是我要测试的内容,所以我只想在测试实际的函数时跳过它们。

因此,我试图在测试方法中的某个地方对名为的模块进行猴子修补,但没有成功。

def test_function_to_be_tested(self):
    import somewhere
    somewhere.__dict__['imported_function'] = lambda : True

问题是,如何在测试时对模块的方法进行修补,以便在测试阶段不会调用它?


Tags: 模块to方法函数importfordeffunction
2条回答

假设您有以下文件:

某处。py

def imported_function():
    return False

测试时间.py

from somewhere import imported_function

def function_to_be_tested():
    return imported_function()

testme.function_to_be_tested()的调用将返回False


现在,诀窍是在testme之前导入somewhere

import somewhere
somewhere.__dict__['imported_function'] = lambda : True

import testme
def test_function_to_be_tested():
    print testme.function_to_be_tested()

test_function_to_be_tested()

输出:

True


或者,重新加载testme模块

import testme

def test_function_to_be_tested():
    print testme.function_to_be_tested()
    import somewhere
    somewhere.__dict__['imported_function'] = lambda : True
    print testme.function_to_be_tested()
    reload(testme)
    print testme.function_to_be_tested()

test_function_to_be_tested()

输出:

False
False
True

我想最好用Mock Library

所以你可以这样做:

from somewhere import imported_function

@patch(imported_function)
def test_function_to_be_tested(self, imported_function):
    imported_function.return_value = True
    #Your test

我认为对于单元测试来说,它比猴子补丁要好。

相关问题 更多 >