如何让Python的unittest不捕获异常?

时间:2012-08-31 00:49:47

标签: python django debugging django-unittest

我正在研究Django项目,但我认为这是一个纯Python unittest问题。

通常,当您运行测试时,测试运行程序将捕获异常并进行相应处理。

出于调试目的,我想禁用此行为,即:

python -i manage.py test
正常情况下,

会在异常上进入交互式Python shell。

怎么做?

编辑:基于到目前为止的答案,似乎这更像是一个特定于Django的问题而不是我意识到的!

3 个答案:

答案 0 :(得分:4)

您可以使用django-nose测试运行器,它适用于unittest测试,并运行您的测试,如python manage.py test -v2 --pdb。鼻子将为你运行pdb

答案 1 :(得分:3)

新的应用django-pdb使这更好,支持在常规代码中打破测试失败或未捕获异常的模式。

答案 2 :(得分:0)

您可以在软件包中的模块中尝试这样的操作,然后在代码中使用CondCatches( 例外 )

# System Imports
import os

class NoSuchException(Exception):
    """ Null Exception will not match any exception."""
    pass

def CondCatches(conditional, *args):
    """
    Depending on conditional either returns the arguments or NoSuchException.

    Use this to check have a caught exception that is suppressed some of the
    time. e.g.:
    from DisableableExcept import CondCatches
    import os
    try:
        # Something like:
        print "Do something bad!"
        print 23/0
    except CondCatches(os.getenv('DEBUG'), Exception), e:
        #handle the exception in non DEBUG
        print 'Somthing has a problem!', e
    """
    if conditional:
        return (NoSuchException, )
    else:
        return args

if __name__ == '__main__':
    # Do SOMETHING if file is called on it's own.
    try:
        print 'To Suppress Catching this exception set DEBUG=anything'
        print 1 / 0
    except CondCatches(os.getenv('DEBUG'), ValueError, ZeroDivisionError), e:
        print "Caught Exception", e