How do I reuse a complicated patch statement?

Viewed 33

I have code that looks like this:

with patch("package.module.func") as f1, \
   patch("package.module.func2") as f2, \
   patch("package.module.func3") as f3, \
   patch("package.module.func4") as f4:
      # Do something with the patched functions

I would like to avoid repeating this context over and over again in my code. I always want the same behaviour in different places.

One approach would be to use decorators and decorate my test class:

@patch("package.module.func")
class TestSomething:
   # do stuff

AFAIK every test of TestSomething now uses the patches.

But if I use the patches again in multiple classes, I have to rewrite the decorators. Is there a way to write these patches only once and reuse them in different test modules?

This does not answer my question, since the question, since it is about having different return values per function, which I don't require.

1 Answers

Found the solution after a good coffee:

Mock example taken from this YT: How to use Python's unittest.mock.patch

class BaseMock(TestCase):
    def setUp(self) -> None:
        self.patcher = mock.patch('src.examplemodule.print_content_cwd', return_value=b"[\"base mocked\"]")
        self.patcher.start()

    def tearDown(self) -> None:
        self.patcher.stop()

# Use the mocking, without defining it again 
class TestDerived1(BaseMock):
    def test_d(self):
        ls = examplemodule.print_content_cwd()
        print(f"TestDerived1: ls returned {ls}\n")

# Use the mocking, without defining it again
class TestDerived2(BaseMock):
    def test_d(self):
        ls = examplemodule.print_content_cwd()
        print(f"TestDerived2: ls returned {ls}\n")

The code we want to mock in src/examplemodule.py:

from subprocess import check_output
def print_content_cwd():
    return check_output(['ls']).split()
Related