Pytest Fixtures concept

Fixtures are the functions which are applied to the test methods that are used to execute before any function which applied to it.

For example, If we need to launch the webpage before executing any test case then we need to create a method and append the fixture to it as “@pytest.fixture”.

@pytest.fixture
def fixtureMethod():
   print("This is a Fixture Method")


Now this method acts as a fixture. We need to pass this method name as a parameter to other methods as shown in below example.

Fixture which is defined in the test file its scope is with in that test file itself.

If we need to use the same fixture in multiple test files then we need to create a test file with the name conftest.py and we need to define the fixture in that file.

Here test file name conftest.py is predefined,We shouldn’t change the name of the file.

Let see about conftest.py in next chapter.


test_FixturesConcept.py

import pytest


@pytest.fixture
def fixtureMethod():
    print("This is a Fixture Method")


def test_methodA(fixtureMethod):
    print("This is method A")


def test_methodB(fixtureMethod):
    print("This is method B")


def test_methodC(fixtureMethod):
    print("This is method C")


def test_methodD(fixtureMethod):
    print("This is method D")


Run the command to execute the pytest file.

pytest -v -s test_FixturesConcept.py


OutPut data

In the below output you can see that before each and every test method a fixtureMethod is executed as we decorated with the @pytest.fixture.


admin@admin-MacBook fixturesconcept % pytest -v -s test_FixturesConcept.py 
============================================================================ test session starts ============================================================================
platform darwin -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /Library/Frameworks/Python.framework/Versions/3.8/bin/python3.8
cachedir: .pytest_cache
rootdir: /Users/admin/Documents/Skill2Lead/Tutorials/pytest/fixturesconcept
plugins: rerunfailures-9.0, allure-pytest-2.8.16, ordering-0.6
collected 4 items                                                                                                                                                           

test_FixturesConcept.py::test_methodA This is a Fixture Method
This is method A
PASSED
test_FixturesConcept.py::test_methodB This is a Fixture Method
This is method B
PASSED
test_FixturesConcept.py::test_methodC This is a Fixture Method
This is method C
PASSED
test_FixturesConcept.py::test_methodD This is a Fixture Method
This is method D
PASSED

============================================================================= 4 passed in 0.03s =============================================================================
admin@admin-MacBook fixturesconcept %