Home > front end >  mock isdir() instead of os.path.isdir() function in unittests
mock isdir() instead of os.path.isdir() function in unittests

Time:02-24

My code use isdir() instead of os.path.isdir(). In my opinion, the first is more readable if occurs multiple times in code. When is tried to unittest the mocking does not works. The test does not pass and get the Exception. Can I mock isdir() without change to name in the source code to os.path.isdir()?

Source code

from os.path import isdir

def check_path_existence(self, path_to_check):
    if isdir(path_to_check):
        pass
    else:
        raise Exception("Directory does not exists")

Test:

@patch("os.path.isdir")
def test_check_path_existence(self, mock_isdir):
    mock_isdir.return_value = True

    self.assertIsNone(check_path_existence("invalid_path")

CodePudding user response:

Expanding on of MrBean Bremen's comment:

If the module that you're testing has an import path like mypackage.mymodule, then you'd want to write your mock like this:

@patch("mypackage.mymodule.isdir")
def test_check_path_existence(self, mock_isdir):
    mock_isdir.return_value = True

    self.assertIsNone(check_path_existence("invalid_path")

This way, you're mocking the instance of isdir that's in the namespace of your module. Patching the original import path os.path.isdir only works if your module uses the isdir function by referencing it as an attribute of os.path, which you've decided against for stylistic reasons.

  • Related