Skip to content Skip to sidebar Skip to footer

How To Unit Test 'mkdir' Function Without File System Access?

I use py.test for unit testing. I have something just like this: Class Site(object): def set_path(self): '''Checks if the blog folder exists. Creates new folder if nec

Solution 1:

There are two approaches you could use, mocking (preferred) or isolation:

Mocking:

At test time, replace os.mkdir with a "mock" version:

class MockMkdir(object):
    def __init__(self):
        self.received_args = None
    def __call__(*args):
        self.received_args = args

class MyTest(unittest.TestCase):
    def setUp():
        self._orig_mkdir = os.mkdir
        os.mkdir = MockMkdir()
    def tearDown():
        os.mkdir = self._orig_mkdir
    def test_set_path(self):
        site = Site()
        site.set_path('foo/bar')
        self.assertEqual(os.mkdir.received_args[0], 'foo/bar')

Mock is a library that helps you do this kind of thing more elegantly and with fewer lines of code.

Isolation

Use chroot to run your unittests within an isolated filesystem. After running each test case, revert the filesystem to a clean state. This is something of a sledgehammer approach but for testing very complicated libraries it might be easier to get this approach to work.


Post a Comment for "How To Unit Test 'mkdir' Function Without File System Access?"