Skip to content
BetaDE
Lesson 20 of 35Python

Python · Lesson 20 · 25 minutes

Your own tests with assert

What you'll learn

  • Check with assert whether code calculates correctly
  • Find and test edge cases
  • Write test functions like the pros

Why test?

The bigger a program gets, the easier it is for a bug to sneak in – often in a place you didn’t even change. Tests automatically check whether your code still calculates correctly. By the way, that’s exactly how the “Check” button on Codelix works!

assert

assert means “I claim”. If the claim is true, nothing happens. If it isn’t, the program stops with an AssertionError:

def double(x):
    return x * 2

assert double(3) == 6
assert double(0) == 0
assert double(-2) == -4
print("All correct!")

Change x * 2 to x + 2 and run it again. Which test raises the alarm first?

With a message

After a comma you can explain what went wrong:

def grade(points):
    if points >= 90:
        return 1
    if points >= 75:
        return 2
    return 3

assert grade(95) == 1, "95 points should be a 1"
assert grade(75) == 2, "Exactly 75 is still a 2"
assert grade(74) == 3, "74 is already a 3"
print("Grade calculator works!")

Edge cases

Most bugs hide at the edges: at 0, with empty lists, exactly at a limit like 75 points. Good tests don’t just check “normal” values but especially these special cases.

Pro tip: Big projects use pytest. There you write functions that start with test_ – just like in the task – and pytest finds and runs them automatically.

Quick check

Before you start the task: what does this program print? Type your guess – then Python works it out.

def double(x):
    return x * 2


assert double(3) == 6
print("Test 1 ok")
assert double(0) == 0
print("Test 2 ok")

Your task

Your turn

The function is_leap_year(year) is already finished. Write a function test_leap_year() that checks it with at least four assert lines – including the two special cases 1900 (not a leap year) and 2000 (a leap year). Call the test function at the end.

def is_leap_year(year):
    if year % 400 == 0:
        return True
    if year % 100 == 0:
        return False
    return year % 4 == 0


def test_leap_year():
    # your assert lines
    pass


test_leap_year()
print("All tests passed!")

Solve it without hints to earn a ⭐ on your progress page.

Show solution

Try it yourself first – mistakes teach you the most. Here is one possible solution:

def is_leap_year(year):
    if year % 400 == 0:
        return True
    if year % 100 == 0:
        return False
    return year % 4 == 0


def test_leap_year():
    assert is_leap_year(2024) == True
    assert is_leap_year(2023) == False
    assert is_leap_year(1900) == False
    assert is_leap_year(2000) == True


test_leap_year()
print("All tests passed!")