问题
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?
回答1:
Empty lists/dicts evaluate to False, so self.assertTrue(d)
gets the job done.
回答2:
Depends exactly what you are looking for.
If you want to make sure the object is an iterable and it is not empty:
# TypeError: object of type 'NoneType' has no len()
# if my_iterable is None
self.assertTrue(len(my_iterable))
If it is OK for the object being tested to be None
:
self.assertTrue(my_maybe_iterable)
回答3:
As @gplayer already mentioned: it's possible to check for non emptiness with assertTrue()
(and vice versa with assertFalse()
for emptiness of course).
But, like @Alex Tereshenkov previously has pointed out in the comments, all those assertTrue()
and assertFalse()
method calls clutter the code and are kind of misleading because we wanted to check for emptiness.
So in the sake of cleaner code we can define our own assertEmpty()
and assertNotEmpty()
methods:
def assertEmpty(self, obj):
self.assertFalse(obj)
def assertNotEmpty(self, obj):
self.assertTrue(obj)
回答4:
Maybe:
self.assertRaises(StopIteration, next(iterable_object))
回答5:
All the credit for this goes to winklerrr, I am just extending his idea: have importable mixins for when you need assertEmpty or assertNotEmpty:
class AssertEmptyMixin( object ):
def assertEmpty(self, obj):
self.assertFalse(obj)
class AssertNotEmptyMixin( object ):
def assertNotEmpty(self, obj):
self.assertTrue(obj)
Caveat, mixins should go on the left:
class MyThoroughTests( AssertNotEmptyMixin, TestCase ):
def test_my_code( self ):
...
self.assertNotEmpty( something )
来源:https://stackoverflow.com/questions/33216488/is-there-any-way-to-check-with-python-unittest-assert-if-an-iterable-is-not-empt