Monday, May 5, 2014

Doctesting Python command line scripts

The purists will hate this one, but the pragmatists may not condemn me so much. I'm writing Python because I want compact, easy to understand and maintain code. If I was into writing a ton of complicated boilerplate I would have used C.

In keeping with this philosophy I love doctest for testing Python code. Many a time writing code with an eye to doctesting it has led me to more modular and functional code. Perhaps this code was a little slower than it could be, but boy was it fast to write and debug and that's the reason we are in Python, right?

One bump in the road is how do you doctest whole command line applications? Vital parts of my code consist of Python scripts that are meant to be called as command line tools. The individual parts have been tested with doctest, but there is often a need for a gestalt test, where several tools are chained and the output needs to be tested.

There is something called shell-doctest which seems to do exactly this, but it is yet another third party package and not very recently maintained, or very widely known. I'm not sure I should use it.

The creator of Python has recommended creating a main function that can be then tested with forced arguments. I like this, and may convert my 'main' sections this way, but there is something to be said to maintaing the 'conversational' style of doctest, where you simply plop down python commands as you would normally and have the correct answers as if you were in an interactive programming environment.

My current experiment is to merge the gestalt test with my instruction manual so that I'm writing the command line examples into my Readme.md file which then doubles as a test file which can be executed by running python -m doctest -v Readme.md

In fact, if you are in IPython, the magic function run does exactly what I want - which, is to run a complete shell command, like run process_data.py arg1 arg2 arg3. Unfortunately doctest uses a vanilla python shell which does not have this facility.

My solution is to define a function I call shell early on in the document.

>>> import shlex, subprocess
>>> def shell(command): subprocess.call(shlex.split(command))

Now, in my Readme.md file I have things like:

You can run the data processing program as

>>> shell('python process_data.py infile.txt outfile.txt')

Which will result in this processed data

>>> with open('outfile.txt','r') as f: print f.read()
Output Data

Which serves both as do by example documentation as well as test.

No comments:

Post a Comment