
In pytest official docs:
conftest.py: sharing fixtures across multiple files
The conftest.py file serves as a means of providing fixtures for an entire directory. Fixtures defined in a conftest.py can be used by any test in that package without needing to import them (pytest will automatically discover them).
You can have multiple nested directories/packages containing your tests, and each directory can have its own conftest.py with its own fixtures, adding on to the ones provided by the conftest.py files in parent directories.
Code language: JavaScript (javascript)
More generally, what is the purpose and correct use of conftest.py file(s) in a pytest test suite?
The use of conftest.py including:
Fixtures
Fixtures are a common use of conftest.py. The fixtures defined will be shared among all tests in the test suite.
Notice that defining fixtures in the root conftest.py might be useless and it would slow down testing if such fixtures are not used by all tests.
Other use of conftest.py includes
- Fixtures: Define fixtures for static data used by tests. This data can be accessed by all tests in the suite.
- External plugin loading: you can also use conftest.py to import external plugins or modules.
pytest will load the plugin if specified in the following global variable
pytest_plugins = "someapp.someplugin"
Code language: JavaScript (javascript)
- Hooks: You can define hooks in conftest.py, for example setup and teardown methods :
def pytest_runtest_setup(item):
""" called before ``pytest_runtest_call(item). """
#do some stuff`
Code language: PHP (php)
- Test root path: if define conftest.py in your root path, pytest will then recognizing your modules without specifying
PYTHONPATH
.
Can I have more than one conftest.py file?
Yes you can . conftest.py files have directory scope. Therefore, creating targeted fixtures and helpers is a good practice, if you have a complex test structure.
However, in order to share fixtures among multiple test files, you have to use a conftest.py file somewhere centrally located for all of the tests. Fixtures can be shared by any test