Chapter 21. Testing your code made easy(-er)

 

This chapter covers

  • Testing your code
  • Debugging with the assert statement
  • Using Python’s debug variable
  • Testing using docstrings
  • Creating and using unit tests

The problem with writing code is that you’re never sure you’ve got it right. Every time you turn around, bugs crop up, and what’s worse, fixing those bugs is likely to create more bugs. Fortunately, Python encourages readable code, which helps in debugging; but we still need all the help we can get in maintaining our code.

21.1. Why you need to have tests

Almost all code needs maintenance. Sometimes it requires minor bug fixes, but other times it needs major changes or additions, or even a complete redesign. The more you change your code, the more likely you are to inadvertently introduce new problems or mistakes. What you need is a way to make sure you don’t create new bugs when you fix the old ones and that everything still works when you redesign and refactor and improve your code. You need ways to verify that what used to work still works. You need tests.

21.2. The assert statement

The quickest way to put a test into your code is with the assert statement. An assert statement is a simple way of putting a conditional in your code that will raise an exception if an expression isn’t true. That makes it an ideal watchdog for situations where a particular precondition must always be true for the code to function correctly. For example, see the file in listing 21.1.

21.3. Tests in docstrings: doctests

21.4. Using unit tests to test everything, every time

21.5. Summary