Exemplo n.º 1
0
    def test_history_form_view_getting_history_with_setting_off(self):
        request = RequestFactory().post('/')
        request.session = 'session'
        request._messages = FallbackStorage(request)
        request.user = self.user
        request.POST = {'_change_history': True}

        poll = Poll.objects.create(question="why?", pub_date=today)
        poll.question = "how?"
        poll.save()
        history = poll.history.all()[0]

        admin_site = AdminSite()
        admin = SimpleHistoryAdmin(Poll, admin_site)

        with patch('simple_history.admin.render') as mock_render:
            with patch('simple_history.admin.SIMPLE_HISTORY_EDIT', False):
                admin.history_form_view(request, poll.id, history.pk)

        context = {
            # Verify this is set for history object not poll object
            'original': poll,
            'change_history': False,

            'title': 'Revert %s' % force_text(poll),
            'adminform': ANY,
            'object_id': poll.id,
            'is_popup': False,
            'media': ANY,
            'errors': ANY,
            'app_label': 'tests',
            'original_opts': ANY,
            'changelist_url': '/admin/tests/poll/',
            'change_url': ANY,
            'history_url': '/admin/tests/poll/1/history/',
            'add': False,
            'change': True,
            'has_add_permission': admin.has_add_permission(request),
            'has_change_permission': admin.has_change_permission(
                request, poll),
            'has_delete_permission': admin.has_delete_permission(
                request, poll),
            'has_file_field': True,
            'has_absolute_url': False,
            'form_url': '',
            'opts': ANY,
            'content_type_id': ANY,
            'save_as': admin.save_as,
            'save_on_top': admin.save_on_top,
            'root_path': getattr(admin_site, 'root_path', None),
        }
        mock_render.assert_called_once_with(
            request, admin.object_history_form_template, context, **extra_kwargs)
Exemplo n.º 2
0
    def test_gdpr_delete_user(self):
        # django.contrib.messages has a bug which effects unittests
        # more info here -> https://code.djangoproject.com/ticket/17971
        setattr(self.request, 'session', 'session')
        messages = FallbackStorage(self.request)
        setattr(self.request, '_messages', messages)

        count = AdminLogEntry.objects.count()
        self.view().delete(self.request)
        self.user.reload()
        nt.assert_true(self.user.deleted)
        nt.assert_equal(AdminLogEntry.objects.count(), count + 1)
Exemplo n.º 3
0
    def test_get_social_message_errors(self):
        request = RequestFactory().get('/')
        # RequestFactory is very limited, so we have to tweak this request in order to work with
        # messages middleware
        request.session = {}
        request._messages = FallbackStorage(request)

        messages.add_message(request, messages.ERROR, 'test')
        msgs = get_social_message_errors(request)
        self.assertEquals(len(msgs), 1)
        self.assertEquals(msgs[0].message, 'test')
        self.assertEquals(msgs[0].level, messages.ERROR)
Exemplo n.º 4
0
    def setUpClass(cls):
        """Setup the TestCase class"""
        super(ConnectMessageTestCase, cls).setUpClass()
        cls.group1 = mommy.make(Group, tos_accepted_at=now())
        cls.group2 = mommy.make(Group)

        cls.superuser.add_to_group(cls.group1.pk)
        cls.superuser.add_to_group(cls.group2.pk)
        cls.normal_user.add_to_group(cls.group1.pk)
        cls.staff_user.add_to_group(cls.group1.pk)

        cls.thread1 = mommy.make(Thread,
                                 group=cls.group1,
                                 subject=THREAD_SUBJECT)
        cls.message1 = mommy.make(Message,
                                  thread=cls.thread1,
                                  sender=cls.superuser,
                                  text=MESSAGE_TEXT,
                                  status='approved')
        cls.message2 = mommy.make(Message,
                                  thread=cls.thread1,
                                  sender=cls.normal_user,
                                  text=MESSAGE_TEXT,
                                  status='approved')

        cls.thread2 = mommy.make(Thread,
                                 group=cls.group2,
                                 subject=THREAD_SUBJECT)
        cls.message3 = mommy.make(Message,
                                  thread=cls.thread2,
                                  sender=cls.superuser,
                                  text=MESSAGE_TEXT,
                                  status='approved')

        cls.directthread1 = mommy.make(Thread,
                                       thread_type='direct',
                                       subject=THREAD_SUBJECT)
        cls.directmessage1 = mommy.make(Message,
                                        thread=cls.directthread1,
                                        sender=cls.user1,
                                        text=MESSAGE_TEXT,
                                        status='approved')

        mommy.make(UserThread, user=cls.normal_user, thread=cls.directthread1)
        mommy.make(UserThread, user=cls.staff_user, thread=cls.directthread1)

        cls.request_factory = RequestFactory()
        cls.request = cls.request_factory.get('/')
        setattr(cls.request, 'session', 'session')
        messages = FallbackStorage(cls.request)
        setattr(cls.request, '_messages', messages)
        cls.request.user = cls.superuser
        cls._group = None
    def test_user_create_edit_view(self):

        data = {'name': 'my bucketlist', 'itemname': 'my item1', 'done': ''}
        data1 = {'name': 'my new bucketlist'}

        #test user can create bucketlist
        request = self.factory.post('/bucketlist/action/samuel', data1)
        request.user = self.user
        setattr(request, 'session', 'session')
        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)
        response = CreateBucketlistView.as_view()(request)

        self.assertEquals(response.status_code, 302)

        #test user can edit bucketlist created
        request = self.factory.post('/bucketlist/19', data1)
        request.user = self.user
        setattr(request, 'session', 'session')
        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)

        response = DeleteUpdateBucketlistView.as_view()(request, id=19)
        self.assertEquals(response.status_code, 302)

        #test user toggle done field
        response = self.client.get(
            reverse_lazy('done', kwargs={
                'id': 17,
                'item_id': 19,
            }))
        self.assertEquals(response.status_code, 302)

        #test reverse toggle
        response = self.client.get(
            reverse_lazy('done', kwargs={
                'id': 17,
                'item_id': 19,
            }))
        self.assertEquals(response.status_code, 302)
Exemplo n.º 6
0
    def setUp(self):
        self.factory = RequestFactory()
        self.view = MergeOrderView()

        event = EventFactory(collect_housing_data=True)
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)

        self.person = PersonFactory()
        self.order1 = OrderFactory(event=event, person=self.person)
        self.order2 = OrderFactory(event=event,
                                   person=None,
                                   email=self.person.email)

        self.tr1 = TransactionFactory(event=event, order=self.order1)
        self.tr2 = TransactionFactory(event=event, order=self.order2)

        self.order1.add_to_cart(item_option)
        self.order1.mark_cart_paid(self.tr1)

        self.order2.add_to_cart(item_option)
        self.order2.add_to_cart(item_option)
        self.order2.mark_cart_paid(self.tr2)

        self.att1 = AttendeeFactory(
            order=self.order1,
            bought_items=self.order1.bought_items.all(),
            email='*****@*****.**')
        self.att2 = AttendeeFactory(
            order=self.order2,
            bought_items=self.order2.bought_items.all(),
            email='*****@*****.**')

        self.housing2 = EventHousingFactory(
            event=event,
            order=self.order2,
            contact_name='Picard',
            contact_email='*****@*****.**',
            contact_phone='111-111-1111',
            public_transit_access=True,
            person_prefer='Dr. Crusher',
            person_avoid='Wesley Crusher')

        self.attendee1 = AttendeeFactory(order=self.order1)
        self.attendee2 = AttendeeFactory(order=self.order2)

        self.view.request = self.factory.post('/', {'pk': self.order2.pk})
        self.view.request.user = self.person

        setattr(self.view.request, 'session', 'session')
        messages = FallbackStorage(self.view.request)
        setattr(self.view.request, '_messages', messages)
    def test_history_form_view_without_getting_history(self):
        request = RequestFactory().post("/")
        request.session = "session"
        request._messages = FallbackStorage(request)
        request.user = self.user

        poll = Poll.objects.create(question="why?", pub_date=today)
        poll.question = "how?"
        poll.save()
        history = poll.history.all()[0]

        admin_site = AdminSite()
        admin = SimpleHistoryAdmin(Poll, admin_site)

        with patch("simple_history.admin.render") as mock_render:
            admin.history_form_view(request, poll.id, history.pk)

        context = {
            # Verify this is set for original object
            "original": poll,
            "change_history": False,
            "title": "Revert %s" % force_text(poll),
            "adminform": ANY,
            "object_id": poll.id,
            "is_popup": False,
            "media": ANY,
            "errors": ANY,
            "app_label": "tests",
            "original_opts": ANY,
            "changelist_url": "/admin/tests/poll/",
            "change_url": ANY,
            "history_url": "/admin/tests/poll/1/history/",
            "add": False,
            "change": True,
            "has_add_permission": admin.has_add_permission(request),
            "has_change_permission":
            admin.has_change_permission(request, poll),
            "has_delete_permission":
            admin.has_delete_permission(request, poll),
            "has_file_field": True,
            "has_absolute_url": False,
            "form_url": "",
            "opts": ANY,
            "content_type_id": ANY,
            "save_as": admin.save_as,
            "save_on_top": admin.save_on_top,
            "root_path": getattr(admin_site, "root_path", None),
        }
        context.update(admin_site.each_context(request))
        mock_render.assert_called_once_with(request,
                                            admin.object_history_form_template,
                                            context)
Exemplo n.º 8
0
    def test_post_redirects_to_profile_page_if_user_is_logged_in(self):
        request = self.factory.post('/fake/')

        # Django bug with messages. Work around provided here:
        # https://stackoverflow.com/questions/11938164/why-dont-my-django-unittests-know-that-messagemiddleware-is-installed
        setattr(request, 'session', 'session')
        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)

        request.user = self.user
        response = ProfileView.as_view()(request)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, reverse('account_info:account_profile'))
Exemplo n.º 9
0
    def test_create_topic(self):
        request = self.factory.post('/forum/newtopic/',
                                    self.topic_creation_form)

        # This is necessary to test with messages.
        setattr(request, 'session', 'session')
        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)

        request.user = self.user
        response = create_topic(request)
        self.assertEqual(response.status_code, REQUEST_REDIRECT)
        self.assertEqual(response.url, '/en/forum/topics/')
Exemplo n.º 10
0
    def test_get_with_creator(self):
        view = ApplicationDelete.as_view()
        url = reverse('admin:app_delete', kwargs={'app_id': self.app.id})
        request = APIRequestFactory().get(url)

        from django.contrib.messages.storage.fallback import FallbackStorage
        setattr(request, 'session', 'session')
        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)

        request.user = self.creator
        response = view(request, app_id=self.app.id)
        self.assertTrue(isinstance(response, HttpResponseRedirect))
Exemplo n.º 11
0
    def test_invalid_id_flag_patient(self):
        request = self.factory.post('/patients/profile/flag/?id=' + str(99999),
                                    {'notes': "Didn't respond to emails."})
        self.middleware.process_request(request)
        request.session.save()
        request.user = self.user

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

        response = flag_patient(request)
        self.assertEqual(response.status_code, 302)
Exemplo n.º 12
0
 def test_load_sucessful(self):
     request = self.factory.get("/")
     request.user = self.user
     request.session = {}
     request._messages = FallbackStorage(request)
     self.assertEqual(len(mail.outbox), 0)
     response = self.view(request, id=self.invoice.id)
     self.assertEqual(len(mail.outbox), 1)
     self.assertEqual(response.status_code, 302)
     redirect_url = reverse(
         "invoices:invoice-detail", kwargs={"id": self.invoice.id}
     )
     self.assertEqual(response["location"], redirect_url)
Exemplo n.º 13
0
    def test_response_from_add_to_cart_view(self):
        factory = RequestFactory()
        request = factory.get('')
        setattr(request, 'session', 'session')
        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)
        request.user = self.user
        response = AddToCartView.as_view()(request,
                                           ct_model="notebook",
                                           slug="test-slug")

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, '/cart/')
Exemplo n.º 14
0
    def post_request(self, rf):
        request = rf.post('/')

        # adding session
        middleware = SessionMiddleware()
        middleware.process_request(request)
        request.session.save()

        # adding messages
        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)
        setattr(request, 'user', AnonymousUser())
        return request
Exemplo n.º 15
0
    def test_if_register_was_made(self):
        request = self.factory.post('user/register/', self.form, follow=True)

        # This is necessary to test with messages.
        setattr(request, 'session', 'session')
        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)

        request.user = User()
        request.user.id = None
        response = register_view(request)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, '/')
Exemplo n.º 16
0
def admin_request(rf, admin_user, rel_url):
    """
    Returns a valid HttpRequest object for the Django admin backend.
    """
    url = reverse(rel_url)
    request = rf.get(url)
    request.user = admin_user
    middleware = SessionMiddleware()
    middleware.process_request(request)
    request.session.save()
    messages = FallbackStorage(request)
    setattr(request, '_messages', messages)
    return request
Exemplo n.º 17
0
    def test_show_the_game(self):
        """This method test the show_the_game url."""
        info = {'id': self.last_game}
        user = get_user_model()
        request = self.factory.get('/chess_app/show_the_game.html', data=info)

        request.user = user.objects.get(username='******')
        response = show_the_game(request)
        self.assertEqual(response.status_code, 200)

        info = {'id': self.last_game}
        user = get_user_model()
        request = self.factory.get('/chess_app/show_the_game.html', data=info)

        request.user = AnonymousUser()
        setattr(request, 'session', 'session')
        setattr(request, '_messages', FallbackStorage(request))
        response = show_the_game(request)
        self.assertEqual(response.status_code, 200)

        info = {'id': 2345}
        user = get_user_model()
        request = self.factory.get('/chess_app/show_the_game.html', data=info)

        request.user = user.objects.get(username='******')
        setattr(request, 'session', 'session')
        setattr(request, '_messages', FallbackStorage(request))
        response = show_the_game(request)
        self.assertEqual(response.status_code, 200)

        info = {'id': 2345}
        user = get_user_model()
        request = self.factory.get('/chess_app/show_the_game.html', data=info)

        request.user = AnonymousUser()
        setattr(request, 'session', 'session')
        setattr(request, '_messages', FallbackStorage(request))
        response = show_the_game(request)
        self.assertEqual(response.status_code, 200)
Exemplo n.º 18
0
def add_middleware_to_request(request):
    """
    Función para agregar middleware a un request creado con RequestFactory
    """
    # Add session middleware
    middleware = SessionMiddleware()
    middleware.process_request(request)
    request.session.save()

    # Add messages middleware
    messages = FallbackStorage(request)
    request._messages = messages
    return request
Exemplo n.º 19
0
    def request(self, user=None, **request):
        request = super().request(**request)
        request.user = user or AnonymousUser()
        request.session = SessionStore()
        request._messages = FallbackStorage(request)

        request.basket = self.Basket()
        request.basket_hash = None
        strategy = self.selector.strategy(
            request=request, user=request.user)
        request.strategy = request.basket.strategy = strategy

        return request
Exemplo n.º 20
0
    def test_post(self):
        data = {'content': 'a'}
        request = RequestFactory().post('/fake', data=data)
        request.user = self.user

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

        response = self.post(views.CreateAnswerView,
                             request=request,
                             question_id=self.question_one.id)
        self.response_302(response)
 def test_attribute_form_view(self):
     form_data = {'eduPersonPrincipalName': 'User Identification'}
     request = self.factory.post(
         reverse('attribute-list', kwargs={'pk': self.user_sp.pk}),
         form_data)
     request.user = self.user
     setattr(request, 'session', 'session')
     messages = FallbackStorage(request)
     setattr(request, '_messages', messages)
     response = attribute_list(request, pk=self.user_sp.pk)
     self.assertEqual(response.status_code, 200)
     self.assertEqual(len(self.user_sp.attributes.all()), 1)
     self.assertEqual(self.user_sp.attributes.all()[0], self.attr_eppn)
    def test_increase_cart(self):
        request = self.factory.get('/shop/increase/1')
        request.user = self.user
        setattr(request, 'session', 'session')
        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)
        response = _views.increase_cart(request,1)
        cart = _models.Cart.objects.get(user=request.user)

        self.assertEqual(response.status_code, 302, "Should get a successfull response.")
        self.assertEqual(cart.quantity, 2, "quantity of an item should be zero at first time.")
        self.assertFalse(cart.purchased, "Purchased should be false by default.")
        self.assertEqual(cart.item.name, "Iphone 12 pro max", "Should add the 1st product in the cart.")
Exemplo n.º 23
0
    def test_fail_post_update_page(self):
        request = self.factory.post('/assigned/procedure/?id=134512342344')
        self.middleware.process_request(request)

        request.session.save()
        request.user = self.user

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

        response = update(request)
        self.assertEqual(response.status_code, 302)
Exemplo n.º 24
0
 def test_create_claim_with_logged_user(self):
     data = {
         'category': self.category.id,
         'address': 'test address',
         'description': 'description',
     }
     request = self.factory.post('/', data=data)
     request.user = self.user
     request.session = {}
     request._messages = FallbackStorage(request)
     response = self.view(request)
     self.assertEqual(response.status_code, 302)
     self.assertEqual(response['location'], reverse('claims:claim-list'))
Exemplo n.º 25
0
 def test_redirect_when_try_to_edit_a_non_draft_invoice(self):
     request = self.factory.get("/")
     request.user = self.user
     request.session = {}
     request._messages = FallbackStorage(request)
     self.invoice.status = Invoice.OPEN
     self.invoice.save()
     response = self.view(request, id=self.invoice.id)
     self.assertEqual(response.status_code, 302)
     self.assertEqual(
         response["location"],
         reverse("invoices:invoice-detail", kwargs={"id": self.invoice.id}),
     )
Exemplo n.º 26
0
    def setUp(self):
        """Set up test."""
        self.admin = UserFactory.create()
        self.regular_user = UserFactory.create()
        self.anonymous_user = AnonymousUser()
        self.sapelli_project = create_horniman_sapelli_project(self.admin)

        self.view = DataLogsDownload.as_view()
        self.request = HttpRequest()
        self.request.method = 'GET'

        setattr(self.request, 'session', 'session')
        setattr(self.request, '_messages', FallbackStorage(self.request))
Exemplo n.º 27
0
    def post_request(self, rf):
        request = rf.post("/")

        # adding session
        middleware = SessionMiddleware(lambda x: "Response")
        middleware.process_request(request)
        request.session.save()

        # adding messages
        messages = FallbackStorage(request)
        setattr(request, "_messages", messages)
        setattr(request, "user", AnonymousUser())
        return request
Exemplo n.º 28
0
 def test_remove_stuck_registration_with_an_addon(self):
     # Prevents circular import that prevents admin app from starting up
     from django.contrib.messages.storage.fallback import FallbackStorage
     self.registration.add_addon('github', auth=Auth(self.user))
     view = RemoveStuckRegistrationsView()
     view = setup_log_view(view, self.request, guid=self.registration._id)
     setattr(self.request, 'session', 'session')
     messages = FallbackStorage(self.request)
     setattr(self.request, '_messages', messages)
     view.post(self.request)
     self.registration.refresh_from_db()
     nt.assert_true(self.registration.is_deleted)
     nt.assert_true(self.registration.deleted is not None)
Exemplo n.º 29
0
    def post(self, user, data):
        view = CategoryCreate.as_view()
        url = reverse('admin:category_create',
                      kwargs={'project_id': self.project.id})
        request = self.factory.post(url, data, follow=True)

        from django.contrib.messages.storage.fallback import FallbackStorage
        setattr(request, 'session', 'session')
        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)

        request.user = user
        return view(request, project_id=self.project.id)
Exemplo n.º 30
0
    def test_mixin_messages(self):

        class MySubjectLocatorViewMixin(SubjectLocatorViewMixin):
            subject_locator_model_wrapper_cls = DummyModelWrapper
            subject_locator_model = 'edc_locator.subjectlocator'

        mixin = MySubjectLocatorViewMixin()
        mixin.kwargs = {'subject_identifier': self.subject_identifier}
        mixin.request = HttpRequest()
        setattr(mixin.request, 'session', 'session')
        messages = FallbackStorage(mixin.request)
        setattr(mixin.request, '_messages', messages)
        self.assertGreater(len(mixin.request._messages._queued_messages), 0)