¿Hay alguna forma de comprobar con Python unittest assert si un iterable no está vacío?


Después de enviar consultas a un servicio, obtengo un diccionario / una lista y quiero asegurarme de que no esté vacía. Estoy en Python 2.7.

Me sorprende no ver ningún método assertEmpty para la instancia de la clase unittest.TestCase.

Las alternativas existentes tales como:

self.assertTrue(bool(d))

Y

self.assertNotEqual(d,{})

Y

self.assertGreater(len(d),0)

Simplemente no se ven bien.

¿Falta este tipo de método en el framework Python unittest? Si es así, ¿cuál sería la forma más pitónica de afirmar que un iterable no está vacío?

Author: Josh J, 2015-10-19

5 answers

Las listas/dictados vacíos se evalúan como False, por lo que self.assertTrue(d) realiza el trabajo.

 52
Author: gplayer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-19 14:08:02

Depende exactamente de lo que esté buscando.

Si desea asegurarse de que el objeto es iterable y no está vacío:

# TypeError: object of type 'NoneType' has no len()
# if my_iterable is None
self.assertTrue(len(my_iterable))

Si está bien que el objeto que se está probando sea None:

self.assertTrue(my_maybe_iterable)
 5
Author: Josh J,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-19 14:16:14

Como @gplayer ya mencionó: es posible comprobar si no hay vacío con assertTrue() (y viceversa con assertFalse() para el vacío, por supuesto).

Pero, como @Alex Tereshenkov ha señalado anteriormente en los comentarios, todas las llamadas a los métodos assertTrue() y assertFalse() desordenan el código y son un poco engañosas porque queríamos verificar si había vacío.

Así que en aras de un código más limpio podemos definir nuestros propios métodos assertEmpty() y assertNotEmpty():

def assertEmpty(self, obj):
    self.assertFalse(obj)

def assertNotEmpty(self, obj):
    self.assertTrue(obj)
 1
Author: winklerrr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-20 14:28:57

Tal vez:

self.assertRaises(StopIteration, next(iterable_object))
 0
Author: Eugene Soldatov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-03 15:07:30

Todo el crédito para esto va a winklerrr, solo estoy extendiendo su idea: tenga mixins importables para cuando necesite assertEmpty o assertNotEmpty:

class AssertEmptyMixin( object ):
    def assertEmpty(self, obj):
        self.assertFalse(obj)

class AssertNotEmptyMixin( object ):
    def assertNotEmpty(self, obj):
        self.assertTrue(obj)

Advertencia, mixins debe ir a la izquierda:

class MyThoroughTests( AssertNotEmptyMixin, TestCase ):
    def test_my_code( self ):
        ...
        self.assertNotEmpty( something )
 0
Author: Rick Graves,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-29 01:05:35