Unittest:断言正确的SystemExit代码

时间:2012-11-21 10:55:30

标签: python unit-testing

我正在使用unittest声明我的脚本会引发正确的SystemExit代码。

基于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)

然而,这不起作用。出现以下错误

AttributeError: 'SystemExit' object has no attribute 'error_code'

1 个答案:

答案 0 :(得分:9)

SystemExit直接从BaseException而不是StandardError派生,因此它没有属性error_code

而不是error_code,您必须使用属性code。示例如下所示:

with self.assertRaises(SystemExit) as cm:
    do_something()

the_exception = cm.exception
self.assertEqual(the_exception.code, 3)
相关问题