【问题标题】:How can I get Python's unittest to not catch exceptions?如何让 Python 的单元测试不捕获异常?
【发布时间】:2012-08-31 00:49:47
【问题描述】:

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

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

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

python -i manage.py test

在异常时会像往常一样闯入交互式 Python shell。

怎么做?

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

【问题讨论】:

    标签: python django debugging django-unittest


    【解决方案1】:

    您可以使用django-nose 测试运行器,它与unittest 测试一起使用,并像python manage.py test -v2 --pdb 一样运行您的测试。鼻子会为你跑pdb

    【讨论】:

    • 谢谢。我听说过很多关于鼻子的各种好处,比如这个,它在我的待办事项清单上要学习,但现在,我希望有一种方法可以在没有它的情况下做到这一点。你知道标准测试运行器是否绝对不可能吗?
    • 这不是很好,但是您可以在代码中捕获异常并运行 pdb。
    • 仅供参考,我正在尝试弄清楚如何安装 django-nose,它看起来很棒。到目前为止,这给我带来了麻烦......见stackoverflow.com/questions/12215520/…
    • @Ghopper21,回答了你的问题
    • 如果我只想让它冒泡并被 PyCharm 抓住怎么办?它不允许使用 pdb。
    【解决方案2】:

    一个新的应用程序django-pdb 使它变得更好,支持在常规代码中中断测试失败或未捕获异常的模式。

    【讨论】:

    • +1,这与新的 manage.py test --pdb 标志配合得很好。我现在正在尝试安装 django-nose,以便比较这两种方法。 (顺便说一句,我将继续使用 django-pdb 来进行其他调试增强。)
    【解决方案3】:

    你可以在你的包中的一个模块中尝试这样的事情,然后在你的代码中使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-22
      • 2015-10-10
      • 2021-07-29
      相关资源
      最近更新 更多