Online Tutorials & Training Materials | STechies.com
Register Login

Pytest Parameters Unit Testing Framework

|| 0

Pytest Parameters Unit Testing Framework
Stechies

Python Unit Test Using Pytest Parameters

This tutorial explains step by step how to combine multiple python unit tests into one by using pytest parameters.

Please follow the steps below:

1.You take a ‘mathlib.py’ function to calculate the square of a number.

def calc_square (num) :
      return num*num

2.Go to the test tab. Give the first test case, calculate the square of number 5.

import mathlib

def test_calc_square_1 () :
     result = mathlab.calc_square (5)
     assert == 25

3.Similarly, copy the test code to create multiple tests.

import mathlib

def test_calc_square_1 () :
    result = mathlab.calc_square (5)
    assert == 25

def test_calc_square_2 () :
    result = mathlab.calc_square (9)
    assert == 81

def test_calc_square_3 () :
    result = mathlab.calc_square (10)
    assert == 100

4.Next, run the program to view the output. You will see that the tests are successful.

5.In the above code, the test code is repeated multiple times. Now you will learn how to perform multiple tests in a single function. This is where pytest comes in.

import mathlib

  def test_calc_square (test_input, expected_output) :
  result = mathlib.calc_square (test_input)
  assert result == expected_output

6.First import the ‘pytest’ module then write a function to parameterize. First you create a string argument and then add the test cases.

import mathlib
import pytest

@pytest.mark.parametrize ("test_input, expected_output",
                          [
                          (5, 25)
                          (9, 81)
                          (10,100)
                          ]
                          )


def test_calc_square (test_input, expected_output) :
    result = mathlib.calc_square (test_input)
    assert result == expected_output

7.Run the program and view the output. You will see that all the test cases are successful. You can use this function when there are similarities between test cases.


Related Articles