Ignore class level patch decorator for one test

Viewed 130

I have a class in a module like this:

class Foo:
    def bar1(self) -> str:
        return "bar1"

    def bar2(self) -> str:
        bar = bar1()
        return bar

    def bar3(self) -> str:
        bar = bar1()
        return bar

    def bar4(self) -> str:
        bar = bar1()
        return bar

I have a test class in another module where I want to mock method bar1 for each barX function except when I test my bar1 itself. In reality, I have a lot of barX methods (and thus tests), so I don't want to simply put the same patch decorator above each of the barX test methods (except the test_bar1 function).

I solved this by patching the bar1 method with a @patch decorator on class leverl, but how can I negate that decorator for 1 test method (my test for bar1()?

My test code:

foo = Foo()

def mock_bar1() -> str:
    return "mocked_bar1"

@patch("foo_module.Foo.bar1", mock_bar1)
class FooTest(TestCase):
    def test_bar1(self) -> None:
        # fails because bar1() is mocked, I want to disabed the mock here
        self.assertEqual("bar1", foo.bar1())

    def test_bar2(self) -> None:
        self.assertEqual("mocked_bar1", foo.bar2())

    def test_bar3(self) -> None:
        self.assertEqual("mocked_bar1", foo.bar3())

    def test_bar4(self) -> None:
        self.assertEqual("mocked_bar1", foo.bar4())

So how can I ignore/negate the patched method for my test method test_bar1?

1 Answers

Why not have a second class in the same test module, and move the bar1 tests to it like so:

foo = Foo()

def mock_bar1() -> str:
    return "mocked_bar1"

@patch("foo_module.Foo.bar1", mock_bar1)
class FooTest(TestCase):
    def test_bar2(self) -> None:
        self.assertEqual("mocked_bar1", foo.bar2())

    def test_bar3(self) -> None:
        self.assertEqual("mocked_bar1", foo.bar3())

    def test_bar4(self) -> None:
        self.assertEqual("mocked_bar1", foo.bar4())

class FooBar1Test(TestCase):
    def test_bar1(self) -> None:
        self.assertEqual("bar1", foo.bar1())
Related