Labs ICT
โญ Pro Login

Assert Statements

Using plain assert for verifying test outcomes.

Plain assert Statements

pytest uses plain Python assert statements instead of specialized assertion methods. This means you do not need to remember method names like assertEqual or assertTrue.

def test_basic_assertions():
    assert 1 + 1 == 2
    assert "hello" == "hello"
    assert True
    assert [1, 2, 3] == [1, 2, 3]

Detailed Failure Messages

When an assertion fails, pytest introspects the expression and shows you exactly what went wrong:

def test_with_details():
    x = 10
    y = 20
    assert x + y == 35

# Output:
# assert 30 == 35
#  +  where 30 = (10 + 20)

pytest breaks down the expression, showing intermediate values so you can pinpoint the issue.

Custom Failure Messages

You can add a custom message to any assert statement to make failures clearer:

def test_with_custom_message():
    result = calculate_tax(100)
    assert result == 10, f"Expected tax of 10 for $100, got {result}"

def test_list_length():
    items = get_items()
    assert len(items) > 0, "Item list should not be empty"

Common Assertion Patterns

Here are patterns you will use frequently:

def test_common_patterns():
    # Equality
    assert result == expected

    # Inequality
    assert result != unexpected
    assert result > 0
    assert result <= 100

    # Membership
    assert "hello" in "hello world"
    assert 3 in [1, 2, 3]

    # Truthiness
    assert value is not None
    assert items  # checks truthiness (non-empty)

    # Exception testing
    import pytest
    with pytest.raises(ValueError):
        int("not_a_number")

๐Ÿงช Quick Quiz

Which assertion style does pytest encourage?