如何更改Python AssertionError中的消息?
我正在写一个程序,目的是在比较两个多行的Unicode文本块时,能生成一个比较好的错误信息。内部的方法负责比较,但它抛出的错误提示对我来说没什么用。
我需要在下面这样的代码中添加一些东西:
def assert_long_strings_equal(one, other):
lines_one = one.splitlines()
lines_other = other.splitlines()
for line1, line2 in zip(lines_one, lines_other):
try:
my_assert_equal(line1, line2)
except AssertionError, error:
# Add some information to the printed result of error??!
raise
我搞不清楚怎么修改我捕获到的AssertionError中的错误信息。我总是得到这样的输出:AssertionError: u'something' != 'something else'
,这只显示了输出的第一行。
我该怎么做才能把错误提示改成我想要的内容呢?
如果有关系的话,我正在使用nose
来运行测试。
4 个回答
6
你想要把捕获到的错误信息转换成字符串,然后把它和一些额外的信息组合在一起,最后再抛出一个新的错误。
x = 3
y = 5
try:
assert( x == y )
except AssertionError, e:
raise( AssertionError( "Additional info. %s"%e ) )
143
assert expression, info
举个例子,
>>> assert False, "Oopsie"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: Oopsie
来自文档的内容:
assert语句是一种方便的方式,可以在程序中插入调试断言:
assert_stmt ::= "assert" expression ["," expression]
简单的形式,
assert expression
,相当于if __debug__: if not expression: raise AssertionError
扩展的形式
assert expression1, expression2
if __debug__: if not expression1: raise AssertionError(expression2)
这些等价关系假设
__debug__
和AssertionError
是指代那些名称的内置变量。在当前的实现中,内置变量__debug__
在正常情况下为True,当请求优化时(命令行选项 -O)为False。当前的代码生成器在编译时请求优化时不会为assert语句生成任何代码。请注意,错误信息中不需要包含失败表达式的源代码;它会作为堆栈跟踪的一部分显示出来。
77
使用 e.args
,e.message
已经不推荐使用了。
try:
assert False, "Hello!"
except AssertionError as e:
e.args += ('some other', 'important', 'information', 42)
raise
这样做可以保留原始的错误追踪信息。最后的部分看起来是这样的:
AssertionError: ('Hello!', 'some other', 'important', 'information', 42)
在 Python 2.7 和 Python 3 中都可以使用。