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()
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:
I corrected the code to call post_mortem on the exception instead of set_trace.
To apply @cmcginty's answer to the successor nose 2 (recommended by nose available on Debian-based systems via
apt-get install nose2
), you can drop into the debugger on failures and errors by callingin your test directory.
For this, you need to have a suitable
.unittest.cfg
in your home directory orunittest.cfg
in the project directory; it needs to contain the linesA simple option is to just run the tests without result collection and letting the first exception crash down the stack (for arbitrary post mortem handling) by e.g.
Another option: Override
unittest.TextTestResult
'saddError
andaddFailure
in a debug test runner for immediate post_mortem debugging (beforetearDown()
) - or for collecting and handling errors & tracebacks in an advanced way.(Doesn't require extra frameworks or an extra decorator for test methods)
Basic example:
Here's a built-in, no extra modules, solution:
call it with
python myunittest.py --pdb
and it will halt. Otherwise it won't.