Making Nosetests w/Coverage Awesome

So I've become test infected, nosetests is a great testing framework and with the coverage plugin it'll even tell me how good (or generally bad) I am at testing all of my code. Coverage does have one major problem, it's really finicky about how you call it and its really dumb when it comes to auto-detecting what you want it to do.

Well being a lazy person (I'm a programmer after all) I figured I'd write a quick shell function for my .bashrc file to make coverage not suck; and so I humbly deliver to you, teh intarwebs, the following:

function nosecover
{
    local basepath="${SB}/src/applib/"
    if [[ `pwd` != ${basepath}* ]]; then
        echo "You don't want to run this outside your sandbox."
        return 1
    fi

    # sed pretty much hates it if you don't escape your slashes
    local cb=`echo ${basepath} | sed -e 's/\\//\\\\\//g'`
    local loc=`pwd | sed -e "s/$cb//g" -e "s/\\//./g" -e "s/\\.tests//g"`
    local tf="./"

    # If $1 has test_*.py then use that as our nose path
    if [[ $1 == *test_*.py ]]; then
        tf=$1

    # If $2 has test_*.py then use that as our nose path
    # and assume $1 is our cover package
    elif [[ $2 == *test_*.py ]]; then
        tf=$2
        loc=$1
    fi

    # Always remember to pick your nose before use
    find . \( -name '*.pyc' -o -name '.coverage' \) -exec rm '{}' \;

    echo "nosetests --with-coverage --cover-erase --cover-package=$loc $tf"
    nosetests --with-coverage --cover-erase --cover-package=$loc $tf
}

In a nutshell if you just run nosecover and you're in the directory of the package for which you'd like to get coverage info this function will figure out what your cover-package is and run nose for you. Optionally you may pass a single argument of the specific test to run, or you may pass both a cover package and a test file (in that order) to just skip typing the nose command. This will also clean out any *.pyc and .coverage files so you get accurate results from nose. That's about it, nothing revolutionary, just a nice shortcut.

Now, for the keen observer, you'll note that there are some AGI specific things in here that you'll need to customize for your environment. You'll need to change basepath to wherever your Python code lives but that should be about it.

Go forth and suck less!