Tests en Python

@jjmerelo

git.io/pytests

Se testea para que falle

¿Es de verdad un mojón?

import json

class HitosIV:
    """Una clase para los hitos del proyecto de Infraestructura Virtual"""

    def __init__(self):
        try: # De https://stackoverflow.com/questions/2835559/parsing-values-from-a-json-file
            with open('hitos.json') as data_file:
                self.hitos = json.load(data_file)
        except IOError as fallo:
            print("Error %d leyendo hitos.json: %s", fallo.errno,fallo.strerror)

    def todos_hitos(self):
        return self.hitos

    def cuantos(self):
        return len(self.hitos['hitos'])

    def uno(self,hito_id):
        if hito_id > len(self.hitos['hitos']) or hito_id < 0:
            raise IndexError("Índice fuera de rango")
        return self.hitos['hitos'][hito_id]

Datos

{
    "comment": "Hitos del proyecto de IV http://jj.github.io/IV",
    "hitos" : [
	{ "file": "0.Repositorio",
	  "title": "Git y GitHub",
	  "fecha": "21/09/2017"},
	{ "file": "1.Infraestructura",
	  "title": "Infraestructura del proyecto",
          "fecha": "28/9/2017"}
    ]
}

¿Esto funciona?: Assert


from HitosIV import HitosIV

def test_should_initialize_object_OK():
    hitos = HitosIV()
    assert type(hitos) is HitosIV, "No se han podido inicializar los hitos"

def test_should_have_hitos_stored_correctly():
    hitos = HitosIV()
    assert type(hitos.todos_hitos()) is dict, "hitos no contiene un diccionario"
    assert hitos.cuantos() is 2, "El número de hitos es incorrecto"
def test_should_return_hitos_correctly_and_raise_error():
    hitos = HitosIV()
    assert hitos.uno(0)["file"] ==  "0.Repositorio"
    try:
        zipi = hitos.uno(-1)
    except Exception as fallo:
        assert type(fallo) is IndexError

    try:
        zipi = hitos.uno(99)
    except Exception as fallo:
        assert type(fallo) is IndexError

Instalar pytest

pasando pytest

Alternativa: Usando unittest

import unittest
from HitosIV import HitosIV


class TestHitosIV(unittest.TestCase):

    def setUp(self):
        self.hitos = HitosIV() #...
    def test_should_initialize_object_OK(self):
        self.assertIsInstance(self.hitos,HitosIV, "Objeto creado correctamente")

    def test_should_have_hitos_stored_correctly( self):
        self.assertIsInstance( self.hitos.todos_hitos(), dict, "El objeto hitos contiene un diccionario")
        self.assertEqual(self.hitos.cuantos(), 2, "El número de hitos es incorrecto")
            
    def test_should_return_hitos_correctly_and_raise_error(self):
        self.assertEqual( self.hitos.uno(0)["file"],  "0.Repositorio" )
        with self.assertRaises(IndexError):
            zape = self.hitos.uno(-1)

        with self.assertRaises(IndexError):
            zipi = self.hitos.uno(99)

Con o sin nariz

pasando tests unitarios pasando
		 nosetests

✓ Testea siempre

✓ Usa aserciones y nombres descriptivos

✓ Hay Más de 1 Forma de Hacerlo

✓ Pasa tests automáticamente con Travis

Créditos