0
0
PyTesttesting~5 mins

Single parameter in PyTest

Choose your learning style9 modes available
Introduction

Using a single parameter in pytest helps you run the same test with different inputs easily. It saves time and avoids repeating code.

You want to check if a function works correctly with different values.
You need to test a feature with multiple inputs without writing many test functions.
You want to make your tests cleaner and easier to maintain.
Syntax
PyTest
@pytest.mark.parametrize('param', [value1, value2, value3])
def test_example(param):
    assert some_function(param) == expected_result

The string 'param' is the name of the parameter your test function will receive.

The list contains all the values you want to test with.

Examples
This test checks if the numbers 1, 2, and 3 are positive.
PyTest
@pytest.mark.parametrize('number', [1, 2, 3])
def test_is_positive(number):
    assert number > 0
This test checks that each word has at least one letter.
PyTest
@pytest.mark.parametrize('word', ['cat', 'dog', 'bird'])
def test_word_length(word):
    assert len(word) > 0
Sample Program

This test runs three times with num = 0, 5, and 10. It checks that each number is zero or positive.

PyTest
import pytest

@pytest.mark.parametrize('num', [0, 5, 10])
def test_is_non_negative(num):
    assert num >= 0
OutputSuccess
Important Notes

Use simple and clear parameter names to understand what each test value means.

Each value in the list will run the test separately, so you get detailed results for each case.

Summary

Single parameter lets you test one input with many values easily.

It helps avoid repeating similar test code.

Each test run shows if a specific input passed or failed.