0
0
PyTesttesting~10 mins

Conditional parametrize in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses pytest's parametrize decorator with a condition to run different inputs. It verifies the function returns expected results only for allowed inputs.

Test Code - pytest
PyTest
import pytest

def is_even(n):
    return n % 2 == 0

# Parametrize only even numbers
@pytest.mark.parametrize('num', [n for n in [2, 3, 4, 5] if n % 2 == 0])
def test_is_even(num):
    assert is_even(num) is True
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test startspytest test runner initialized-PASS
2pytest collects test_is_even with parametrize values filtered to even numbers [2, 4]Test cases ready for num=2 and num=4-PASS
3Test runs test_is_even with num=2Function is_even called with 2assert is_even(2) is TruePASS
4Test runs test_is_even with num=4Function is_even called with 4assert is_even(4) is TruePASS
5Test ends with all parameterized cases passedTest report shows 2 passed tests-PASS
Failure Scenario
Failing Condition: If the test runs with an odd number like 3 or 5, assertion fails
Execution Trace Quiz - 3 Questions
Test your understanding
What values does the test actually run with?
A[2, 4]
B[2, 3, 4, 5]
C[3, 5]
D[]
Key Result
Use conditional filtering in parametrize to run tests only on relevant inputs, avoiding unnecessary failures.