Skip to content

Using git hooks to automate tests

Bryn M. Reeves edited this page Jul 14, 2017 · 5 revisions

Now we have the pep8 conformance checks automated with Travis (as well as the py2 and py3 noestests suites) it's useful to automatically check each commit before allowing it into the tree. Git provides hooks that allow a script to run before a commit takes place and that can reject the commit by exiting with failure. See man 5 githooks for more information.

To enable a simple hook that runs pep8, nosetests and nosetests-3.3 add a file at .git/hooks/pre-commit with the following content:

$ cat .git/hooks/pre-commit
#!/bin/bash

do_nosetests() {
    $1 -v --with-coverage --cover-package=sos --cover-html
}

fail () {
    echo "$@: [FAILED]"
    exit 1
}

if git rev-parse --verify HEAD >/dev/null 2>&1
then
        against=HEAD
else
        # Initial commit: diff against an empty tree object
        against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

echo "checking pep8 conformance"
pep8 sos || fail pep8
echo "checking unit test suite (py3)"
do_nosetests nosetests-3 || fail nosetests-3
echo "checking unit test suite (py2)"
do_nosetests nosetests-2 || fail nosetests-2

# If there are whitespace errors, print the offending file names and fail.
exec git diff-index --check --cached $against --

A failure in any of the tests will cause the commit to be rejected. Fix the problem, update the index and try again.

For current Fedora systems you should have the python2-nose and python3-nose packages installed to be able to run both versions of the suite. Earlier Red Hat distributions may call the Python 2 version python-nose instead. Earlier releases may also require the command name in the script to be adjusted to match the installed binary (nosetests-3.x vs. nosetests-3, where x is the minor version number of the installed package).

Other distributions may use different package and command names: consult your distribution's Python documentation for details.