CodeBlanks Logo Icon CodeBlanks

assert

Learn assertions with assert.

assert

assert checks that a condition is true. If false, it raises AssertionError and the test fails. If true, it continues silently.

The syntax is assert condition or assert condition, message. The message adds context when an error occurs.

assert 2 + 2 == 4
assert len("abc") == 3, "length should be 3"
assert [1, 2, 3] == [1, 2, 3]

pytest catches AssertionError and marks the test as failed. If the condition is true, the test passes silently; you can add a marker like print("ok") at the end.

Approaches: equality and membership

The most common checks are equality (==), inequality (!=), greater/less than (>, <) and membership (in).

Example: when testing a filter function, you compare directly with assert filter([1, 2, 3]) == [2, 3]. To check if an item is included, write assert 3 in filter([1, 2, 3]).

Multiple asserts can live in one test; each is a separate check. The first failure stops the test.

Practice Test the is_even function

Write is_even(n) returning n % 2 == 0. In test_is_even() add three checks: assert is_even(4), assert not is_even(5) and assert is_even(0). End the file with test_is_even() and print("ok").

Starter code

main.py
# is_even function: return True/False for even n
# test_is_even function: three checks (4 even, 5 odd, 0 even)
# call test_is_even() then print "ok"

Sample solution

main.py
def is_even(n):
    return n % 2 == 0

def test_is_even():
    assert is_even(4)
    assert not is_even(5)
    assert is_even(0)

test_is_even()
print("ok")

Expected output

ok

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the assert forms

Term Meaning
assert x == 5 Equality check
assert x != 0 Inequality check
assert cond, msg Check with message
assert x in items Membership check

2 What happens when an assert condition is false?

  • The test passes silently
  • AssertionError is raised and the test fails Correct answer
  • Only a warning is printed
  • The program crashes and exits

Explanation: assert raises AssertionError on a false condition; pytest marks the test as failed.

3 Complete the assert with message

Question
assert len("abc") == 3, ____
Answer
assert len("abc") == 3, "uzunluk 3 olmalı"

Explanation: The second argument is the message; it shows with AssertionError.

All lessons in Advanced