0
0
PyTesttesting~5 mins

Basic assert statement in PyTest

Choose your learning style9 modes available
Introduction

The basic assert statement checks if something is true in your test. It helps find mistakes by stopping the test if the check fails.

To check if a function returns the expected result.
To verify that a value is equal to what you expect.
To confirm that a condition is true before continuing.
To catch errors early in simple tests.
To make sure your code behaves as planned.
Syntax
PyTest
assert expression, "optional failure message"

The expression should be something that is True or False.

If the expression is False, the test fails and shows the message if given.

Examples
Checks if 5 equals 5, which is true, so the test passes.
PyTest
assert 5 == 5
Checks if 'a' is in 'apple'. If not, it shows the message.
PyTest
assert 'a' in 'apple', "Letter 'a' not found"
Checks if the list length is 3.
PyTest
assert len([1, 2, 3]) == 3
Sample Program

This test script has two tests. The first checks if the sum of numbers is 6. The second checks if 'hello' becomes 'HELLO' when uppercased.

PyTest
def test_sum():
    total = sum([1, 2, 3])
    assert total == 6, "Sum should be 6"

def test_uppercase():
    word = "hello".upper()
    assert word == "HELLO"

# Run tests with pytest
OutputSuccess
Important Notes

Use assert to check one thing at a time for clear test results.

Write helpful messages to understand failures quickly.

pytest shows detailed info when assert fails, making debugging easier.

Summary

Assert checks if a condition is true in tests.

It helps find bugs by stopping tests when conditions fail.

Use clear messages to explain what went wrong.