This is part of a series of posts on Python unit testing.
This post briefly covers some tools for debugging failing tests.
If looking at the traceback from a test failure isn’t enough there are a few tools to help debug a failing test:
--showlocalsargument to pytest will print out the values of all local variables after the traceback whenever a test fails. Sometimes this can be enough extra information to find the problem:
$ tox -e py27-h tests/h -- --showlocals
Pytest will capture the output of any Python
Just remember to delete the
Tip: Try wrapping a
ifclause, so that something is printed out only if some expression is true. This can be useful for only printing out the valuable information, and not a lot of noise, if the
--pdbargument to pytest will drop into a pdb debugger shell whenever a test fails, at the line of code that fails:
$ tox -e py27-h tests/h -- --pdb
From this shell you can inspect the values of variables and arguments, evaluate expressions, step through code one line at a time, etc. For some tips see pdb on pymotw.
ipdbis an enhanced debugger shell based on ipython, with syntax highlighting, tab completion, etc. To use it you first need to install ipdb into tox’s virtual environment:
$ .tox/py27-h/bin/pip install robpol86-pytest-ipdb
pytest-ipdbpackage is broken.
Then run the tests with the
--ipdbargument instead of
$ tox -e py27-h tests/h -- --ipdb
set_trace()lets you drop into a debugger shell on any line of code, whether in a test or in the code under test, rather than just when a test fails. Put this line anywhere in the Python code:
import pdb; pdb.set_trace()
and you’ll drop into pdb whenever execution hits that line.
For ipdb you would use
import ipdb; ipdb.set_trace().
ifstatements can be a useful trick.
set_trace()lines again before committing the code. Fortunately you can easily grep the entire codebase for
set_trace, since this should never appear in production code.
Those are the main tools that I use to debug failing Python tests. The next post covers writing new tests…
— Sean Hammond,