0

I want to run all the test methods inherited from another class. Is there a way to do so? For example, for the following code, I want pytest to test all the test methods of TestTwo and TestTwelve inherited from Test.

class Test:

    def __init__(self, n):
        self.n = n

    def test_even(self):
        assert self.n % 2 == 0

    def test_not_big(self):
        assert self.n < 100


class TestTwo(Test):

    def __init__(self):
        super(TestTwo, self).__init__(2)


class TestTwelve(Test):

    def __init__(self):
        super(TestTwelve, self).__init__(12)

However, pytest complains the existence of a __init__ constructor. I want a way to circumvent this.

The overall goal is to make my tests more modular so that I can test similar problems on multiple classes.

taper
  • 528
  • 5
  • 22
  • 1
    Don't override `__init__` methods (here is a [statement from `pytest` dev](https://stackoverflow.com/a/21440548/2650249)). What you are trying to implement is test parametrization; `pytest` offers an elegant way of parametrizing tests via decorators. Check out [Parametrizing fixtures and test functions](https://docs.pytest.org/en/latest/parametrize.html) for more details. – hoefling Oct 15 '18 at 08:34

1 Answers1

-1

The correct usage of pytest to reuse test methods is to use Fixtures. Here is a related question and an example solution.

Thank @hoefling for pointing out in the comment that __init__ is bad for testing.

taper
  • 528
  • 5
  • 22