Automatic Unit-testing with git

If you (like me) have always wanted to automatically run your unit tests before commiting your work to git the following steps might be of interest to you.

Let’s assume we have a small python app we want to automatically test on git-commit.

For this purpose i use “nose“, a python extension which recursively discovers all unit tests in the current directory and runs them after issuing a quick “nosetests” in the desired directory.

Fine. But how do we run that command automatically when using git? The commit should of course be aborted if there are errors.

The first thing to do is to add some lines to the pre-commit hook in the .git directory. This hook is executed every time we do a git commit.

I added the following lines to the top of the script:

# Run test suite
nosetests
# Check its output
if [ "$?" = "0" ]; then
    echo "Testsuite passed. Commiting..."
else
    echo "Testsuite failed. Aborting commit"
    exit 1
fi

And we’re almost done. If the “nosetests” command fails (which means that a test failed) we exit the pre-commit hook with exit code != 0. Git will then abort the commit. The only thing left to do is make the pre-commit hook script executable:

chmod +x .git/hooks/pre-commit

If you now try to commit some buggy code git should give the expected error message “Testsuite failed. Aborting commit” like we specified in our code.

RSS 2.0 | Trackback | Comment

2 Responses to “Automatic Unit-testing with git”


  1. Yes, I do think your opinion is righteous. (So do lots of people). Luckily majority of people are intelligent :).


  2. Thanks for the info!

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>