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 −

conftest.py

import pytest

@pytest.fixture
def input_value():
   input = 39
   return input

test_div_by_3_6.py

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

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 session starts ================================
platform win32 -- Python 3.14.2, pytest-9.0.2, pluggy-1.6.0 
-- C:\Users\mahes\AppData\Local\Programs\Python\Python314\python.exe
cachedir: .pytest_cache
rootdir: D:\Projects\python\myenv\automation
collected 8 items / 5 deselected / 3 selected

test_div_by_13.py::test_divisible_by_13 PASSED                             [ 33%]
test_div_by_3_6.py::test_divisible_by_3 PASSED                             [ 66%]
test_div_by_3_6.py::test_divisible_by_6 FAILED                             [100%]

============================ 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
================================ short test summary info =========================
FAILED test_div_by_3_6.py::test_divisible_by_6 - assert (39 % 6) == 0
================================ 1 failed, 2 passed, 5 deselected in 0.08s =======

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.

Advertisements