Python Unit Tests
26 April, 2009 § Leave a comment
Yesterday, I wrote my first project from scratch in Python using TDD and it was a pleasure.
The integration of unittests in the Python language took away many headaches that come from setting up an environment in other languages such as C++ or C#. To get started, just
import unittest. The next step to configuring is to call
unittest.main() from your main loop. That’s all the configuration necessary to start writing unit tests in Python.
When I was writing the tests, I followed Kent Beck’s recommendation to make a to-do list and I really liked how it turned out. The first thing I did was read through some of the documentation and write down different tests I could write. After writing them down, I picked the easiest one out of the list. Moving through the list this way made the work less stressful, not to mention the whole part about having the tests check to make sure everything works.
When I chose an item from the list I made it bold, and when I had finished it I put a strike through it. If anything came up while working on that item, I added it to the list.
The only hiccup that I ran into while working on it was IDLE’s improper handling of the unittest’s exit. When the tests are finished, they throw some type of exception. Apparently this isn’t a problem with other runtimes, so the way I fixed it was surrounding the
unittest.main() with a
except:. Nothing is hidden from the developer if a unit test fails.