Fixtures - naveens33/selenium_python GitHub Wiki
Fixtures are the functions to run before test function. Also, it helps to feed data to the test function and act as dependencies.
Basic Fixture function
To make a function as a fixture, you need to mark that function below with the marker
@pytest.fixture
def initialize():
print("initialize")
Ways to apply fixture to the test function
- name it in test function parameter
- usefixtures decorator
- autouse
Follow the below example,
1. name it in test function parameter:
import pytest
@pytest.fixture
def initialize():
print("initialize")
def test_01(initialize):
print("test_01")
2. usefixtures decorator
import pytest
@pytest.fixture
def initialize():
print("initialize")
@pytest.mark.usefixtures("initialize")
def test_01():
print("test_01")
3. autouse
autouse is the optional parameter to the fixture decorator. The default value is False, such that the fixture cannot be applied to the test function. If you provide True then it will automatically apply to the test function.
Note: autouse will apply to the test function as per the scope of the fixture. The default scope of fixture is "function". Please go through the parameter section of fixture decorator to learn more about the scope.
import pytest
@pytest.fixture(autouse=True)
def initialize():
print("initialize")
def test_01():
print("test_01")
Parameters of fixture decorator
1. scope
scope defines how often the fixture gets called. Following are options for scope,
- function - Run once per test function
- class - Run once per class
- module - Run once per module
- session - Run once per session
2. params
an optional list of parameters which will cause multiple invocations of the fixture function and all of the tests using it. The current parameter is available in request.param.
import pytest
@pytest.fixture( params=[
("username1","password1"),
("username2","password2"),
("username3","password3")
] )
def initialize(request):
print(request.param[0],request.param[1])
In the above example, that fixture is invoked multiple times as many parameter we have provide. I.e. initialize fixture runs for thrice and the data from the parameter can be received/get using request.param
3. autouse
Please go through the Ways to apply fixture to the test function section
Return from fixture
Fixtures can feed data to the test function and act as dependencies with the help of return statement
For example,
import pytest
@pytest.fixture
def input_value():
age = 56
return age
def test_01(input_value):
assert input_value >= 18
Add cleanup/teardown code to the fixture
Cleanups or teardown to the fixtures can be achived in below ways,
1. Using yeild
By using a yield statement instead of return, all the code after the yield statement serves as the teardown,