【问题标题】:Unittest: assert right SystemExit codeUnittest:断言正确的 SystemExit 代码
【发布时间】:2012-11-21 10:55:29
【问题描述】:

我使用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'

【问题讨论】:

标签: python unit-testing


【解决方案1】:

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

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

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

the_exception = cm.exception
self.assertEqual(the_exception.code, 3)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    相关资源
    最近更新 更多