Pytest – Conftest.py
”;
We can define the fixture functions in this file to make them accessible across multiple test
files.
Create a new file conftest.py and add the below code into it −
import pytest @pytest.fixture def input_value(): input = 39 return input
Edit the test_div_by_3_6.py to remove the fixture function −
import pytest def test_divisible_by_3(input_value): assert input_value % 3 == 0 def test_divisible_by_6(input_value): assert input_value % 6 == 0
Create a new file test_div_by_13.py −
import pytest def test_divisible_by_13(input_value): assert input_value % 13 == 0
Now, we have the files test_div_by_3_6.py and test_div_by_13.py making use of the fixture defined in conftest.py.
Run the tests by executing the following command −
pytest -k divisible -v
The above command will generate the following result −
test_div_by_13.py::test_divisible_by_13 PASSED test_div_by_3_6.py::test_divisible_by_3 PASSED test_div_by_3_6.py::test_divisible_by_6 FAILED ============================================== FAILURES ============================================== ________________________________________ test_divisible_by_6 _________________________________________ input_value = 39 def test_divisible_by_6(input_value): > assert input_value % 6 == 0 E assert (39 % 6) == 0 test_div_by_3_6.py:7: AssertionError ========================== 1 failed, 2 passed, 6 deselected in 0.09 seconds ==========================
The tests will look for fixture in the same file. As the fixture is not found in the file, it will check for fixture in conftest.py file. On finding it, the fixture method is invoked and the result is returned to the input argument of the test.
”;