Test Driven Development in Python - Customer Comes First
Archive - Originally posted on "The Horse's Mouth" - 2013-05-16 05:46:48 - Graham Ellis
The Customer comes first!
When you're writing code, you should be thinking of your user. That may be your end user or - if you're writing a module or classes - that might be a fellow developer, set of developers or even yourself. Whichever it is, the important thing is to get it right for them. It needs to be well specified, robust, well tested - and that's why you're encouraged to use Test Driven Development.
Writing the tests first helps you ensure that you're providing the right product. It helps you ensure that each of the elements work. And it lets you use testing tools which allow you to build up, rerun and retest time and time again with correlated results. How many times have I written code, come back to it years later and added something in the process breaking an obscure but important feature? With test driven development, and unit test tools, I can now build up test procedures and have an ever-growing validation set. That way, features won't get left behind.
Python coding has always encouraged redientary testing with if __name__ == "__main__":
but we can now go further - and we did on yesterday's Intermediate Python course.
My first test code is [here]. It's a simple exercise of an object, with the user having to check the results and ensure that they're as expected.
I extended that [here], testing multiple objects - but still a manual look through the results to ask "was that OK?"
Using unittest[here], I ran a series of tests and they come out with a neat report to show how they've done and
finally [here] I ran a series of tests in severl test groups. And indeed I can keep adding if I wish.
With all working tests, the final results are as short as
munchkin:yi grahamellis$ python tdd_3
.....
----------------------------------------------------------------------
Ran 5 tests in 0.001s
OK
munchkin:yi grahamellis$
which is really all I need.
With a failed test, you get a need log telling you where the issue lies:
----------------------------------------------------------------------
Ran 5 tests in 0.001s
FAILED (failures=1)
munchkin:yi grahamellis$
The sample class I was testing through these examples is [here]. You'll note that it's independent of the tests in that there's noting at all that changes in the class for it to be run under the test harness.