Search code examples
pythoninheritancepytestfixtures

Python - Use pytest to test test methods written in subclass


I am a novice to pytest. I have a scenario wherein i wanted to test some test methods written in a subclass.

Assume that the following is my code structure

class Superclass:
    def __init__(self, a):
        self.a = a
    def dummy_print():
        print("This is a dummy function")

class TestSubClass(Superclass):

def test_1_eq_1():
    assert 1 == 1

Upon executing the following command

py.test -s -v test_filename.py

I get the following error messgae:

cannot collect test class 'Test_Super' because it has a init constructor

The same is mentioned in the pytest documentation as well.

Is there a workaround for this?

I need the superclass' __init__() method because all my test files would need to inherit from the super class.


Solution

  • Pytest is different beast than, say unittests. It prohibits class hierarchies, which you can see in the warning message.

    If you need some pre-initialization steps, do them using fixtures:

    @pytest.fixture(autouse=True)
    def pre_run_initialization():
        # do before test
        yield
        # do after test