Esempio n. 1
0
    def test_delete_all_learning_units_year_case_success_have_attribution_new_without_charge(
            self):
        learning_unit_years = self.learning_unit_year_list
        ly1 = learning_unit_years[1]
        AttributionNewFactory(
            learning_container_year=ly1.learning_container_year)
        request_factory = RequestFactory()

        request = request_factory.post(
            reverse(delete_all_learning_units_year, args=[ly1.id]))
        request.user = self.user
        setattr(request, 'session', 'session')
        setattr(request, '_messages', FallbackStorage(request))

        response = delete_all_learning_units_year(request, ly1.id)

        msg_level = [m.level for m in get_messages(request)]
        msg = [m.message for m in get_messages(request)]
        self.assertEqual(len(msg), 5)
        self.assertIn(messages.SUCCESS, msg_level)

        for y in range(4):
            self.assertFalse(
                LearningUnitYear.objects.filter(
                    pk=learning_unit_years[y].pk).exists())

        # Check redirection to identification
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, reverse('learning_units'))
    def test_add_message_suggest_caslogout(self):
        expected_msg_base_str = (
            "To logout of The Provider, please close your browser, or visit "
            "this <a href=\"/accounts/theid/logout/?{}\">link</a>.")

        # Defaults.
        req1 = self.request

        self.provider.add_message_suggest_caslogout(req1)

        expected_msg1 = Message(
            messages.INFO,
            expected_msg_base_str.format(urlencode({'next': '/test/'})),
        )
        self.assertIn(expected_msg1, get_messages(req1))

        # Custom arguments.
        req2 = self._get_request()

        self.provider.add_message_suggest_caslogout(req2,
                                                    next_page='/redir/',
                                                    level=messages.WARNING)

        expected_msg2 = Message(
            messages.WARNING,
            expected_msg_base_str.format(urlencode({'next': '/redir/'})),
        )
        self.assertIn(expected_msg2, get_messages(req2))
Esempio n. 3
0
    def test_delete_all_learning_units_year_case_error_start_date(self):
        learning_unit_years = self.learning_unit_year_list
        request_factory = RequestFactory()
        learning_unit_years[1].learning_unit.start_year = 2014
        learning_unit_years[1].learning_unit.save()

        request = request_factory.post(
            reverse(delete_all_learning_units_year,
                    args=[learning_unit_years[1].id]))
        request.user = self.user
        setattr(request, 'session', 'session')
        setattr(request, '_messages', FallbackStorage(request))

        response = delete_all_learning_units_year(request,
                                                  learning_unit_years[1].id)

        msg_level = [m.level for m in get_messages(request)]
        msg = [m.message for m in get_messages(request)]

        self.assertIn(messages.ERROR, msg_level, msg)

        for y in range(4):
            self.assertTrue(
                LearningUnitYear.objects.filter(
                    pk=learning_unit_years[y].pk).exists())

        # Check redirection to identification
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, reverse('learning_units'))
Esempio n. 4
0
def home(request):
    """User's home view after being logged in"""
    messages = get_messages(request)
    locations = db.locations.find({'user': request.user.email})
    return render(request, 'home.html', {
        'messages': get_messages(request),
        'locations': locations
    })
Esempio n. 5
0
def home(request):
    """User's home view after being logged in"""
    messages = get_messages(request)
    locations = db.locations.find({'user': request.user.email})
    return render(request, 'home.html', {
        'messages': get_messages(request),
        'locations': locations
    })
    def test_edit_profile(self):
        self.client.force_login(self.participant_user)

        response = self.client.post(
            reverse('mydata_profile'), {
                'first_name': 'Użytkownik',
                'last_name': 'Testowy',
                'email': '*****@*****.**',
                'gender': 'M',
                'school': 'Internet WWW',
                'matura_exam_year': 2038,
                'how_do_you_know_about': 'GitHub',
            })
        self.assertRedirects(response, reverse('mydata_profile'))
        messages = get_messages(response.wsgi_request)
        self.assertEqual(len(messages), 1)
        self.assertEqual(list(messages)[0].message, 'Zapisano.')

        response = self.client.post(reverse('mydata_profile_page'), {
            'profile_page': '<p>mój profil</p>',
        })
        self.assertRedirects(response, reverse('mydata_profile_page'))
        messages = get_messages(response.wsgi_request)
        self.assertEqual(len(messages), 1)
        self.assertEqual(list(messages)[0].message, 'Zapisano.')

        response = self.client.post(reverse('mydata_cover_letter'), {
            'cover_letter': '<p>mój list</p>',
        })
        self.assertRedirects(response, reverse('mydata_cover_letter'))
        messages = get_messages(response.wsgi_request)
        self.assertEqual(len(messages), 1)
        self.assertEqual(list(messages)[0].message, 'Zapisano.')

        self.participant_user.refresh_from_db()
        self.participant_user.user_profile.refresh_from_db()
        self.assertEqual(self.participant_user.first_name, 'Użytkownik')
        self.assertEqual(self.participant_user.last_name, 'Testowy')
        self.assertEqual(self.participant_user.email, '*****@*****.**')
        self.assertEqual(self.participant_user.user_profile.gender, 'M')
        self.assertEqual(self.participant_user.user_profile.school,
                         'Internet WWW')
        self.assertEqual(self.participant_user.user_profile.matura_exam_year,
                         2038)
        self.assertEqual(
            self.participant_user.user_profile.how_do_you_know_about, 'GitHub')
        self.assertHTMLEqual(self.participant_user.user_profile.profile_page,
                             '<p>mój profil</p>')
        self.assertHTMLEqual(
            self.participant_user.user_profile.camp_participation_for(
                self.year_2020).cover_letter, '<p>mój list</p>')
Esempio n. 7
0
    def test_delete_from_given_learning_unit_year_case_success(
            self, mock_render):
        learning_unit_years = self.learning_unit_year_list

        from base.views.learning_unit_deletion import delete_from_given_learning_unit_year

        request_factory = RequestFactory()

        request = request_factory.get(
            reverse(delete_from_given_learning_unit_year,
                    args=[learning_unit_years[1].id]))
        request.user = self.user

        delete_from_given_learning_unit_year(request,
                                             learning_unit_years[1].id)

        self.assertTrue(mock_render.called)
        request, template, context = mock_render.call_args[0]

        self.assertEqual(
            _('msg_warning_delete_learning_unit') % learning_unit_years[1],
            context['title'])

        # click on accept button
        request = request_factory.post(
            reverse(delete_from_given_learning_unit_year,
                    args=[learning_unit_years[1].id]))
        request.user = self.user
        setattr(request, 'session', 'session')
        setattr(request, '_messages', FallbackStorage(request))

        delete_from_given_learning_unit_year(request,
                                             learning_unit_years[1].id)

        msg_level = [m.level for m in get_messages(request)]
        msg = [m.message for m in get_messages(request)]
        self.assertEqual(len(msg), 4)
        self.assertIn(messages.SUCCESS, msg_level)

        with self.assertRaises(ObjectDoesNotExist):
            LearningUnitYear.objects.get(id=learning_unit_years[1].id)

        with self.assertRaises(ObjectDoesNotExist):
            LearningUnitYear.objects.get(id=learning_unit_years[2].id)

        with self.assertRaises(ObjectDoesNotExist):
            LearningUnitYear.objects.get(id=learning_unit_years[3].id)

        self.assertIsNotNone(
            LearningUnitYear.objects.get(id=learning_unit_years[0].id))
Esempio n. 8
0
    def test_delete_all_learning_units_year_case_error_have_attributionnew_with_charge(
            self):
        learning_unit_years = self.learning_unit_year_list
        ly1 = learning_unit_years[1]
        attrib_new_1 = AttributionNewFactory(
            learning_container_year=ly1.learning_container_year)
        learning_component_year_1 = LearningComponentYearFactory(
            learning_unit_year=ly1)
        AttributionChargeNewFactory(
            attribution=attrib_new_1,
            learning_component_year=learning_component_year_1)

        request_factory = RequestFactory()

        request = request_factory.post(
            reverse(delete_all_learning_units_year, args=[ly1.id]))
        request.user = self.user

        setattr(request, 'session', 'session')
        setattr(request, '_messages', FallbackStorage(request))

        response = delete_all_learning_units_year(request, ly1.id)

        # Get message from context
        msg = [m.message for m in get_messages(request)]
        msg_level = [m.level for m in get_messages(request)]
        self.assertEqual(len(msg), 1)
        self.assertIn(messages.ERROR, msg_level)

        # Check error message
        subtype = _('The partim') if ly1.is_partim() else _(
            'The learning unit')
        self.assertIn(
            _("%(subtype)s %(acronym)s is assigned to %(tutor)s for the year %(year)s"
              ) % {
                  'subtype': subtype,
                  'acronym': ly1.acronym,
                  'tutor': attrib_new_1.tutor,
                  'year': ly1.academic_year
              }, msg)

        # Check that record is not deleted
        self.assertTrue(LearningUnitYear.objects.filter(pk=ly1.pk).exists())

        # Check redirection to identification
        self.assertEqual(response.status_code, 302)
        self.assertEqual(
            response.url,
            reverse('learning_unit', kwargs={'learning_unit_year_id': ly1.pk}))
Esempio n. 9
0
 def process_request(self, request):
     if not hasattr(request, 'context'):
         request.context = {}
     request.context.update({
         'messages': get_messages(request),
         'DEFAULT_MESSAGE_LEVELS': DEFAULT_LEVELS,
     })
Esempio n. 10
0
def error(request):
  """
  <Purpose>
    If a OpenID/OAuth backend itself has an error(not a user or Seattle Clearinghouse's fault) 
    a user will get redirected here.  This can happen if the backend rejects the user or from
    user cancelation.

  <Arguments>
    request:
      An HTTP request object.

  <Exceptions>
    None

  <Side Effects>
    None

  <Returns>
    An HTTP response object that represents the error page.
  """
  #Retrieve information which caused an error 
  messages = get_messages(request)
  info =''
  try:
    user = _validate_and_get_geniuser(request)
    return profile(request, info, info, messages)
  except:
    return _show_login(request, 'accounts/login.html', {'messages' : messages}) 
Esempio n. 11
0
def messages(obj):
    """
    Messages to be displayed to the current session.
    """
    if isinstance(obj, BaseForm):
        return obj.non_field_errors()
    return get_messages(obj)
Esempio n. 12
0
    def test_sucesso_adicionar_permissao_jogador(self):
        """Testa adicionar permissão com sucesso"""
        self.client.login(username=self.jogador_2.user.username,
                          password=SENHA_TESTE)
        response = self.client.post(
            reverse('ladder:add_permissao_aumento_range'),
            {'jogador': self.jogador_1.id})
        self.assertEqual(response.status_code, 302)

        messages = list(get_messages(response.wsgi_request))
        self.assertEqual(len(messages), 1)
        self.assertEqual(
            str(messages[0]),
            PermissaoAumentoRange.MENSAGEM_SUCESSO_PERMISSAO_AUMENTO_RANGE)

        self.assertRedirects(
            response,
            reverse('jogadores:detalhar_jogador',
                    kwargs={'username': self.jogador_1.user.username}))

        # Verificar criação de permissão
        self.assertEqual(
            PermissaoAumentoRange.objects.filter(
                admin_permissor=self.jogador_2,
                jogador=self.jogador_1).count(), 1)
Esempio n. 13
0
    def _redirect_to_good_causes_view(self, request):
        """
        Checks if a given profile has selected any good cause to donate.
        Redirects to the good profile selection view if not.
        """
        redirect_to_good_causes = False
        try:
            UserCause.objects.get(consumer=request.user)
        except UserCause.DoesNotExist:
            redirect_to_good_causes = True

        if request.session.has_key('first_login') and \
                request.session['first_login']:
            redirect_to_good_causes = True

        if redirect_to_good_causes:
            default_good_cause = self._get_default_good_cause(request.user)

            get_messages(request).used = True  # Clean messages list.
            messages.add_message(
                request, messages.SUCCESS,
                self.causes_message % {'target': default_good_cause})

            # unflag this redirect so it doesn't happen again
            request.session['first_login'] = False

            return HttpResponseRedirect(reverse('causes_list'))
Esempio n. 14
0
 def render_to_response(self, context, **response_kwargs):
     if self.has_snippet():
         extra_content = response_kwargs['extra_content'] = response_kwargs.get('extra_content', {})
         extra_content_messages = extra_content['messages'] = {}
         for message in get_messages(self.request):
             extra_content_messages[message.tags] = force_text(message)
     return super(DefaultFormView, self).render_to_response(context, **response_kwargs)
Esempio n. 15
0
 def _adds_default_error_messages(self, request, response):
     if len(get_messages(request)) > 0:
         return
     
     if response.status_code == 400:                         
         messages.add_message(request, messages.ERROR, 
                                  "400 Bad Request - The request cannot be fulfilled due to bad syntax.")
     
     if response.status_code == 401:                         
         messages.add_message(request, messages.ERROR, 
                                  "401 Unauthorized - Authentication failed.")
     
     if response.status_code == 403:                         
         messages.add_message(request, 
                              messages.ERROR, 
                              "403 Forbidden - The request was a valid request, \
                              but the server is refusing to respond to it.")
     
     if response.status_code == 404:                         
         messages.add_message(request, messages.ERROR, 
                                  "404 Not Found - The requested resource could not be found.") 
         
     if response.status_code == 500:                         
         messages.add_message(request, messages.ERROR, 
                                  "500 Internal Server Error - Please contact the administrator.")            
Esempio n. 16
0
 def test_assign_vouchers(self):
     mommy.make_recipe("dpnk.test.UserAttendanceRecipe")
     queryset = models.UserAttendance.objects.all()
     sandwich_type = mommy.make(
         "smmapdfs.PdfSandwichType",
         template_pdf="example.pdf",
     )
     voucher_type = mommy.make(
         "VoucherType",
         name="rekola",
         teaser_img="/image.png",
         sandwich_type=sandwich_type,
     )
     vouchers = mommy.make(
         "Voucher",
         voucher_type1=voucher_type,
         token="vouchertoken",
         campaign=queryset[0].campaign,
         _quantity=2,
     )
     voucher = vouchers[0]
     self.assertEqual(voucher.user_attendance, None)
     actions.assign_vouchers(self.modeladmin, self.request, queryset)
     voucher.refresh_from_db()
     self.assertNotEqual(voucher.user_attendance.pk, None)
     message = get_messages(self.request)._queued_messages[0].message
     self.assertEqual(str(message),
                      "Přiřazeno vouchery k 1 uživatelům: rekola: 1")
Esempio n. 17
0
def error(request):
    """Error view"""
    messages = get_messages(request)
    return render(request, 'accounts/frontend/oauth/error.html', {
        'version': version,
        'messages': messages
    })
Esempio n. 18
0
def auth_error(request):
    """Error view"""
    messages = get_messages(request)
    return render(request, 'auth_error.html', {
        'version': version,
        'messages': messages
    })
Esempio n. 19
0
def messages(obj):
    """
    Messages to be displayed to the current session.
    """
    if isinstance(obj, BaseForm):
        return obj.non_field_errors()
    return get_messages(obj)
Esempio n. 20
0
    def request(self,
                method='GET',
                user=AnonymousUser(),
                url_kwargs={},
                post_data={},
                get_data={},
                view_kwargs={},
                request_meta={},
                session_data={}):
        kwargs = locals()
        del kwargs['self']
        self._request, response = self._make_request(**kwargs)

        content_disp = response._headers.get('content-disposition')
        content = None
        if hasattr(response, 'render'):
            content = remove_csrf(response.render().content.decode('utf-8'))
        elif (hasattr(response, 'content')
              and not (content_disp and 'attachment' in content_disp[1])):
            content = response.content.decode('utf-8')

        return Response(status_code=response.status_code,
                        content=content,
                        location=response.get('location', None),
                        messages=[str(m) for m in get_messages(self._request)],
                        headers=response._headers)
Esempio n. 21
0
    def request(self,
                method='GET',
                user=AnonymousUser(),
                url_kwargs={},
                post_data={},
                get_data={},
                content_type='application/json',
                request_meta={},
                view_kwargs={}):
        kwargs = locals()
        del kwargs['self']
        self._request, response = self._make_request(
            auth_func=force_authenticate, **kwargs)

        content = response.render().content.decode('utf-8')
        if 'application/json' in response._headers.get('content-type', ()):
            content = json.loads(content)
        elif 'application/xml' in response._headers.get('content-type', ()):
            content = response.data

        return Response(status_code=response.status_code,
                        content=content,
                        location=response.get('location', None),
                        messages=[str(m) for m in get_messages(self._request)],
                        headers=response._headers)
Esempio n. 22
0
def error(request):
    """Error view"""
    messages = get_messages(request)
    return render_to_response(
        'error.html',
        {'messages': messages},
        RequestContext(request))
Esempio n. 23
0
def location_admin(request):
    """admin view of all locations"""
    locations = db.locations.find()
    return render(request, 'admin.html', {
        'messages': get_messages(request),
        'locations': locations
    })
Esempio n. 24
0
def json_render(request, template=None, context=None, status='success', redirect_fallback=None):
    if not request.is_ajax() and redirect_fallback is not None:
        return redirect(redirect_fallback)

    result = context or {}

    if template is not None:
        request_context = RequestContext(request)

        # `context` not specified in RequestContext constructor since otherwise
        # the returned instance may have overriden keys, since the template
        # context processors take precedence over `context`. So, we have to
        # update after instantiation.
        request_context.update(context or {})

        result = {
            'html': render_to_string(template, request_context),
        }

    result.update({
        'status': status,
        '__messages__': [{
            'level': x.tags.split(' ')[0],
            'message': x.message,
        } for x in get_messages(request)],
    })

    return result
Esempio n. 25
0
def index(request):
    if request.user and request.user.is_authenticated and request.user.is_superuser:
        return redirect(dashboard)

    return render(request,
                  'index.html',
                  context={'messages': get_messages(request)})
Esempio n. 26
0
    def test_email_sent_when_valid_data(self):
        """Test app sends email"""
        response = self.client.post(reverse('contacto'), {
            'name': 'some user',
            'email': '*****@*****.**',
            'subject': 'Questions',
            'message': 'I have a lot of questions'
        },
                                    follow=True)

        assert response.status_code == 200, 'Should be successful'
        self.assertRedirects(response, reverse('home'))

        assert len(mail.outbox) == 1, 'should send the email'
        email = mail.outbox[0]
        assert settings.SUPERUSER_EMAIL in email.to, 'my email should be here'
        assert '*****@*****.**' in email.body, \
               'the email from the person should be here'
        assert 'Questions' in email.subject, 'the subject must appear'
        assert 'I have a lot of questions' in email.body, \
               'the text must appear'

        messages = list(get_messages(response.wsgi_request))
        assert len(messages) == 1, 'There should be one message'
        assert 'Tu mensaje ha sido enviado exitosamente.'\
               == messages[0].message, \
               'Should return a success message'
        assert messages[0].tags == 'alert-success', \
            'There should be a success message.'

        assert 'INFO' in str(self.logger), 'Should return an info log'
        assert 'Message from [email protected] sent' in str(self.logger), \
            'Log from confirmation sending'
Esempio n. 27
0
def error(request):
  """
  <Purpose>
    If a OpenID/OAuth backend itself has an error(not a user or Seattle Clearinghouse's fault) 
    a user will get redirected here.  This can happen if the backend rejects the user or from
    user cancelation.

  <Arguments>
    request:
      An HTTP request object.

  <Exceptions>
    None

  <Side Effects>
    None

  <Returns>
    An HTTP response object that represents the error page.
  """
  #Retrieve information which caused an error 
  messages = get_messages(request)
  info =''
  try:
    user = _validate_and_get_geniuser(request)
    return profile(request, info, info, messages)
  except:
    return _show_login(request, 'accounts/login.html', {'messages' : messages}) 
 def test_validar_desafio_historico_alterando_ladder_atual(self):
     """Testar se validar desafio histórico altera ladder atual"""
     # Guardar ladder atual
     ladder_atual_antes = list(PosicaoLadder.objects.all().order_by('posicao'))
     
     self.client.login(username=self.teets.user.username, password=SENHA_TESTE)
     response = self.client.post(reverse('ladder:validar_desafio_ladder', kwargs={'desafio_id': self.desafio_ladder_simples_historico.id}),
                                {'salvar': 1})
     self.assertEqual(response.status_code, 302)
     
     # Verificar ladder atual após alteração
     ladder_atual_depois = list(PosicaoLadder.objects.all().order_by('posicao'))
     
     # Ver confirmação no messages
     messages = list(get_messages(response.wsgi_request))
     self.assertEqual(len(messages), 1)
     self.assertEqual(str(messages[0]), MENSAGEM_SUCESSO_VALIDAR_DESAFIO_LADDER)
     
     # Desafio deve ter validador
     self.desafio_ladder_simples_historico = DesafioLadder.objects.get(id=self.desafio_ladder_simples_historico.id)
     self.assertEqual(self.desafio_ladder_simples_historico.admin_validador, self.teets)
     
     # Posição deve ter sido alterada na ladder atual
     self.assertNotEqual(ladder_atual_antes[0].jogador, ladder_atual_depois[0].jogador)
     
     # Ladder atual deve ser igual a ladder histórico
     for ladder_historico, ladder_atual in zip(HistoricoLadder.objects.all().order_by('posicao'), ladder_atual_depois):
         self.assertEqual(ladder_historico.posicao, ladder_atual.posicao)
         self.assertEqual(ladder_historico.jogador, ladder_atual.jogador)
Esempio n. 29
0
def login_error(request):
    """Error view"""
    messages = get_messages(request)
    return render_to_response('om_auth/error.html',
                              {'version': version,
                               'messages': messages},
                              RequestContext(request))
Esempio n. 30
0
 def test_update_mailing_coordinator(self):
     queryset = models.CompanyAdmin.objects.all()
     actions.update_mailing_coordinator(self.modeladmin, self.request,
                                        queryset)
     message = get_messages(self.request)._queued_messages[0].message
     self.assertEquals(message,
                       "Úspěšně aktualizován mailing pro 3 koordinátorů")
 def test_validar_desafio_novos_entrantes_vitoria_desafiante(self):
     """Testar validação de desafio com novos entrantes, ladder adiciona 2 posições, desafiante ganhando na frente"""
     # Verificar posições na ladder
     situacao_ladder_antes = PosicaoLadder.objects.all().order_by('posicao').values_list('jogador', 'posicao')
     self.assertNotIn(self.new.id, [jogador_posicao[0] for jogador_posicao in situacao_ladder_antes])
     self.assertNotIn(self.new_2.id, [jogador_posicao[0] for jogador_posicao in situacao_ladder_antes])
     
     self.client.login(username=self.teets.user.username, password=SENHA_TESTE)
     response = self.client.post(reverse('ladder:validar_desafio_ladder', kwargs={'desafio_id': self.desafio_ladder_novos_entrantes.id}),
                                {'salvar': 1})
     self.assertEqual(response.status_code, 302)
     
     # Ver confirmação no messages
     messages = list(get_messages(response.wsgi_request))
     self.assertEqual(len(messages), 1)
     self.assertEqual(str(messages[0]), MENSAGEM_SUCESSO_VALIDAR_DESAFIO_LADDER)
     
     # Desafio deve ter validador
     self.desafio_ladder_novos_entrantes = DesafioLadder.objects.get(id=self.desafio_ladder_novos_entrantes.id)
     self.assertEqual(self.desafio_ladder_novos_entrantes.admin_validador, self.teets)
     
     # Verificar alterações na ladder
     situacao_ladder_apos = PosicaoLadder.objects.all().order_by('posicao').values_list('jogador', 'posicao')
     
     self.assertIn((self.new.id, 11), situacao_ladder_apos)
     self.assertIn((self.new_2.id, 12), situacao_ladder_apos)
     
     # Jogadores abaixo no ranking permanecem inalterados
     for situacao_antes, situacao_apos in zip(situacao_ladder_antes[:10], situacao_ladder_apos[:10]):
         self.assertEqual(situacao_antes, situacao_apos)
     
     # A ladder deve possuir um jogador a mais
     self.assertTrue(len(situacao_ladder_antes) + 2 == len(situacao_ladder_apos))
Esempio n. 32
0
def location_admin(request):
    """admin view of all locations"""
    locations = db.locations.find()
    return render(request, 'admin.html', {
        'messages': get_messages(request),
        'locations': locations
    })
 def test_validar_desafio_sucesso_historico(self):
     """Testa validação de um desafio para ladder histórico com sucesso"""
     # Verificar posições na ladder
     situacao_ladder_antes = HistoricoLadder.objects.filter(ano=self.ano, mes=self.mes).order_by('posicao').values_list('jogador', 'posicao')
     self.assertIn((self.teets.id, 1), situacao_ladder_antes)
     self.assertIn((self.saraiva.id, 2), situacao_ladder_antes)
     self.assertIn((self.sena.id, 3), situacao_ladder_antes)
     self.assertIn((self.mad.id, 4), situacao_ladder_antes)
     
     self.client.login(username=self.teets.user.username, password=SENHA_TESTE)
     response = self.client.post(reverse('ladder:validar_desafio_ladder', kwargs={'desafio_id': self.desafio_ladder_simples_historico.id}),
                                {'salvar': 1})
     self.assertEqual(response.status_code, 302)
     
     # Ver confirmação no messages
     messages = list(get_messages(response.wsgi_request))
     self.assertEqual(len(messages), 1)
     self.assertEqual(str(messages[0]), MENSAGEM_SUCESSO_VALIDAR_DESAFIO_LADDER)
     
     # Desafio deve ter validador
     self.desafio_ladder_simples_historico = DesafioLadder.objects.get(id=self.desafio_ladder_simples_historico.id)
     self.assertEqual(self.desafio_ladder_simples_historico.admin_validador, self.teets)
     
     # Verificar alterações na ladder
     situacao_ladder_apos = HistoricoLadder.objects.filter(ano=self.ano, mes=self.mes).order_by('posicao').values_list('jogador', 'posicao')
     self.assertIn((self.sena.id, 1), situacao_ladder_apos)
     self.assertIn((self.teets.id, 2), situacao_ladder_apos)
     self.assertIn((self.saraiva.id, 3), situacao_ladder_apos)
     
     # Jogadores abaixo no ranking permanecem inalterados
     for situacao_antes, situacao_apos in zip(situacao_ladder_antes[3:], situacao_ladder_apos[3:]):
         self.assertEqual(situacao_antes, situacao_apos)
     
     # A ladder deve possuir a mesma quantidade de jogadores
     self.assertEqual(len(situacao_ladder_antes), len(situacao_ladder_apos))
Esempio n. 34
0
def login(request):
    """Login View"""
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('home'))
    else:
        messages = get_messages(request)
        return render(request, 'login.html', {'messages': messages})
    def _assert_solution_upload_accessible(self, can_edit=True):
        response = self.client.get(reverse('workshop_my_solution', args=[self.workshop.year.pk, self.workshop.name]))
        self.assertEqual(response.status_code, 200)
        initial_forms = response.context['form_attachments'].management_form.initial['INITIAL_FORMS']

        with mock.patch('wwwapp.models.Solution.save', autospec=True, side_effect=Solution.save) as save_solution:
            with mock.patch('wwwapp.models.SolutionFile.save', autospec=True, side_effect=SolutionFile.save) as save_solution_file:
                response = self.client.post(reverse('workshop_my_solution', args=[self.workshop.year.pk, self.workshop.name]), {
                    'message': 'To są testy',
                    'files-INITIAL_FORMS': str(initial_forms),
                    'files-TOTAL_FORMS': '2',
                    'files-0-id': '',
                    'files-0-file': SimpleUploadedFile('solution.pdf', os.urandom(1024 * 1024)),
                    'files-0-DELETE': '',
                    'files-1-id': '',
                    'files-1-file': SimpleUploadedFile('attachment.zip', os.urandom(1024 * 1024)),
                    'files-1-DELETE': '',
                })
                if can_edit:
                    self.assertRedirects(response, reverse('workshop_my_solution', args=[self.workshop.year.pk, self.workshop.name]))
                    messages = get_messages(response.wsgi_request)
                    self.assertEqual(len(messages), 1)
                    self.assertEqual(list(messages)[0].message, 'Zapisano.')
                    save_solution.assert_called()
                    save_solution_file.assert_called()
                else:
                    self.assertEqual(response.status_code, 403)
                    save_solution.assert_not_called()
                    save_solution_file.assert_not_called()
Esempio n. 36
0
def login(request):
    """Login View"""
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('home'))
    else:
        messages = get_messages(request)
        return render(request, 'login.html', {'messages': messages})
Esempio n. 37
0
def error(request):
    """Error view"""
    messages = get_messages(request)
    return render_to_response('error.html', {
        'version': version,
        'messages': messages
    }, RequestContext(request))
Esempio n. 38
0
 def test_touch_items_team(self):
     queryset = models.Team.objects.all()
     actions.touch_items(self.modeladmin, self.request, queryset)
     message = get_messages(self.request)._queued_messages[0].message
     self.assertEquals(
         str(message),
         "Obnova 4 denormalizovaných položek byla zadána ke zpracování")
Esempio n. 39
0
def login_error(request):
    messages = get_messages(request)
    return render_to_response(
        'login.html',
        {"error": messages},
        RequestContext(request)
    )
    def test_validar_desafio_novo_entrante_vitoria(self):
        """Testa validação de desafio com novo entrante derrotando último da ladder"""
        # Verificar posições na ladder
        situacao_ladder_antes = PosicaoLadder.objects.all().order_by('posicao').values_list('jogador', 'posicao')
        self.assertIn((self.tiovsky.id, 10), situacao_ladder_antes)
        
        self.client.login(username=self.teets.user.username, password=SENHA_TESTE)
        response = self.client.post(reverse('ladder:validar_desafio_ladder', kwargs={'desafio_id': self.desafio_ladder_novo_entrante.id}),
                                   {'salvar': 1})
        self.assertEqual(response.status_code, 302)
#         self.assertRedirects(response, reverse('ladder:detalhar_ladder_atual'))
        
        # Ver confirmação no messages
        messages = list(get_messages(response.wsgi_request))
        self.assertEqual(len(messages), 1)
        self.assertEqual(str(messages[0]), MENSAGEM_SUCESSO_VALIDAR_DESAFIO_LADDER)
        
        # Desafio deve ter validador
        self.desafio_ladder_novo_entrante = DesafioLadder.objects.get(id=self.desafio_ladder_novo_entrante.id)
        self.assertEqual(self.desafio_ladder_novo_entrante.admin_validador, self.teets)
        
        # Verificar alterações na ladder
        situacao_ladder_apos = PosicaoLadder.objects.all().order_by('posicao').values_list('jogador', 'posicao')
        self.assertIn((self.new.id, 10), situacao_ladder_apos)
        self.assertIn((self.tiovsky.id, 11), situacao_ladder_apos)
        
        # Jogadores abaixo no ranking permanecem inalterados
        for situacao_antes, situacao_apos in zip(situacao_ladder_antes[:9], situacao_ladder_apos[:9]):
            self.assertEqual(situacao_antes, situacao_apos)
        
        # A ladder deve possuir um jogador a mais
        self.assertTrue(len(situacao_ladder_antes) + 1 == len(situacao_ladder_apos))
    def test_solution_delete_file(self):
        with freeze_time('2020-01-01 00:00:00'):
            initial_solution = Solution.objects.create(workshop_participant=WorkshopParticipant.objects.get(workshop=self.workshop, camp_participation__user_profile=self.participant_user.user_profile), message='To są testy')
            initial_solution_file = initial_solution.files.create(file=SimpleUploadedFile('solution.pdf', os.urandom(1024 * 1024)))
        self.assertEqual(SolutionFile.objects.filter(solution=initial_solution).count(), 1)
        self.assertEqual(SolutionFile.all_objects.filter(solution=initial_solution).count(), 1)

        self.client.force_login(self.participant_user)
        response = self.client.post(reverse('workshop_my_solution', args=[self.workshop.year.pk, self.workshop.name]), {
            'message': 'To są testy',
            'files-INITIAL_FORMS': '1',
            'files-TOTAL_FORMS': '1',
            'files-0-id': initial_solution_file.id,
            'files-0-DELETE': 'on',
        })
        self.assertRedirects(response, reverse('workshop_my_solution', args=[self.workshop.year.pk, self.workshop.name]))
        messages = get_messages(response.wsgi_request)
        self.assertEqual(len(messages), 1)
        self.assertEqual(list(messages)[0].message, 'Zapisano.')

        solution = Solution.objects.get(workshop_participant=WorkshopParticipant.objects.get(workshop=self.workshop, camp_participation__user_profile=self.participant_user.user_profile))
        self.assertEqual(solution.pk, initial_solution.pk)
        self.assertEqual(solution.message, 'To są testy')
        self.assertEqual(solution.last_changed, datetime.datetime(2020, 5, 1, 12, 00, 00, tzinfo=pytz.utc))  # even though the message has not changed, the attachments did
        files = solution.files.all()
        self.assertEqual(len(files), 0)

        self.assertEqual(SolutionFile.objects.filter(solution=initial_solution).count(), 0)
        self.assertEqual(SolutionFile.all_objects.filter(solution=initial_solution).count(), 1)
    def test_erro_cancelar_remocao_desafio_posterior_impossivel(self):
        """Testa cancelar remoção com desafio de jogador que se torna impossível"""
        # Gerar desafio entre o 2 + LIMITE_POSICOES_DESAFIO e o 2
        jogador_limite = PosicaoLadder.objects.get(
            posicao=(2 + DesafioLadder.LIMITE_POSICOES_DESAFIO)).jogador
        desafio_ladder = criar_desafio_ladder_simples_teste(
            jogador_limite, self.saraiva, 1, 3, timezone.localtime(), False,
            self.saraiva)
        validar_desafio_ladder_teste(desafio_ladder, self.teets)

        self.client.login(username=self.teets.user.username,
                          password=SENHA_TESTE)
        response = self.client.post(
            reverse('ladder:cancelar_remocao_jogador_ladder',
                    kwargs={'remocao_id': self.remocao_admin.id}),
            {'salvar': 1})
        self.assertEqual(response.status_code, 200)

        # Verificar mensagens
        messages = list(get_messages(response.wsgi_request))
        self.assertEqual(len(messages), 1)
        #         self.assertEqual(str(messages[0]), f'Remoção não pode ser cancelada')
        regex = re.escape(f'Desafio Ladder {desafio_ladder.id}: ') + r'.+'
        self.assertRegex(str(messages[0]), regex)

        self.assertTrue(
            RemocaoJogador.objects.filter(id=self.remocao_admin.id).exists())
Esempio n. 43
0
    def test_email_sent_when_invalid_data(self):
        """Test app wont send email"""
        response = self.client.post(reverse('contacto'), {
            'name': 'some user',
            'email': 'someuser',
            'subject': 'Questions',
            'message': 'I have a lot of questions'
        },
                                    follow=True)

        assert response.status_code == 200, 'Should be successful'

        assert len(mail.outbox) == 0, 'should send the email'

        messages = list(get_messages(response.wsgi_request))
        assert len(messages) == 1, 'There should be one message'
        assert 'Ha habido un error y tu mensaje no ha sido enviado.'\
               == messages[0].message, \
               'Should return a success message'
        assert messages[0].tags == 'alert-danger', \
            'There should be an error message.'

        assert 'ERROR' in str(self.logger), 'Should return an info log'
        assert 'Error trying to send message from someuser' in \
            str(self.logger), 'Log from error in sending'
Esempio n. 44
0
def messages(request):
    """
    Returns a lazy 'messages' context variable.
    """
    return {
        'messages': get_messages(request),
        'DEFAULT_MESSAGE_LEVELS': DEFAULT_LEVELS,
    }
Esempio n. 45
0
def sorted_messages(request):
    """ das Django-Messages-Framework laesst in Kombination mit dem Template-System
        keine Moeglichkeit, vernueftig die Messages nach Loglevel gruppiert auszugeben.
        Deshalb sortieren wir hier die Messages vor. """
    msgs = defaultdict(list)
    for msg in get_messages(request):
        msgs["%s_messages" % msg.tags].append(msg)
    return msgs
Esempio n. 46
0
def login_error(request):
    """
    Return an error page for errors during login
    
    :Rest Types: ``GET``
    :URL: ``^login/error/$``
    """
    messages = get_messages(request)
    return render_to_response('app_auth/error.html', {'messages': messages}, RequestContext(request))
    def process_response(self, request, response):
        if request.is_ajax() and isinstance(response, TemplateResponse):

            messages_html = render_to_string('front/messages.html',
                                             {'messages': get_messages(request)})

            response.content = smart_text(response.content) + smart_text(messages_html)

        return response
Esempio n. 48
0
        def _wrapped_view(request, *args, **kwargs):

            #Don't cache pages that have unique messages
            messages = get_messages(request)
            if len(messages) > 0 or test_func(request.user):

                return view_func(request, *args, **kwargs)

            else:
                return cache_page(cache_duration)(view_func)(request, *args, **kwargs) 
Esempio n. 49
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     is_rietveld = view_func.__module__.startswith("codereview")
     user = request.user
     if is_rietveld and user.is_anonymous():
         # Pre-fetch messages before changing request.user so that
         # they're cached (for Django 1.2.5 and above).
         request._messages = get_messages(request)
         request.user = None
     response = view_func(request, *view_args, **view_kwargs)
     request.user = user
     return response
Esempio n. 50
0
    def process_response(self, request, response):
        if (
            request.is_ajax()
            and isinstance(response, TemplateResponse)
            and response.template_name[0] != "front/messages.html"
        ):
            messages_html = render_to_string("front/messages.html", {"messages": get_messages(request)})

            response.content = smart_text(response.content) + smart_text(messages_html)

        return response
Esempio n. 51
0
 def configure_accounts(self, request):
     logger.info(self.model._meta)
     logger.info(self.model._meta.app_label)
     return TemplateResponse(
         request,
         'admin/location/configure.html', {
             'messages': get_messages(request),
             'title': 'Configure Accounts',
             'domain': Site.objects.get_current().domain
         }
     )
Esempio n. 52
0
 def horizon_message_already_queued(_message):
     _message = force_text(_message)
     if request.is_ajax():
         for tag, msg, extra in request.horizon['async_messages']:
             if _message == msg:
                 return True
     else:
         for msg in msg_api.get_messages(request):
             if msg.message == _message:
                 return True
     return False
Esempio n. 53
0
def status(request):
    """In order to promote (efficient) caching on (low-powered)
    distributed devices, we do not include ANY user data in our
    templates.  Instead, an AJAX request is made to download user
    data, and javascript used to update the page.

    This view is the view providing the json blob of user information,
    for each page view on the distributed server.

    Besides basic user data, we also provide access to the
    Django message system through this API, again to promote
    caching by excluding any dynamic information from the server-generated
    templates.
    """
    # Build a list of messages to pass to the user.
    #   Iterating over the messages removes them from the
    #   session storage, thus they only appear once.
    message_dicts = []
    for message in get_messages(request):
        # Make sure to escape strings not marked as safe.
        # Note: this duplicates a bit of Django template logic.
        msg_txt = message.message
        if not (isinstance(msg_txt, SafeString) or isinstance(msg_txt, SafeUnicode)):
            msg_txt = cgi.escape(unicode(msg_txt))

        message_dicts.append({
            "tags": message.tags,
            "text": msg_txt,
        })

    # Default data
    data = {
        "is_logged_in": request.is_logged_in,
        "registered": request.session["registered"],
        "is_admin": request.is_admin,
        "is_django_user": request.is_django_user,
        "points": 0,
        "current_language": request.session[settings.LANGUAGE_COOKIE_NAME],
        "messages": message_dicts,
    }
    # Override properties using facility data
    if "facility_user" in request.session:  # Facility user
        user = request.session["facility_user"]
        data["is_logged_in"] = True
        data["username"] = user.get_name()
        if "points" not in request.session:
            request.session["points"] = compute_total_points(user)
        data["points"] = request.session["points"]
    # Override data using django data
    if request.user.is_authenticated():  # Django user
        data["is_logged_in"] = True
        data["username"] = request.user.username

    return JsonResponse(data)
Esempio n. 54
0
def __populate_response_args(request, *_arg):
    """
    Dodaje argumenty związane z kontekstem, zawierającym informacje o zalogowanym
    użytkowniku, komunikatami z django.contrib.messages oraz oryginalnym requestem.
    """
    arg = []
    for x in _arg:
        arg.append(x)
    arg.append(RequestContext(request))
    arg[1]['messages'] = get_messages(request)
    arg[1]['request'] = request
    return arg
    def render(self, request, instance, **kwargs):
        # While overwriting get_context() would be sufficient here, this is rather easier to understand.
        # Implemented a custom rendering function instead.

        # The process_form() function is designed with Django CMS in mind,
        # and responds to both the GET and POST request.
        context = process_form(request, instance.form_definition, {}, **{_disable_redirection: True})
        context['messages'] = get_messages(request)  # No matter what, because the template needs it.

        # Render the plugin
        render_template = self.get_render_template(request, instance, **kwargs)
        return self.render_to_string(request, render_template, context)
def notifications(request):
    """
    Returns a lazy 'messages' context variable.
    """

    return_dict = {}

    return_dict['notifications'] = [ m.message for m in get_messages(request)]

    if hasattr(request, '_notifications_count'):
    	return_dict['notifications_count'] = request._notifications_count

    return return_dict
Esempio n. 57
0
def get_messages_for_api_calls(request):
    """
    Re-usable function that returns a list of messages to be used by API calls.
    """
    message_lists = []
    for message in get_messages(request):
        # Make sure to escape strings not marked as safe.
        # Note: this duplicates a bit of Django template logic.
        msg_txt = message.message
        if not (isinstance(msg_txt, SafeString) or isinstance(msg_txt, SafeUnicode)):
            msg_txt = cgi.escape(unicode(msg_txt))
        msg_type = message.tags
        message_lists.append({msg_type: msg_txt})
    return message_lists
def core(request):
    # If all messages have "link-dialog" tag then adding ``all_hidden``
    # attribute
    messages = get_messages(request)
    if messages:
        messages.all_hidden = reduce(and_, ["link-dialog" in m.tags for m in messages])

    return {
        "REV": settings.REV,
        "SITE_URL": "http://%s" % Site.objects.get_current().domain,
        "campaign_cid": request.campaign_id,
        "campaign_sid": request.sid,
        "affiliate": request.affiliate,
        "messages": messages,
    }
Esempio n. 59
0
    def delete_detail(self, request, *args, **kwargs):
        """
        DELETE handler. Only supports deletion of single items at the moment.
        """
        instance = self.detail_object_or_404()

        if not self.modelview.deletion_allowed(request, instance):
            raise APIException(status=httplib.FORBIDDEN, data={
                'messages': [{
                    'message': '%s' % msg,
                    'tags': msg.tags,
                } for msg in get_messages(request)],
            })

        instance.delete()
        return self.serialize_response({}, status=httplib.NO_CONTENT)
Esempio n. 60
0
def assert_has_message(response, message, level=None):
    messages = get_messages(response.wsgi_request)
    found = False
    for msg in messages:
        if message in str(msg):
            if level and level != msg.level:
                error = (
                    'Message containing "%s" was set '
                    "but didn't have level %s (it had %s)"
                )
                raise AssertionError(error % (message, level, message.level))
            found = True

    if not found:
        raise AssertionError(
            'Message containing "%s" was not set during the request' % message
        )