本文介绍了单元测试:断言正确的 SystemExit 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 unittest 来断言我的脚本引发正确的 SystemExit
代码.
I am using unittest to assert that my script raises the right SystemExit
code.
基于 http://docs.python 的示例.org/3.3/library/unittest.html#unittest.TestCase.assertRaises
with self.assertRaises(SomeException) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
我对此进行了编码:
with self.assertRaises(SystemExit) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
然而,这不起作用.出现以下错误:
However, this does not work. The following error comes up:
AttributeError: 'SystemExit' object has no attribute 'error_code'
推荐答案
SystemExit直接从 BaseException 而不是 StandardError 派生,因此它没有属性 error_code
.
SystemExit derives directly from BaseException and not StandardError, thus it does not have the attribute error_code
.
您必须使用属性 code
而不是 error_code
.该示例如下所示:
Instead of error_code
you have to use the attribute code
. The example would look like this:
with self.assertRaises(SystemExit) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.code, 3)
这篇关于单元测试:断言正确的 SystemExit 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!