def test_store(self):
     self.request._messages = default_storage(self.request)
     self.request._messages.level = DEBUG
     add_message(self.request, STORED_ERROR, "an SOS to the world ☢")
     add_message(self.request, DEBUG, "this won't be persisted ☢")
     self.assertEqual(len(get_messages(self.request)), 2)
     self.assertEqual(len(self.backend.archive_list(self.user)), 1)
Exemplo n.º 2
0
def fake_request(path='/', method='GET', user=None, extra={}):
    params = {
        'REQUEST_METHOD': method,
        'PATH_INFO': path,
        'wsgi.input': StringIO()
    }
    params.update(extra)

    req = WSGIRequest(params)

    req.user = user or AnonymousUser()
    req.user.id = ''
    req.user.username = '******'
    req.user.first_name = 'mock_user'
    req.user.is_superuser = True
    req.user.groups.all = lambda: [GroupFactory(id=1)]

    req.build_absolute_uri = lambda x=None: '/'

    # for sessions middleware
    req.session = build_fake_session()

    # for messages middleware
    req._messages = default_storage(req)

    req.get_host = lambda x=None: 'localhost'

    return req
Exemplo n.º 3
0
    def assertMessageCount(self, **kwargs):
        """
        Asserts that the specified number of messages have been attached
        for various message types. Usage would look like
        ``self.assertMessageCount(success=1)``.
        """
        temp_req = self.client.request(**{"wsgi.input": None})
        temp_req.COOKIES = self.client.cookies
        storage = default_storage(temp_req)
        messages = []
        # To gain early access to the messages we have to decode the
        # cookie on the test client.
        if "messages" in self.client.cookies:
            messages = storage._decode(self.client.cookies["messages"].value)

        # If we don't have messages and we don't expect messages, we're done.
        if not any(kwargs.values()) and not messages:
            return

        # If we expected messages and have none, that's a problem.
        if any(kwargs.values()) and not messages:
            error_msg = "Messages were expected, but none were set."
            assert 0 == sum(kwargs.values()), error_msg

        # Otherwise, make sure we got the expected messages.
        for msg_type, count in kwargs.items():
            msgs = [m.message for m in messages if msg_type in m.tags]
            assert len(msgs) == count, "%s messages not as expected: %s" % (msg_type.title(), ", ".join(msgs))
Exemplo n.º 4
0
 def test_mission_proba(self):
     for i in range(5):
         # Create enough data to allow learn model to exist
         a = create_lead()
         a.state="WON"
         a.save()
     lead = Lead.objects.get(id=1)
     lead.state="LOST"  # Need more than one target class to build a solver
     lead.save()
     f = RequestFactory()
     request = f.get("/")
     request.user = User.objects.get(id=1)
     request.session = {}
     request._messages = default_storage(request)
     lead = create_lead()
     lead.state = "OFFER_SENT"
     lead.save()
     postSaveLead(request, lead, [], sync=True)
     mission = lead.mission_set.all()[0]
     if leads_learn.HAVE_SCIKIT:
         self.assertEqual(mission.probability, lead.stateproba_set.get(state="WON").score)
     else:
         self.assertEqual(mission.probability, 50)
     lead.state = "WON"
     lead.save()
     postSaveLead(request, lead, [], sync=True)
     mission = Mission.objects.get(id=mission.id)  # reload it
     self.assertEqual(mission.probability, 100)
Exemplo n.º 5
0
    def check_attribute_change_action(self, klass, factory,
         admin_action, attr, initial, final,
         factory_extra=None):
        if factory_extra is None:
            d = {}
        else:
            d = factory_extra

        d.update({attr: initial})
        r0 = factory(**d)
        r0.save()
        r1 = factory(**d)
        r1.save()
        rs = klass.objects.filter(
            id__in=[r0.id, r1.id])

        req = self.factory.post('/', {})
        req.user = self.user
        req._messages = default_storage(req)

        result = admin_action(req, rs)
        self.assertIsNone(result)
        rs = klass.objects.filter(id__in=[
            r0.id, r1.id
        ])
        for r in rs:
            self.assertEqual(getattr(r, attr), final)
Exemplo n.º 6
0
    def test_tag_all(self):
        req = self.factory.post('/', {})
        req.user = self.user
        factories.FoiRequestFactory(site=self.site)
        factories.FoiRequestFactory(site=self.site)
        frs = FoiRequest.objects.all()[:2]
        result = self.request_admin.tag_all(req, frs)
        self.assertEqual(result.status_code, 200)
        self.assertEqual(frs[0].tags.count(), 0)
        self.assertEqual(frs[1].tags.count(), 0)

        req = self.factory.post('/', {'tags': 'one, two'})
        req.user = self.user
        req._messages = default_storage(req)

        frs = FoiRequest.objects.filter(
            id__in=[frs[0].id, frs[1].id])

        result = self.request_admin.tag_all(req, frs)
        self.assertIsNone(result)
        frs = list(frs)
        frs[0] = FoiRequest.objects.get(id=frs[0].id)
        frs[1] = FoiRequest.objects.get(id=frs[1].id)
        self.assertEqual(frs[0].tags.count(), 2)
        self.assertEqual(frs[1].tags.count(), 2)
        self.assertEqual(set([t.name for t in frs[0].tags.all()]), set(['one', 'two']))
Exemplo n.º 7
0
    def test_mark_same_as(self):
        req = self.factory.post('/', {})
        req.user = self.user
        factories.FoiRequestFactory(site=self.site)
        factories.FoiRequestFactory(site=self.site)
        frs = FoiRequest.objects.all()[:2]
        result = self.request_admin.mark_same_as(req, frs)
        self.assertEqual(result.status_code, 200)

        same_as = factories.FoiRequestFactory(site=self.site)
        same_as.save()

        req = self.factory.post('/', {'req_id': same_as.id})
        req.user = self.user
        req._messages = default_storage(req)

        frs = FoiRequest.objects.filter(
            id__in=[frs[0].id, frs[1].id])

        result = self.request_admin.mark_same_as(req, frs)
        self.assertIsNone(result)
        same_as = FoiRequest.objects.get(id=same_as.id)
        self.assertEqual(same_as.same_as_count, 2)
        frs = list(frs)
        frs[0] = FoiRequest.objects.get(id=frs[0].id)
        frs[1] = FoiRequest.objects.get(id=frs[1].id)
        self.assertEqual(frs[0].same_as, same_as)
        self.assertEqual(frs[1].same_as, same_as)
Exemplo n.º 8
0
    def test_redeliver(self):
        foireq = FoiRequest.objects.all()[0]
        dm = factories.DeferredMessageFactory()
        dm.save()
        req = self.factory.post('/', {})
        req.user = self.user

        result = self.admin.redeliver(req,
                DeferredMessage.objects.filter(
                    id__in=[dm.id]))
        self.assertEqual(result.status_code, 200)

        req = self.factory.post('/', {
            'req_id': foireq.id
        })
        req.user = self.user
        req._messages = default_storage(req)

        result = self.admin.redeliver(req,
                DeferredMessage.objects.filter(
                    id__in=[dm.id]))
        self.assertIsNone(result)

        dm = DeferredMessage.objects.get(id=dm.id)
        self.assertEqual(dm.request, foireq)
 def test_store(self):
     self.request._messages = default_storage(self.request)
     self.request._messages.level = DEBUG
     add_message(self.request, STORED_ERROR, "an SOS to the world ☢")
     add_message(self.request, DEBUG, "this won't be persisted ☢")
     storage = get_messages(self.request)
     self.assertEqual(len(storage), 2)
     self.assertEqual(MessageArchive.objects.filter(user=self.user).count(), 1)
Exemplo n.º 10
0
 def get_request(self):
     request = HttpRequest()
     request.META['REMOTE_ADDR'] = '1.2.3.4'
     request.method = 'POST'
     request.session = SessionStore()
     request._messages = default_storage(request)
     request.user = AnonymousUser()
     return request
 def test_expire(self):
     self.request._messages = default_storage(self.request)
     add_message(self.request, STORED_ERROR, "an SOS to the world ☢")
     ma = MessageArchive.objects.all()[0]
     ma.message.date = now() - timedelta(days=365)
     ma.message.save()
     inbox = Inbox.objects.create(user=ma.user, message=ma.message)
     self.assertTrue(inbox.expired())
 def test_store_anonymous(self):
     self.request.user = mock.MagicMock(wraps=self.user)
     self.request.user.is_anonymous.return_value = True
     self.request.user.is_authenticated.return_value = False
     self.request._messages = default_storage(self.request)
     add_message(self.request, STORED_ERROR, "an SOS to the world ☢")
     add_message(self.request, ERROR, "this error won't be persisted ☢")
     storage = get_messages(self.request)
     self.assertEqual(len(storage), 2)
Exemplo n.º 13
0
    def test_update_message_mixin(self):
        request = self.factory.post('/fake-path', {
            'username': '******',
            'email': '*****@*****.**',
        })
        request._messages = default_storage(request)
        UpdateMessageView.as_view()(request)

        self.assertEqual(len(get_messages(request)), 1)
Exemplo n.º 14
0
def get_level(request):
    """
    Returns the minimum level of messages to be recorded.

    The default level is the ``MESSAGE_LEVEL`` setting. If this is not found,
    the ``INFO`` level is used.
    """
    storage = getattr(request, '_messages', default_storage(request))
    return storage.level
Exemplo n.º 15
0
 def test_too_few_lead(self):
     lead = create_lead()
     f = RequestFactory()
     request = f.get("/")
     request.user = User.objects.get(id=1)
     request.session = {}
     request._messages = default_storage(request)
     lead = create_lead()
     postSaveLead(request, lead, [], sync=True)  # Learn model cannot exist, but it should not raise error
Exemplo n.º 16
0
    def setUp(self):

        assert settings.DEBUG == True

        django.utils.translation.activate("en") # to test for error messages, just in case...

        reset_zodb_structure()
        create_game_instance(game_instance_id=TEST_GAME_INSTANCE_ID,
                             creator_login="******",
                             skip_randomizations=True)  # handy to test stuffs

        try:

            test_http_host = "localhost:80"

            self.client = Client()
            self.factory = RequestMock(HTTP_HOST=test_http_host)

            self.request = self.factory.get(HOME_URL)
            assert self.request.user
            assert self.request.datamanager.user.datamanager.request # double linking
            assert self.request.session
            assert self.request._messages is not None
            assert self.request.datamanager

            # we mimic messages middleware
            from django.contrib.messages.storage import default_storage
            self.request._messages = default_storage(self.request)

            self.dm = self.request.datamanager
            assert self.dm.is_initialized
            assert self.dm.connection

            self.dm.clear_all_event_stats()
            self.dm.check_database_coherency() # important
            assert self.dm.get_event_count("BASE_CHECK_DB_COHERENCY_PUBLIC_CALLED") == 1 # no bypassing because of wrong override

            self.dm.set_game_state(True)
            self.dm.set_activated_game_views(self.dm.get_activable_views().keys()) # QUICK ACCESS FIXTURE

            self.dm.clear_all_event_stats()

            #self.default_player = self.dm.get_character_usernames()[0]
            #self._set_user(self.TEST_LOGIN)

            self.initial_msg_sent_length = len(self.dm.get_all_dispatched_messages())
            self.initial_msg_queue_length = len(self.dm.get_all_queued_messages())

            # comment this to have eclipse's autocompletion to work for datamanager anyway
            self.dm = AutoCheckingDM(self.dm) # protection against uncommitted, pending changes

            # NO NEED TO COMMIT - transaction watcher should do it all #

        except Exception, e:
            print(">>>>>>>>>", repr(e))
            self.tearDown(check=False) # cleanup of connection
            raise
Exemplo n.º 17
0
 def test_create_network_alias_message(self):
     url = reverse('horizon:project:networking:alias:networks:create')
     response = self.client.post(url, self.form_data)
     storage = default_storage(response.request)
     message_cookie = response.cookies['messages'].value
     messages = [m.message for m in storage._decode(message_cookie)]
     msg = "Successfully created network alias: %s"
     self.assertIn(msg % self.form_data['name'], messages)
     self.assertMessageCount(success=1)
Exemplo n.º 18
0
 def _post_request(self, user):
     data = {
         'plugin_type': 'TextPlugin',
         'placeholder': self._placeholder.pk,
         'language': 'en',
     }
     request = self.get_post_request(data)
     request.user = self.reload(user)
     request._messages = default_storage(request)
     return request
Exemplo n.º 19
0
 def _post_request(self, user):
     data = {
         'plugin_type': 'TextPlugin',
         'placeholder': self._placeholder.pk,
         'language': 'en',
     }
     request = self.get_post_request(data)
     request.user = self.reload(user)
     request._messages = default_storage(request)
     return request
Exemplo n.º 20
0
def test_unicode_dups():
    """Test that unicode values are preserved."""
    request = HttpRequest()
    setattr(request, '_messages', default_storage(request))

    info(request, u'Titlé', u'Body')
    info(request, u'Titlé', u'Body')
    info(request, u'Another Titlé', u'Another Body')

    storage = django_messages.get_messages(request)
    assert len(storage) == 2, 'Too few or too many messages recorded.'
Exemplo n.º 21
0
def test_l10n_dups():
    """Test that L10n values are preserved."""
    request = HttpRequest()
    setattr(request, "_messages", default_storage(request))

    info(request, _("Title"), _("Body"))
    info(request, _("Title"), _("Body"))
    info(request, _("Another Title"), _("Another Body"))

    storage = django_messages.get_messages(request)
    eq_(len(storage), 2, "Too few or too many messages recorded.")
Exemplo n.º 22
0
def test_unicode_dups():
    """Test that unicode values are preserved."""
    request = HttpRequest()
    setattr(request, "_messages", default_storage(request))

    info(request, u"Titlé", u"Body")
    info(request, u"Titlé", u"Body")
    info(request, u"Another Titlé", u"Another Body")

    storage = django_messages.get_messages(request)
    eq_(len(storage), 2, "Too few or too many messages recorded.")
Exemplo n.º 23
0
def test_no_dupes():
    """Test that duplicate messages aren't saved."""
    request = HttpRequest()
    setattr(request, "_messages", default_storage(request))

    info(request, "Title", "Body")
    info(request, "Title", "Body")
    info(request, "Another Title", "Another Body")

    storage = django_messages.get_messages(request)
    eq_(len(storage), 2, "Too few or too many messages recorded.")
Exemplo n.º 24
0
def test_no_dupes():
    """Test that duplicate messages aren't saved."""
    request = HttpRequest()
    setattr(request, '_messages', default_storage(request))

    info(request, 'Title', 'Body')
    info(request, 'Title', 'Body')
    info(request, 'Another Title', 'Another Body')

    storage = django_messages.get_messages(request)
    assert len(storage) == 2, 'Too few or too many messages recorded.'
Exemplo n.º 25
0
def test_l10n_dups():
    """Test that L10n values are preserved."""
    request = HttpRequest()
    setattr(request, '_messages', default_storage(request))

    info(request, gettext('Title'), gettext('Body'))
    info(request, gettext('Title'), gettext('Body'))
    info(request, gettext('Another Title'), gettext('Another Body'))

    storage = django_messages.get_messages(request)
    assert len(storage) == 2, 'Too few or too many messages recorded.'
Exemplo n.º 26
0
def test_unicode_dups():
    """Test that unicode values are preserved."""
    request = HttpRequest()
    setattr(request, '_messages', default_storage(request))

    info(request, 'Titlé', 'Body')
    info(request, 'Titlé', 'Body')
    info(request, 'Another Titlé', 'Another Body')

    storage = django_messages.get_messages(request)
    assert len(storage) == 2, 'Too few or too many messages recorded.'
Exemplo n.º 27
0
def test_l10n_dups():
    """Test that L10n values are preserved."""
    request = HttpRequest()
    setattr(request, '_messages', default_storage(request))

    info(request, _('Title'), _('Body'))
    info(request, _('Title'), _('Body'))
    info(request, _('Another Title'), _('Another Body'))

    storage = django_messages.get_messages(request)
    assert len(storage) == 2, 'Too few or too many messages recorded.'
Exemplo n.º 28
0
def test_no_dupes():
    """Test that duplicate messages aren't saved."""
    request = HttpRequest()
    setattr(request, '_messages', default_storage(request))

    info(request, 'Title', 'Body')
    info(request, 'Title', 'Body')
    info(request, 'Another Title', 'Another Body')

    storage = django_messages.get_messages(request)
    assert len(storage) == 2, 'Too few or too many messages recorded.'
Exemplo n.º 29
0
    def request(self, *args, **kwargs):
        user = kwargs.pop('user', self.user)
        request = super(UserRequestFactory, self).request(*args, **kwargs)

        request.user = user

        request.session = import_string(settings.SESSION_ENGINE + '.SessionStore')()

        request._messages = default_storage(request)

        return request
Exemplo n.º 30
0
 def test_too_few_lead(self):
     lead = create_lead()
     f = RequestFactory()
     request = f.get("/")
     request.user = User.objects.get(id=1)
     request.session = {}
     request._messages = default_storage(request)
     lead = create_lead()
     postSaveLead(
         request, lead, [], sync=True
     )  # Learn model cannot exist, but it should not raise error
Exemplo n.º 31
0
    def test_response_whitout_GET(self):
        from django.contrib.messages.storage import default_storage

        request = HttpRequest()
        request.session = SessionStore('asd')
        request._messages = default_storage(request)

        response = easy.action_response(request)

        self.assertEqual(len(request._messages._queued_messages), 0)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], '.')
Exemplo n.º 32
0
def get_level(request):
    """
    Returns the minimum level of messages to be recorded.

    The default level is the ``MESSAGE_LEVEL`` setting. If this is not found,
    the ``INFO`` level is used.
    """
    if hasattr(request, "_messages"):
        storage = request._messages
    else:
        storage = default_storage(request)
    return storage.level
Exemplo n.º 33
0
    def test_response_whitout_GET(self):
        from django.contrib.messages.storage import default_storage

        request = HttpRequest()
        request.session = SessionStore('asd')
        request._messages = default_storage(request)

        response = easy.action_response(request)

        self.assertEqual(len(request._messages._queued_messages), 0)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], '.')
Exemplo n.º 34
0
 def test_remove_center_post_valid(self):
     view = views.RemoveCenterView.as_view()
     center = create_center('12345')
     data = {'center_number': center.code}
     request = self.factory.post('/', data)
     request.user = self.user
     request.session = {}
     request._messages = default_storage(request)
     response = view(request)
     self.assertEqual(response.status_code, 302)
     with self.assertRaises(Center.DoesNotExist):
         Center.objects.get(code=center.code)
Exemplo n.º 35
0
 def test_remove_center_post_valid(self):
     view = views.RemoveCenterView.as_view()
     center = create_center('12345')
     data = {'center_number': center.code}
     request = self.factory.post('/', data)
     request.user = self.user
     request.session = {}
     request._messages = default_storage(request)
     response = view(request)
     self.assertEqual(response.status_code, 302)
     with self.assertRaises(Center.DoesNotExist):
         Center.objects.get(code=center.code)
Exemplo n.º 36
0
    def request(self, *args, **kwargs):
        user = kwargs.pop('user', self.user)
        request = super(UserRequestFactory, self).request(*args, **kwargs)

        request.user = user

        request.session = import_string(settings.SESSION_ENGINE +
                                        '.SessionStore')()

        request._messages = default_storage(request)

        return request
Exemplo n.º 37
0
def test_too_greedy(session, api_rf, filled_cart):
    product = filled_cart.items.all()[0].product
    data = {'quantity': 10, 'product': product.id}
    request = api_rf.put('/shop/api/cart', data)
    request.customer = filled_cart.customer
    request.session = session
    request._messages = default_storage(request)
    response = CartViewSet.as_view({'put': 'update'})(request, pk=product.id)
    assert response.status_code == 200
    filled_cart.refresh_from_db()
    assert filled_cart.num_items == 1
    assert filled_cart.items.all()[0].quantity == 5  # not 10, as requested
Exemplo n.º 38
0
def get_level(request):
    """
    Returns the minimum level of messages to be recorded.

    The default level is the ``MESSAGE_LEVEL`` setting. If this is not found,
    the ``INFO`` level is used.
    """
    if hasattr(request, '_messages'):
        storage = request._messages
    else:
        storage = default_storage(request)
    return storage.level
Exemplo n.º 39
0
    def test_not_exist_view(self):
        from django.contrib.messages.storage import default_storage

        request = HttpRequest()
        request.session = SessionStore('asd')
        request._messages = default_storage(request)

        response1 = self.admin.easy_list_view(request, 'not')
        response2 = self.admin.easy_object_view(request, 1, 'not')

        self.assertEqual(response1.status_code, 302)
        self.assertEqual(response2.status_code, 302)
        self.assertEqual(len(request._messages._queued_messages), 2)
Exemplo n.º 40
0
    def test_not_exist_view(self):
        from django.contrib.messages.storage import default_storage

        request = HttpRequest()
        request.session = SessionStore('asd')
        request._messages = default_storage(request)

        response1 = self.admin.easy_list_view(request, 'not')
        response2 = self.admin.easy_object_view(request, 1, 'not')

        self.assertEqual(response1.status_code, 302)
        self.assertEqual(response2.status_code, 302)
        self.assertEqual(len(request._messages._queued_messages), 2)
Exemplo n.º 41
0
 def test_form_invalid_deve_adicionar_mensagem_de_erro(self):
     request = RequestFactory().get(self.view_url)
     request.user = self.usuario_homologador
     request.session = {}
     storage = default_storage(request)
     request._messages = storage
     view = views.UpdateAvaliacaoHomologadorInscricaoView()
     view.setup(request, pk=self.avaliacao.id)
     view.object = None
     view.form_invalid(mock.Mock())
     self.assertTrue(storage.added_new)
     self.assertIn("Por favor, corrija os erros abaixo para continuar.",
                   [m.message for m in storage])
Exemplo n.º 42
0
    def test_response_normal(self):
        from django.contrib.messages.storage import default_storage

        request = HttpRequest()
        request.GET = QueryDict('test=asd')
        request.session = SessionStore('asd')
        request._messages = default_storage(request)

        response = easy.action_response(request, 'Some message')

        self.assertEqual(len(request._messages._queued_messages), 1)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], './?test=asd')
Exemplo n.º 43
0
    def test_response_without_querystring(self):
        from django.contrib.messages.storage import default_storage

        request = HttpRequest()
        request.GET = QueryDict('test=asd')
        request.session = SessionStore('asd')
        request._messages = default_storage(request)

        response = easy.action_response(request, 'Some message', keep_querystring=False)

        self.assertEqual(len(request._messages._queued_messages), 1)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], '.')
Exemplo n.º 44
0
 def test_form_valid_deve_adicionar_mensagem_de_sucesso(self, form_valid):
     request = RequestFactory().get("/")
     request.user = mock.Mock()
     request.session = {}
     view = views.GenericDeleteResultadoView()
     view.setup(request, pk=self.resultado.id)
     view.model = mock.Mock()
     view.success_message = "Teste"
     storage = default_storage(request)
     request._messages = storage
     view.form_valid(form=mock.MagicMock())
     self.assertTrue(storage.added_new)
     self.assertIn(view.success_message, [m.message for m in storage])
Exemplo n.º 45
0
 def test_form_valid_deve_adicionar_mensagem_de_sucesso(
         self, form_valid, delay):
     request = RequestFactory().get("/")
     request.user = mock.Mock()
     request.session = {}
     view = views.ResultadoFileView()
     view.setup(request, resultado_pk=self.resultado.id)
     storage = default_storage(request)
     request._messages = storage
     view.form_valid(form=mock.MagicMock())
     self.assertTrue(storage.added_new)
     self.assertIn(
         "Sua solicitação está sendo processada. Você receberá os arquivos por e-mail.",
         [m.message for m in storage])
Exemplo n.º 46
0
 def test_form_valid_deve_adicionar_mensagem_de_sucesso(self, redistribuir):
     INSCRICOES_A_REDISTRIBUIR = 1
     redistribuir.return_value = INSCRICOES_A_REDISTRIBUIR
     request = RequestFactory().get(self.view_url)
     request.session = {}
     view = views.RedistribuirInscricaoView()
     view.setup(request, fase_pk=self.fase_analise.id)
     storage = default_storage(request)
     request._messages = storage
     view.form_valid(RedistribuirForm(fase=self.fase_analise))
     self.assertTrue(storage.added_new)
     self.assertIn(
         f"{INSCRICOES_A_REDISTRIBUIR} inscrições foram redistribuídas com sucesso",
         [m.message for m in storage])
Exemplo n.º 47
0
 def test_remove_center_post_valid(self):
     tally = create_tally()
     tally.users.add(self.user)
     center = create_center('12345', tally=tally)
     view = views.RemoveCenterView.as_view()
     data = {
         'center_number': center.code,
         'tally_id': tally.pk,
     }
     request = self.factory.post('/', data)
     request.user = self.user
     request.session = {}
     request._messages = default_storage(request)
     response = view(request, tally_id=tally.pk)
     self.assertEqual(response.status_code, 302)
Exemplo n.º 48
0
 def test_form_valid_deve_adicionar_mensagem_de_sucesso(
         self, new, gerar_resultado_preliminar, form_valid):
     request = RequestFactory().get("/")
     request.user = mock.Mock()
     request.session = {}
     view = views.ResultadoPreliminarView()
     view.setup(request, fase_pk=self.fase_analise.id)
     storage = default_storage(request)
     request._messages = storage
     view.form_valid(form=mock.Mock())
     self.assertTrue(storage.added_new)
     self.assertIn(
         "Sua solicitação está sendo processada."
         " Esta operação pode demorar alguns minutos.",
         [m.message for m in storage])
Exemplo n.º 49
0
def test_html_rendered_properly():
    """Html markup is properly displayed in final template."""
    request = HttpRequest()
    setattr(request, '_messages', default_storage(request))

    # This will call _file_message, which in turn calls _make_message, which in
    # turn renders the message_content.html template, which adds html markup.
    # We want to make sure this markup reaches the final rendering unescaped.
    info(request, 'Title', 'Body')

    messages = django_messages.get_messages(request)

    template = loader.get_template('messages.html')
    html = template.render({'messages': messages})
    assert '<h2>' in html  # The html from _make_message is not escaped.
Exemplo n.º 50
0
def get_level(request):
    """
<<<<<<< HEAD
    Returns the minimum level of messages to be recorded.

    The default level is the ``MESSAGE_LEVEL`` setting. If this is not found,
    the ``INFO`` level is used.
=======
    Return the minimum level of messages to be recorded.

    The default level is the ``MESSAGE_LEVEL`` setting. If this is not found,
    use the ``INFO`` level.
>>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435
    """
    storage = getattr(request, '_messages', default_storage(request))
    return storage.level
Exemplo n.º 51
0
    def assertMessageCount(self, response=None, **kwargs):
        """Asserts that the expected number of messages have been attached.

        The expected number of messages can be specified per message type.
        Usage would look like ``self.assertMessageCount(success=1)``.
        """
        temp_req = self.client.request(**{'wsgi.input': None})
        temp_req.COOKIES = self.client.cookies
        storage = default_storage(temp_req)
        messages = []

        if response is None:
            # To gain early access to the messages we have to decode the
            # cookie on the test client.
            if 'messages' in self.client.cookies:
                message_cookie = self.client.cookies['messages'].value
                messages = storage._decode(message_cookie)
        # Check for messages in the context
        elif hasattr(response, "context") and "messages" in response.context:
            messages = response.context["messages"]
        # Check for messages attached to the request on a TemplateResponse
        elif hasattr(response, "_request") and hasattr(response._request,
                                                       "_messages"):
            messages = response._request._messages._queued_messages

        # If we don't have messages and we don't expect messages, we're done.
        if not any(kwargs.values()) and not messages:
            return

        # If we expected messages and have none, that's a problem.
        if any(kwargs.values()) and not messages:
            error_msg = "Messages were expected, but none were set."
            assert 0 == sum(kwargs.values()), error_msg

        # Otherwise, make sure we got the expected messages.
        for msg_type, count in kwargs.items():
            msgs = [
                force_text(m.message) for m in messages if msg_type in m.tags
            ]
            assert len(msgs) == count, \
                "%s messages not as expected: %s" % (msg_type.title(),
                                                     ", ".join(msgs))
Exemplo n.º 52
0
 def test_remove_station_post_valid(self):
     center = create_center('12345')
     station = create_station(center)
     self.assertEqual(
         Station.objects.get(center__code=center.code,
                             station_number=station.station_number),
         station)
     view = views.RemoveStationView.as_view()
     data = {
         'center_number': center.code,
         'station_number': station.station_number
     }
     request = self.factory.post('/', data)
     request.user = self.user
     request.session = {}
     request._messages = default_storage(request)
     response = view(request)
     self.assertEqual(response.status_code, 302)
     with self.assertRaises(Station.DoesNotExist):
         Station.objects.get(center__code=center.code,
                             station_number=station.station_number)
Exemplo n.º 53
0
    def test_redeliver(self):
        foireq = FoiRequest.objects.all()[0]
        dm = factories.DeferredMessageFactory()
        dm.save()
        req = self.factory.post('/', {})
        req.user = self.user

        result = self.admin.redeliver(
            req, DeferredMessage.objects.filter(id__in=[dm.id]))
        self.assertEqual(result.status_code, 200)

        req = self.factory.post('/', {'req_id': foireq.id})
        req.user = self.user
        req._messages = default_storage(req)

        result = self.admin.redeliver(
            req, DeferredMessage.objects.filter(id__in=[dm.id]))
        self.assertIsNone(result)

        dm = DeferredMessage.objects.get(id=dm.id)
        self.assertEqual(dm.request, foireq)
Exemplo n.º 54
0
def get_messages(request):
    """
    Return the message storage on the request if it exists, otherwise return
    an empty list.
    """
    return getattr(request, '_messages', [])


def get_level(request):
    """
    Return the minimum level of messages to be recorded.

    The default level is the ``MESSAGE_LEVEL`` setting. If this is not found,
    use the ``INFO`` level.
    """
    storage = getattr(request, '_messages', default_storage(request))
    return storage.level


def set_level(request, level):
    """
    Set the minimum level of messages to be recorded, and return ``True`` if
    the level was recorded successfully.

    If set to ``None``, use the default level (see the get_level() function).
    """
    if not hasattr(request, '_messages'):
        return False
    request._messages.level = level
    return True
Exemplo n.º 55
0
 def post(self, *args, **kwargs):
     req = super().post(*args, **kwargs)
     req.user = User()
     req.session = SessionStore()
     req._messages = default_storage(req)
     return req
 def test_add_empty(self):
     self.request._messages = default_storage(self.request)
     add_message(self.request, DEBUG, '')
     self.assertEqual(len(get_messages(self.request)), 0)