pytest中的assertTrue()断言空列表

coo*_*l77 6 python pytest

有没有办法像python单元测试pytest中的函数一样使用assertTrue()或assertFalse().我有一个函数,如果返回元素列表,测试需要通过断言失败.

有下面的东西:

assertFalse(function_returns_list()), "the list is non empty, contains error elements"
Run Code Online (Sandbox Code Playgroud)

Ant*_*off 14

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

assert len(function_returns_list()) == 0, "the list is non empty"
Run Code Online (Sandbox Code Playgroud)

  • @sashk PEP20说"明确比隐含更好".偏转!虽然你有一个好点 (4认同)
  • 这将起作用,但是需要更多键入。PEP8建议[对于序列((​​字符串,列表,元组),请使用空序列为假的事实)(https://www.python.org/dev/peps/pep-0008/#programming-recommendations)。 (3认同)

sas*_*shk 8

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

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

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

assert not function_returns_list()
Run Code Online (Sandbox Code Playgroud)

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