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