Search code examples
pythonpytestfixtures

How to have a pytest fixture applied to multiple files


What's the recommended way to have pytest fixtures applied to multiple test files without setting the fixture scope to session (which is too global)?

Here's the structure I'm hoping to use:

test_component_1/conftest.py
test_component_1/test_feature_1.py
test_component_1/test_feature_2.py

test_component_2/conftest.py
test_component_2/test_feature_1.py
test_component_2/test_feature_2.py

Using scope='module' re-applies the fixtures for each file.

I'd like the following behavior instead:

  1. set up component_1 fixtures from test_component_1/conftest.py
  2. run component_1 tests
  3. tear down component_1 fixtures
  4. set up component_2 fixtures from test_component_2/conftest.py
  5. run component_2 tests
  6. tear down component_2 fixtures

Thanks!


Solution

  • There is no way to expand the scope to more modules (files) without using scope='session'. It is anyway good practice to gather all tests for a module in a single file. But if you have very good reasons to do so, you can split it up by renaming

    test_feature_1.py --> feature_1_tests.py
    test_feature_2.py --> feature_2_tests.py
    

    and establish test_component_1.py which invokes the tests from those files.