Python Unit Testing: Automatically Running the Debugger when a test fails

import unittest
import sys
import pdb
import functools
import traceback
def debug_on(*exceptions):
    if not exceptions:
        exceptions = (AssertionError, )
    def decorator(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except exceptions:
                info = sys.exc_info()
                traceback.print_exception(*info) 
                pdb.post_mortem(info[2])
        return wrapper
    return decorator

class tests(unittest.TestCase):
    @debug_on()
    def test_trigger_pdb(self):
        assert 1 == 0

I corrected the code to call post_mortem on the exception instead of set_trace.


I think what you are looking for is nose. It works like a test runner for unittest.

You can drop into the debugger on errors, with the following command:

nosetests --pdb

Third party test framework enhancements generally seem to include the feature (nose and nose2 were already mentioned in other answers). Some more:

pytest supports it.

pytest --pdb

Or if you use absl-py's absltest instead of unittest module:

name_of_test.py --pdb_post_mortem