Valeriy
Valeriy

Reputation: 1435

How to test a function that creates a directory?

How to test a function in Python which creates a directory? Can you give an example make_directory_test() function?

def make_directory(directory):
    if not os.path.exists(directory):
        os.makedirs(directory)

Upvotes: 8

Views: 7955

Answers (2)

idjaw
idjaw

Reputation: 26578

A good practice here would be to learn how to use testing frameworks like mock or flexmock

Furthermore, you should use Python's unittest Framework.

Your objective here is not necessarily to make sure that something gets created, but rather that it gets called. So what you would want to do is mock out the external calls to help test the proper flow of your method. So in this case you should mock exists and makedirs. Then ensure that it gets called. That would be an acceptable unit test. You would do something like this:

Let us assume your main code is being housed in a module called my_module.py. So you would want to create a test file, let's call it test.py to keep it simple and do something like this in your unit test:

from mock import patch
import my_module
import unittest


class MyTest(unittest.TestCase):
    @patch('my_module.exists')
    @patch('my_module.makedirs')
    def test_create_dir(self, mock_make_dirs, mock_exists):
        mock_exists.return_value = True

        make_directory('thing_to_create')

        mock_make_dirs.assert_called_with('thing_to_create')

So, what's happening here is that you are telling the mock that you want to mock out the makedirs and exists. You are making exists return with a True as specified with the mock_exists.return_value. Then you are making your actual call, your mocks will take effect in that method call. The last line with mock_make_dirs.assert_called_with will ensure that your method for making the dir will actually be called.

If you want to still test that something does actually get created

What you can do in this case, is maybe venture down the path of using a context manager and create a temporary folder to test in, do your work to test your method and anything else you have to do, and once you are done your work, the context manager will destroy itself.

For information on context managers, check out contextlib

Upvotes: 7

hspandher
hspandher

Reputation: 16733

Just test that directory exists

def test_make_directory(self):
    directory_path = '...' # somepath

    make_directory(directory_path)

    self.assertTrue(os.path.exists(directory_path))

And do ensure that any directories created in unit tests are deleted after each tests in tearDown or setUp, to ensure independency of tests

Upvotes: 9

Related Questions