What is a parameterization?
Roughly speaking, parametrization is a process of varying (changing) one or more coefficients in a mathematical equation. In the context of testing, parametrization is a process of running the same test with varying sets of data. Each combination of a test and data is counted as a new test case.
The most simple form of parameterization:
@pytest.mark.parametrize("number", [10, 20, 30, 0, 42]) def test_big(number): assert number > 0
In this case we are getting five tests: for number 10, 20, 30, 0 and 42. Each of those tests can fail independently of one another (if in this example the test with 0 will fail, and four others will pass). This approach is much more convenient for debugging and development compared with a simple loop with an assert in it.
Parameterizing of a test is done to run the test against multiple sets of inputs. We can do this by using the following marker −
@pytest.mark.parametrize
Write the following code in your sample.py file:
def add(a, b): return a + b
Now, the test_sample.py file is as follows:
import sample import pytest @pytest.mark.parametrize('num1, num2, result', [ (90, 3, 93), ('Hello', ' World', 'Hello World'), (15.5, 25.5, 41) ] ) def test_add(num1, num2, result): assert sample.add(num1, num2) == result
- Pass the values according to the parametrize argument i.e. on adding 90 and 3 we will get 93, so we have passed num1=90, num2=3, result=93. If you want to fail any test case simply change the result which will give wrong output.
- In your terminal type the following command:
pytest test_sample.py -v
- Now let’s change the value 93 to 90 and perform testing:
- We can see two test cases passed and one failed.