Search code examples
pythonunit-testingpython-mock

Patching a function with Mock only for one module?


I need to patch os.listdir and other os functions to test my Python function. But when they're patched, the import statement fails. Is it possible to patch this function only inside that single module, the real one, and leave tests.py work normally?

Here's an example that breaks import:

import os
from mock import patch

# when both isdir and isfile are patched
# the function crashes
@patch('os.path.isdir', return_value=False)
@patch('os.path.isfile', return_value=False)
def test(*args):
    import ipdb; ipdb.set_trace()
    real_function(some_arguments)
    pass

test()

I want real_function to see a patched os.path, and tests to see normal functions.

here's the traceback


Solution

  • You can use patch as a context manager, so it will only apply to the code inside the with statement:

    import os
    from mock import patch
    
    def test(*args):
        import ipdb; ipdb.set_trace()
        with patch('os.path.isdir', return_value=False):
            with patch('os.path.isfile', return_value=False):
                real_function(some_arguments)
        pass
    
    test()