0
0
PyTesttesting~15 mins

Basic assert statement in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify that the sum of two numbers is correct
Preconditions (2)
Step 1: Create a function that adds two numbers
Step 2: Call the function with inputs 2 and 3
Step 3: Check if the result equals 5 using an assert statement
✅ Expected Result: The assert statement passes confirming the sum is correct
Automation Requirements - pytest
Assertions Needed:
Assert that the sum of 2 and 3 equals 5
Best Practices:
Use clear and simple assert statements
Keep test functions small and focused
Name test functions starting with 'test_'
Automated Solution
PyTest
def add_numbers(a: int, b: int) -> int:
    return a + b

def test_add_numbers():
    result = add_numbers(2, 3)
    assert result == 5, f"Expected 5 but got {result}"

The add_numbers function adds two numbers and returns the result.

The test function test_add_numbers calls this function with 2 and 3, then uses an assert statement to check if the result is 5.

If the result is not 5, the assert will fail and show a clear message.

This simple test shows how to use basic assert statements in pytest.

Common Mistakes - 3 Pitfalls
Not using assert statement and just printing the result
{'mistake': "Using assert with wrong comparison operator like '=' instead of '=='", 'why_bad': "Single '=' is assignment, not comparison, causing syntax errors.", 'correct_approach': "Use '==' to compare values in assert statements."}
Not providing a helpful message in assert
Bonus Challenge

Now add data-driven testing with 3 different pairs of numbers and their expected sums

Show Hint