使用mock来测试目录是否存在

时间:2015-08-24 17:15:56

标签: unit-testing mocking python-mock

我几天来一直在探索mock和pytest。

我有以下方法:

def func():
    if not os.path.isdir('/tmp/folder'):
        os.makedirs('/tmp/folder')

为了对它进行单元测试,我决定修补os.path.isdir和os.makedirs,如下所示:

@patch('os.path.isdir')
@patch('os.makedirs')
def test_func(patch_makedirs, patch_isdir):
    patch_isdir.return_value = False
    assert patch_makedirs.called == True

无论patch_isdir的返回值如何,断言都会失败。有人可以帮我弄清楚我哪里出错了吗?

2 个答案:

答案 0 :(得分:1)

无法确定是否拥有完整的代码,但我感觉它与where you're patching有关。

您应该修补被测试模块导入的os模块。

所以,如果你有这样的话:

mymodule.py

def func():
    if not os.path.isdir('/tmp/folder'):
        os.makedirs('/tmp/folder')

你应该像你这样做_test_mymodule.py_:

@patch('mymodule.os')
def test_func(self, os_mock):
    os_mock.path.isdir.return_value = False
    assert os_mock.makedirs.called

请注意,此特定测试没有那么有用,因为它基本上测试模块os是否有效 - 并且您可以假设它经过了充分测试。 ;)

如果专注于您的应用程序逻辑(可能是调用func的代码?),您的测试可能会更好。

答案 1 :(得分:0)

您缺少对func()的调用。

@patch('os.path.isdir')
@patch('os.makedirs')
def test_func(patch_makedirs, patch_isdir):
    patch_isdir.return_value = False
    yourmodule.func()
    assert patch_makedirs.called == True