In this tutorial, we will understand the use of Fixtures in the PyTest Framework.
What is a Fixture?
Fixtures define the steps and data that constitute the arranged phase of a test. In PyTest, they are functions we define that serve this purpose. They can also be used to define a test’s act phase; this is a powerful technique for designing more complex tests.
Fixture can be used to set up and tear down resources, such as establishing database connections, creating temporary files, initializing objects, or any other operations needed to prepare the environment for your tests.
Fixtures in pytest are created using the @pytest.fixture decorator.
Below is an example of a fixture.
import pytest
@pytest.fixture()
def setup():
print("This will be executed before any test")
def test_fixture(setup):
print("This is the fixture main method")
In this example, the setup fixture is defined using the @pytest.fixture decorator. It will be executed before any test. The test function (test_fixture) use this fixture as an argument.
The output of the above program is

What is yield in PyTest?
The yield statement is used in fixtures to create a setup and teardown mechanism for test resources. When a fixture contains a yield statement, the code before the yield acts as the setup code (code executed before the test), and the code after the yield acts as the teardown code (code executed after the test).
Below is an example of yield.
import pytest
@pytest.fixture()
def setup():
print("This will be executed before any test")
yield
print("This will be executed after any test")
def test_fixture(setup):
print("This is the fixture main method")
The output of the above program is

That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!