Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert that an iterable is not empty on Unittest?

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

I am surprised of not having any assertEmpty method for the unittest.TestCase class instance.

The existing alternatives just don't look right:

self.assertTrue(bool(d)) self.assertNotEqual(d,{}) self.assertGreater(len(d),0) 

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

like image 610
Alex Tereshenkov Avatar asked Oct 19 '15 14:10

Alex Tereshenkov


People also ask

How do you assert an empty list in Python?

Empty lists are considered False in Python, hence the bool() function would return False if the list was passed as an argument. Other methods you can use to check if a list is empty are placing it inside an if statement, using the len() methods, or comparing it with an empty list.

What is assert Isinstance?

assertIsInstance() in Python is a unittest library function that is used in unit testing to check whether an object is an instance of a given class or not. This function will take three parameters as input and return a boolean value depending upon the assert condition.

How do you use assertTrue in Pytest?

assertTrue() in Python is a unittest library function that is used in unit testing to compare test value with true. This function will take two parameters as input and return a boolean value depending upon the assert condition. If test value is true then assertTrue() will return true else return false.

What does unittest main () do?

Internally, unittest. main() is using a few tricks to figure out the name of the module (source file) that contains the call to main() . It then imports this modules, examines it, gets a list of all classes and functions which could be tests (according the configuration) and then creates a test case for each of them.


1 Answers

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

like image 173
gplayer Avatar answered Sep 21 '22 19:09

gplayer