Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 11.1 — Why Test, and What a Test Is
Python · Example 2 of 2

How assert behaves: pass, fail with a message, stop the program

The last assert has no message and is not caught, so the traceback ends the program. Fix the expected value to 15 and run again.

A test is a small program that runs your code with a chosen input and checks the result against the answer you expect. Tests are a safety net: they let you change code and find out in seconds whether something broke.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write is_adult(age) that returns True from 18 up. Write three tests: below, on and above the boundary, and run them with a loop like the one in this topic.

02

This function should return the largest number in a list, but the test with [-5, -2, -9] fails. Find the bug: def biggest(nums): top = 0 then a loop that sets top = n when n > top, then return top. Write the failing test first.

03

Write a test for average([]). Decide what it should do (raise ZeroDivisionError, or return 0?), write the test for your decision, then make the function match.

Explain it without notes

01

What is a test, and what are arrange, act and assert?

02

What does the assert statement do, and why should you not use it to validate user input?

03

What is a regression, and how do tests protect against one?

04

Explain the test pyramid. Why are there more unit tests than end-to-end tests?

05

How would you choose inputs for a function that has a rule like "free shipping from 500 up"?

How assert behaves: pass, fail with a message, stop the program
Sign in to run this example in your browser.

Expected output

first assert passed
caught AssertionError: average of 1, 2 should be 2
empty list raises ZeroDivisionError: division by zero
Traceback (most recent call last):
  File "main.py", line 21, in <module>
    assert average([10, 20]) == 20
           ^^^^^^^^^^^^^^^^^^^^^^^
AssertionError