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

Matt Wheeler m at funkyhat.org
Thu Nov 24 04:24:49 PST 2016


On Wed, 23 Nov 2016 at 21:58 Saravanan Shanmugham <sarvi at yahoo.com> wrote:

>
>
> 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
> @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
> @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?
>

You can patch it directly in builtins:

```
if sys.version_info.major == 2:
    # if you need to support python2
    import __builtin__ as builtins
else:
    import builtins


@patch.object(builtins, 'open', mopen)
def test_...
```
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20161124/51cfa0e9/attachment.html>


More information about the testing-in-python mailing list