9

To programmatically combine context managers I use the following code:

== helpers.py ==

from contextlib import nested
import mock

def multiple_patch(obj_to_be_patch, *methods):
    return nested(
        *[mock.patch.object(obj_to_be_patch, method) for method in methods]
    )

== tests.py ==

def test_foo(self):
    with helpers.multiple_patch(Foo, "method1", "method2", "method3",    "method3") as mocks:
         mock_method1 = mocks[0]
         ....
         # asserts on mocks

Because I'm stuck with this version of python I can't use contextlib.ExitStack and contextlib.nested is deprecated.

Thanks

Ali SAID OMAR
  • 6,404
  • 8
  • 39
  • 56

1 Answers1

13

Check out contextlib2.ExitStack, a backport of Python3's contextlib.ExitStack.

pjvandehaar
  • 1,070
  • 1
  • 10
  • 24
  • 4
    Historical trivia: technically the PyPI version came first (to work out the API details), and then it was forward ported from there into the Python 3 standard library. See https://bugs.python.org/issue13585#msg159754 for more info. – ncoghlan Dec 03 '18 at 07:42
  • 1
    @ncoghlan Thanks for the correction and for all your design work to make `ExitStack` so effective. – pjvandehaar Dec 04 '18 at 20:18