0
0
PyTesttesting~5 mins

Why assert is PyTest's core mechanism

Choose your learning style9 modes available
Introduction

Assert helps check if your code works as expected. PyTest uses assert because it is simple and clear to find mistakes.

When you want to check if a function returns the right result.
When you want to make sure a value is true or false in your test.
When you want to stop a test if something is wrong.
When you want to compare two values to see if they match.
When you want to write easy-to-read tests without extra code.
Syntax
PyTest
assert expression, 'optional error message'
The expression should be something that is True when the test passes.
If the expression is False, the test fails and shows the error message if given.
Examples
Checks if 5 equals 5, test passes because it is true.
PyTest
assert 5 == 5
Checks if 'hello' is inside 'hello world'. Shows message if it fails.
PyTest
assert 'hello' in 'hello world', 'Text not found!'
Checks if the list has 3 items.
PyTest
assert len([1, 2, 3]) == 3
Sample Program

This test script checks if sum of numbers is 6 and if 'hello' becomes 'HELLO' when uppercased. If any assert fails, pytest shows the error.

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

def test_upper():
    word = 'hello'.upper()
    assert word == 'HELLO'

# Run tests with pytest
OutputSuccess
Important Notes

Assert statements are easy to write and read, making tests simple.

PyTest shows clear messages when asserts fail, helping find bugs fast.

You do not need special assert functions; plain assert works well in PyTest.

Summary

Assert checks if something is true in your test.

PyTest uses assert because it is simple and shows clear errors.

Use assert to write easy and readable tests.