在python assert中,如何在Assert失败时打印条件?

jvlzgdj9  于 2023-03-11  发布在  Python
关注(0)|答案(3)|浏览(268)

在Python中,我可以:

assert result==100, "result should be 100"

但这是多余的,因为我必须键入两次条件。
有没有办法告诉Python在Assert失败时自动显示条件?

7gcisfzg

7gcisfzg1#

来自木星笔记本

回溯时会发生这种情况。例如:

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?中的答案

m0rkklqb

m0rkklqb2#

使用纯Python,你不能很容易地自动重现Assert的条件。pytest测试框架做的正是你想要的,但是这个魔术的实现是but trivial的一切。简而言之,pytestrewrites the code of your assertions到复杂的代码,以捕获生成所需错误消息所需的信息。

ovfsdjhp

ovfsdjhp3#

assertpy是一个小巧漂亮的包,它可以打印出有用的错误信息:

>>> assert_that('foo').is_equal_to('bar')

Expected <foo> to be equal to <bar>, but was not.

相关问题