PageRenderTime 52ms CodeModel.GetById 8ms app.highlight 39ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/regressiontests/comment_tests/tests/comment_view_tests.py

https://code.google.com/p/mango-py/
Python | 282 lines | 258 code | 18 blank | 6 comment | 2 complexity | 9562b8fc67876e8d432716fa0bd307d1 MD5 | raw file
  1import re
  2from django.conf import settings
  3from django.contrib.auth.models import User
  4from django.contrib.comments import signals
  5from django.contrib.comments.models import Comment
  6from regressiontests.comment_tests.models import Article, Book
  7from regressiontests.comment_tests.tests import CommentTestCase
  8
  9post_redirect_re = re.compile(r'^http://testserver/posted/\?c=(?P<pk>\d+$)')
 10
 11class CommentViewTests(CommentTestCase):
 12
 13    def testPostCommentHTTPMethods(self):
 14        a = Article.objects.get(pk=1)
 15        data = self.getValidData(a)
 16        response = self.client.get("/post/", data)
 17        self.assertEqual(response.status_code, 405)
 18        self.assertEqual(response["Allow"], "POST")
 19
 20    def testPostCommentMissingCtype(self):
 21        a = Article.objects.get(pk=1)
 22        data = self.getValidData(a)
 23        del data["content_type"]
 24        response = self.client.post("/post/", data)
 25        self.assertEqual(response.status_code, 400)
 26
 27    def testPostCommentBadCtype(self):
 28        a = Article.objects.get(pk=1)
 29        data = self.getValidData(a)
 30        data["content_type"] = "Nobody expects the Spanish Inquisition!"
 31        response = self.client.post("/post/", data)
 32        self.assertEqual(response.status_code, 400)
 33
 34    def testPostCommentMissingObjectPK(self):
 35        a = Article.objects.get(pk=1)
 36        data = self.getValidData(a)
 37        del data["object_pk"]
 38        response = self.client.post("/post/", data)
 39        self.assertEqual(response.status_code, 400)
 40
 41    def testPostCommentBadObjectPK(self):
 42        a = Article.objects.get(pk=1)
 43        data = self.getValidData(a)
 44        data["object_pk"] = "14"
 45        response = self.client.post("/post/", data)
 46        self.assertEqual(response.status_code, 400)
 47
 48    def testPostInvalidIntegerPK(self):
 49        a = Article.objects.get(pk=1)
 50        data = self.getValidData(a)
 51        data["comment"] = "This is another comment"
 52        data["object_pk"] = u'\ufffd'
 53        response = self.client.post("/post/", data)
 54        self.assertEqual(response.status_code, 400)
 55
 56    def testPostInvalidDecimalPK(self):
 57        b = Book.objects.get(pk='12.34')
 58        data = self.getValidData(b)
 59        data["comment"] = "This is another comment"
 60        data["object_pk"] = 'cookies'
 61        response = self.client.post("/post/", data)
 62        self.assertEqual(response.status_code, 400)
 63
 64    def testCommentPreview(self):
 65        a = Article.objects.get(pk=1)
 66        data = self.getValidData(a)
 67        data["preview"] = "Preview"
 68        response = self.client.post("/post/", data)
 69        self.assertEqual(response.status_code, 200)
 70        self.assertTemplateUsed(response, "comments/preview.html")
 71
 72    def testHashTampering(self):
 73        a = Article.objects.get(pk=1)
 74        data = self.getValidData(a)
 75        data["security_hash"] = "Nobody expects the Spanish Inquisition!"
 76        response = self.client.post("/post/", data)
 77        self.assertEqual(response.status_code, 400)
 78
 79    def testDebugCommentErrors(self):
 80        """The debug error template should be shown only if DEBUG is True"""
 81        olddebug = settings.DEBUG
 82
 83        settings.DEBUG = True
 84        a = Article.objects.get(pk=1)
 85        data = self.getValidData(a)
 86        data["security_hash"] = "Nobody expects the Spanish Inquisition!"
 87        response = self.client.post("/post/", data)
 88        self.assertEqual(response.status_code, 400)
 89        self.assertTemplateUsed(response, "comments/400-debug.html")
 90
 91        settings.DEBUG = False
 92        response = self.client.post("/post/", data)
 93        self.assertEqual(response.status_code, 400)
 94        self.assertTemplateNotUsed(response, "comments/400-debug.html")
 95
 96        settings.DEBUG = olddebug
 97
 98    def testCreateValidComment(self):
 99        a = Article.objects.get(pk=1)
100        data = self.getValidData(a)
101        self.response = self.client.post("/post/", data, REMOTE_ADDR="1.2.3.4")
102        self.assertEqual(self.response.status_code, 302)
103        self.assertEqual(Comment.objects.count(), 1)
104        c = Comment.objects.all()[0]
105        self.assertEqual(c.ip_address, "1.2.3.4")
106        self.assertEqual(c.comment, "This is my comment")
107
108    def testPostAsAuthenticatedUser(self):
109        a = Article.objects.get(pk=1)
110        data = self.getValidData(a)
111        data['name'] = data['email'] = ''
112        self.client.login(username="normaluser", password="normaluser")
113        self.response = self.client.post("/post/", data, REMOTE_ADDR="1.2.3.4")
114        self.assertEqual(self.response.status_code, 302)
115        self.assertEqual(Comment.objects.count(), 1)
116        c = Comment.objects.all()[0]
117        self.assertEqual(c.ip_address, "1.2.3.4")
118        u = User.objects.get(username='normaluser')
119        self.assertEqual(c.user, u)
120        self.assertEqual(c.user_name, u.get_full_name())
121        self.assertEqual(c.user_email, u.email)
122
123    def testPostAsAuthenticatedUserWithoutFullname(self):
124        """
125        Check that the user's name in the comment is populated for
126        authenticated users without first_name and last_name.
127        """
128        user = User.objects.create_user(username='jane_other',
129                email='jane@example.com', password='jane_other')
130        a = Article.objects.get(pk=1)
131        data = self.getValidData(a)
132        data['name'] = data['email'] = ''
133        self.client.login(username="jane_other", password="jane_other")
134        self.response = self.client.post("/post/", data, REMOTE_ADDR="1.2.3.4")
135        c = Comment.objects.get(user=user)
136        self.assertEqual(c.ip_address, "1.2.3.4")
137        self.assertEqual(c.user_name, 'jane_other')
138        user.delete()
139
140    def testPreventDuplicateComments(self):
141        """Prevent posting the exact same comment twice"""
142        a = Article.objects.get(pk=1)
143        data = self.getValidData(a)
144        self.client.post("/post/", data)
145        self.client.post("/post/", data)
146        self.assertEqual(Comment.objects.count(), 1)
147
148        # This should not trigger the duplicate prevention
149        self.client.post("/post/", dict(data, comment="My second comment."))
150        self.assertEqual(Comment.objects.count(), 2)
151
152    def testCommentSignals(self):
153        """Test signals emitted by the comment posting view"""
154
155        # callback
156        def receive(sender, **kwargs):
157            self.assertEqual(kwargs['comment'].comment, "This is my comment")
158            self.assertTrue('request' in kwargs)
159            received_signals.append(kwargs.get('signal'))
160
161        # Connect signals and keep track of handled ones
162        received_signals = []
163        expected_signals = [
164            signals.comment_will_be_posted, signals.comment_was_posted
165        ]
166        for signal in expected_signals:
167            signal.connect(receive)
168
169        # Post a comment and check the signals
170        self.testCreateValidComment()
171        self.assertEqual(received_signals, expected_signals)
172
173        for signal in expected_signals:
174            signal.disconnect(receive)
175
176    def testWillBePostedSignal(self):
177        """
178        Test that the comment_will_be_posted signal can prevent the comment from
179        actually getting saved
180        """
181        def receive(sender, **kwargs): return False
182        signals.comment_will_be_posted.connect(receive, dispatch_uid="comment-test")
183        a = Article.objects.get(pk=1)
184        data = self.getValidData(a)
185        response = self.client.post("/post/", data)
186        self.assertEqual(response.status_code, 400)
187        self.assertEqual(Comment.objects.count(), 0)
188        signals.comment_will_be_posted.disconnect(dispatch_uid="comment-test")
189
190    def testWillBePostedSignalModifyComment(self):
191        """
192        Test that the comment_will_be_posted signal can modify a comment before
193        it gets posted
194        """
195        def receive(sender, **kwargs):
196             # a bad but effective spam filter :)...
197            kwargs['comment'].is_public = False
198
199        signals.comment_will_be_posted.connect(receive)
200        self.testCreateValidComment()
201        c = Comment.objects.all()[0]
202        self.assertFalse(c.is_public)
203
204    def testCommentNext(self):
205        """Test the different "next" actions the comment view can take"""
206        a = Article.objects.get(pk=1)
207        data = self.getValidData(a)
208        response = self.client.post("/post/", data)
209        location = response["Location"]
210        match = post_redirect_re.match(location)
211        self.assertTrue(match != None, "Unexpected redirect location: %s" % location)
212
213        data["next"] = "/somewhere/else/"
214        data["comment"] = "This is another comment"
215        response = self.client.post("/post/", data)
216        location = response["Location"]
217        match = re.search(r"^http://testserver/somewhere/else/\?c=\d+$", location)
218        self.assertTrue(match != None, "Unexpected redirect location: %s" % location)
219
220    def testCommentDoneView(self):
221        a = Article.objects.get(pk=1)
222        data = self.getValidData(a)
223        response = self.client.post("/post/", data)
224        location = response["Location"]
225        match = post_redirect_re.match(location)
226        self.assertTrue(match != None, "Unexpected redirect location: %s" % location)
227        pk = int(match.group('pk'))
228        response = self.client.get(location)
229        self.assertTemplateUsed(response, "comments/posted.html")
230        self.assertEqual(response.context[0]["comment"], Comment.objects.get(pk=pk))
231
232    def testCommentNextWithQueryString(self):
233        """
234        The `next` key needs to handle already having a query string (#10585)
235        """
236        a = Article.objects.get(pk=1)
237        data = self.getValidData(a)
238        data["next"] = "/somewhere/else/?foo=bar"
239        data["comment"] = "This is another comment"
240        response = self.client.post("/post/", data)
241        location = response["Location"]
242        match = re.search(r"^http://testserver/somewhere/else/\?foo=bar&c=\d+$", location)
243        self.assertTrue(match != None, "Unexpected redirect location: %s" % location)
244
245    def testCommentPostRedirectWithInvalidIntegerPK(self):
246        """
247        Tests that attempting to retrieve the location specified in the
248        post redirect, after adding some invalid data to the expected
249        querystring it ends with, doesn't cause a server error.
250        """
251        a = Article.objects.get(pk=1)
252        data = self.getValidData(a)
253        data["comment"] = "This is another comment"
254        response = self.client.post("/post/", data)
255        location = response["Location"]
256        broken_location = location + u"\ufffd"
257        response = self.client.get(broken_location)
258        self.assertEqual(response.status_code, 200)
259
260    def testCommentNextWithQueryStringAndAnchor(self):
261        """
262        The `next` key needs to handle already having an anchor. Refs #13411.
263        """
264        # With a query string also.
265        a = Article.objects.get(pk=1)
266        data = self.getValidData(a)
267        data["next"] = "/somewhere/else/?foo=bar#baz"
268        data["comment"] = "This is another comment"
269        response = self.client.post("/post/", data)
270        location = response["Location"]
271        match = re.search(r"^http://testserver/somewhere/else/\?foo=bar&c=\d+#baz$", location)
272        self.assertTrue(match != None, "Unexpected redirect location: %s" % location)
273
274        # Without a query string
275        a = Article.objects.get(pk=1)
276        data = self.getValidData(a)
277        data["next"] = "/somewhere/else/#baz"
278        data["comment"] = "This is another comment"
279        response = self.client.post("/post/", data)
280        location = response["Location"]
281        match = re.search(r"^http://testserver/somewhere/else/\?c=\d+#baz$", location)
282        self.assertTrue(match != None, "Unexpected redirect location: %s" % location)