Open In App

Pytest Fixtures

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Pytest fixtures are a powerful feature that allows you to set up and tear down resources needed for your tests. They help in creating reusable and maintainable test code by providing a way to define and manage the setup and teardown logic. A Fixture is a piece of code that runs and returns output before the execution of each test. In this article, we will study the fixtures in Pytest.

Pre-requisite

Fixtures in Pytest:

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.

Example 1:

In this example, we have declared one fixture, input_value for declaring the input and passing the input to each test. Here, we have declared two tests, test_check_difference, and test_check_square_root, that use the value declared by the fixture.

Python3




# Importing the math and pytest libraries
import math
import pytest
  
# Creating the common function for input
@pytest.fixture
def input_value():
   input = 8
   return input
  
# 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 test using the following command in terminal:

pytest test.py

Screenshot-2023-10-30-195916-(1)

Example2:

In this example, we have declared one fixture, string_match that removes leading and trailing spaces from input and passes the input to each test, i.e., test_remove_G, test_remove_e, and test_remove_o.

Python3




# Import pytest library
import pytest
  
# Creating the common function for input
@pytest.fixture
def string_match():
   string = "   Geeks For Geeks   "
   return string.strip()
  
# Creating first test case
def test_remove_G(string_match):
    assert string_match.replace('G','')=="eeks For eeks"
  
# Creating second test case
def test_remove_e(string_match):
    assert string_match.replace('e','')=="Gaks For Gaks"
  
# Creating third test case
def test_remove_o(string_match):
    assert string_match.replace('o','')=="Geeks Fr Geeks"


Output:

Now, run the test using the following command in terminal:

pytest test.py

After running this command you will get this output

Screenshot-2023-10-30-195618-(1)

Conclusion

The fixtures help the user to use the certain part of code just by declaring and reading it once, thus it becomes a crucial part of Pytest. I hope the above article might have helped you in understanding the fixtures in Pytest.



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

Similar Reads