Python单元测试:测试失败时自动运行调试器

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)

  • 如果你使用`self.assertEquals`而不是普通`assert`,那么测试有一个"失败"而不是"错误",那么运行的命令将是`nosetest --pdb-failures`. (2认同)

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.

  • 我还建议你使用全局标志来打开和关闭这个调试.这会使运行测试变得更复杂.如果我运行某人的测试套件并且它弹出一个调试器,我会非常生气. (2认同)