And*_*ack 47 python exception nose assertions
我正在编写以下内容,在比较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用来运行测试.
Kat*_*iel 82
assert expression, info
例如,
>>> assert False, "Oopsie"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: Oopsie
来自文档:
断言语句是将调试断言插入程序的便捷方式:
Run Code Online (Sandbox Code Playgroud)assert_stmt ::= "assert" expression ["," expression]简单的形式,
assert expression相当于Run Code Online (Sandbox Code Playgroud)if __debug__: if not expression: raise AssertionError扩展形式
Run Code Online (Sandbox Code Playgroud)assert expression1, expression2相当于
Run Code Online (Sandbox Code Playgroud)if __debug__: if not expression1: raise AssertionError(expression2)这些等价假定
__debug__并AssertionError使用这些名称引用内置变量.在当前实现中,内置变量__debug__在正常情况下为True,在请求优化时为False(命令行选项-O).在编译时请求优化时,当前代码生成器不会为assert语句发出任何代码.请注意,不必在错误消息中包含失败的表达式的源代码; 它将显示为堆栈跟踪的一部分.
Hon*_*rek 54
使用e.args,e.message已弃用.
try:
    assert False, "Hello!"
except AssertionError as e:
    e.args += ('some other', 'important', 'information', 42)
    raise
这保留了原始追溯.它的最后一部分看起来像这样:
AssertionError: ('Hello!', 'some other', 'important', 'information', 42)
适用于Python 2.7和Python 3.
您希望获取捕获的异常,将其转换为字符串,将其与一些其他字符串信息组合,并引发新的异常.
x = 3
y = 5
try:
    assert( x == y )
except AssertionError, e:
    raise( AssertionError( "Additional info. %s"%e ) )