How to apply fixture from conftest.py to inner folders only

I have a fixture that located in conftest.py.

@pytest.fixture(scope='module', autouse=True) 
def my_fixture():
    """
    Some useful code
    """

The structure is like below:

tests
 |
 |--first_folder
 |   |--__init__.py
 |   |--test_first_1.py
 |   |--test_first_2.py
 |   
 |--second_folder
 |   |--__init__.py
 |   |--test_second_1.py
 |
 |--__init__.py   
 |--conftest.py
 |--test_common_1.py

I want that fixture to be auto-used in inner folders test scripts only: in test_first_1.py, test_first_2.py, test_second_1.py, but NOT in test_common_1.py.

I can create conftest with that fixture in each inner folder, but I don't want to duplicate the code

Is there any way to apply fixture from conftest to test scripts from inner folders and ignore it in common folder test scripts?

2 answers

  • answered 2020-07-07 17:50 Ben

    You can achive this by moving the folders 'first folder' and 'second folder' to a new folder and have a conftest.py file in that new folder. Like this -

    tests
     |
     |--new folder
     |  |--first_folder
     |  |  |--__init__.py
     |  |  |--test_first_1.py
     |  |  |--test_first_2.py
     |  |
     |  |--second_folder
     |  |  |--__init__.py
     |  |  |--test_second_1.py
     |  |--conftest.py
     |
     |--__init__.py   
     |--conftest.py
     |--test_common_1.py
    

  • answered 2020-07-07 20:46 lmiguelvargasf

    One possible solution, is you do not want to change the structure of your folders, is that you use the request object in your fixture to check the markers used on the test, so you do anything if a specific marker is set:

    @pytest.fixture(scope='module', autouse=True) 
    def my_fixture(request):
        """
        Some useful code
        """
        if 'noautofixt' in request.keywords:
            return
        # more code
    

    Then mark your tests as follows:

    @pytest.mark.noautofixt
    def test_no_running_my_fixture():
        pass