Pages

Unit Testing and Test-Driven Development in Python

There are both advantages and disadvantages to being self-taught in any given discipline. In certain cases, the advantages and disadvantages can overlap or even coincide. For example, when you are self-taught, you are not confined by institutional structures and courses of study. On the one hand, this allows for a distinct measure of freedom to pursue one’s own interests in the field, which would not necessarily be afforded to a person following a traditional disciplinary curriculum. On the other hand, this also means that it can be quite easy to develop gaps in one’s basic knowledge of the discipline, for the simple reason that these areas of study did not fall within your area of interest.

I discovered one such gap in my study of programming in general, and Python in particular, a number of months ago when I came across a quote online that went something like this: “Code that is not tested is broken by definition.” Testing? “You mean running the code to see if it works?” I thought to myself. Within the next hour I had my first exposure to the method of test-driven development and the Python unittest module.

This was literally the exact opposite of how I had approached my own programming projects up until then, which might be termed “error-driven development”: write some code; run it; see if it works; if it doesn’t work, tinker at random until it does; write some more code and repeat. I quickly realized that, according to the above quote, all my code was broken, by definition.

The test-driven development model is the reverse of this: write a test, run it and watch it fail; write some code to make the test pass; refactor; write another test and repeat. It was an enlightening experience to attempt writing even a simple program under a test-driven model, as it was immediately obvious that I had only the vaguest notions about things that I thought I knew fairly well.

Since then, I’ve re-written a number of programs I’d created for myself under a completely test-driven developmental model, and have integrated testing into my everyday coding practice. I’ve also collected a bunch of resources that I've found helpful along the way, which you can find below. Also, as you may know, of late there has been something of a controversy brewing on the merit and value of test driven software development. Some links on this are supplied at the end. As always, further recommendations are welcome in the comments!