Mocking Directory Structure in Python
I have the code below which I am using to input files, open and process and then output some data. I got the functionality and now I am testing it, below is the sample code.
def foo(dir):
path_to_search = join(dir, "/baz/foo")
if isdir(path_to_search):
#path exists so do stuff...
for fname in listdir(path_to_search):
do_stuff()
else:
print "path doesn't exist"
I was able to create a test where the past does not exist easily enough, but as you can see above, I am claiming that part of the // baz / foo directory structure exists (when creating the directory structure, this file must have, in some cases it will not and we don't need to handle it.)
I tried to create a temporary directory structure using TempDir and join, but the code always gives a message that the path does not exist.
Is it possible to mock the output of os.listdir so that I don't have to create a temporary directory structure that follows the required / baz / foo convention?
source to share
You don't need to create a fake directory structure, all you need to do is mock functions isdir()
and listdir()
.
Using unittest.mock
library (or external mock
library , which is the same for Python versions <3.3):
try:
# Python >= 3.3
from unittest import mock
except ImportError:
# Python < 3.3
import mock
with mock.patch('yourmodule.isdir') as mocked_isdir, \
mock.patch('yourmodule.listdir') as mocked_listdir:
mocked_isdir.return_value = True
mocked_listdir.return_value = ['filename1', 'filename2']
yourmodule.foo('/spam/eggs')
mocked_isdir.assert_called_with('/spam/eggs/baz/foo')
mocked_listdir.assert_called_with('/spam/eggs/baz/foo')
source to share