Debugging python unit tests while using Tox and nosetests

Tox is a test command line tool that facilitates test driven development in Python. It uses virtualenv to create an isolated environment, allowing you to test the same code against different python interpreters or to setup different test levels such as unit or functional tests.
Nose is a python unit test framework that “extends unittest to make testing easier.” Nose comes with the nosetests scripts, which is used to run tests.

To tie all this together, I will provide a simplified version of the tox.ini file from the Gluster-Swift project:

[tox]
envlist = py26,py27,pep8,functest,ksfunctest

[testenv]
setenv = ...
deps = ...
commands = nosetests -v --exe {posargs}
....

When tox is invoked with an envlist, it will create the virtualenv environment with the correct interpreters (e.g., python2.6 or python2.7) and run the nosetests command.

Tox allows for passing new parameters not defined in the tox.ini file to the nosetests commands, just invoke tox like this:

tox -e py27 -- [new_parameters]

Whatever is passed after --, will be substituted where {posargs} is specified in the tox.ini file.

Sometimes you might need to debug your unit test or the code you are trying to test. To debug while using using tox, follow the steps below:

Set a breakpoint in your test code. Here’s an example:

    def test_write_metadata(self):
        import pdb; pdb.set_trace()
        path = "/tmp/foo/w"
        orig_d = {'bar': 'foo'}
        ...

Run tox with the -s parameter (that will be passed to nosetests).

tox -e py27 -- -s

You can also specify to run a single module, test class or even method (i.e., test case). This will speed up your debugging process in case you have a large set of tests.

  • Module: tox -e py27 -- -s test.unit.common.test_utils
  • Class: tox -e py27 -- -s test.unit.common.test_utils:TestUtils
  • Method: tox -e py27 -- -s test.unit.common.test_utils:TestUtils.test_write_metadata

Here are some debugger comands:

w - print stack
s - step into
n - step over
c - continue
p - print
a - print arguments of the current function

2 thoughts on “Debugging python unit tests while using Tox and nosetests

  1. Pingback: tox and pbd | gerva's blog

  2. This was really close to what I was looking for, but when I tried it I got a ‘error: no such option: -s’ from testr. Since we are using testr instead of Nosetests, that becomes a problem.

Leave a comment