如何在Python AssertionError中更改消息? [英] How to change the message in a Python AssertionError?

查看:58
本文介绍了如何在Python AssertionError中更改消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在按照以下内容写作,其中我尝试在比较两个多行Unicode文本块时产生一个不错的错误消息。进行比较的内部方法会引发一个断言,但是默认的解释对我来说没有用

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

我无法弄清楚如何更改所捕获的assertionerror中的打印错误消息。我总是得到 AssertionError:u'something'!='something else',它仅显示输出的第一行。

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.

如何更改断言消息以打印出我想要的内容?

如果相关,我正在使用鼻子运行测试。

If it's relevant, I am using nose to run the test.

推荐答案

使用 e。 args e.message 已弃用。

try:
    assert False, "Hello!"
except AssertionError as e:
    e.args += ('some other', 'important', 'information', 42)
    raise

这将保留原始回溯。然后,它的最后一部分如下所示:

This preserves the original traceback. Its last part then looks like this:

AssertionError: ('Hello!', 'some other', 'important', 'information', 42)

在Python 2.7和Python 3中均可使用。

Works in both Python 2.7 and Python 3.

这篇关于如何在Python AssertionError中更改消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆