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

牧云@^-^@ 提交于 2019-12-04 22:11:49

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

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)

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)

Maybe:

self.assertRaises(StopIteration, next(iterable_object))

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