Test addition function with multiple inputs using @pytest.mark.parametrize
Preconditions (3)
✅ Expected Result: The test runs three times with different inputs and all assertions pass
import pytest def add(a: int, b: int) -> int: return a + b @pytest.mark.parametrize("a,b,expected", [ (1, 2, 3), (5, 5, 10), (0, 0, 0) ]) def test_add(a, b, expected): result = add(a, b) assert result == expected, f"Expected {expected} but got {result}"
This code defines a simple addition function add.
The @pytest.mark.parametrize decorator runs the test_add function three times with different inputs and expected outputs.
Inside the test, it calls add with the inputs and checks if the result matches the expected value.
This way, we test multiple cases without writing separate test functions.
Now add data-driven testing with 3 different inputs including negative numbers and zero
@pytest.mark.parametrize decorator in pytest?@pytest.mark.parametrize allows running one test function multiple times with different inputs.@pytest.mark.parametrize for testing a function with inputs 1 and 2?@pytest.mark.parametrize with parameters as strings and list of values.import pytest
@pytest.mark.parametrize('x,y', [(1,2), (3,4)])
def test_sum(x, y):
assert x + y == 3@pytest.mark.parametrize:@pytest.mark.parametrize('num', [1, 2, 3])
def test_even():
assert num % 2 == 0is_valid_age(age) that returns True if age is between 18 and 65 inclusive. Which @pytest.mark.parametrize usage correctly tests ages 17, 18, 30, 65, and 70 with expected results?Pass the test and this pattern moves unknown