assert-based tests & edge cases

Test your own code

Lesson 15 of 20 · 12 min · Module 4: When things go wrong

Professional code comes with tests: small functions that call your code and check the results. Tests catch mistakes the moment you make them, and let you change code without fear.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Write test functions with assert
  • Choose edge cases that reveal bugs
  • Check that tests can actually fail

The idea

A test function calls the code and uses assert condition. If the condition is false, an AssertionError stops the test. Good tests cover a normal case, edge cases (empty input, extra spaces), and tricky cases. Tools such as pytest find and run functions named test_….

def add(a, b):
    return a + b

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0

test_add()
print("all tests passed")

01A test is just a function

test_slugify() calls slugify with known inputs and asserts the expected outputs. Running it silently means everything passed; an AssertionError points to the first wrong result.

02Edge cases find bugs

Most bugs hide at the edges: empty strings, leading and trailing spaces, repeated separators, punctuation only. One assert for each of these is worth more than five similar normal cases.

import re
slug = lambda t: re.sub(r"[^a-z0-9]+", "-", t.lower())
print(slug("  Hi!  "))
Output
-hi-

03A test that cannot fail is useless

The checks here swap in broken versions of slugify and expect your test to fail. Doing this yourself, by breaking the code on purpose for a moment, is a quick way to trust your tests.

Your turn

Write slugify(text) that turns a title into a URL slug: lowercase, every run of characters that are not letters or digits becomes one hyphen, and no hyphens at the start or end. Then write test_slugify() with at least four asserts that a broken slugify would fail. The checks will run your test against a broken version.

What the checks look for

  • slugify handles titles, punctuation and spaces
  • test_slugify passes with your slugify
  • test_slugify catches a version that forgets to strip hyphens
  • test_slugify catches a version that only lowercases
Try it in the editor →

Take this with you

Good tests describe the behaviour precisely enough that broken code fails them.

Go a little further

Install pytest on your computer and run your test function with the pytest command.

Learn Python Intermediate for free

20 short lessons with real code and instant checks.

See the whole course →