Search code examples
pythonunit-testingtestingpytestfixtures

pytest fixtures in nested Classes


I have written the following testcase using pytest.

import pytest
data_arg = ["arg1", "arg2"]

class TestParentClass1:
    @pytest.fixture(scope="class", params=data_arg,autouse=True)
    def common_setup(self, request):
      print(f'Configure the system according to {request.param}')

    class TestClass1:
        def test_class1_test1(self):
            print("Executing test1 of class1")

        def test_class1_test2(self):
            print("Executing test2 of class1")

    class TestClass2:
        def test_class2_test1(self):
            print("Executing test1 of class2")

        def test_class2_test2(self):
            print("Executing test2 of class2")

I have the following requirements:-

  • There are two classes (TestClass1 and TestClass2) in which I have written several testcases.
  • I want the following flow:-
    • For arg1, execute the common_setup, configure the system according to the arg1 then call the testcases written in TestClass1 and TestClass2.
    • Then do the same for arg2.
  • I have to keep the TestClass1 and TestClass2. I can't merge the testcases of them, this is necessary for me.

I am unable to achieve this flow. Can somebody please help me on how can I do it?


Solution

  • You can try with changing scope=class to scope=module

    @pytest.fixture(scope="module", params=data_arg,autouse=True)