コード例 #1
0
def test_comando_nueva_tarea():

    comando_repo = ComandoRepository()
    cnt_alta = ComandoNuevaTarea(idd=Idd(Idefier()),
                                 tarea=Tarea(idd=Idd(Idefier()),
                                             nombre="tareaalta",
                                             parametros="parametros",
                                             prioridad=1,
                                             accionid="accion"))

    cnt_baja = ComandoNuevaTarea(idd=Idd(Idefier()),
                                 tarea=Tarea(idd=Idd(Idefier()),
                                             nombre="tareabaja",
                                             parametros="parametros",
                                             prioridad=0,
                                             accionid="accion"))
    comando_repo.send_comando(cnt_alta)
    comando_repo.send_comando(cnt_baja)

    count = 0
    for ccnt in comando_repo.next_comando():
        assert isinstance(ccnt, ComandoNuevaTarea)
        assert ccnt.tarea.nombre in ("tareabaja", "tareaalta")
        print(f"vamos por contador: {count}")
        count = count + 1
        if count == 2:
            break
    assert count == 2
コード例 #2
0
def test_get_all():
    accion_repo = AccionRepository()
    evento_repo = EventoRepository()

    accion_repo.purge_table()
    a = Accion(idd=Idd(Idefier()),
               nombre="accion_buen_humor",
               script_url="git://script_url",
               tipo=TipoAccion(nombre="buenhumor"))
    a1 = Accion(idd=Idd(Idefier()),
                nombre="accion_buen_humor1",
                script_url="git://script_url",
                tipo=TipoAccion(nombre="buenhumor"))

    a2 = Accion(idd=Idd(Idefier()),
                nombre="accion_mal_humor",
                script_url="git://script_url",
                tipo=TipoAccion(nombre="malhumor"))
    accion_repo.append_accion(a, evento_repo)
    accion_repo.append_accion(a1, evento_repo)
    accion_repo.append_accion(a2, evento_repo)

    count = 0
    for acc in accion_repo.get_all_json():
        assert isinstance(acc, dict)
        count = count + 1
    assert count == 3
コード例 #3
0
def test_send_evento_accion_terminada():
    evento_repo = EventoRepository()

    evento = AccionTerminada(idd=Idd(Idefier()),
                             tarea_idd=Idd(Idefier()),
                             resultado=ResultadoAccion(
                                 codigo=CodigoResultado(codigo="BIEN"),
                                 msg="Mensaje de prueba"))

    assert evento_repo.pub_event(evento=evento)
コード例 #4
0
def test_idd():
    idd1 = Idd(Idefier())
    idd2 = Idd(Idefier())
    assert isinstance(idd1.id, str)
    assert idd1 == idd1
    assert idd2 != idd1
    assert idd1 != idd2

    idd3 = Idd(Idefier(), idd_str=idd1.id)
    assert idd1 == idd3
    assert idd3 == idd1
コード例 #5
0
ファイル: web.py プロジェクト: plievana/jpardobl-trastobrain
async def new_accion(request):
    logger.debug("Solicitada new_accion")
    comando_repo = ComandoRepository()
    r = await request.json()

    await comando_repo.send_comando(
        ComandoNuevaAccion(idd=Idd(Idefier()),
                           accion=Accion(idd=Idd(Idefier()),
                                         nombre=r['nombre'],
                                         script_url=r['script_url'],
                                         tipo=TipoAccion(r['tipo']))))
    return web.json_response()
コード例 #6
0
def create_task():
    logger.debug("Solicitada new_task")
    comando_repo = ComandoRepository()
    r = request.get_json(force=True)

    comando_repo.send_comando(
        ComandoNuevaTarea(idd=Idd(Idefier()),
                          tarea=Tarea(Idd(Idefier()),
                                      nombre=r['nombre'],
                                      accionid=r['accionid'],
                                      prioridad=r['prioridad'])))
    logger.debug("Se ha enviado el comando new_task")
    return {"msg": "solicitud recibida", "request": r}
コード例 #7
0
 def from_json(self, json_str_accion: str):
     json_accion = json.loads(json_str_accion)
     return Accion(
         idd=Idd(idefier=Idefier(), idd_str=json_accion['idd']),
         nombre=json_accion['nombre'],
         script_url=json_accion['script_url'],
         tipo=json_accion['tipo']
     )
コード例 #8
0
ファイル: web.py プロジェクト: plievana/jpardobl-trastobrain
async def new_task(request):
    logger.debug("Solicitada new_task")
    comando_repo = ComandoRepository()
    r = await request.json()

    await comando_repo.send_comando(
        ComandoNuevaTarea(idd=Idd(Idefier()),
                          tarea=Tarea(Idd(Idefier()),
                                      nombre=r['nombre'],
                                      accionid=r['accionid'],
                                      prioridad=r['prioridad'])))
    logger.debug("Se ha enviado el comando new_task")
    return web.json_response({
        "msg": "solicitud recibida",
        "request": r
    },
                             status=200)
コード例 #9
0
    def ejecuta_tarea(self, tarea: Tarea, id_repo: IdefierInterface,
                      evento_repo: EventRepositoryInterface,
                      accion_repo: AccionRepositoryInterface):

        evento = None
        resultado = None
        try:
            accionid = tarea.accionid
            print(f"ha llegado el accion id: {accionid}")
            idd = Idd(idefier=id_repo, idd_str=accionid)
            self.logger.debug(
                f"Intentamos ejecutar ---- accionid: {idd}, repo: {accion_repo}"
            )

            accion = accion_repo.get_accion_by_id(idd)
            self.logger.debug(f"Ejecutamos: {accion} (dormimos 10s)")

            #TODO implementar realmente la ejecucion, ahora solo hay un ejemplo
            time.sleep(10)
            self.logger.debug("despertamos, tarea ejecutada")

            if int(tarea.nombre[-1]) > 0:
                resultado = ResultadoAccion(codigo=CodigoResultado(
                    codigo=CodigoResultado.BUEN_RESULTADO),
                                            msg="la tarea ha ido bien")
            else:
                resultado = ResultadoAccion(codigo=CodigoResultado(
                    codigo=CodigoResultado.MAL_RESULTADO),
                                            msg="la tarea ha ido mal")
            evento = AccionTerminada(idd=Idd(idefier=Idefier()),
                                     tarea_idd=tarea.idd,
                                     resultado=resultado)
            evento_repo.pub_event(evento=evento)

        except AccionNotFoundError as exx:
            self.logger.error(f"No se ha encontrado la Accion {exx}")
            resultado = ResultadoAccion(
                codigo=CodigoResultado(codigo=CodigoResultado.MAL_RESULTADO),
                msg=f"No existe la tarea {exx}")
            evento = AccionTerminada(idd=Idd(idefier=Idefier()),
                                     tarea_idd=tarea.idd,
                                     resultado=resultado)
            evento_repo.pub_event(evento=evento)
        except Exception as ekk:
            self.logger.error(f"Error no identificado: {ekk}")
コード例 #10
0
def test_evento_nueva_accion_creada():
    evento_repo = EventoRepository()

    evento = NuevaAccionCreada(idd=Idd(Idefier()),
                               accion_idd=Idd(Idefier()),
                               accion_nombre="Nombre accion")

    assert evento_repo.pub_event(evento)

    for ev in evento_repo.subscribe_event():
        try:
            assert ev.idd == evento.idd
            assert ev.accion_idd == evento.accion_idd
        except Exception as ex:
            print(ex)
        finally:

            break
コード例 #11
0
def new_accion():
    try:
        logger.debug("Solicitada new_accion")
        comando_repo = ComandoRepository()
        r = request.get_json(force=True)

        comando_repo.send_comando(
            ComandoNuevaAccion(idd=Idd(Idefier()),
                               accion=Accion(idd=Idd(Idefier()),
                                             nombre=r['nombre'],
                                             script_url=r['script_url'],
                                             tipo=TipoAccion(r['tipo']))))
        return {}
    except KeyError as ke:
        return ({"message": str(ke)}, 400)
    except Exception as ex:
        logger.error(ex)
        print_exc()
        return ({"message": str(ex)}, 500)
コード例 #12
0
def test_comando_nueva_accion():
    comando_repo = ComandoRepository()

    cna = ComandoNuevaAccion(idd=Idd(Idefier()),
                             accion=Accion(
                                 idd=Idd(Idefier()),
                                 nombre="nombreaccion",
                                 script_url="url",
                                 tipo=TipoAccion(nombre="buenhumor")))

    comando_repo.send_comando(cna)
    count = 0
    for ccna in comando_repo.next_comando():
        assert not ccna is None
        assert isinstance(ccna, ComandoNuevaAccion)
        assert ccna.accion.nombre == "nombreaccion"
        count = count + 1
        break
    assert count == 1
コード例 #13
0
def test_enviar_recibir():
    tarea_repo = TareaRepository()
    tarea_repo.purge_queue()
    task_baja = Tarea(
        idd=Idd(Idefier()),
        nombre="tarea_baja",
        accionid="accion_id",
        parametros={"param1": "hola"},
        prioridad=0
    )
    task_alta = Tarea(
        idd=Idd(Idefier()),
        nombre="tarea_alta",
        accionid="accion_id",
        parametros={"param1": "hola"},
        prioridad=1
    )

    tarea_repo.append(task_baja)
    tarea_repo.append(task_alta)

    count = 0
    for taskc in tarea_repo.next_tarea():
        assert not taskc is None
        assert isinstance(taskc, Tarea)
        assert taskc.nombre == task_alta.nombre
        assert taskc.prioridad == task_alta.prioridad
        
        count = count + 1
        break
    assert count == 1

    for taskc in tarea_repo.next_tarea():
        assert not taskc is None
        assert isinstance(taskc, Tarea)
        assert taskc.nombre == task_baja.nombre
        assert taskc.prioridad == task_baja.prioridad
        
        count = count + 1
        break
    assert count == 2
コード例 #14
0
def test_get_by_id():

    accion_repo = AccionRepository()
    evento_repo = EventoRepository()
    accion_repo.purge_table()
    a = Accion(idd=Idd(Idefier()),
               nombre="nombreaccion",
               script_url="git://script_url",
               tipo=TipoAccion(nombre="buenhumor"))

    accion_repo.append_accion(a, evento_repo)
    a2 = Accion(idd=Idd(Idefier()),
                nombre="nombreaccion2",
                script_url="git://script_url2",
                tipo=TipoAccion(nombre="malhumor"))

    with pytest.raises(AccionNotFoundException):
        acc = accion_repo.get_accion_by_id(a2.idd)

    acc = accion_repo.get_accion_by_id(a.idd)
    assert acc.idd == a.idd
    assert acc.tipo == a.tipo
コード例 #15
0
def test_evento_accion_terminada():
    evento_repo = EventoRepository()

    evento = AccionTerminada(
        idd=Idd(Idefier()),
        tarea_idd=Idd(Idefier()),
        resultado=ResultadoAccion(
            codigo=CodigoResultado(codigo=CodigoResultado.BUEN_RESULTADO),
            msg="Mensaje de prueba"))

    assert evento_repo.pub_event(evento=evento)

    logger.debug("Buscamos eventos")
    for ev in evento_repo.subscribe_event():
        try:
            logger.debug("ha llegado")
            assert ev.idd == evento.idd
            assert ev.tarea_idd == evento.tarea_idd
            assert ev.resultado.codigo == "BIEN"
        except Exception as ex:
            print(ex)
        finally:

            break
コード例 #16
0
 def update_humor_from_task_result(
         self, resultado: ResultadoAccion,
         humor_repo: EstadoHumorRepositoryInterface,
         evento_repo: EventRepositoryInterface):
     try:
         print(resultado)
         humor_repo.mejora() if resultado.is_good() else humor_repo.empeora(
         )
         self.logger.debug("El humor ha cambiado a : {}".format(
             humor_repo.que_tal()))
         evento_repo.pub_event(
             EstadoHumorCambiado(idd=Idd(Idefier()),
                                 nuevo_estado_humor=humor_repo.que_tal()))
     except Exception as ex:
         self.logger.error(ex)
         traceback.print_exc()
コード例 #17
0
 def append_accion(self, accion: Accion,
                   evento_repo: EventRepositoryInterface):
     try:
         self.logger.debug(
             f"Apending nueva accion: tabla: {self.acciones} item: {AccionRepository.to_json(accion)}"
         )
         self.acciones.put_item(Item=AccionRepository.to_json(accion))
         emitido = evento_repo.pub_event(
             NuevaAccionCreada(idd=Idd(idefier=Idefier()),
                               accion_idd=accion.idd,
                               accion_nombre=accion.nombre))
         if not emitido:
             self.rollback_append_accion(accion=accion)
     except Exception as ex:
         self.logger.error(ex)
         self.rollback_append_accion(accion=accion)
コード例 #18
0
def test_get_by_id():

    idefier = Idefier()
    accion = Accion(Idd(idefier), "nombre", "script_url", "enfado")
    evento_repo = EventoRepository()
    accion_repo = AccionRepository()

    accion_repo.append_accion(accion, evento_repo)
    acciones = accion_repo.get_all()

    #with pytest.raises(AccionNotFoundException):
    #    accion = accion_repo.get_accion_by_id(Idd(idefier, "estanoexiste"))
    print(acciones)
    id_str = acciones[0].idd

    accion = accion_repo.get_accion_by_id(Idd(idefier, id_str))
    assert accion.idd == id_str, "Deberia haber recuperado la accion con idd igual al que creo"
コード例 #19
0
def test_get_all():
    idefier = Idefier()
    accion = Accion(Idd(idefier), "nombre", "script_url", "enfado")
    evento_repo = EventoRepository()
    accion_repo = AccionRepository()

    acciones = accion_repo.get_all_json()

    assert len(acciones) == 0, "Deberia mostrar ninguna accion"

    accion_repo.append_accion(accion, evento_repo)
    acciones = accion_repo.get_all_json()
    assert len(acciones) == 1, "Deberia mostrar una sola accion"

    accion_repo.append_accion(accion, evento_repo)
    acciones = accion_repo.get_all_json()
    assert len(acciones) == 2, "Deberia mostrar dos acciones"
コード例 #20
0
def test_evento_estado_humor_cambiado():

    evento_repo = EventoRepository()

    evento = EstadoHumorCambiado(idd=Idd(Idefier()), nuevo_estado_humor=300)

    assert evento_repo.pub_event(evento=evento)

    for ev in evento_repo.subscribe_event():
        try:
            assert ev.idd == evento.idd
            assert ev.nuevo_estado_humor == 300
        except Exception as ex:
            print(ex)

        finally:

            break
コード例 #21
0
ファイル: web.py プロジェクト: plievana/jpardobl-trastobrain
    async def start_background_tasks(self, app):

        t_executor = ThreadPoolExecutor(max_workers=10)

        humor_repo = EstadoDeHumorRepository()
        tarea_repo = TareaRepository()
        comando_repo = ComandoRepository()

        evento_repo = EventoRepository()
        id_repo = Idefier()

        app['brain'] = self.loop.create_task(
            brain(thread_executor=t_executor,
                  id_repo=id_repo,
                  tarea_repo=tarea_repo,
                  comando_repo=comando_repo,
                  humor_repo=humor_repo,
                  accion_repo=self.accion_repo,
                  evento_repo=evento_repo))
コード例 #22
0
def test_estado_humor():

    e = EstadoHumor(Idd(idefier=Idefier()))
    assert e.estado == 0
    assert e.como_estas() == "Normal"
    e.mejora()  #1
    assert int(e.estado) == 1
    assert e.como_estas() == "Bien"
    e.mejora()  #2
    e.mejora()  #3
    assert e.como_estas() == "Muy bien"
    e.empeora()  #2
    e.empeora()  #1
    e.empeora()  #0
    e.empeora()  #-1
    assert e.estado == -1
    assert e.como_estas() == "Mal"
    e.empeora()  #-2
    e.empeora()  #-3
    assert e.como_estas() == "Muy mal"
コード例 #23
0
def test_valida_nombre_tarea():

    with pytest.raises(AttributeError):
        Tarea(idd=Idd(Idefier()),
              nombre="",
              accionid=Idd(idefier=Idefier()),
              prioridad=Prioridad(1))

    with pytest.raises(AttributeError):
        Tarea(idd=Idd(Idefier()),
              nombre="hola",
              accionid=Idd(idefier=Idefier()),
              prioridad=Prioridad(1))

    with pytest.raises(AttributeError):
        Tarea(idd=Idd(Idefier()),
              nombre="ho",
              accionid=Idd(idefier=Idefier()),
              prioridad=Prioridad(1))
コード例 #24
0
 def deserialize_comando_nueva_accion(comando: dict) -> ComandoNuevaAccion:
     return ComandoNuevaAccion(idd=Idd(Idefier(), idd_str=comando['idd']),
                               accion=AccionRepository.deserialize(
                                   comando['accion']))
コード例 #25
0
def start():
    Ejecutor().listen_for_next_tarea(Idefier(), TareaRepository(), EventoRepository(), AccionRepository())
コード例 #26
0
 def deserialize_comando_nueva_tarea(comando: dict) -> ComandoNuevaTarea:
     return ComandoNuevaTarea(idd=Idd(Idefier(), idd_str=comando['idd']),
                              tarea=TareaRepository.deserialize(
                                  comando['tarea']))