python

Automatically running unit tests on save with watchdog and a bash script

I’m a big fan of Red/Green Test Driven Development. A critical component to adopting TDD is fast, automatic feedback from your unit tests.  In the Ruby world, I used tools such as autotest, watchr, and guard, and when I started writing Python code at Jana, I found the watchdog package for Python.

Watchdog mostly accomplishes what I want, but it takes quite a bit of command line configuration to get it to run my nosetests automatically. You can pip install watchdog to get started.

Here’s an example watchdog command that will clear the terminal, and then run tests in path/to/my/tests when I save any python files.

$> watchmedo shell-command --patterns="*.py" --recursive 
--command="clear; nosetests path/to/my/tests" .

That’s quite a long command, and I’m too lazy to type that over and over, if I can even remember it.  So I created myself a simple bash script and put it in my bash path.  I happened to called it autotest because it’s fairly close to nosetests in case I change from running the test once manually to repeatedly and automatically.

NOTE: I saved this to ~/bin/autotest, which is on my path

#!/bin/bash

watchmedo shell-command --patterns="*.py" --recursive
--command="clear; nosetests $1" .

This simple script is just a parameterized version of my original command that I can use like this:

$> autotest path/to/my/tests

If I want to run a specific test, I can use the standard options that nosetests provides:

# run one file
$> autotest tests/fizzbuzz_test.py

# run one test case class
$> autotest tests/fizzbuzz_test.py:FizzBuzzTestCase

# run one test case
$> autotest tests/fizzbuzz_test.py:FizzBuzzTestCase.test_fizz_buzz

What other tips and tricks do you use to make TDD better? I’ve been looking for a good red/green coloring for nosetests but haven’t found one yet. 😦

Tags:

Discussion

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Pingbacks & Trackbacks

  1. Exploring Refactoring with Color | Jana Technology
  2. Patching Your Workflow | Jana Technology