Table Of Contents

Previous topic

(Re)designing code

Next topic

Modules, packages, oh my!!

This Page

Function breakdown and Testing Intro

In the elex2/ directory, we’ve chopped up the original code into a bunch of functions and turned this code directory into a package by adding an file.

We’ve also added a suite of tests. This way we can methodically change the underlying code in later phases, while having greater confidence that we haven’t corrupted our summary numbers.

Note: We can’t stress this step enough: Testing existing code is THE critical first step in refactoring.

If the code doesn’t have tests, write some, at least for the most important bits of logic. Otherwise you’re just changing shit.

Fortunately, our code has a suite of unit tests for name parsing and, most importantly, the summary logic.

Python has built-in facilities for running tests, but they’re a little raw for our taste. We’ll use the nose library to more easily run our tests:

nosetests -v tests/
# or run all tests in the tests/ directory
nosetests -v tests/*.py


At a high level, this code is an improvement over elex1/, but it could still be much improved. We’ll get to that in Phase 3, when we introduce modules and packages.


  • What is and why do we use it?
  • In what order are test methods run?
  • What does the TestCase setUp method do?
  • What other TestCase methods are available?


  • Install nose and run the tests. Try breaking a few tests and run them to see the results.
  • List three ways this code is better than the previous version; and three ways it could be improved.
  • Organize functions in into two or more new modules. (Hint: There is no right answer here. Naming things is hard; aim for directory and file names that are short but meaningful to a normal human).