Esempio n. 1
0
def test_preidentificacion_create_view_post(fiscal_client):
    content = open('adjuntos/tests/acta.jpg', 'rb')
    file = SimpleUploadedFile('acta.jpg',
                              content.read(),
                              content_type="image/jpeg")

    mesa_1 = MesaFactory()
    data = {
        'file_field': (file, ),
        'circuito': mesa_1.circuito.id,
        'seccion': mesa_1.circuito.seccion.id,
        'distrito': mesa_1.circuito.seccion.distrito.id,
    }
    response = fiscal_client.post(reverse('agregar-adjuntos'), data)
    assert response.status_code == HTTPStatus.OK

    attachment = Attachment.objects.all().first()

    assert attachment.pre_identificacion is not None
    assert attachment.status == Attachment.STATUS.sin_identificar

    pre_identificacion = attachment.pre_identificacion
    assert pre_identificacion.circuito == mesa_1.circuito
    assert pre_identificacion.seccion == mesa_1.circuito.seccion
    assert pre_identificacion.distrito == mesa_1.circuito.seccion.distrito
Esempio n. 2
0
def test_identificacion_create_view_post__desde_unidad_basica(
        fiscal_client, admin_user):
    mesa_1 = MesaFactory()
    attachment = AttachmentFactory()
    admin_user.fiscal.asignar_attachment(attachment)
    attachment.asignar_a_fiscal()
    data = {
        'mesa': mesa_1.numero,
        'circuito': mesa_1.circuito.numero,
        'seccion': mesa_1.circuito.seccion.numero,
        'distrito': mesa_1.circuito.seccion.distrito.id,
    }
    response = fiscal_client.post(
        reverse('asignar-mesa-ub', args=[attachment.id]), data)
    assert response.status_code == HTTPStatus.FOUND
    assert response.url == reverse('cargar-desde-ub',
                                   kwargs={'mesa_id': mesa_1.id})

    # Refrescamos el attachment desde la base.
    attachment.refresh_from_db()

    assert attachment.identificaciones.count() == 1
    assert attachment.status == Attachment.STATUS.identificada

    identificacion = attachment.identificaciones.first()
    assert attachment.identificacion_testigo == identificacion
    assert identificacion.status == Identificacion.STATUS.identificada
    assert identificacion.source == Identificacion.SOURCES.csv
    assert identificacion.mesa == mesa_1
    # La identificación está consolidada, por lo tanto ya existe en la mesa
    assert mesa_1.attachments.exists()
Esempio n. 3
0
def test_identificacion_problema_create_view_post_ajax(fiscal_client,
                                                       admin_user):
    a = AttachmentFactory()
    data = {
        'status': 'problema',
        'tipo_de_problema': 'falta_lista',
        'descripcion': 'Un problema'
    }
    # ajax post
    url = reverse('asignar-problema', args=[a.id])
    response = fiscal_client.post(url,
                                  data,
                                  HTTP_X_REQUESTED_WITH='XMLHttpRequest')
    assert response.status_code == 200
    # hack
    assert response.json() == {'status': 'hack'}

    assert a.identificaciones.count() == 1
    i = a.identificaciones.first()
    assert i.status == 'problema'
    assert i.fiscal == admin_user.fiscal
    assert i.mesa is None
    # mesa no tiene attach aun
    a.refresh_from_db()
    assert a.identificacion_testigo is None

    # hay un problema asociado al attach con un reporte asociado
    problema = a.problemas.get()  # demuestra que es 1 solo
    assert problema.estado == 'potencial'
    reporte = problema.reportes.get()  # idem, es 1 solo
    assert reporte.tipo_de_problema == 'falta_lista'
    assert reporte.reportado_por == admin_user.fiscal
    assert reporte.descripcion == 'Un problema'
Esempio n. 4
0
def test_web_upload_con_errores(fiscal_client, carga_inicial):
    archivo = 'falta_jpc_carga_parcial.csv'
    content = open(PATH_ARCHIVOS_TEST + archivo, 'rb')
    file = SimpleUploadedFile(archivo, content.read(), content_type="text/csv")
    data = {
        'file_field': (file, ),
    }

    assert CSVTareaDeImportacion.objects.count() == 0

    response = fiscal_client.post(reverse('agregar-adjuntos-csv'), data)
    assert response.status_code == HTTPStatus.OK

    assert CSVTareaDeImportacion.objects.count() == 1

    tarea = CSVTareaDeImportacion.objects.first()

    assert tarea.status == CSVTareaDeImportacion.STATUS.pendiente

    importar_csv = ImportarCSV()

    importar_csv.wait_and_process_task()

    tarea.refresh_from_db()

    assert tarea.status == CSVTareaDeImportacion.STATUS.procesado
    assert tarea.mesas_total_ok == 0
    assert tarea.mesas_parc_ok == 1
    assert "Faltan las opciones: ['JpC'] en la mesa" in tarea.errores
    assert len(tarea.errores.split('\n')) == 6  # 6 líneas de error.

    cargas_totales = Carga.objects.filter(tipo=Carga.TIPOS.total)

    assert cargas_totales.count() == 1
Esempio n. 5
0
def test_referidos_post_confirma_conoce(fiscal_client, admin_user):
    fiscal = admin_user.fiscal
    referidos_ids = [
        f.id for f in FiscalFactory.create_batch(2, referente=fiscal)
    ]
    assert fiscal.referidos.filter(referencia_confirmada=True).count() == 0
    response = fiscal_client.post(reverse('referidos'),
                                  data={
                                      'conozco': '',
                                      'referido': referidos_ids
                                  })
    assert response.status_code == 200
    assert fiscal.referidos.filter(referencia_confirmada=True).count() == 2
Esempio n. 6
0
def test_preidentificacion_sin_datos(fiscal_client):
    content = open('adjuntos/tests/acta.jpg', 'rb')
    file = SimpleUploadedFile('acta.jpg',
                              content.read(),
                              content_type="image/jpeg")

    mesa_1 = MesaFactory()
    data = {
        'file_field': (file, ),
    }
    response = fiscal_client.post(reverse('agregar-adjuntos'), data)
    assert response.status_code == HTTPStatus.OK

    attachment = Attachment.objects.all().first()
    assert attachment is None
    assert "Este campo es requerido" in response.content.decode('utf8')
Esempio n. 7
0
def test_identificacion_problema_create_view_post_no_ajax(
        fiscal_client, mocker):
    info = mocker.patch('adjuntos.views.messages.info')
    a = AttachmentFactory()
    data = {
        'status': 'problema',
        'tipo_de_problema': 'falta_lista',
        'descripcion': 'Un problema'
    }
    # ajax post
    url = reverse('asignar-problema', args=[a.id])
    response = fiscal_client.post(url, data)
    assert response.status_code == 302
    assert info.call_args[0][
        1] == 'Gracias por el reporte. Ahora pasamos a la siguiente acta.'
    assert response.url == reverse('siguiente-accion')
    # estrictamente, acá no se crea ningun problema
    assert not a.problemas.exists()
Esempio n. 8
0
def test_enviar_email_post(fiscal_client, admin_user, mailoutbox, settings):
    settings.DEFAULT_FROM_EMAIL = '*****@*****.**'
    f = FiscalFactory(nombres='Diego Armando')
    f.agregar_dato_de_contacto('email', '*****@*****.**')
    data = {'asunto': 'hola', 'template': '<p>Hola {{ fiscal.nombres }}</p>'}
    url = f"{reverse('enviar-email')}?ids={f.id}"
    response = fiscal_client.post(url, data)

    # se guardan variables de session
    assert fiscal_client.session.get('enviar_email_asunto') == 'hola'
    assert fiscal_client.session.get(
        'enviar_email_template') == '<p>Hola {{ fiscal.nombres }}</p>'

    assert response.status_code == 302
    assert len(mailoutbox) == 1
    m = mailoutbox[0]
    assert m.subject == 'hola'
    assert 'Hola Diego Armando' in m.body  # text version
    html = m.alternatives[0][0]  # html version
    assert '<p>Hola Diego Armando</p>' in html
    assert html.startswith('<!doctype html>\n<html>\n  <head>\n')
    assert m.from_email == '*****@*****.**'
    assert m.to == ['*****@*****.**']
Esempio n. 9
0
def test_identificacion_create_view_post(fiscal_client, admin_user):
    m1 = MesaFactory()
    a = AttachmentFactory()
    admin_user.fiscal.asignar_attachment(a)
    a.asignar_a_fiscal()
    data = {
        'mesa': m1.numero,
        'circuito': m1.circuito.numero,
        'seccion': m1.circuito.seccion.numero,
        'distrito': m1.circuito.seccion.distrito.id,
    }
    response = fiscal_client.post(reverse('asignar-mesa', args=[a.id]), data)
    assert response.status_code == HTTPStatus.FOUND
    assert response.url == reverse('siguiente-accion')
    assert a.identificaciones.count() == 1
    i = a.identificaciones.first()
    assert i.status == Identificacion.STATUS.identificada
    assert i.mesa == m1
    assert i.fiscal == admin_user.fiscal
    # La identificación todavía no está consolidada.
    a.refresh_from_db()
    assert a.identificacion_testigo is None
    assert not m1.attachments.exists()
    assert a.cant_fiscales_asignados == 0
Esempio n. 10
0
def test_cargar_resultados_mesa_desde_ub_con_id_de_mesa(
        db, fiscal_client, admin_user, django_assert_num_queries):
    """
    Es un test desaconsejadamente largo, pero me sirvió para entender el escenario.
    Se hace un recorrido por la carga de dos categorías desde una UB.

    Cuando se llama a cargar-desde-ub, cuando va por GET, es para cargar el template carga-ub.html.
    Cuando se le pega con POST, va a cargar un resultado.

    Cuando ya no tiene más categorías para cargar, te devuelve a agregar-adjunto-ub
    """
    categoria_1 = CategoriaFactory()
    categoria_2 = CategoriaFactory()

    mesa = MesaFactory(categorias=[categoria_1, categoria_2])

    mesa_categoria_1 = MesaCategoriaFactory(mesa=mesa,
                                            categoria=categoria_1,
                                            coeficiente_para_orden_de_carga=1)
    mesa_categoria_2 = MesaCategoriaFactory(mesa=mesa,
                                            categoria=categoria_2,
                                            coeficiente_para_orden_de_carga=2)

    opcion_1 = OpcionFactory()
    opcion_2 = OpcionFactory()

    CategoriaOpcionFactory(categoria=categoria_1,
                           opcion=opcion_1,
                           prioritaria=True)
    CategoriaOpcionFactory(categoria=categoria_1,
                           opcion=opcion_2,
                           prioritaria=True)
    CategoriaOpcionFactory(categoria=categoria_2,
                           opcion=opcion_1,
                           prioritaria=True)
    CategoriaOpcionFactory(categoria=categoria_2,
                           opcion=opcion_2,
                           prioritaria=True)

    AttachmentFactory(mesa=mesa)

    IdentificacionFactory(
        mesa=mesa,
        status=Identificacion.STATUS.identificada,
        source=Identificacion.SOURCES.csv,
    )
    consumir_novedades_identificacion()
    assert MesaCategoria.objects.count() == 2

    for mc in MesaCategoria.objects.all():
        mc.actualizar_coeficiente_para_orden_de_carga()

    nombre_categoria = "Un nombre en particular"  # Sin tilde que si no falla el 'in' más abajo.
    categoria_1.nombre = nombre_categoria
    categoria_1.save(update_fields=['nombre'])

    categoria_2.nombre = 'Otro nombre'
    categoria_2.save(update_fields=['nombre'])

    url_carga = reverse('cargar-desde-ub', kwargs={'mesa_id': mesa.id})
    response = fiscal_client.get(url_carga)

    # Nos aseguramos que haya cargado el template específico para UB. No es una redirección.
    assert response.status_code == HTTPStatus.OK
    assert url_carga in str(response.content)
    # categoria1 debería aparecer primero porque su mesa categoria tiene un coeficiente_para_orden_de_carga más grande
    assert nombre_categoria in str(response.content)

    tupla_opciones_electores = [
        (opcion_1.id, mesa.electores // 2, mesa.electores // 2),
        (opcion_2.id, mesa.electores // 2, mesa.electores // 2)
    ]
    request_data = _construir_request_data_para_carga_de_resultados(
        tupla_opciones_electores)
    with django_assert_num_queries(47):
        response = fiscal_client.post(url_carga, request_data)

    # Tiene otra categoría, por lo que debería cargar y redirigirnos nuevamente a cargar-desde-ub
    carga = Carga.objects.get()
    assert carga.tipo == Carga.TIPOS.total
    assert response.status_code == HTTPStatus.FOUND
    assert response.url == reverse('cargar-desde-ub',
                                   kwargs={'mesa_id': mesa.id})

    # Hacemos el get hacia donde nos manda el redirect. Esto hace el take.
    response = fiscal_client.get(response.url)

    # Posteamos los nuevos datos.
    response = fiscal_client.post(url_carga, request_data)

    carga.refresh_from_db()

    cargas = Carga.objects.all()
    assert len(cargas) == 2
    assert carga.tipo == Carga.TIPOS.total

    # Me lleva a continuar con el workflow.
    assert response.status_code == HTTPStatus.FOUND
    assert response.url == reverse('cargar-desde-ub',
                                   kwargs={'mesa_id': mesa.id})

    # La mesa no tiene más categorías, nos devuelve a la pantalla de carga de adjuntos.

    assert response.status_code == 302
    # Hacemos el get hacia donde nos manda el redirect.
    response = fiscal_client.get(response.url)
    assert response.url == reverse('agregar-adjuntos-ub')
Esempio n. 11
0
def test_referidos_post_regenera_link(fiscal_client, admin_user, mocker):
    crear_mock = mocker.patch(
        'fiscales.models.Fiscal.crear_codigo_de_referidos')
    response = fiscal_client.post(reverse('referidos'), data={'link': ''})
    assert response.status_code == 200
    assert crear_mock.call_count == 1