使用mock测试目录是否存在

Anv*_*ith 3 unit-testing mocking python-mock

我已经探索模拟和 pytest 几天了。

我有以下方法:

def func():
    if not os.path.isdir('/tmp/folder'):
        os.makedirs('/tmp/folder')
Run Code Online (Sandbox Code Playgroud)

为了对其进行单元测试,我决定修补 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
Run Code Online (Sandbox Code Playgroud)

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

Eli*_*les 5

不能肯定地说拥有完整的代码,但我感觉它与您要修补的位置有关。

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

所以,如果你有这样的:

mymodule.py

def func():
    if not os.path.isdir('/tmp/folder'):
        os.makedirs('/tmp/folder')
Run Code Online (Sandbox Code Playgroud)

你应该让你的 _test_mymodule.py_ 像这样:

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

请注意,这个特定的测试并不是那么有用,因为它本质上是测试模块是否os工作——并且您可能会假设它已经过良好的测试。;)

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