Given a directory tests
with a few subdirectories each containing test modules, how can one create a pytest
fixture to be run before each test found in a particular subdirectory only?
tests
├── __init__.py
├── subdirXX
│ ├── test_module1.py
│ ├── test_module2.py
│ ├── __init__.py
├── subdirYY
│ ├── test_module3.py
│ ├── test_module4.py
│ ├── __init__.py
I'd like to have a fixture that will run before each test found in modules within the subdirYY
only (in this case, in modules test_module3.py
and test_module4.py
).
I currently have a fixture defined twice, once inside each module within the subdirYY
which works but is redundant:
@pytest.fixture(autouse=True)
def clean_directory():
...
If this is not possible to achieve, each of the tests within the subdirYY
is decorated with a custom mark (@pytest.mark.mycustommark
) so making sure that a certain fixture will run before each test marked with a particular custom mark is a viable option, too.
Put your autouse fixture in a conftest.py
file inside subdirYY
.
For more information, see the pytest docs about sharing fixtures and the docs on autouse fixtures which specifically mention conftest.py
:
if an autouse fixture is defined in a conftest.py file then all tests in all test modules belows its directory will invoke the fixture.