Python pytest 中的 assertTrue() 来断言空列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37589745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:35:53  来源:igfitidea点击:

assertTrue() in pytest to assert empty lists

pythonpytest

提问by cool77

Is there a way to use assertTrue()or assertFalse()like a function in pytest for python unittests? I have a function which returns a list of elements. If the list is empty the test needs to fail through assertion.

有没有办法在 pytest 中使用assertTrue()assertFalse()喜欢 python 单元测试中的函数?我有一个返回元素列表的函数。如果列表为空,则测试需要通过断言失败。

Is there anything like below:

有没有像下面这样的:

assertFalse(function_returns_list()), "the list is non empty, contains error elements"

回答by Anton Strogonoff

Why not test for the length of the list:

为什么不测试列表的长度:

assert len(function_returns_list()) == 0, "the list is non empty"

回答by sashk

You can assert listto confirm list is not empty, or assert not listto confirm list is empty:

您可以assert list确认列表不为空,或者assert not list确认列表为空:

>>> assert not []
>>> assert []
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError
>>> assert [1, 2, 3]

So in your case, you can just write down:

所以在你的情况下,你可以写下:

assert not function_returns_list()

You can read more about Truth Value Testingon python.org.

您可以在 python.org 上阅读有关真值测试的更多信息。