English 中文(简体)
Pytest - Conftest.py
  • 时间:2024-11-03

Pytest - Conftest.py


Previous Page Next Page  

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_span_by_3_6.py to remove the fixture function −

import pytest

def test_spanisible_by_3(input_value):
   assert input_value % 3 == 0

def test_spanisible_by_6(input_value):
   assert input_value % 6 == 0

Create a new file test_span_by_13.py

import pytest

def test_spanisible_by_13(input_value):
   assert input_value % 13 == 0

Now, we have the files test_span_by_3_6.py and test_span_by_13.py making use of the fixture defined in conftest.py.

Run the tests by executing the following command −

pytest -k spanisible -v

The above command will generate the following result −

test_span_by_13.py::test_spanisible_by_13 PASSED
test_span_by_3_6.py::test_spanisible_by_3 PASSED
test_span_by_3_6.py::test_spanisible_by_6 FAILED
============================================== FAILURES
==============================================
________________________________________ test_spanisible_by_6
_________________________________________
input_value = 39
   def test_spanisible_by_6(input_value):
>  assert input_value % 6 == 0
E  assert (39 % 6) == 0
test_span_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.

Advertisements