assertTrue() in pytest to assert empty lists

Question:

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"
Asked By: cool77

||

Answers:

Why not test for the length of the list:

assert len(function_returns_list()) == 0, "the list is non empty"
Answered By: 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.

Answered By: sashk

I’d say use assertEqual([], function_returns_list()).

unittest would print a nice output with list contents, which is useful for debugging:

======================================================================
FAIL: test_timeout_orphan (tests.test_process_runner.TestProcessRunner)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/unittest/async_case.py", line 68, in _callTearDown
    self.tearDown()
  File "/drone/src/client/tests/test_process_runner.py", line 24, in tearDown
    self.assertEqual([], list(psutil.Process().children()), "should be no left-over processes")
AssertionError: Lists differ: [] != [psutil.Process(pid=26, name='sleep', status='zombie', started='02:17:40')]

Second list contains 1 additional elements.
First extra element 0:
psutil.Process(pid=26, name='sleep', status='zombie', started='02:17:40')

- []
+ [psutil.Process(pid=26, name='sleep', status='zombie', started='02:17:40')] : should be no left-over processes
Answered By: WGH
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.