Published

Integrating Coverage and Unittest Discovery

by Pete Fein

A quick little howto on integrating coverage with the new test discovery.

Test discovery is awesome – it let’s you add tests to your suite by just writing a new file. Yeah, DRY. As of 2.7, the stdlib’s unittest supports basic discovery (killing my main reason for using nose). If you’re on <=2.6, you can use the backport unittest2 package.

On 2.7, you can run test discovery like so (see the —help for more options):

$ python -m unittest discover

Unfortunately, coverage only supports running a script, not a module (see this bug). Trying to pass the path to the unittest package in your interpreter’s stdlib results in borked imports.

Stuff the following in a script (I called mine unittest_main.py):

”“Main entry point”“” # copied directly from 2.7’s unittest/__main__.py b/c coverage can’t do -m import sys if sys.argv[0].endswith(“__main__.py”): sys.argv[0] = “python -m unittest” __unittest = True from unittest.main import main, TestProgram, USAGE_AS_MAIN TestProgram.USAGE = USAGE_AS_MAIN main(module=None)

And then run your automagically discovered tests under coverage as:

$ coverage run unittest_main.py

Nothing too fancy, but it took me a little while to figure out how to make this work. Hopefully I can save someone else the trouble.

Address
Pittsburgh, US
Email
contact@snake.dev
Social
Twitter | LinkedIn