测试通过,仍然出现回溯

20 投票
5 回答
10473 浏览
提问于 2025-04-17 12:37

我在使用Python的unittest库进行测试,所有的测试都通过了,但我还是收到了一个错误追踪信息,我不明白该怎么解决这个问题。

........
----------------------------------------------------------------------
Ran 8 tests in 0.020s

OK

Traceback (most recent call last):
  File "C:\Users\Paul\Desktop\bloomfilter\test_bloomfilter.py", line 85, in <module>
    unittest.main()
  File "C:\Programming\PythonX86\Python27\lib\unittest\main.py", line 95, in __init__
    self.runTests()
  File "C:\Programming\PythonX86\Python27\lib\unittest\main.py", line 231, in runTests
    sys.exit(not self.result.wasSuccessful())
SystemExit: False
>>> 

5 个回答

7

在你的单元测试文件的最后加上:

if __name__=='__main__':
    try:
        unittest.main()
    except SystemExit as inst:
        if inst.args[0] is True: # raised by sys.exit(True) when tests failed
            raise
21

为了避免执行结束时出现错误追踪信息:

if __name__ == '__main__':
    unittest.main(exit=False)
16

看起来你是在Python的命令行环境中运行代码,这个环境会帮你捕捉错误,这样你就可以继续调试。如果你是在普通的命令行中运行,下面这行代码

sys.exit(not self.result.wasSuccessful())

会让你的程序退出,并返回一个退出码0,这表示程序成功结束(如果你不太了解程序和命令行的互动,这可能会让你感到困惑)。不过因为你是在解释器中运行,所以错误被捕捉到了。

我想说,你的程序或者测试没有问题。可能是单元测试框架没有预料到你会以交互的方式运行它!

撰写回答