Exemplo n.º 1
0
    def test_comment_post_missing(self):
        """
        Make an ajax post.
        """
        content_type = "article.article"
        timestamp = str(int(time.time()))
        article = factories.create_article()

        form = CommentForm(article)
        security_hash = form.generate_security_hash(content_type,
                                                    str(article.pk), timestamp)
        post_data = {
            "content_type": content_type,
            "object_pk": article.pk,
            "timestamp": timestamp,
            "security_hash": security_hash,
        }
        url = reverse("comments-post-comment-ajax")
        response = self.client.post(url,
                                    post_data,
                                    HTTP_X_REQUESTED_WITH="XMLHttpRequest")
        self.assertEqual(response.status_code, 200)

        json_response = json.loads(response.content.decode("utf-8"))
        self.assertFalse(json_response["success"])
        self.assertEqual(set(json_response["errors"].keys()),
                         set(["name", "email", "comment"]))
    def test_comment_post(self):
        """
        Make an ajax post.
        """
        content_type = "article.article"
        timestamp = str(int(time.time()))
        article = factories.create_article()

        form = CommentForm(article)
        security_hash = form.generate_security_hash(content_type, str(article.pk), timestamp)
        post_data = {
            "content_type": content_type,
            "object_pk": article.pk,
            "name": "Testing name",
            "email": "*****@*****.**",
            "comment": "Testing comment",
            "timestamp": timestamp,
            "security_hash": security_hash,
        }
        url = reverse("comments-post-comment-ajax")
        response = self.client.post(url, post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertContains(response, "Testing comment", status_code=200)
        self.assertEqual(response.status_code, 200)

        json_response = json.loads(response.content.decode("utf-8"))
        self.assertTrue(json_response['success'])
        self.assertEqual(json_response['errors'], {})
        self.assertIn('Testing name', json_response['html'])
Exemplo n.º 3
0
    def test_unpin_invalid_comment(self):
        self.login(self.admin)

        self.assertEqual(MessageBoardComment.objects.all().count(), 0)
        data = CommentForm(target_object=self.unicef).generate_security_data()
        data.update({
            'name': 'the supplied name',
            'comment': 'Foo'
        })
        response = self.url_post(
            self.unicef,
            reverse('comments-post-comment'), data)
        self.assertEqual(MessageBoardComment.objects.all().count(), 1)

        # Pin in Nyaruka org
        response = self.url_post(
            self.unicef,
            reverse('msg_board.messageboardcomment_pin', kwargs={'pk': MessageBoardComment.objects.all().first().pk})
        )
        self.assertEqual(response.status_code, 204)

        # Unpin in Unicef org
        response = self.url_post(
            self.unicef,
            reverse('msg_board.messageboardcomment_unpin', kwargs={'pk': 9999})
        )
        self.assertEqual(response.status_code, 404)
Exemplo n.º 4
0
    def test_unpin(self):
        self.assertEqual(MessageBoardComment.objects.all().count(), 0)
        data = CommentForm(target_object=self.unicef).generate_security_data()
        data.update({"name": "the supplied name", "comment": "Foo"})
        response = self.url_post(self.unicef, reverse("comments-post-comment"),
                                 data)
        self.assertEqual(MessageBoardComment.objects.all().count(), 1)
        response = self.url_post(
            self.unicef,
            reverse(
                "msg_board.messageboardcomment_pin",
                kwargs={"pk": MessageBoardComment.objects.all().first().pk}),
        )
        self.assertEqual(response.status_code, 204)
        self.assertEqual(
            MessageBoardComment.get_all(self.unicef, pinned=True).count(), 1)

        response = self.url_get(
            "unicef", reverse("msg_board.messageboardcomment_pinned"))
        self.assertEqual(len(response.json["results"]), 1)

        response = self.url_post(
            self.unicef,
            reverse(
                "msg_board.messageboardcomment_unpin",
                kwargs={"pk": MessageBoardComment.objects.all().first().pk}),
        )
        self.assertEqual(response.status_code, 204)
        self.assertEqual(
            MessageBoardComment.get_all(self.unicef, pinned=True).count(), 0)

        response = self.url_get(
            "unicef", reverse("msg_board.messageboardcomment_pinned"))
        self.assertEqual(len(response.json["results"]), 0)
Exemplo n.º 5
0
    def test_unpin_invalid_comment(self):
        self.login(self.admin)

        self.assertEqual(MessageBoardComment.objects.all().count(), 0)
        data = CommentForm(target_object=self.unicef).generate_security_data()
        data.update({"name": "the supplied name", "comment": "Foo"})
        response = self.url_post(self.unicef, reverse("comments-post-comment"),
                                 data)
        self.assertEqual(MessageBoardComment.objects.all().count(), 1)

        # Pin in Nyaruka org
        response = self.url_post(
            self.unicef,
            reverse(
                "msg_board.messageboardcomment_pin",
                kwargs={"pk": MessageBoardComment.objects.all().first().pk}),
        )
        self.assertEqual(response.status_code, 204)

        # Unpin in Unicef org
        response = self.url_post(
            self.unicef,
            reverse("msg_board.messageboardcomment_unpin", kwargs={"pk":
                                                                   9999}))
        self.assertEqual(response.status_code, 404)
Exemplo n.º 6
0
    def test_unpin(self):
        self.assertEqual(MessageBoardComment.objects.all().count(), 0)
        data = CommentForm(target_object=self.unicef).generate_security_data()
        data.update({'name': 'the supplied name', 'comment': 'Foo'})
        response = self.url_post(self.unicef, reverse('comments-post-comment'),
                                 data)
        self.assertEqual(MessageBoardComment.objects.all().count(), 1)
        response = self.url_post(
            self.unicef,
            reverse(
                'msg_board.messageboardcomment_pin',
                kwargs={'pk': MessageBoardComment.objects.all().first().pk}))
        self.assertEqual(response.status_code, 204)
        self.assertEqual(
            MessageBoardComment.get_all(self.unicef, pinned=True).count(), 1)

        response = self.url_get(
            'unicef', reverse('msg_board.messageboardcomment_pinned'))
        self.assertEqual(len(response.json['results']), 1)

        response = self.url_post(
            self.unicef,
            reverse(
                'msg_board.messageboardcomment_unpin',
                kwargs={'pk': MessageBoardComment.objects.all().first().pk}))
        self.assertEqual(response.status_code, 204)
        self.assertEqual(
            MessageBoardComment.get_all(self.unicef, pinned=True).count(), 0)

        response = self.url_get(
            'unicef', reverse('msg_board.messageboardcomment_pinned'))
        self.assertEqual(len(response.json['results']), 0)
Exemplo n.º 7
0
 def tamperWithForm(self, **kwargs):
     a = Article.objects.get(pk=1)
     d = self.getValidData(a)
     d.update(kwargs)
     f = CommentForm(Article.objects.get(pk=1), data=d)
     self.assertFalse(f.is_valid())
     return f
Exemplo n.º 8
0
    def test_comment_post(self):
        """
        Make an ajax post.
        """
        content_type = "article.article"
        timestamp = str(int(time.time()))
        article = factories.create_article()

        form = CommentForm(article)
        security_hash = form.generate_security_hash(content_type, str(article.pk), timestamp)
        post_data = {
            "content_type": content_type,
            "object_pk": article.pk,
            "name": "Testing name",
            "email": "*****@*****.**",
            "comment": "Testing comment",
            "timestamp": timestamp,
            "security_hash": security_hash,
        }
        url = reverse("comments-post-comment-ajax")
        response = self.client.post(url, post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertContains(response, "Testing comment", status_code=200)
        self.assertEqual(response.status_code, 200)

        json_response = json.loads(response.content.decode("utf-8"))
        self.assertTrue(json_response['success'])
        self.assertEqual(json_response['errors'], {})
        self.assertIn('Testing name', json_response['html'])
 def tamperWithForm(self, **kwargs):
     a = Article.objects.get(pk=1)
     d = self.getValidData(a)
     d.update(kwargs)
     f = CommentForm(Article.objects.get(pk=1), data=d)
     self.assertFalse(f.is_valid())
     return f
Exemplo n.º 10
0
    def test_unpin(self):
        self.assertEqual(MessageBoardComment.objects.all().count(), 0)
        data = CommentForm(target_object=self.unicef).generate_security_data()
        data.update({
            'name': 'the supplied name',
            'comment': 'Foo'
        })
        response = self.url_post(
            self.unicef,
            reverse('comments-post-comment'), data)
        self.assertEqual(MessageBoardComment.objects.all().count(), 1)
        response = self.url_post(
            self.unicef,
            reverse('msg_board.messageboardcomment_pin', kwargs={'pk': MessageBoardComment.objects.all().first().pk})
        )
        self.assertEqual(response.status_code, 204)
        self.assertEqual(MessageBoardComment.get_all(self.unicef, pinned=True).count(), 1)

        response = self.url_get('unicef', reverse('msg_board.messageboardcomment_pinned'))
        self.assertEqual(len(response.json['results']), 1)

        response = self.url_post(
            self.unicef,
            reverse('msg_board.messageboardcomment_unpin', kwargs={'pk': MessageBoardComment.objects.all().first().pk})
        )
        self.assertEqual(response.status_code, 204)
        self.assertEqual(MessageBoardComment.get_all(self.unicef, pinned=True).count(), 0)

        response = self.url_get('unicef', reverse('msg_board.messageboardcomment_pinned'))
        self.assertEqual(len(response.json['results']), 0)
Exemplo n.º 11
0
 def test_post_comment(self):
     data = CommentForm(self.unicef).generate_security_data()
     data.update({"name": "the supplied name", "comment": "Foo"})
     response = self.url_post("unicef", reverse("comments-post-comment"),
                              data)
     self.assertEqual(response.status_code, 302)
     self.assertEqual(MessageBoardComment.objects.all().count(), 1)
     self.assertEqual(MessageBoardComment.objects.all().first().comment,
                      "Foo")
Exemplo n.º 12
0
def post_comment(request, next=None, using=None):
    """
    Post a comment.

    HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are
    errors a preview template, ``comments/preview.html``, will be rendered.
    """
    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()
    if request.user.is_authenticated():
        if not data.get('name', ''):
            data["name"] = request.user.get_full_name() or request.user.username
        if not data.get('email', ''):
            data["email"] = request.user.email

    # Check to see if the POST data overrides the view's next argument.
    next = data.get("next", next)

    # Look up the object we're trying to comment about
    ctype = data.get("content_type")
    object_pk = data.get("object_pk")
    model = apps.get_model(*ctype.split(".", 1))
    target = model._default_manager.using(using).get(pk=object_pk)


    # Construct the comment form
    form = CommentForm(target, data=data)

    # Check security information
    if form.security_errors():
        return None
    # Create the comment
    comment = form.get_comment_object()
    comment.ip_address = request.META.get("REMOTE_ADDR", None)
    if request.user.is_authenticated():
        comment.user = request.user

    # Signal that the comment is about to be saved
    responses = signals.comment_will_be_posted.send(
        sender  = comment.__class__,
        comment = comment,
        request = request
    )

    # Save the comment and signal that it was saved
    comment.save()
    message = get_object_or_404(Message, pk = object_pk)
    message.envoyer_commentaire_notification(comment.pk, request.user.username)
    
    signals.comment_was_posted.send(
        sender  = comment.__class__,
        comment = comment,
        request = request
    )

    comment_list = [comment]
    return render(request, 'comments/list.html', {'comment_list': comment_list})    
Exemplo n.º 13
0
    def test_comment_post_moderated(self):
        """
        See that soft delete works properly.
        """
        # Double check preconditions for moderation
        self.assertIsNotNone(get_model_moderator(Article))
        self.assertTrue(len(signals.comment_will_be_posted.receivers))
        self.assertEqual(id(get_comment_model()),
                         signals.comment_will_be_posted.receivers[0][0][1])

        content_type = "article.article"
        timestamp = str(int(time.time()))
        article = factories.create_article()

        form = CommentForm(article)
        security_hash = form.generate_security_hash(content_type,
                                                    str(article.pk), timestamp)
        post_data = {
            "content_type": content_type,
            "object_pk": article.pk,
            "name": "Testing name",
            "email": "*****@*****.**",
            "comment": "Testing comment",
            "timestamp": timestamp,
            "security_hash": security_hash,
        }

        for url, is_ajax in [
            (reverse("comments-post-comment-ajax"), True),
            (reverse("comments-post-comment"), False),
        ]:
            with patch.object(Akismet,
                              "_request",
                              return_value=MockedResponse(True)) as m:
                response = self.client.post(
                    url, post_data, HTTP_X_REQUESTED_WITH="XMLHttpRequest")
            self.assertEqual(m.call_count, 1, "Moderator not called by " + url)

            if is_ajax:
                self.assertContains(response,
                                    "Testing comment",
                                    status_code=200)
                self.assertEqual(response.status_code, 200)

                json_response = json.loads(response.content.decode("utf-8"))
                self.assertTrue(json_response["success"])
                self.assertEqual(json_response["errors"], {})
            else:
                self.assertRedirects(response,
                                     reverse("comments-comment-done") + "?c=1")

            comment = get_comment_model().objects.filter(
                user_email="*****@*****.**")[0]
            self.assertFalse(comment.is_public, "Not moderated by " + url)
            self.assertTrue(comment.is_removed)
Exemplo n.º 14
0
 def test_post_comment(self):
     data = CommentForm(self.unicef).generate_security_data()
     data.update({
         'name': 'the supplied name',
         'comment': 'Foo',
     })
     response = self.url_post(
         'unicef',
         reverse('comments-post-comment'), data)
     self.assertEqual(response.status_code, 302)
     self.assertEqual(MessageBoardComment.objects.all().count(), 1)
     self.assertEqual(MessageBoardComment.objects.all().first().comment, 'Foo')
Exemplo n.º 15
0
 def test_post_comment(self):
     data = CommentForm(self.unicef).generate_security_data()
     data.update({
         'name': 'the supplied name',
         'comment': 'Foo',
     })
     response = self.url_post('unicef', reverse('comments-post-comment'),
                              data)
     self.assertEqual(response.status_code, 302)
     self.assertEqual(MessageBoardComment.objects.all().count(), 1)
     self.assertEqual(MessageBoardComment.objects.all().first().comment,
                      'Foo')
Exemplo n.º 16
0
    def test_updates(self):
        mail.outbox = []
        req = FoiRequest.objects.all()[0]
        comment_user = factories.UserFactory()
        user = User.objects.get(username='******')
        self.client.login(username='******', password='******')
        response = self.client.post(
            reverse('foirequestfollower-follow', kwargs={"slug": req.slug}))
        self.assertEqual(response.status_code, 302)
        self.client.logout()
        self.client.login(username=comment_user.username, password='******')
        mes = list(req.messages)[-1]
        d = {
            'name': 'Jim Bob',
            'email': '*****@*****.**',
            'url': '',
            'comment': 'This is my comment',
        }

        f = CommentForm(mes)
        d.update(f.initial)
        self.client.post(reverse("comments-post-comment"), d)
        _batch_update()
        self.assertEqual(len(mail.outbox), 2)
        self.assertEqual(mail.outbox[0].to[0], req.user.email)
        self.assertEqual(mail.outbox[1].to[0], user.email)
Exemplo n.º 17
0
 def test_comment_post_blocked(self):
     comments_moderation.admin.EmailFilter.objects.create(
         email="*****@*****.**", active=True)
     content_type = "webmap.poi"
     object_pk = "205"
     timestamp = "1451927336"
     security_hash = CommentForm.generate_security_hash(
         None, content_type, object_pk, timestamp)
     post_data = {
         "content_type": content_type,
         "object_pk": object_pk,
         "name": "Testing name",
         "email": "*****@*****.**",
         "comment": "Testing comment",
         "timestamp": timestamp,
         "security_hash": security_hash,
     }
     response = self.client.post(reverse("comments-post-comment-ajax"),
                                 post_data,
                                 HTTP_X_REQUESTED_WITH='XMLHttpRequest',
                                 secure=True)
     self.assertEqual(response.status_code, 200,
                      response.content.decode("utf-8"))
     self.assertContains(
         response,
         '<div class=\\"comment-text\\"><p>Testing comment</p></div>')
     self.assertContains(
         response,
         'Testing name\\n                  <span class=\\"comment-date\\">on Jan. 4, 2016, 5:10 p.m.</span>'
     )
     self.assertContains(
         response,
         '<span class=\\"comment-moderated-flag\\">(moderated)</span>')
Exemplo n.º 18
0
    def test_integrity_error_on_duplicate_spam_comments(self):
        class AllIsSpamModerator(EntryCommentModerator):
            spam_checker_backends = [
                'zinnia.spam_checker.backends.all_is_spam'
            ]

        moderator_stack.unregister(Entry)
        moderator_stack.register(Entry, AllIsSpamModerator)

        datas = {
            'name': 'Jim Bob',
            'email': '*****@*****.**',
            'url': '',
            'comment': 'This is my comment'
        }

        f = CommentForm(self.entry)
        datas.update(f.initial)
        url = reverse('comments-post-comment')
        self.assertEqual(self.entry.comment_count, 0)
        connect_discussion_signals()
        self.client.post(url, datas)
        self.client.post(url, datas)
        disconnect_discussion_signals()
        self.assertEqual(comments.get_model().objects.count(), 1)
        entry_reloaded = Entry.objects.get(pk=self.entry.pk)
        self.assertEqual(entry_reloaded.comment_count, 0)
Exemplo n.º 19
0
 def test_comment_post(self):
     mommy.make('CaptchaStore',
                hashkey='foocaptcha',
                response='XAGS',
                expiration='2018-01-01')
     content_type = "webmap.poi"
     object_pk = "205"
     timestamp = "1451927336"
     security_hash = CommentForm.generate_security_hash(
         None, content_type, object_pk, timestamp)
     post_data = {
         "content_type": content_type,
         "object_pk": object_pk,
         "name": "Testing name",
         "email": "*****@*****.**",
         "comment": "Testing comment",
         "captcha_0": 'foocaptcha',
         "captcha_1": 'XAGS',
         "timestamp": timestamp,
         "security_hash": security_hash,
     }
     response = self.client.post(reverse("comments-post-comment-ajax"),
                                 post_data,
                                 HTTP_X_REQUESTED_WITH='XMLHttpRequest',
                                 secure=True)
     self.assertEqual(response.status_code, 200,
                      response.content.decode("utf-8"))
     self.assertContains(
         response,
         '<div class=\\"comment-text\\"><p>Testing comment</p></div>')
     self.assertContains(
         response,
         'Testing name\\n                  <span class=\\"comment-date\\">on Jan. 4, 2016, 5:10 p.m.</span>'
     )
    def testGetCommentObject(self):
        f = self.testValidPost()
        c = f.get_comment_object()
        self.assertTrue(isinstance(c, Comment))
        self.assertEqual(c.content_object, Article.objects.get(pk=1))
        self.assertEqual(c.comment, "This is my comment")
        c.save()
        self.assertEqual(Comment.objects.count(), 1)

        # Create a comment for the second site. We only test for site_id, not
        # what has already been tested above.
        a = Article.objects.get(pk=1)
        d = self.getValidData(a)
        d["comment"] = "testGetCommentObject with a site"
        f = CommentForm(Article.objects.get(pk=1), data=d)
        c = f.get_comment_object(site_id=self.site_2.id)
        self.assertEqual(c.site_id, self.site_2.id)
    def test_comment_post_moderated(self):
        """
        See that soft delete works properly.
        """
        # Double check preconditions for moderation
        self.assertIsNotNone(get_model_moderator(Article))
        self.assertTrue(len(signals.comment_will_be_posted.receivers))
        self.assertEqual(id(get_comment_model()), signals.comment_will_be_posted.receivers[0][0][1])

        content_type = "article.article"
        timestamp = str(int(time.time()))
        article = factories.create_article()

        form = CommentForm(article)
        security_hash = form.generate_security_hash(content_type, str(article.pk), timestamp)
        post_data = {
            "content_type": content_type,
            "object_pk": article.pk,
            "name": "Testing name",
            "email": "*****@*****.**",
            "comment": "Testing comment",
            "timestamp": timestamp,
            "security_hash": security_hash,
        }

        for url, is_ajax in [
            (reverse("comments-post-comment-ajax"), True),
            (reverse("comments-post-comment"), False),
        ]:
            with patch.object(Akismet, '_request', return_value=MockedResponse(True)) as m:
                response = self.client.post(url, post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
            self.assertEqual(m.call_count, 1, "Moderator not called by " + url)

            if is_ajax:
                self.assertContains(response, "Testing comment", status_code=200)
                self.assertEqual(response.status_code, 200)

                json_response = json.loads(response.content.decode("utf-8"))
                self.assertTrue(json_response['success'])
                self.assertEqual(json_response['errors'], {})
            else:
                self.assertRedirects(response, reverse('comments-comment-done') + "?c=1")

            comment = get_comment_model().objects.filter(user_email="*****@*****.**")[0]
            self.assertFalse(comment.is_public, "Not moderated by " + url)
            self.assertTrue(comment.is_removed)
Exemplo n.º 22
0
    def testGetCommentObject(self):
        f = self.testValidPost()
        c = f.get_comment_object()
        self.assertTrue(isinstance(c, Comment))
        self.assertEqual(c.content_object, Article.objects.get(pk=1))
        self.assertEqual(c.comment, "This is my comment")
        c.save()
        self.assertEqual(Comment.objects.count(), 1)

        # Create a comment for the second site. We only test for site_id, not
        # what has already been tested above.
        a = Article.objects.get(pk=1)
        d = self.getValidData(a)
        d["comment"] = "testGetCommentObject with a site"
        f = CommentForm(Article.objects.get(pk=1), data=d)
        c = f.get_comment_object(site_id=self.site_2.id)
        self.assertEqual(c.site_id, self.site_2.id)
Exemplo n.º 23
0
    def test_pin_of_comment_in_another_org(self):
        self.login(self.admin)

        self.assertEqual(MessageBoardComment.objects.all().count(), 0)
        data = CommentForm(target_object=self.nyaruka).generate_security_data()
        data.update({'name': 'the supplied name', 'comment': 'Foo'})
        response = self.url_post(self.nyaruka,
                                 reverse('comments-post-comment'), data)
        self.assertEqual(MessageBoardComment.objects.all().count(), 1)

        # pin in Unicef org
        response = self.url_post(
            self.unicef,
            reverse(
                'msg_board.messageboardcomment_pin',
                kwargs={'pk': MessageBoardComment.objects.all().first().pk}))
        self.assertEqual(response.status_code, 404)
Exemplo n.º 24
0
    def test_updates_avoid(self):
        mail.outbox = []
        req = FoiRequest.objects.all()[0]
        dummy_user = User.objects.get(username='******')
        req2 = factories.FoiRequestFactory.create(site=self.site,
                                                  user=req.user)
        mes = list(req.messages)[-1]
        mes2 = factories.FoiMessageFactory.create(request=req2)
        self.client.login(username=req.user.username, password='******')
        d = {
            'name': 'Jim Bob',
            'email': '*****@*****.**',
            'url': '',
            'comment': 'This is my comment',
        }
        f = CommentForm(mes)
        d.update(f.initial)
        self.client.post(reverse("comments-post-comment"), d)

        _batch_update(update_requester=False)

        self.assertEqual(len(mail.outbox), 0)

        mail.outbox = []
        self.client.logout()

        def do_follow(req, username):
            self.client.login(username=username, password='******')
            response = self.client.post(
                reverse('foirequestfollower-follow', kwargs={"slug":
                                                             req.slug}))
            self.assertEqual(response.status_code, 302)
            self.client.logout()

        def do_comment(mes, username):
            self.client.login(username=username, password='******')
            f = CommentForm(mes)
            d.update(f.initial)
            self.client.post(reverse("comments-post-comment"), d)

        do_follow(req, 'dummy')
        do_comment(mes, 'sw')

        do_follow(req2, 'dummy')
        do_comment(mes2, 'sw')

        _batch_update()
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(mail.outbox[0].to[0], dummy_user.email)

        Comment.objects.all().delete()
        mail.outbox = []

        do_comment(mes2, 'dummy')

        _batch_update()
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(mail.outbox[0].to[0], req.user.email)
Exemplo n.º 25
0
def bind_comment(request, comment):
    """Bind the data into the form."""
    commdict = model_to_dict(comment)
    form = CommentForm(comment, commdict)
    tagform = CommentTagForm
    return render(request, 'comments/edit_comment.html', {
        'form': form,
        'tagform': tagform
    })
Exemplo n.º 26
0
    def test_comment_post_bad_requests(self):
        """
        See how error handling works on bad requests
        """
        content_type = "article.article"
        timestamp = str(int(time.time()))
        article = factories.create_article()

        form = CommentForm(article)
        security_hash = form.generate_security_hash(content_type,
                                                    str(article.pk), timestamp)
        correct_data = {
            "content_type": content_type,
            "object_pk": article.pk,
            "timestamp": timestamp,
            "security_hash": security_hash,
        }
        url = reverse("comments-post-comment-ajax")
        headers = dict(HTTP_X_REQUESTED_WITH="XMLHttpRequest")

        # No data
        self.assertEqual(self.client.post(url, {}, **headers).status_code, 400)

        # invalid pk
        post_data = correct_data.copy()
        post_data["object_pk"] = 999
        self.assertEqual(
            self.client.post(url, post_data, **headers).status_code, 400)

        # invalid content type
        post_data = correct_data.copy()
        post_data["content_type"] = "article.foo"
        self.assertEqual(
            self.client.post(url, post_data, **headers).status_code, 400)

        # invalid security hash
        post_data = correct_data.copy()
        post_data["timestamp"] = 0
        self.assertEqual(
            self.client.post(url, post_data, **headers).status_code, 400)
Exemplo n.º 27
0
    def testProfanities(self):
        """Test COMMENTS_ALLOW_PROFANITIES and PROFANITIES_LIST settings"""
        a = Article.objects.get(pk=1)
        d = self.getValidData(a)

        # Save settings in case other tests need 'em
        saved = getattr(settings, 'PROFANITIES_LIST',
                        []), getattr(settings, 'COMMENTS_ALLOW_PROFANITIES',
                                     False)

        # Don't wanna swear in the unit tests if we don't have to...
        settings.PROFANITIES_LIST = ["rooster"]

        # Try with COMMENTS_ALLOW_PROFANITIES off
        settings.COMMENTS_ALLOW_PROFANITIES = False
        f = CommentForm(a, data=dict(d, comment="What a rooster!"))
        self.assertFalse(f.is_valid())

        # Now with COMMENTS_ALLOW_PROFANITIES on
        settings.COMMENTS_ALLOW_PROFANITIES = True
        f = CommentForm(a, data=dict(d, comment="What a rooster!"))
        self.assertTrue(f.is_valid())

        # Restore settings
        settings.PROFANITIES_LIST, settings.COMMENTS_ALLOW_PROFANITIES = saved
Exemplo n.º 28
0
    def test_list(self):
        data = CommentForm(self.unicef).generate_security_data()
        data.update({'comment': 'Foo'})
        self.url_post('unicef', reverse('comments-post-comment'), data)

        data = CommentForm(self.unicef).generate_security_data()
        data.update({'comment': 'Bar'})
        self.url_post('unicef', reverse('comments-post-comment'), data)

        response = self.url_get('unicef', reverse('msg_board.messageboardcomment_list'))

        comment1, comment2 = list(MessageBoardComment.objects.order_by('pk'))

        self.assertEqual(response.json, {'results': [
            {
                'id': comment2.pk,
                'comment': "Bar",
                'user': {'id': self.user1.pk, 'name': "Evan"},
                'submitted_on': format_iso8601(comment2.submit_date),
                'pinned_on': None
            },
            {
                'id': comment1.pk,
                'comment': "Foo",
                'user': {'id': self.user1.pk, 'name': "Evan"},
                'submitted_on': format_iso8601(comment1.submit_date),
                'pinned_on': None
            }
        ]})
Exemplo n.º 29
0
    def test_comment_on_idea(self):
        comment_post_url = '/projects/comments/post/'
        form = CommentForm(Idea.objects.get(pk=1))
        data = form.initial

        # verify i can't post some empty comment
        # unfortunately the framework returns a 200 OK response, so we have to check based on response contents
        request = self.client.post(comment_post_url, data=data)
        self.assertIn('This field is required.', request.content)

        # verify i can post some comment
        data['comment'] = 'nice!'
        request = self.client.post(comment_post_url, data=data)
        self.assertEqual(request.status_code, 302)
    def testProfanities(self):
        """Test COMMENTS_ALLOW_PROFANITIES and PROFANITIES_LIST settings"""
        a = Article.objects.get(pk=1)
        d = self.getValidData(a)

        # Save settings in case other tests need 'em
        saved = getattr(settings, 'PROFANITIES_LIST', []), getattr(settings, 'COMMENTS_ALLOW_PROFANITIES', False)

        # Don't wanna swear in the unit tests if we don't have to...
        settings.PROFANITIES_LIST = ["rooster"]

        # Try with COMMENTS_ALLOW_PROFANITIES off
        settings.COMMENTS_ALLOW_PROFANITIES = False
        f = CommentForm(a, data=dict(d, comment="What a rooster!"))
        self.assertFalse(f.is_valid())

        # Now with COMMENTS_ALLOW_PROFANITIES on
        settings.COMMENTS_ALLOW_PROFANITIES = True
        f = CommentForm(a, data=dict(d, comment="What a rooster!"))
        self.assertTrue(f.is_valid())

        # Restore settings
        settings.PROFANITIES_LIST, settings.COMMENTS_ALLOW_PROFANITIES = saved
    def test_comment_post_missing(self):
        """
        Make an ajax post.
        """
        content_type = "article.article"
        timestamp = str(int(time.time()))
        article = factories.create_article()

        form = CommentForm(article)
        security_hash = form.generate_security_hash(content_type, str(article.pk), timestamp)
        post_data = {
            "content_type": content_type,
            "object_pk": article.pk,
            "timestamp": timestamp,
            "security_hash": security_hash,
        }
        url = reverse("comments-post-comment-ajax")
        response = self.client.post(url, post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 200)

        json_response = json.loads(response.content.decode("utf-8"))
        self.assertFalse(json_response['success'])
        self.assertEqual(set(json_response['errors'].keys()), set(['name', 'email', 'comment']))
    def test_comment_post_bad_requests(self):
        """
        See how error handling works on bad requests
        """
        content_type = "article.article"
        timestamp = str(int(time.time()))
        article = factories.create_article()

        form = CommentForm(article)
        security_hash = form.generate_security_hash(content_type, str(article.pk), timestamp)
        correct_data = {
            "content_type": content_type,
            "object_pk": article.pk,
            "timestamp": timestamp,
            "security_hash": security_hash,
        }
        url = reverse("comments-post-comment-ajax")
        headers = dict(HTTP_X_REQUESTED_WITH='XMLHttpRequest')

        # No data
        self.assertEqual(self.client.post(url, {}, **headers).status_code, 400)

        # invalid pk
        post_data = correct_data.copy()
        post_data['object_pk'] = 999
        self.assertEqual(self.client.post(url, post_data, **headers).status_code, 400)

        # invalid content type
        post_data = correct_data.copy()
        post_data['content_type'] = 'article.foo'
        self.assertEqual(self.client.post(url, post_data, **headers).status_code, 400)

        # invalid security hash
        post_data = correct_data.copy()
        post_data['timestamp'] = 0
        self.assertEqual(self.client.post(url, post_data, **headers).status_code, 400)
Exemplo n.º 33
0
    def test_adding_a_comment(self):
        router = self.create_node('test.router.dev', 'router')

        f = CommentForm(router)
        data = f.initial

        data['comment'] = 'Neat comment yay'
        data['next'] = router.get_absolute_url()

        response = self.client.post('/comments/post/', data)
        self.assertRedirects(
            response,
            router.get_absolute_url() +
            '?c={}'.format(Comment.objects.latest('id').pk),
        )
        # check that the comment is shown on the details page
        resp2 = self.client.get(router.get_absolute_url())
        self.assertContains(resp2, 'Neat comment yay')
Exemplo n.º 34
0
    def test_list(self):
        data = CommentForm(self.unicef).generate_security_data()
        data.update({"comment": "Foo"})
        self.url_post("unicef", reverse("comments-post-comment"), data)

        data = CommentForm(self.unicef).generate_security_data()
        data.update({"comment": "Bar"})
        self.url_post("unicef", reverse("comments-post-comment"), data)

        response = self.url_get("unicef",
                                reverse("msg_board.messageboardcomment_list"))

        comment1, comment2 = list(MessageBoardComment.objects.order_by("pk"))

        self.assertEqual(
            response.json,
            {
                "results": [
                    {
                        "id": comment2.pk,
                        "comment": "Bar",
                        "user": {
                            "id": self.user1.pk,
                            "name": "Evan"
                        },
                        "submitted_on": format_iso8601(comment2.submit_date),
                        "pinned_on": None,
                    },
                    {
                        "id": comment1.pk,
                        "comment": "Foo",
                        "user": {
                            "id": self.user1.pk,
                            "name": "Evan"
                        },
                        "submitted_on": format_iso8601(comment1.submit_date),
                        "pinned_on": None,
                    },
                ]
            },
        )
Exemplo n.º 35
0
    def test_comment_count_denormalization(self):
        class AllIsSpamModerator(EntryCommentModerator):
            spam_checker_backends = [
                'zinnia.spam_checker.backends.all_is_spam'
            ]

        class NoMailNoSpamModerator(EntryCommentModerator):
            def email(self, *ka, **kw):
                pass

            def moderate(self, *ka, **kw):
                return False

        datas = {
            'name': 'Jim Bob',
            'email': '*****@*****.**',
            'url': '',
            'comment': 'This is my comment'
        }

        f = CommentForm(self.entry)
        datas.update(f.initial)
        url = reverse('comments-post-comment')

        moderator_stack.unregister(Entry)
        moderator_stack.register(Entry, AllIsSpamModerator)

        self.assertEqual(self.entry.comment_count, 0)
        connect_discussion_signals()
        self.client.post(url, datas)
        entry_reloaded = Entry.objects.get(pk=self.entry.pk)
        self.assertEqual(entry_reloaded.comment_count, 0)

        moderator_stack.unregister(Entry)
        moderator_stack.register(Entry, NoMailNoSpamModerator)

        datas['comment'] = 'This a published comment'
        self.client.post(url, datas)
        disconnect_discussion_signals()
        entry_reloaded = Entry.objects.get(pk=self.entry.pk)
        self.assertEqual(entry_reloaded.comment_count, 1)
Exemplo n.º 36
0
 def test_comment_post(self):
     mommy.make('CaptchaStore', hashkey='foocaptcha', response='XAGS', expiration='2018-01-01')
     content_type = "webmap.poi"
     object_pk = "205"
     timestamp = "1451927336"
     security_hash = CommentForm.generate_security_hash(None, content_type, object_pk, timestamp)
     post_data = {
         "content_type": content_type,
         "object_pk": object_pk,
         "name": "Testing name",
         "email": "*****@*****.**",
         "comment": "Testing comment",
         "captcha_0": 'foocaptcha',
         "captcha_1": 'XAGS',
         "timestamp": timestamp,
         "security_hash": security_hash,
     }
     response = self.client.post(reverse("comments-post-comment-ajax"), post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest', secure=True)
     self.assertEqual(response.status_code, 200, response.content.decode("utf-8"))
     self.assertContains(response, '<div class=\\"comment-text\\"><p>Testing comment</p></div>')
     self.assertContains(response, 'Testing name\\n                  <span class=\\"comment-date\\">on Jan. 4, 2016, 5:10 p.m.</span>')
Exemplo n.º 37
0
    def test_list(self):
        data = CommentForm(self.unicef).generate_security_data()
        data.update({'comment': 'Foo'})
        self.url_post('unicef', reverse('comments-post-comment'), data)

        data = CommentForm(self.unicef).generate_security_data()
        data.update({'comment': 'Bar'})
        self.url_post('unicef', reverse('comments-post-comment'), data)

        response = self.url_get('unicef',
                                reverse('msg_board.messageboardcomment_list'))

        comment1, comment2 = list(MessageBoardComment.objects.order_by('pk'))

        self.assertEqual(
            response.json, {
                'results':
                [{
                    'id': comment2.pk,
                    'comment': "Bar",
                    'user': {
                        'id': self.user1.pk,
                        'name': "Evan"
                    },
                    'submitted_on': format_iso8601(comment2.submit_date),
                    'pinned_on': None
                }, {
                    'id': comment1.pk,
                    'comment': "Foo",
                    'user': {
                        'id': self.user1.pk,
                        'name': "Evan"
                    },
                    'submitted_on': format_iso8601(comment1.submit_date),
                    'pinned_on': None
                }]
            })
Exemplo n.º 38
0
 def getValidData(self, obj):
     f = CommentForm(obj)
     d = self.getData()
     d.update(f.initial)
     return d
Exemplo n.º 39
0
 def testValidPost(self):
     a = Article.objects.get(pk=1)
     f = CommentForm(a, data=self.getValidData(a))
     self.assertTrue(f.is_valid(), f.errors)
     return f
Exemplo n.º 40
0
def get_comment_form(idea):
    return CommentForm(idea)
Exemplo n.º 41
0
 def do_comment(mes, username):
     self.client.login(username=username, password='******')
     f = CommentForm(mes)
     d.update(f.initial)
     self.client.post(reverse("comments-post-comment"), d)
Exemplo n.º 42
0
 def testInit(self):
     f = CommentForm(Article.objects.get(pk=1))
     self.assertEqual(f.initial['content_type'], str(Article._meta))
     self.assertEqual(f.initial['object_pk'], "1")
     self.assertNotEqual(f.initial['security_hash'], None)
     self.assertNotEqual(f.initial['timestamp'], None)
Exemplo n.º 43
0
 def testValidPost(self):
     a = Article.objects.get(pk=1)
     f = CommentForm(a, data=self.getValidData(a))
     self.assertTrue(f.is_valid(), f.errors)
     return f