2015-08-24 45 views
0

我一直在探索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的返回值如何。有人能帮我弄清楚我哪里出错了吗?

回答

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的工作原理 - 你可能会认为是wel我测试过了。 ;)

如果将注意力集中在您的应用程序逻辑(可能是调用func?的代码),那么您的测试可能会更好。

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 
相关问题