示例#1
0
    def test_blind_reviewing_types_as_reviewer(self):
        """Verify whether BLIND_REVIEWERS setting works properly."""
        # This is not applicable for POSTing views.
        if self.http_method_name == "post":
            return
        self._add_to_reviewers_group()
        proposals = self._create_proposals()
        for proposal in proposals:
            # Create feedback from a random user.
            ProposalFeedbackFactory(proposal=proposal)
            # Create feedback from the proposal's speaker.
            ProposalFeedbackFactory(proposal=proposal,
                                    author=proposal.speaker.user)

        with override_config(BLIND_REVIEWERS=True):
            response = self.client.get(
                reverse(self.reverse_view_name, args=self.reverse_view_args))
            for proposal in proposals:
                self.assertNotContains(response, proposal.speaker.name)
                self.assertNotContains(response,
                                       proposal.speaker.user.username)
                self.assertNotContains(response, proposal.speaker.email)

        with override_config(BLIND_REVIEWERS=False):
            response = self.client.get(
                reverse(self.reverse_view_name, args=self.reverse_view_args))
            for proposal in proposals:
                self.assertContains(response, proposal.speaker.name)
示例#2
0
    def test_google_analytics(self):
        url = reverse('home')

        with override_config(GOOGLE_ANALYTICS_ACCOUNT='0'):
            response = self.client.get(url, follow=True)
            eq_(200, response.status_code)
            assert 'ga(\'create' not in response.content

        with override_config(GOOGLE_ANALYTICS_ACCOUNT='UA-99999999-9'):
            response = self.client.get(url, follow=True)
            eq_(200, response.status_code)
            assert 'ga(\'create' in response.content
示例#3
0
    def test_google_analytics(self):
        url = reverse('home')

        with override_config(GOOGLE_ANALYTICS_ACCOUNT='0'):
            r = self.client.get(url, follow=True)
            eq_(200, r.status_code)
            ok_('ga(\'create' not in r.content)

        with override_config(GOOGLE_ANALYTICS_ACCOUNT='UA-99999999-9'):
            r = self.client.get(url, follow=True)
            eq_(200, r.status_code)
            ok_('ga(\'create' in r.content)
示例#4
0
    def test_cant_send_emails_if_not_properly_configured(self) -> None:
        with override_config(EMAIL_HOST=None):
            with self.assertRaises(ImproperlyConfigured) as e:
                EmailMessage("test_campaign", "Subject", "template")
            self.assertEqual(
                str(e.exception), "Email is not enabled in this instance.",
            )

        with override_config(EMAIL_ENABLED=False):
            with self.assertRaises(ImproperlyConfigured) as e:
                EmailMessage("test_campaign", "Subject", "template")
            self.assertEqual(
                str(e.exception), "Email is not enabled in this instance.",
            )
示例#5
0
文件: bitcoin.py 项目: CCrypto/ccvpn3
    def test_rounding(self):
        """ Rounding test
        300 / 300 = 1 => 1.00000 BTC
        300 / 260 = Decimal('1.153846153846153846153846154') => 1.15385 BTC
        """
        with override_config(BTC_EUR_VALUE=300):
            backend = BitcoinBackend(dict(URL=''))
            backend.make_rpc = FakeBTCRPCNew
            backend.new_payment(self.p)
            self.assertEqual(self.p.status_message, "Please send 1.00000 BTC to TEST_ADDRESS")

        with override_config(BTC_EUR_VALUE=260):
            backend = BitcoinBackend(dict(URL=''))
            backend.make_rpc = FakeBTCRPCNew
            backend.new_payment(self.p)
            self.assertEqual(self.p.status_message, "Please send 1.15385 BTC to TEST_ADDRESS")
示例#6
0
def test_troll_parcial_dc_a_sin_consolidar(db, settings):
    with override_config(
            SCORING_MINIMO_PARA_CONSIDERAR_QUE_FISCAL_ES_TROLL=20):
        fiscal_1 = nuevo_fiscal()
        fiscal_2 = nuevo_fiscal()
        presi = CategoriaFactory()
        mesa_1 = MesaFactory(categorias=[presi])
        mesa_categoria_1 = MesaCategoria.objects.filter(
            mesa=mesa_1, categoria=presi).first()
        attach_1 = AttachmentFactory()
        identificar(attach_1, mesa_1, fiscal_1)
        identificar(attach_1, mesa_1, fiscal_2)

        refrescar_data(
            [presi, fiscal_1, fiscal_2, mesa_1, mesa_categoria_1, attach_1])

        assert not fiscal_1.troll
        assert not fiscal_2.troll

        nueva_carga(mesa_categoria_1, fiscal_1, [20, 35], Carga.TIPOS.parcial)
        nueva_carga(mesa_categoria_1, fiscal_2, [20, 35], Carga.TIPOS.parcial)

        consumir_novedades_carga()
        refrescar_data([mesa_categoria_1])

        assert mesa_categoria_1.status == MesaCategoria.STATUS.parcial_consolidada_dc
        assert Carga.objects.filter(invalidada=True).count() == 0

        aplicar_marca_troll(fiscal_2)
        consumir_novedades_carga()
        refrescar_data([mesa_categoria_1, fiscal_2])

        assert mesa_categoria_1.status == MesaCategoria.STATUS.parcial_sin_consolidar
        assert Carga.objects.filter(invalidada=True).count() == 1
示例#7
0
def test_registro_cambio_estado_troll(db, settings):
    """
    Se comprueba que un CambioEstadoTroll se genere con los valores correctos.
    """

    with override_config(
            SCORING_MINIMO_PARA_CONSIDERAR_QUE_FISCAL_ES_TROLL=320):
        fiscal = nuevo_fiscal()
        attach1 = AttachmentFactory()
        attach2 = AttachmentFactory()
        identi1 = reportar_problema_attachment(attach1, fiscal)
        identi2 = reportar_problema_attachment(attach2, fiscal)

        cantidad_cambios_estado_antes = CambioEstadoTroll.objects.count()
        aumentar_scoring_troll_identificacion(200, identi1)
        assert CambioEstadoTroll.objects.count(
        ) == cantidad_cambios_estado_antes
        assert CambioEstadoTroll.objects.filter(
            fiscal_afectado=fiscal).count() == 0
        aumentar_scoring_troll_identificacion(200, identi2)
        assert CambioEstadoTroll.objects.count(
        ) == cantidad_cambios_estado_antes + 1
        cambioEstado = CambioEstadoTroll.objects.filter(
            fiscal_afectado=fiscal).first()
        assert cambioEstado.automatico
        assert cambioEstado.actor is None
        assert cambioEstado.evento_disparador == fiscal.eventos_scoring_troll.order_by(
            'created').last()
        assert cambioEstado.troll
示例#8
0
def test_aumentar_scrolling(db, settings):
    """
    Se comprueba que al disparar eventos de aumento de scoring, el efecto sea el esperado
    """
    with override_config(
            SCORING_MINIMO_PARA_CONSIDERAR_QUE_FISCAL_ES_TROLL=400):
        fiscal1 = nuevo_fiscal()
        fiscal2 = nuevo_fiscal()
        assert fiscal1.scoring_troll() == 0
        assert fiscal2.scoring_troll() == 0

        mesa1 = MesaFactory()
        attach1 = AttachmentFactory()
        attach2 = AttachmentFactory()
        identi1 = identificar(attach1, mesa1, fiscal1)
        identi2 = identificar(attach1, mesa1, fiscal2)
        identi3 = identificar(attach2, mesa1, fiscal1)
        aumentar_scoring_troll_identificacion(100, identi1)
        aumentar_scoring_troll_identificacion(150, identi2)
        aumentar_scoring_troll_identificacion(250, identi3)
        assert fiscal1.scoring_troll() == 350
        assert fiscal2.scoring_troll() == 150
        assert not fiscal1.troll
        assert not fiscal2.troll

        attach3 = AttachmentFactory()
        identi4 = reportar_problema_attachment(attach3, fiscal1)
        aumentar_scoring_troll_identificacion(80, identi4)
        assert fiscal1.scoring_troll() == 430
        assert fiscal2.scoring_troll() == 150
        assert fiscal1.troll
        assert not fiscal2.troll
示例#9
0
    def test_notifications_enabled(self):
        """
        Tests that the notifications enabled context gets passed to the
        template.
        """
        self.authenticate()

        with override_config(PUSH_NOTIFICATIONS_ENABLED=True):
            response = self.get_application()

            self.assertTrue(response.context['notifications_enabled'])

        with override_config(PUSH_NOTIFICATIONS_ENABLED=False):
            response = self.get_application()

            self.assertFalse(response.context['notifications_enabled'])
示例#10
0
文件: tests.py 项目: 30mps/testpilot
 def test_urlintegrity_override(self):
     expected_url = 'http://example.com'
     expected_hash = '8675309'
     overrides = json.dumps({expected_url: expected_hash})
     with self.settings(URL_INTEGRITY_HASHES={expected_url: 'override me'}):
         with override_config(URL_INTEGRITY_HASHES_OVERRIDES=overrides):
             result = self.environment.globals['urlintegrity'](None, expected_url)
             self.assertEqual(result, expected_hash)
示例#11
0
 def test_urlintegrity_override(self):
     expected_url = 'http://example.com'
     expected_hash = '8675309'
     overrides = json.dumps({expected_url: expected_hash})
     with self.settings(URL_INTEGRITY_HASHES={expected_url: 'override me'}):
         with override_config(URL_INTEGRITY_HASHES_OVERRIDES=overrides):
             result = self.environment.globals['urlintegrity'](None, expected_url)
             self.assertEqual(result, expected_hash)
示例#12
0
def test_desmarca_masiva(db, settings):
    fiscal_1 = nuevo_fiscal()
    fiscal_2 = nuevo_fiscal()
    fiscal_3 = nuevo_fiscal()
    fiscal_4 = nuevo_fiscal()
    fiscal_5 = nuevo_fiscal()
    fiscal_6 = nuevo_fiscal()
    fiscal_7 = nuevo_fiscal()

    attach = AttachmentFactory()
    mesa_1 = MesaFactory()
    mesa_2 = MesaFactory()
    mesa_3 = MesaFactory()
    mesa_4 = MesaFactory()
    mesa_5 = MesaFactory()

    with override_config(
            SCORING_MINIMO_PARA_CONSIDERAR_QUE_FISCAL_ES_TROLL=200):
        identi_1 = reportar_problema_attachment(attach, fiscal_1)
        identi_2 = identificar(attach, mesa_1, fiscal_2)
        identi_3 = identificar(attach, mesa_2, fiscal_3)
        identi_4 = identificar(attach, mesa_3, fiscal_4)
        identi_5 = identificar(attach, mesa_4, fiscal_5)
        identi_6 = identificar(attach, mesa_5, fiscal_6)

        aumentar_scoring_troll_identificacion(300, identi_1)
        aumentar_scoring_troll_identificacion(400, identi_2)
        aumentar_scoring_troll_identificacion(500, identi_3)
        aumentar_scoring_troll_identificacion(100, identi_4)
        aumentar_scoring_troll_identificacion(50, identi_5)

        assert fiscal_1.troll
        assert fiscal_2.troll
        assert fiscal_3.troll
        assert not fiscal_4.troll
        assert not fiscal_5.troll
        assert not fiscal_6.troll

        Fiscal.destrolleo_masivo(fiscal_7, 450, 80)
        for fiscal in [
                fiscal_1, fiscal_2, fiscal_3, fiscal_4, fiscal_5, fiscal_6
        ]:
            fiscal.refresh_from_db()

        assert not fiscal_1.troll
        assert fiscal_1.scoring_troll() == 80
        assert not fiscal_2.troll
        assert fiscal_2.scoring_troll() == 80
        eventos = list(
            fiscal_2.eventos_scoring_troll.order_by('created').all())
        assert len(eventos) == 2
        assert eventos[1].variacion == -320
        assert fiscal_3.troll
        assert not fiscal_4.troll
        assert fiscal_4.scoring_troll() == 100
        assert not fiscal_5.troll
        assert fiscal_5.scoring_troll() == 50
        assert not fiscal_6.troll
示例#13
0
def test_scheduler_orden_distinto(db, settings):
    # Creamos 5 attachments sin identificar
    attachments = AttachmentFactory.create_batch(
        5, status=Attachment.STATUS.sin_identificar)

    c1 = CategoriaFactory(sensible=True)
    c2 = CategoriaFactory(sensible=True)
    m1 = MesaFactory(categorias=[c1])
    IdentificacionFactory(
        mesa=m1,
        status='identificada',
        source=Identificacion.SOURCES.csv,
    )
    m2 = MesaFactory(categorias=[c1, c2])
    assert MesaCategoria.objects.count() == 3
    IdentificacionFactory(
        mesa=m2,
        status='identificada',
        source=Identificacion.SOURCES.csv,
    )
    # Ambas consolidadas vía csv.

    consumir_novedades_identificacion()
    # Si hay más fotos que attachments primero se ponen las fotos,
    # hasta que haya la misma cantidad de cargas pendients.
    with override_config(COEFICIENTE_IDENTIFICACION_VS_CARGA=1):
        scheduler()
    assert ColaCargasPendientes.largo_cola() == 16

    # items = ColaCargasPendientes.objects.all().order_by('orden')
    # for i in range(16):
    #     it = items[i]
    #     print(f'{i}: ({it.orden},{it.attachment},{it.mesa_categoria})')

    # Las primeras seis tareas son de identificaciones.
    for i in range(6):
        consumir()

    assert ColaCargasPendientes.largo_cola() == 10

    # Luego vienen dos cargas...
    for i in range(2):
        consumir(False)

    assert ColaCargasPendientes.largo_cola() == 8

    # luego dos identificaciones y dos cargas, dos veces:
    for j in range(2):
        for i in range(2):
            consumir()

        for i in range(2):
            consumir(False)

    # Ya no queda nada en la cola.
    assert ColaCargasPendientes.largo_cola() == 0
    (mc, attachment) = ColaCargasPendientes.siguiente_tarea(fiscal=None)
    assert mc is None and attachment is None
示例#14
0
    def test_rounding(self):
        """ Rounding test
        300 / 300 = 1 => 1.00000 BTC
        300 / 260 = Decimal('1.153846153846153846153846154') => 1.15385 BTC
        """
        with override_config(BTC_EUR_VALUE=300):
            backend = BitcoinBackend(dict(URL=''))
            backend.make_rpc = FakeBTCRPCNew
            backend.new_payment(self.p)
            self.assertEqual(self.p.status_message,
                             "Please send 1.00000 BTC to TEST_ADDRESS")

        with override_config(BTC_EUR_VALUE=260):
            backend = BitcoinBackend(dict(URL=''))
            backend.make_rpc = FakeBTCRPCNew
            backend.new_payment(self.p)
            self.assertEqual(self.p.status_message,
                             "Please send 1.15385 BTC to TEST_ADDRESS")
示例#15
0
文件: tests.py 项目: tbille/ccvpn3
    def test_trial_fail(self):
        p = timedelta(days=1)
        with self.settings(RECAPTCHA_API='TEST'):
            with override_config(TRIAL_PERIOD_HOURS=24, TRIAL_PERIOD_MAX=2):
                bad_data = {'g-recaptcha-response': 'TOTALLY-NOT-TEST-TOKEN'}

                response = self.client.post('/account/trial', bad_data)
                self.assertRedirects(response, '/account/')

                user = User.objects.get(username='******')
                self.assertRemaining(user.vpnuser, timedelta())
示例#16
0
文件: tests.py 项目: tbille/ccvpn3
    def test_trial_refused(self):
        p = timedelta(days=1)
        u = User.objects.get(username='******')
        payment = Payment.objects.create(user=u, status='confirmed', amount=300,
                                         time=timedelta(days=30))
        payment.save()

        vu = u.vpnuser

        with override_config(TRIAL_PERIOD_HOURS=24, TRIAL_PERIOD_MAX=2):
            self.assertEqual(vu.remaining_trial_periods, 2)
            self.assertFalse(vu.can_have_trial)
    def test_blind_reviewing_means_no_notes_section(self):
        """
        Verify that the Notes section does not appear if BLIND_REVIEWERS is on.
        """
        self._add_to_reviewers_group()
        # Set this proposal's notes field to something memorable.
        self.proposal.additional_notes = "xyzzy"
        self.proposal.save()

        with override_config(BLIND_REVIEWERS=True):
            response = self.client.get(
                reverse(self.reverse_view_name, args=self.reverse_view_args))
            self.assertNotContains(response, "Notes")
            self.assertNotContains(response, self.proposal.additional_notes)
示例#18
0
def test_cargar_resultados_redirige_a_parcial_si_es_necesario_con_scheduler(
        db, fiscal_client, status, parcial):
    mesa = MesaFactory()
    a = AttachmentFactory(mesa=mesa)
    c1 = CategoriaFactory(requiere_cargas_parciales=True, sensible=True)
    with override_config(ASIGNAR_MESA_EN_EL_MOMENTO_SI_NO_HAY_COLA=False):
        m1c1 = MesaCategoriaFactory(categoria=c1,
                                    coeficiente_para_orden_de_carga=0.1,
                                    status=status,
                                    mesa=mesa)
        scheduler()
        response = fiscal_client.get(reverse('siguiente-accion'))
        assert response.status_code == HTTPStatus.FOUND
        assert response.url == reverse(
            'carga-parcial' if parcial else 'carga-total', args=[m1c1.id])
    def test_blind_reviewing_types_as_author(self):
        """Verify whether BLIND_AUTHORS setting works properly."""
        self._i_am_the_speaker_now()

        # Create a feedback comment, otherwise this test will pass
        # when it should fail.
        ProposalFeedbackFactory(proposal=self.proposal,
                                author=self.reviewer.user)

        with override_config(BLIND_AUTHORS=True):
            response = self.client.get(
                reverse(self.reverse_view_name, args=self.reverse_view_args))
            self.assertNotContains(response, self.reviewer.name)
            self.assertNotContains(response, self.reviewer.user.username)
            self.assertNotContains(response, self.reviewer.email)
示例#20
0
def test_quitar_marca_troll(db, settings):
    with override_config(
            SCORING_MINIMO_PARA_CONSIDERAR_QUE_FISCAL_ES_TROLL=300):
        fiscal = nuevo_fiscal()
        usuario_experto = nuevo_fiscal()
        assert not fiscal.troll

        # aumento el scoring x identificacion, para forzarlo a pasar a troll por scoring
        attach = AttachmentFactory()
        identi = reportar_problema_attachment(attach, fiscal)
        aumentar_scoring_troll_identificacion(400, identi)
        assert fiscal.troll

        # le saco la marca troll dejandolo en 150
        fiscal.quitar_marca_troll(usuario_experto, 150)

        # reviso status troll, scoring troll, y eventos
        assert not fiscal.troll
        assert fiscal.scoring_troll() == 150
        eventos = list(fiscal.eventos_scoring_troll.order_by('created').all())
        assert len(eventos) == 2
        primer_evento = eventos[0]
        assert primer_evento.motivo == EventoScoringTroll.MOTIVOS.identificacion_attachment_distinta_a_confirmada
        assert primer_evento.automatico
        assert primer_evento.actor is None
        assert primer_evento.fiscal_afectado == fiscal
        assert primer_evento.variacion == 400
        segundo_evento = eventos[1]
        assert segundo_evento.motivo == EventoScoringTroll.MOTIVOS.remocion_marca_troll
        assert not segundo_evento.automatico
        assert segundo_evento.actor == usuario_experto
        assert segundo_evento.fiscal_afectado == fiscal
        assert segundo_evento.variacion == -250

        # reviso cambios de estado
        cambios_estado = list(
            fiscal.cambios_estado_troll.order_by('created').all())
        assert len(cambios_estado) == 2
        primer_cambio_estado = cambios_estado[0]
        assert primer_cambio_estado.automatico
        assert primer_cambio_estado.actor is None
        assert primer_cambio_estado.evento_disparador == primer_evento
        assert primer_cambio_estado.troll
        segundo_cambio_estado = cambios_estado[1]
        assert not segundo_cambio_estado.automatico
        assert segundo_cambio_estado.actor == usuario_experto
        assert segundo_cambio_estado.evento_disparador == segundo_evento
        assert not segundo_cambio_estado.troll
    def test_reviewer_cannot_view_other_reviewers_names(self):
        """Verify that a reviewer cannot view other reviewers' names."""
        other_vote = ProposalVoteFactory(proposal=self.proposal)
        other_feedback = ProposalFeedbackFactory.create(proposal=self.proposal)

        self._add_to_reviewers_group()
        with override_config(BLIND_REVIEWERS=True):
            response = self.client.get(
                reverse(self.reverse_view_name, args=self.reverse_view_args))
            self.assertContains(response, "Anonymous")

            self.assertNotContains(response, other_vote.voter.username)
            self.assertNotContains(response, other_vote.voter.email)

            self.assertNotContains(response, other_feedback.author.username)
            self.assertNotContains(response, other_feedback.author.email)
示例#22
0
    def test_blind_reviewers_as_superuser(self):
        """Verify that superusers ignore the BLIND_REVIEWERS setting."""
        # This is not applicable for POSTing views.
        if self.http_method_name == "post":
            return
        self._become_superuser()
        proposals = self._create_proposals()
        for proposal in proposals:
            ProposalFeedbackFactory(proposal=proposal)

        with override_config(BLIND_REVIEWERS=True):
            response = self.client.get(
                reverse(self.reverse_view_name, args=self.reverse_view_args))
            self.assertContains(response, "Your superuser status")
            for proposal in proposals:
                self.assertContains(response, proposal.speaker.name)
示例#23
0
def test_orden_por_prioridad_status(db):
    statuses = [s[0] for s in settings.MC_STATUS_CHOICE]

    # creo una mesa para cada status
    mcs = []
    for s in statuses:
        mcs.append(MesaCategoriaFactory(status=s).id)
    # el factory indirectamente crea otra mesa categoria para la default
    # las borro
    MesaCategoria.objects.exclude(id__in=mcs).delete()

    shuffle(statuses)
    with override_config(PRIORIDAD_STATUS='\n'.join(statuses)):
        mesas_result = MesaCategoria.objects.anotar_prioridad_status(
            ).order_by('prioridad_status')
    assert [m.status for m in mesas_result] == statuses
示例#24
0
def test_confirmacion_carga_total_mesa_categoria_con_antitrolling(
        db, settings):
    """
    Se simula que se confirma la carga total de una MesaCategoria, usando la función de consolidación.
    Se comprueba que el efecto sobre el scoring de troll de los fiscales que hicieron cargas es el correcto.
    Nota: la funcion auxiliar nueva_carga agrega una carga de tipo total.
    """

    settings.MIN_COINCIDENCIAS_CARGAS = 2
    settings.MIN_COINCIDENCIAS_CARGAS_PROBLEMA = 2
    with override_config(
            SCORING_TROLL_PROBLEMA_MESA_CATEGORIA_CON_CARGA_CONFIRMADA=150,
            SCORING_TROLL_DESCUENTO_ACCION_CORRECTA=40):
        # escenario
        fiscal_1 = nuevo_fiscal()
        fiscal_2 = nuevo_fiscal()
        fiscal_3 = nuevo_fiscal()
        fiscal_4 = nuevo_fiscal()
        fiscal_5 = nuevo_fiscal()
        categoria = nueva_categoria(["o1", "o2", "o3"])
        mesa = MesaFactory(categorias=[categoria])
        mesa_categoria = MesaCategoria.objects.filter(mesa=mesa).first()

        # entran cuatro cargas: tres con resultados diferentes, una que marca un problema
        carga_1 = nueva_carga(mesa_categoria, fiscal_1, [32, 20, 10])
        carga_2 = nueva_carga(mesa_categoria, fiscal_2, [30, 20, 10])
        carga_3 = nueva_carga(mesa_categoria, fiscal_3, [5, 40, 15])
        carga_4 = reportar_problema_mesa_categoria(mesa_categoria, fiscal_4)
        # la consolidacion no deberia afectar el scoring de ningun fiscal, porque la mesa_categoria no queda consolidada
        consolidar_cargas(mesa_categoria)
        for fiscal in [fiscal_1, fiscal_2, fiscal_3, fiscal_4, fiscal_5]:
            fiscal.refresh_from_db()
        for fiscal in [fiscal_1, fiscal_2, fiscal_3, fiscal_4, fiscal_5]:
            assert fiscal.scoring_troll() == 0

        # entra una quinta carga, coincidente con la segunda
        carga_5 = nueva_carga(mesa_categoria, fiscal_5, [30, 20, 10])
        # ahora la mesa_categoria queda consolidada, y por lo tanto, deberia afectarse el scoring de los fiscales
        # cuya carga no coincide con la aceptada
        consolidar_cargas(mesa_categoria)
        for fiscal in [fiscal_1, fiscal_2, fiscal_3, fiscal_4, fiscal_5]:
            fiscal.refresh_from_db()
        assert fiscal_1.scoring_troll() == 2
        assert fiscal_2.scoring_troll() == -40
        assert fiscal_3.scoring_troll() == 50
        assert fiscal_4.scoring_troll() == 150
        assert fiscal_5.scoring_troll() == -40
示例#25
0
def test_efecto_confirmar_carga_mesa_categoria(db):
    """
    Se comprueba que el efecto de afectar el scoring de troll
    a partir de la confirmacion de la carga de una mesa_categoria sea el correcto.
    O sea, que se aumente el scoring de los fiscales que cargaron valores distintos a los aceptados,
    y que no aumente el scoring de los fiscales que hicieron la identificacion aceptada.
    """

    with override_config(SCORING_TROLL_DESCUENTO_ACCION_CORRECTA=30):
        # escenario
        fiscal_1 = nuevo_fiscal()
        fiscal_2 = nuevo_fiscal()
        fiscal_3 = nuevo_fiscal()
        fiscal_4 = nuevo_fiscal()
        categoria = nueva_categoria(["o1", "o2", "o3"])
        mesa = MesaFactory(categorias=[categoria])
        mesa_categoria = MesaCategoria.objects.filter(mesa=mesa).first()

        # simulo que se hacen cuatro cargas, tengo que pedir explicitamente que se actualice la firma
        # (lo hace la UI de carga)
        carga1 = nueva_carga(mesa_categoria, fiscal_1, [32, 20, 10])
        carga2 = nueva_carga(mesa_categoria, fiscal_2, [30, 20, 10])
        carga3 = nueva_carga(mesa_categoria, fiscal_3, [5, 40, 15])
        carga4 = nueva_carga(mesa_categoria, fiscal_4, [30, 20, 10])
        for carga in [carga1, carga2, carga3, carga4]:
            carga.actualizar_firma()

        # se define que las cargas de fiscal_2 y fiscal_4 son las correctas
        mesa_categoria.actualizar_status(
            MesaCategoria.STATUS.total_consolidada_dc, carga2)

        # antes de afectar el scoring troll: los cuatro fiscales tienen scoring 0
        for fiscal in [fiscal_1, fiscal_2, fiscal_3, fiscal_4]:
            assert fiscal.scoring_troll() == 0

        # hago la afectacion de scoring trol
        efecto_scoring_troll_confirmacion_carga(mesa_categoria)

        # ahora los fiscales que cargaron distinto a lo aceptado deberian tener mas scoring, el resto no
        for fiscal in [fiscal_1, fiscal_2, fiscal_3, fiscal_4]:
            fiscal.refresh_from_db()
        assert fiscal_1.scoring_troll() == 2
        assert fiscal_2.scoring_troll() == -30
        assert fiscal_3.scoring_troll() == 50
        assert fiscal_4.scoring_troll() == -30
示例#26
0
def test_efecto_ignora_cargas_incompatibles(db, caplog):
    with override_config(SCORING_TROLL_DESCUENTO_ACCION_CORRECTA=28):
        fiscal_1 = nuevo_fiscal()
        fiscal_2 = nuevo_fiscal()
        mesa_categoria = MesaCategoriaFactory()
        carga_1 = nueva_carga(mesa_categoria, fiscal_1, [30, 20, 10])
        carga_1.actualizar_firma()
        mesa_categoria.carga_testigo = carga_1
        mesa_categoria.save()

        # incompatible
        carga_2 = nueva_carga(mesa_categoria, fiscal_2, [30, 20])
        carga_2.actualizar_firma()
        efecto_scoring_troll_confirmacion_carga(mesa_categoria)

        # se ignoran las diferencias, sólo se genera evento con variación negativa para la carga testigo
        assert EventoScoringTroll.objects.count() == 1
        assert EventoScoringTroll.objects.get().variacion == -28
示例#27
0
文件: tests.py 项目: tbille/ccvpn3
    def test_grant_trial(self):
        p = timedelta(days=1)
        u = User.objects.get(username='******')
        vu = u.vpnuser

        with override_config(TRIAL_PERIOD_HOURS=24, TRIAL_PERIOD_MAX=2):
            self.assertEqual(vu.remaining_trial_periods, 2)
            self.assertTrue(vu.can_have_trial)
            vu.give_trial_period()
            self.assertRemaining(vu, p)

            self.assertEqual(vu.remaining_trial_periods, 1)
            self.assertTrue(vu.can_have_trial)
            vu.give_trial_period()
            self.assertRemaining(vu, p * 2)

            self.assertEqual(vu.remaining_trial_periods, 0)
            self.assertFalse(vu.can_have_trial)
示例#28
0
def test_scheduler_orden_estandar(db, settings):
    # Creamos 5 attachments sin identificar
    attachments = AttachmentFactory.create_batch(
        5, status=Attachment.STATUS.sin_identificar)

    c1 = CategoriaFactory(sensible=True)
    c2 = CategoriaFactory(sensible=True)
    m1 = MesaFactory(categorias=[c1])
    IdentificacionFactory(
        mesa=m1,
        status='identificada',
        source=Identificacion.SOURCES.csv,
    )
    m2 = MesaFactory(categorias=[c1, c2])
    assert MesaCategoria.objects.count() == 3
    IdentificacionFactory(
        mesa=m2,
        status='identificada',
        source=Identificacion.SOURCES.csv,
    )
    # Ambas consolidadas vía csv.

    consumir_novedades_identificacion()
    with override_config(COEFICIENTE_IDENTIFICACION_VS_CARGA=10):
        scheduler()
    assert ColaCargasPendientes.largo_cola() == 16

    # Las primeras seis tareas son de carga de votos.
    for i in range(6):
        consumir(False)

    assert ColaCargasPendientes.largo_cola() == 10

    # las siguientes diez son identificaciones.
    for i in range(10):
        consumir()

    assert ColaCargasPendientes.largo_cola() == 0

    # Ya no queda nada en la cola.
    (mc, attachment) = ColaCargasPendientes.siguiente_tarea(fiscal=None)
    assert mc is None and attachment is None
示例#29
0
    def test_retrieve_secret_setting(self):

        response = self.client.get(f"/api/instance_settings/EMAIL_HOST_PASSWORD")
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        json_response = response.json()

        self.assertEqual(json_response["key"], "EMAIL_HOST_PASSWORD")
        self.assertEqual(json_response["value"], "")  # empty values are returned
        self.assertEqual(json_response["editable"], True)
        self.assertEqual(json_response["is_secret"], True)

        # When a value is set, the value is never exposed again
        with override_config(EMAIL_HOST_PASSWORD="******"):
            response = self.client.get(f"/api/instance_settings/EMAIL_HOST_PASSWORD")
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        json_response = response.json()

        self.assertEqual(json_response["key"], "EMAIL_HOST_PASSWORD")
        self.assertEqual(json_response["value"], "*****")  # note redacted value
        self.assertEqual(json_response["is_secret"], True)
示例#30
0
def test_asociacion_attachment_con_antitrolling(db, settings):
    """
    Se simula que se asocia un Attachment a una mesa, usando la función de consolidación.
    Se comprueba que el efecto sobre el scoring de troll de los fiscales que hicieron identificaciones es el correcto.
    """

    settings.MIN_COINCIDENCIAS_IDENTIFICACION = 2
    settings.MIN_COINCIDENCIAS_IDENTIFICACION_PROBLEMA = 2
    with override_config(
            SCORING_TROLL_IDENTIFICACION_DISTINTA_A_CONFIRMADA=180,
            SCORING_TROLL_DESCUENTO_ACCION_CORRECTA=28):
        fiscal_1 = nuevo_fiscal()
        fiscal_2 = nuevo_fiscal()
        fiscal_3 = nuevo_fiscal()
        fiscal_4 = nuevo_fiscal()
        mesa_1 = MesaFactory()
        mesa_2 = MesaFactory()
        attach = AttachmentFactory()

        # Empezamos con dos identificaciones a mesas distintas
        identificar(attach, mesa_1, fiscal_1)
        identificar(attach, mesa_2, fiscal_3)
        # Hasta acá no debería asociarse la mesa, ergo no se afecta el scoring troll de ningun fiscal
        consolidar_identificaciones(attach)
        for fiscal in [fiscal_1, fiscal_2, fiscal_3, fiscal_4]:
            fiscal.refresh_from_db()
        for fiscal in [fiscal_1, fiscal_2, fiscal_3, fiscal_4]:
            assert fiscal.scoring_troll() == 0

        # se agregan dos nuevas identificaciones: el fiscal 2 identifica la misma mesa que el 1, el fiscal 4 reporta un problema
        identificar(attach, mesa_1, fiscal_2)
        reportar_problema_attachment(attach, fiscal_4)
        # ahora si deberia asociarse la mesa, y como consecuencia,
        # aumentar el scoring troll para los fiscales 3 y 4 que identificaron distinto a lo que se decidio
        consolidar_identificaciones(attach)
        for fiscal in [fiscal_1, fiscal_2, fiscal_3, fiscal_4]:
            fiscal.refresh_from_db()
        assert fiscal_1.scoring_troll() == -28
        assert fiscal_2.scoring_troll() == -28
        assert fiscal_3.scoring_troll() == 180
        assert fiscal_4.scoring_troll() == 180
示例#31
0
def test_siguiente_accion_balancea_sin_scheduler(fiscal_client,
                                                 cant_attachments, cant_mcs,
                                                 coeficiente, expect):
    attachments = AttachmentFactory.create_batch(cant_attachments,
                                                 status='sin_identificar')
    mesas = MesaFactory.create_batch(cant_mcs)
    for i in range(cant_mcs):
        attachment_identificado = AttachmentFactory(mesa=mesas[i],
                                                    status='identificada')
        MesaCategoriaFactory(mesa=mesas[i],
                             coeficiente_para_orden_de_carga=1,
                             categoria__sensible=True)

    # Como la URL de identificación pasa un id no predictible
    # y no nos importa acá saber exactamente a que instancia se relaciona la acción
    # lo que evalúo es que redirija a una url que empiece así.
    beginning = reverse(expect, args=[0])[:10]

    with override_config(COEFICIENTE_IDENTIFICACION_VS_CARGA=coeficiente):
        response = fiscal_client.get(reverse('siguiente-accion'))
    assert response.status_code == HTTPStatus.FOUND
    assert response.url.startswith(beginning)
示例#32
0
def test_efecto_consolidar_asociacion_attachment(db, settings):
    """
    Se comprueba que el efecto de afectar el scoring de troll a partir de la asociacion
    de un Attachment a una Mesa sea el correcto.
    O sea, que se aumente el scoring de los fiscales que hicieron identificaciones distintas
    a la aceptada, y que no aumente el scoring de los fiscales que hicieron la identificacion aceptada.
    """
    with override_config(
            SCORING_TROLL_IDENTIFICACION_DISTINTA_A_CONFIRMADA=180,
            SCORING_TROLL_DESCUENTO_ACCION_CORRECTA=40):
        fiscal_1 = nuevo_fiscal()
        fiscal_2 = nuevo_fiscal()
        fiscal_3 = nuevo_fiscal()
        fiscal_4 = nuevo_fiscal()
        mesa_1 = MesaFactory()
        mesa_2 = MesaFactory()
        attach = AttachmentFactory()
        # los cuatro fiscales hacen una identificacion sobre el mismo attachment
        # los fiscales 1 y 2 hacen la identificacion que se va a aceptar, a la mesa 1
        # el fiscal 3 identifica a una mesa distinta
        # el fiscal 4 reporta un problema
        identificar(attach, mesa_1, fiscal_1)
        identificar(attach, mesa_1, fiscal_2)
        identificar(attach, mesa_2, fiscal_3)
        reportar_problema_attachment(attach, fiscal_4)

        # se espera que se generen dos eventos, para los fiscales 3 y 4 que identificaron distinto
        # a la mesa que se indica como asociada al attachment
        cantidad_eventos_antes = EventoScoringTroll.objects.count()
        efecto_scoring_troll_asociacion_attachment(attach, mesa_1)

        for fiscal in [fiscal_1, fiscal_2, fiscal_3, fiscal_4]:
            fiscal.refresh_from_db()
        assert EventoScoringTroll.objects.count() == cantidad_eventos_antes + 4
        assert fiscal_1.scoring_troll() == -40
        assert fiscal_2.scoring_troll() == -40
        assert fiscal_3.scoring_troll() == 180
        assert fiscal_4.scoring_troll() == 180
示例#33
0
def test_data_fiscales_para_monitoreo_antitrolling(db):
    fiscal_1 = nuevo_fiscal()
    fiscal_2 = nuevo_fiscal()
    fiscal_3 = nuevo_fiscal()
    fiscal_4 = nuevo_fiscal()
    fiscal_5 = nuevo_fiscal()
    fiscal_6 = nuevo_fiscal()
    fiscal_7 = nuevo_fiscal()
    fiscal_8 = nuevo_fiscal()

    attach = AttachmentFactory()
    mesa_1 = MesaFactory()
    mesa_2 = MesaFactory()
    mesa_3 = MesaFactory()
    mesa_4 = MesaFactory()
    mesa_5 = MesaFactory()

    with override_config(
            SCORING_MINIMO_PARA_CONSIDERAR_QUE_FISCAL_ES_TROLL=500):
        identi_1 = reportar_problema_attachment(attach, fiscal_1)
        identi_2 = identificar(attach, mesa_1, fiscal_2)
        identi_3 = identificar(attach, mesa_2, fiscal_3)
        identi_4 = identificar(attach, mesa_3, fiscal_4)
        identi_5 = identificar(attach, mesa_4, fiscal_5)
        identi_6 = identificar(attach, mesa_5, fiscal_6)

        aumentar_scoring_troll_identificacion(300, identi_1)
        aumentar_scoring_troll_identificacion(450, identi_2)
        aumentar_scoring_troll_identificacion(520, identi_3)
        aumentar_scoring_troll_identificacion(100, identi_4)
        aumentar_scoring_troll_identificacion(51, identi_5)
        aumentar_scoring_troll_identificacion(30, identi_6)

        # sólo toma en cuenta los fiscales que ingresaron alguna vez
        for fiscal in [
                fiscal_1, fiscal_2, fiscal_3, fiscal_4, fiscal_5, fiscal_6,
                fiscal_7, fiscal_8
        ]:
            fiscal.marcar_ingreso_alguna_vez()
            fiscal.refresh_from_db()

        ParametrosAntitrolling.reset()

        rango_80 = FiscalesEnRangoScoringTroll().setRangoPorcentajes(
            80, None).set_umbrales_de_peligro(5, 7, 10)
        assert rango_80.cantidad_fiscales() == 1
        assert rango_80.porcentaje_fiscales() == 12.5
        assert rango_80.desde_scoring == 401
        assert rango_80.hasta_scoring == None
        assert rango_80.indicador_peligro(
        ) == IndicadorDePeligro.indicador_rojo

        rango_intermedio = FiscalesEnRangoScoringTroll().setRangoPorcentajes(
            30, 60).set_umbrales_de_peligro(30, 40, 50)
        assert rango_intermedio.cantidad_fiscales() == 1
        assert rango_intermedio.porcentaje_fiscales() == 12.5
        assert rango_intermedio.desde_scoring == 151
        assert rango_intermedio.hasta_scoring == 300
        assert rango_intermedio.indicador_peligro(
        ) == IndicadorDePeligro.indicador_verde

        rango_amplio = FiscalesEnRangoScoringTroll().setRangoPorcentajes(
            10, 60).set_umbrales_de_peligro(30, 40, 50)
        assert rango_amplio.cantidad_fiscales() == 3
        assert rango_amplio.porcentaje_fiscales() == 37.5
        assert rango_amplio.desde_scoring == 51
        assert rango_amplio.hasta_scoring == 300
        assert rango_amplio.indicador_peligro(
        ) == IndicadorDePeligro.indicador_amarillo

        data_troll = FiscalesTroll().set_umbrales_de_peligro(5, 10, 15)
        assert data_troll.cantidad_fiscales() == 1
        assert data_troll.porcentaje_fiscales() == 12.5
        assert data_troll.indicador_peligro(
        ) == IndicadorDePeligro.indicador_naranja

        attach_2 = AttachmentFactory()
        identi_2_2 = identificar(attach, mesa_1, fiscal_2)
        aumentar_scoring_troll_identificacion(120, identi_2_2)
        data_troll = FiscalesTroll().set_umbrales_de_peligro(5, 10, 15)
        assert data_troll.cantidad_fiscales() == 2
        assert data_troll.porcentaje_fiscales() == 25
        assert data_troll.indicador_peligro(
        ) == IndicadorDePeligro.indicador_rojo
        data_no_troll = FiscalesNoTroll(data_troll)
        assert data_no_troll.cantidad_fiscales() == 6
        assert data_no_troll.porcentaje_fiscales() == 75
    def test_override_config_as_context_manager_changes_config_value(self):
        """Assert that the context manager changes config.BOOL_VALUE."""
        with override_config(BOOL_VALUE=False):
            self.assertFalse(config.BOOL_VALUE)

        self.assertTrue(config.BOOL_VALUE)