Using mock to test if directory exists or not

坚强是说给别人听的谎言 提交于 2021-01-28 07:44:48

问题


I have been exploring mock and pytest for a few days now.

I have the following method:

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

In order to unit test it, I have decided to patch os.path.isdir and os.makedirs, as shown:

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

The assertion fails, irrespective of the return value from patch_isdir. Can someone please help me figure out where I am going wrong?


回答1:


Can't say for sure having the complete code, but I have the feeling it's related to where you're patching.

You should patch the os module that was imported by the module under test.

So, if you have it like this:

mymodule.py:

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

you should make your _test_mymodule.py_ like this:

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

Note that this specific test is not that useful, since it's essentially testing if the module os works -- and you can probably assume that is well tested. ;)

Your tests would probably be better if focused on your application logic (maybe, the code that calls func?).




回答2:


You are missing the call to 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


来源:https://stackoverflow.com/questions/32187967/using-mock-to-test-if-directory-exists-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!