在Python中,我可以这样做:
assert result==100, "result should be 100"
但这是多余的,因为我必须输入两次条件。
有没有办法让Python在断言失败时自动显示条件?
答案 0 :(得分:5)
使用纯Python,您无法轻松自动重现断言的条件。 pytest测试框架完全符合您的要求,但这种魔法的实现就是but trivial。简而言之, pytest rewrites the code of your assertions复杂代码,以捕获生成所需错误消息所需的信息。
答案 1 :(得分:3)
来自Jupyter笔记本
回溯会发生这种情况。例如:
x = 2
assert x < 1
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-5-0662b7144a79> in <module>()
1 x = 2
----> 2 assert x < 1
AssertionError:
然而,优良作法是人为化(即用语言解释)为什么会出现这种错误。通常,我用它来反馈有用的信息。例如:
x = 2
assert x < 1, "Number is not less than 1: {0}".format(x)
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-4-bd4b9b15ccc2> in <module>()
1 x = 2
----> 2 assert x < 1, "Number is not less than 1: {0}".format(x)
AssertionError: Number is not less than 1: 2
从命令行
此仍然发生回溯。例如:
H:\>python assert.py
Traceback (most recent call last):
File "assert.py", line 1, in <module>
assert 2 < 1
AssertionError
适用于所有环境的解决方案
使用traceback模块。有关详细信息,请参阅How to handle AssertionError in Python and find out which line or statement it occurred on?
上的回答