What a test is
You already know how to write Python functions, you did it all through Python for Beginners. A test is just more Python: a small piece of code that runs your function and checks the answer automatically.
The checking tool is assert, a built-in statement you may remember from Advanced Python. It works like this:
assert conditiondoes nothing if the condition isTrue- if the condition is
False, it raises anAssertionErrorand the program stops
That is the whole trick. Instead of running your code, staring at the output, and judging it by eye, you write the judgment down as code. The computer then re-checks it every time, in milliseconds, forever.
This habit is not optional in real jobs. Professional teams run thousands of these automated checks on every change, and at most companies code that fails them is blocked from shipping. Without tests, every change to a shared codebase is a gamble that you remembered to re-check everything by hand — nobody remembers, which is why untested codebases rot into “do not touch that file” territory. This course teaches you to write those checks, and, in its second half, to debug with a method when they go red.
Code exercise · python
Run this program. Each assert checks one fact about add. Because all three facts are true, nothing stops the program and the final print runs.
When a test fails
Change add above to return a - b and run again. The first assert becomes assert -1 == 5, which is false, so Python raises AssertionError and the print never happens.
That crash is the test doing its job. A failing test is not an annoyance, it is information: this exact fact about my code is no longer true. You found the bug the moment you created it, at your desk, instead of a user finding it next week.
Two words you will use constantly:
- a test passes (or is green) when its assertions are all true
- a test fails (or is red) when an assertion is false or the code crashes
Quiz
What does `assert x == 10` do when x is 7?
Code exercise · python
Your turn. Write three asserts that check is_even: 4 is even, 7 is not, and 0 is even. Then print exactly: all 3 tests passed
Code exercise · python
One more rep of the same muscle, with a new function. Write three asserts for absolute_value: -5 becomes 5, 3 stays 3, and 0 stays 0. Then print exactly: all 3 tests passed