Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 657
culebrón Avatar asked Sep 27 '12 12:09

culebrón


1 Answers

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()
like image 111
ecatmur Avatar answered Sep 22 '22 12:09

ecatmur