To access fixtures in all the test files then we need to create a method and append the required fixtures to it in conftest.py file.
Here test file name conftest.py is predefined,We shouldn’t change the name of the file.
When a defined fixture is not found in the test file where the test methods are created then it will search in the conftest.py file. If it found the required fixture then it will execute it accordingly.
In below example we have created conftest.py and 2 test files as ( test_PytestExample1.py and test_PytestExample2.py)
conftest.py
import pytest @pytest.fixture def fixtureMethod(): print("This is a Fixture Method")
test_PytestExample1.py
def test_methodA(fixtureMethod): print("This is method A") def test_methodB(fixtureMethod): print("This is method B")
test_PytestExample2.py
def test_methodC(fixtureMethod): print("This is method C") def test_methodD(fixtureMethod): print("This is method D")
Run the below command to execute all the test files in the package.
pytest -v -s
OutPut data
admin@admin-MacBook pytest % cd conftestconcept admin@admin-MacBook conftestconcept % pytest -v -s ============================================================================ test session starts ============================================================================ platform darwin -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /Library/Frameworks/Python.framework/Versions/3.8/bin/python3.8 cachedir: .pytest_cache rootdir: /Users/admin/Documents/Skill2Lead/Tutorials/pytest/conftestconcept plugins: rerunfailures-9.0, allure-pytest-2.8.16, ordering-0.6 collected 4 items test_PytestExample1.py::test_methodA This is a Fixture Method This is method A PASSED test_PytestExample1.py::test_methodB This is a Fixture Method This is method B PASSED test_PytestExample2.py::test_methodC This is a Fixture Method This is method C PASSED test_PytestExample2.py::test_methodD This is a Fixture Method This is method D PASSED ============================================================================= 4 passed in 0.03s ============================================================================= admin@admin-MacBook conftestconcept %