patching at TestCase class level without overriding unit_test signatures

Viewed 19

I am patching a method for my TestCase class

@patch(
    "my_function_to_mock"
    side_effect=new_behaviour_function,
)
class MyTestCase(unittests.TestCase):
    def test_my_code():
        assert True

however unit_test fails because of unexpected number of argument

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/unittest/mock.py", line 1325, in patched
    return func(*newargs, **newkeywargs)
TypeError: test_my_code() takes 1 positional argument but 2 were given

Everything seems logical, test_my_code was called with my mock as an argument, this failed because my unit test signature do not except a mock.

How can I apply a patch to my TestCase without having to change all my unit tests signatures? I do not need to access mock inside my test method.

1 Answers

I could solve my problem by manually starting a patch at TestCase class setup.

    @classmethod
    def setUpClass(cls):
        my_patch = patch(
            "my_function_to_mock",
            side_effect=new_behaviour_function,
        )
        my_patch.start()
        cls.addClassCleanup(my_patch.stop)
        super(TestCase, cls).setUpClass()
Related