Search code examples
pythonpytestconftest

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?


Solution

  • @lmiguelvargasf answer (+1) pointed me in the right direction and using request I solved the issue as below:

    @pytest.fixture(scope='module', autouse=True)
    def my_fixture(request):
        if request.config.invocation_dir.basename != 'tests':
            """
            Some useful code
            """
    

    This fixture will be applied only to test-scripts from inner folders as invocation folder name is not equal to 'tests'