Is there any way to check with Python unittest assert if an iterable is not empty?

Alex Tereshenkov picture Alex Tereshenkov · Oct 19, 2015 · Viewed 58.3k times · Source

After submitting queries to a service, I get a dictionary / a list back and I want to make sure it's not empty. I am on Python 2.7.

I am surprised I don't see any assertEmpty method for the unittest.TestCase class instance.

The existing alternatives such as:

self.assertTrue(bool(d))

and

self.assertNotEqual(d,{})

and

self.assertGreater(len(d),0)

just don't look right.

Is this kind of method is missing in the Python unittest framework? If yes, what would be the most pythonic way to assert that an iterable is not empty?

Answer

gplayer picture gplayer · Oct 19, 2015

Empty lists/dicts evaluate to False, so self.assertTrue(d) gets the job done.