Lesson 36. Testing and debugging your programs

 

After reading lesson 36, you’ll be able to

  • Use the unittest library
  • Write tests for your program
  • Efficiently debug your programs

It’s unlikely that you’ll write a perfect program on the first try. Often you’ll write code, test it with a few inputs, make changes to it, and test it again, repeating this process until your program runs as expected.

Consider this

Think about your experience in programming so far. When you write a program and it doesn’t work, what kinds of things do you do to fix it?

Answer:

Look at the error message, if any, and see whether there are clues like line numbers that can direct me toward the issue. Put print statements at certain locations. Try a different input.

36.1. Working with the unittest library

Python has many libraries that can help you create a testing structure around your program. A testing library is especially useful when you have programs that contain different functions. One testing library comes with your Python installation, and its documentation for Python 3.5 is available at https://docs.python.org/3.5/library/unittest.html.

To create a suite of tests, you create a class representing that suite. Methods inside that class represent different tests. Every test that you want to run should have test_ as a prefix, and then any name for the method. The following listing contains code that defines two simple tests and then runs them.

36.2. Separating the program from the tests

 
 
 
 

36.3. Debugging your code

 

Summary

 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage