Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assertTrue() in pytest to assert empty lists

Tags:

python

pytest

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.

Is there anything like below:

assertFalse(function_returns_list()), "the list is non empty, contains error elements"
like image 820
cool77 Avatar asked Jun 02 '16 10:06

cool77


2 Answers

Why not test for the length of the list:

assert len(function_returns_list()) == 0, "the list is non empty"
like image 76
Anton Strogonoff Avatar answered Sep 19 '22 08:09

Anton Strogonoff


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

>>> 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 Testing on python.org.

like image 45
sashk Avatar answered Sep 19 '22 08:09

sashk