Python 单元测试:当测试失败时自动运行调试器 [英] Python Unit Testing: Automatically Running the Debugger when a test fails

查看:42
本文介绍了Python 单元测试:当测试失败时自动运行调试器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在单元测试失败时自动启动调试器?

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

现在我只是手动使用 pdb.set_trace() ,但这非常繁琐,因为我每次都需要添加它并在最后取出它.

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.

例如:

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()

推荐答案

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

我更正了代码,在异常上调用 post_mortem 而不是 set_trace.

I corrected the code to call post_mortem on the exception instead of set_trace.

这篇关于Python 单元测试:当测试失败时自动运行调试器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆