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.
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.