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

删除回忆录丶 提交于 2019-12-05 08:21:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!