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

查看:23
本文介绍了如何更改 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: 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.

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

如果相关,我将使用 nose 来运行测试.

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

推荐答案

使用 e.argse.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天全站免登陆