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

tjb picture tjb · Dec 9, 2010 · Viewed 19.7k times · Source

Is there a way to automatically start the debugger at the point at which a unittest fails?

Right now I am just using pdb.set_trace() manually, but this is very tedious as I need to add it each time and take it out at the end.

For Example:

import unittest

class tests(unittest.TestCase):

    def setUp(self):
        pass

    def test_trigger_pdb(self):
        #this is the way I do it now
        try:
            assert 1==0
        except AssertionError:
            import pdb
            pdb.set_trace()

    def test_no_trigger(self):
        #this is the way I would like to do it:
        a=1
        b=2
        assert a==b
        #magically, pdb would start here
        #so that I could inspect the values of a and b

if __name__=='__main__':
    #In the documentation the unittest.TestCase has a debug() method
    #but I don't understand how to use it
    #A=tests()
    #A.debug(A)

    unittest.main()

Answer

cmcginty picture cmcginty · May 16, 2011

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