Open In App

Conftest in pytest

Last Updated : 08 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The testing framework in Python that is used to write various types of software tests, including unit tests, integration tests, etc is called Pytest. The Pytest gives the user the ability to use the common input in various Python files, this is possible using Conftest. The conftest.py is the Python file in which various functions are declared which can be accessed across various test files.

Conftest in Pytest Python Syntax

@pytest.fixture

def function_name():

input = value_to_be_passed

return input

Here,

  • function_name: It is the function name which is to be used as input in other Python files.
  • value_to_be_passed: It is the common input value which you need to use for testing.

In this example, we will create three files: Conftest.py, test1.py and test2.py. We will perform testing by using Pytest and demonstrate the use of conftest.

Conftest.py

In this Python file, we have defined a function input_value, whose value will be used for all other test files, test1.py and test2.py, and check if the test cases pass or fail for the common value.

Python3




# Importing the Pytest library
import pytest
 
# Creating the common function for input
@pytest.fixture
def input_value():
   input = 8
   return input


test1.py

In this Python file, we have defined two functions test_check_floor and test_check_equal, which we need to test.

Python3




# Importing the math library
import math
 
# Creating first test case
def test_check_floor(input_value):
   assert input_value==math.floor(8.34532)
 
# Creating second test case
def test_check_equal(input_value):
   assert 5 == input_value


test2.py

In this Python file, we have defined two functions test_check_difference and test_check_square_root, which we need to test.

Python3




# Importing the math library
import math
 
# Creating first test case
def test_check_difference(input_value):
   assert 99-93==input_value
 
# Creating second test case
def test_check_square_root(input_value):
   assert input_value==math.sqrt(64)


Output

Now, run the test1.py and test2.py using the following command in terminal:

pytest test1.py, test2.py -k check -v

Video Demonstration



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads