Testing your code

Errors & Exceptions, lesson 7 of 7

🛟 Errors & Exceptions, lesson 7 of 7

Testing your code

Write tests that check your functions, with assert and unittest.

12 min

1 exercise

1 quiz

0/2 solved

Getting Python ready… examples can run in a moment.

You change a function to add a feature. Does the old behavior still work? A test is a small piece of code that calls your function and checks the answer. Run your tests after every change and broken code shows up right away.

Example

A test function

Each assert checks one fact. The print runs only when every assert passes. If one fails, Python stops with an AssertionError that shows your message.

Example

A test that catches a bug

The test found the bug the moment it ran, before anyone used is_even. Change the comparison to == 0 and the test passes.

unittest is Python's built-in testing toolkit. It groups tests into a class and provides checks such as assertEqual, which shows both values when they differ. Copy the shape from the example below: a class that inherits from unittest.TestCase, with test methods whose names start with test_. You'll learn what class and self mean in the next module.

Finish with unittest.main(argv=["x"], exit=False). This app has no command line, so argv gives unittest a list to use instead. exit=False stops it from ending the program when a test fails, which this app would report as an error.

Example

unittest with assertEqual and assertRaises

The report shows in red even when everything passes: unittest writes it to the error stream, which this app displays in red. OK means every test passed. assertRaises(ValueError, average, []) calls average([]) and passes only if it raises ValueError.

Quiz

The program stops with an AssertionError. What printed before that?

Test the edges, not just the easy cases. Empty lists, 0, negative numbers and the boundary values are where bugs hide. Tests can be wrong too, so when one fails, check its expected value before changing a working function. Good test names describe the behavior, like test_empty_list_raises, so a failure report tells you what broke.

Exercise

Test the leap year check

is_leap_year(year) is provided in the starter code. Leap years follow these rules: a year divisible by 4 is a leap year, except years divisible by 100, which are leap years only when they are also divisible by 400.

Your job is to test it. Write a class TestLeapYear that subclasses unittest.TestCase, with test methods whose names start with test_. Use self.assertEqual for the checks. Your tests should catch the mistakes a sloppy version of this function could make. End with unittest.main(argv=["x"], exit=False).