[TIP] Patching the same object in multiple modules, resulting in a single Mock object to the patched function

Saravanan Shanmugham sarvi at yahoo.com
Wed Nov 23 13:58:41 PST 2016



I am testing some code that is distributed across multiple modules. Each module imports a single method that I want to mock, Say check_call from subprocess or open from builtins.
I want to mock out these methods from the multiple modules with one mock object. Whats the best way to do it.
mopen=mock.MagicMock()
# I don't want to see the following, where multiple mock open objects get passed at patch('module1.open',new=mopen)@patch('module2.open',new=mopen)def test_case1(mopen1, mopen2):    m1_open.side_effect  = [OSError]
    m2_open.side_effect = [OSError]    # Test code
I want to see something like the following at patch.special(['module1.open', 'module2.open', 'module3.open'], new=mopen)@patch('module2.open',new=mopen)def test_case1(mopen):    mopen.side_effect = [OSError, OSError]    '# Test code

Is there a way to do this?
Thanks,Sarvi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20161123/7daf09d0/attachment.htm>


More information about the testing-in-python mailing list