tjb*_*tjb 39 python unit-testing pdb python-unittest
有没有办法在单元测试失败时自动启动调试器?
现在我只是手动使用pdb.set_trace(),但这非常繁琐,因为我需要每次添加它并在结束时将其取出.
例如:
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()
Run Code Online (Sandbox Code Playgroud)
cmc*_*nty 36
您可以使用以下命令将错误放入调试器:
nosetests --pdb
Run Code Online (Sandbox Code Playgroud)
Ros*_*ron 24
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
Run Code Online (Sandbox Code Playgroud)
我更正了代码,在异常而不是set_trace上调用post_mortem.