如何更改 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: u'something' != 'something else'
,它只显示输出的第一行。
如何更改断言消息以打印出我想要的任何内容?
如果相关,我将使用 nose
来运行测试。
I'm writing per the following, in which I try to produce a decent error message when comparing two multiline blocks of Unicode text. The interior method that does the comparison raises an assertion, but the default explanation is useless to me
I need to add something to code such as this below:
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
I cannot figure out how to change the printed error message in the assertionerror I catch. I always get AssertionError: u'something' != 'something else'
, which only shows the first line of the output.
How can I change the assertion message to print out whatever I want?
If it's relevant, I am using nose
to run the test.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
例如,
来自 文档:
For instance,
From the docs:
使用
e.args
,e.message
已弃用。这保留了原始的回溯。它的最后一部分如下所示:
Works in those Python 2.7 and Python 3.
Use
e.args
,e.message
is deprecated.This preserves the original traceback. Its last part then looks like this:
Works in both Python 2.7 and Python 3.
您想要获取捕获的异常,将其转换为字符串,将其与一些附加字符串信息组合,然后引发新的异常。
You want to take the caught exception, convert it to a string, combine it with some additional string info, and raise a new exception.
您可以在创建异常时传递所需的消息。
希望这有帮助。
You can pass the desired message when creating the exception.
Hope this helps.