仅为一个模块修补Mock的功能?

cul*_*rón 6 python unit-testing python-mock

我需要补丁os.listdir和其他os函数来测试我的Python函数.但是当它们被修补时,import声明失败了.是否可以仅在单个模块(真实模块)中修补此功能,并使tests.py正常工作?

这是一个打破的例子import:

import os
from mock import patch

# when both isdir and isfile are patched
# the function crashes
@patch('os.path.isdir', return_value=False)
@patch('os.path.isfile', return_value=False)
def test(*args):
    import ipdb; ipdb.set_trace()
    real_function(some_arguments)
    pass

test()
Run Code Online (Sandbox Code Playgroud)

我想看real_function一个修补os.path,并测试看看正常的功能.

这是追溯

eca*_*mur 7

您可以使用它patch作为上下文管理器,因此它只适用于with语句中的代码:

import os
from mock import patch

def test(*args):
    import ipdb; ipdb.set_trace()
    with patch('os.path.isdir', return_value=False):
        with patch('os.path.isfile', return_value=False):
            real_function(some_arguments)
    pass

test()
Run Code Online (Sandbox Code Playgroud)