python - 如何更改 Python AssertionError 中的消息?

标签 python exception assertions nose

我正在编写以下内容,在比较两个多行 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 to

if __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__ and AssertionError 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/

相关文章:

python - PyCharm 中类 'objects' 的未解析属性引用 ''

python - django-piston 的错误重定向

python - 如何将元组中的每个元素除以一个整数?

java - 如何找出导致此 Java FX 应用程序线程异常的原因?

java - BindException 多线程服务器

c++ - 使用 copyTo 函数断言失败 (C++)

javascript - 为什么 ava 无法比较对象列表和对象文字列表?

python - 在 Django 中缓存静态文件

c++ - C风格语言中的异常与非异常处理

ruby - Minitest 不会通过,尽管使用 binding.pry 检查时标准是正确的