unit testing - Mocking Directory Structure in Python -
unit testing - Mocking Directory Structure in Python -
i have code below i'm using take input of files, open , process, , output data. i've gotten functionality working , i'm unit testing now, below illustration of code.
def foo(dir): path_to_search = join(dir, "/baz/foo") if isdir(path_to_search): #path exists stuff... fname in listdir(path_to_search): do_stuff() else: print "path doesn't exist"
i've been able create test past doesn't exist enough, can see above assert "/baz/foo" portion of directory construction exists (in production directory construction must have file, in cases won't , won't need process it.)
i've tried create temporary directory construction using tempdir , join, code kicks out saying path doesn't exists.
is possible mock output of os.listdir such won't need create temporary directory construction follows needed /baz/foo convention?
you don't need create false directory structure, need mock isdir()
, listdir()
functions.
using unittest.mock
library (or external mock
library, exact same thing python versions < 3.3):
try: # python >= 3.3 unittest import mock except importerror: # python < 3.3 import mock mock.patch('yourmodule.isdir') mocked_isdir, \ mock.patch('yourmodule.listdir') 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')
python unit-testing
Comments
Post a Comment