Splitting a conftest.py file into several smaller conftest-like parts
Alternativelly, you could try:
In my_fixtures.py
:
@pytest.fixture
def some_fixture():
yield
In conftest.py
:
import my_fixtures
# Adding the fixture to attributes of `conftest` will register it
some_fixture = my_fixtures.some_fixture
It seems that pytest
detect fixture by iterating over conftest
attributes and checking for some attr._pytestfixturefunction
added by @pytest.fixture
.
So as long as conftest.py
contains fixture attributes, it doesn't really matter which file is the fixture defined:
You can put your stuff in other modules and reference them using a pytest_plugins
variable in your conftest.py
:
pytest_plugins = ['module1', 'module2']
This will also work if your conftest.py
has hooks on them.
You shouldn't need any fancy magic for that. py.test automatically adds the path of the current test file to sys.path
, as well as all parent paths up to the directory it was targeted at.
Because of that, you don't even need to put that shared code into a conftest.py
. You can just put into plain modules or packages and then import it (if you want to share fixtures, those have to be in a conftest.py
).
Also, there is this note about importing from conftest.py
in the documentation:
If you have conftest.py files which do not reside in a python package directory (i.e. one containing an
__init__.py
) then “import conftest
” can be ambiguous because there might be otherconftest.py
files as well on yourPYTHONPATH
orsys.path
. It is thus good practise for projects to either putconftest.py
under a package scope or to never import anything from aconftest.py
file.