Consider a unittest suite like this:

import unittest

class TestClass(unittest.TestCase):
    def test_set_trace(self):
        raise Exception

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(TestClass)
    unittest.TextTestRunner(verbosity=2).run(suite)

When I put the following in the script and run it like so: python -m pdb tmp.py I would expect the Python debugger to catch the exception and bring me inside the test_set_trace method, however unittest catches the exception and hides it from pdb like so:

$ python -m pdb tmp.py
> tmp.py(1)<module>()
-> import unittest
(Pdb) c
test_set_trace (__main__.TestClass) ... ERROR

======================================================================
ERROR: test_set_trace (__main__.TestClass)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "tmp.py", line 5, in test_set_trace
    raise Exception
Exception

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)
The program finished and will be restarted
> tmp.py(1)<module>()
-> import unittest
(Pdb)

This is annoying when writing my tests as I need to go into the testing code and specify pdb.set_trace() manually, then step to the frame that contains the actual bug. Does anyone know of a workaround? Putting an explicit import pdb inside the testing code doesn't help, even if I put the import statement within the actual offending method.

有帮助吗?

解决方案

Use TestSuite.debug.

debug()

Run the tests associated with this suite without collecting the result. This allows exceptions raised by the test to be propagated to the caller and can be used to support running tests under a debugger.


Replace following line:

unittest.TextTestRunner(verbosity=2).run(suite)

with:

suite.debug()
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top