0
0
PyTesttesting~15 mins

Assert with messages in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify sum of two numbers with assertion message
Preconditions (2)
Step 1: Write a function that adds two numbers
Step 2: Call the function with inputs 2 and 3
Step 3: Assert that the result is 5 with a clear failure message if not
✅ Expected Result: Test passes if sum is 5; if not, assertion fails with the message 'Sum of 2 and 3 should be 5'
Automation Requirements - pytest
Assertions Needed:
Assert that the sum of two numbers equals expected value
Include a custom message in the assertion to explain failure
Best Practices:
Use clear and descriptive assertion messages
Keep test functions small and focused
Use pytest's assert statement with message parameter
Automated Solution
PyTest
import 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"Sum of 2 and 3 should be 5 but got {result}"

This test defines a simple function add_numbers that returns the sum of two inputs.

The test function test_add_numbers calls this function with 2 and 3, then asserts the result equals 5.

The assertion includes a message that will show if the test fails, helping to quickly understand what went wrong.

This message uses an f-string to show the actual result, making debugging easier.

Common Mistakes - 3 Pitfalls
Not including an assertion message
Using print statements instead of assertions
Writing complex logic inside the assertion message
Bonus Challenge

Now add data-driven testing with 3 different input pairs and expected sums

Show Hint