0
0
PyTesttesting~15 mins

Single parameter in PyTest - Build an Automation Script

Choose your learning style9 modes available
Test function with single parameter using pytest
Preconditions (2)
Step 1: Create a test function named 'test_is_even' that takes one parameter 'number'
Step 2: Use pytest's @pytest.mark.parametrize decorator to pass the values 2, 3, and 4 to 'number'
Step 3: Inside the test, call 'is_even(number)'
Step 4: Assert that the result is True for 2 and 4, and False for 3
✅ Expected Result: The test passes for inputs 2 and 4 (returns True) and fails for input 3 (returns False)
Automation Requirements - pytest
Assertions Needed:
Assert that is_even(2) returns True
Assert that is_even(3) returns False
Assert that is_even(4) returns True
Best Practices:
Use @pytest.mark.parametrize for single parameter testing
Keep test functions simple and focused
Use clear assertion messages if needed
Automated Solution
PyTest
import pytest

def is_even(number: int) -> bool:
    return number % 2 == 0

@pytest.mark.parametrize('number,expected', [
    (2, True),
    (3, False),
    (4, True)
])
def test_is_even(number, expected):
    result = is_even(number)
    assert result == expected, f'Expected is_even({number}) to be {expected} but got {result}'

This code defines a simple function is_even that checks if a number is even.

The test function test_is_even uses @pytest.mark.parametrize to run the test three times with different inputs and expected results.

Each time, it calls is_even with the parameter and asserts the output matches the expected value.

This approach keeps tests clean and easy to extend with more inputs.

Common Mistakes - 3 Pitfalls
Not using @pytest.mark.parametrize and writing separate test functions for each input
Forgetting to include the expected result in the parameter list
Using print statements instead of assertions
Bonus Challenge

Now add data-driven testing with 3 different inputs including negative and zero values

Show Hint