Reputation: 1136
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"
Upvotes: 26
Views: 83421
Reputation: 3519
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
Upvotes: -1
Reputation: 4213
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.
Upvotes: 29
Reputation: 34122
Why not test for the length of the list:
assert len(function_returns_list()) == 0, "the list is non empty"
Upvotes: 37