【问题标题】:Exceptions within unittests are not caught by the Python debuggerPython 调试器不会捕获单元测试中的异常
【发布时间】:2013-12-24 05:37:45
【问题描述】:

考虑像这样的unittest 套件:

import unittest

class TestClass(unittest.TestCase):
    def test_set_trace(self):
        raise Exception

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(TestClass)
    unittest.TextTestRunner(verbosity=2).run(suite)

当我将以下内容放入脚本并像这样运行它时:python -m pdb tmp.py 我希望 Python 调试器能够捕获异常并将我带入 test_set_trace 方法,但是 unittest 捕获异常并将其隐藏来自pdb 像这样:

$ python -m pdb tmp.py
> tmp.py(1)<module>()
-> import unittest
(Pdb) c
test_set_trace (__main__.TestClass) ... ERROR

======================================================================
ERROR: test_set_trace (__main__.TestClass)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "tmp.py", line 5, in test_set_trace
    raise Exception
Exception

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)
The program finished and will be restarted
> tmp.py(1)<module>()
-> import unittest
(Pdb)

编写测试时这很烦人,因为我需要进入测试代码并手动指定pdb.set_trace(),然后进入包含实际错误的框架。有谁知道解决方法?将明确的import pdb 放在测试代码中并没有帮助,即使我将 import 语句放在实际的违规方法中。

【问题讨论】:

    标签: python unit-testing python-2.7 pdb


    【解决方案1】:

    使用TestSuite.debug

    调试()

    在不收集的情况下运行与该套件相关的测试 结果。这允许传播测试引发的异常 给调用者,可用于支持在 调试器。


    替换以下行:

    unittest.TextTestRunner(verbosity=2).run(suite)
    

    与:

    suite.debug()
    

    【讨论】:

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