VOOZH about

URL: https://www.geeksforgeeks.org/python/fixtures-in-pytest/

⇱ Pytest Fixtures - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Pytest Fixtures

Last Updated : 23 Jul, 2025

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.

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.

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.

Comment