Parameterize Tests

We can pass the parameters to the test function while execution. This is done by using the builtin fixture @pytest.mark.parametrize.

This fixture takes parameters as argument names and argument values @pytest.mark.parametrize(names , values).

argument names : We need to define argument names with the comma-separated string or list/tuple. We can define one or more argument values.

argument values : The list of arg values determines how often a test is invoked with different argument values. If only one arg name was specified argvalues is a list of values. If N argnames were specified, arg values must be a list of N-tuples, where each tuple-element specifies a value for its respective arg name.

In the below example we have created two methods and marked it with the @pytest.mark.parametrize.

Here in the first method we have created with only one parameter argument name and printed all the values.

In the second method we have created two argument names along with argument values which contain a set of 2 values for each tuple. As discussed it should contain argument values based on the number of argument names.


test_ParameterConcept.py

import pytest


@pytest.mark.parametrize("x", (1, 2, 3))
def test_parameterMethod1(x):
    print("This is a parametrized Method_1", x)


@pytest.mark.parametrize("x,y", ((1, 2),(4,5)))
def test_parameterMethod2(x,y):
    print("This is a parametrized Method_2", x+y)




Run the command to execute the pytest file.

pytest -v -s


OutPut data

admin@admin-MacBook parameterconcept % pytest -v -s
============================================================================ 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/parameterconcept
plugins: rerunfailures-9.0, allure-pytest-2.8.16, ordering-0.6
collected 5 items                                                                                                                                                           

test_ParameterConcept.py::test_parameterMethod1[1] This is a parametrized Method_1 1
PASSED
test_ParameterConcept.py::test_parameterMethod1[2] This is a parametrized Method_1 2
PASSED
test_ParameterConcept.py::test_parameterMethod1[3] This is a parametrized Method_1 3
PASSED
test_ParameterConcept.py::test_parameterMethod2[1-2] This is a parametrized Method_2 3
PASSED
test_ParameterConcept.py::test_parameterMethod2[4-5] This is a parametrized Method_2 9
PASSED

============================================================================= 5 passed in 0.04s =============================================================================
admin@admin-MacBook parameterconcept %