我正在编写以下内容,在比较两个多行 Unicode 文本 block 时,我尝试生成一个体面的错误消息。进行比较的内部方法引发了一个断言,但默认解释对我来说毫无用处
我需要在代码中添加一些内容,如下所示:
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
运行测试。
最佳答案
assert expression, info
例如,
>>> assert False, "Oopsie"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: Oopsie
来自 docs :
Assert statements are a convenient way to insert debugging assertions into a program:
assert_stmt ::= "assert" expression ["," expression]
The simple form,
assert expression
, is equivalent toif __debug__: if not expression: raise AssertionError
The extended form
assert expression1, expression2
is equivalent to
if __debug__: if not expression1: raise AssertionError(expression2)
These equivalences assume that
__debug__
andAssertionError
refer to the built-in variables with those names. In the current implementation, the built-in variable__debug__
is True under normal circumstances, False when optimization is requested (command line option -O). The current code generator emits no code for an assert statement when optimization is requested at compile time. Note that it is unnecessary to include the source code for the expression that failed in the error message; it will be displayed as part of the stack trace.
关于python - 如何更改 Python AssertionError 中的消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3807694/