2
0
Эх сурвалжийг харах

Fixed #27153 -- Added validation for HttpResponse status.

Ryan Allen 8 жил өмнө
parent
commit
190d2ff4a7

+ 7 - 1
django/http/response.py

@@ -50,7 +50,13 @@ class HttpResponseBase(six.Iterator):
         self.cookies = SimpleCookie()
         self.closed = False
         if status is not None:
-            self.status_code = status
+            try:
+                self.status_code = int(status)
+            except (ValueError, TypeError):
+                raise TypeError('HTTP status code must be an integer.')
+
+            if not 100 <= self.status_code <= 599:
+                raise ValueError('HTTP status code must be an integer from 100 to 599.')
         self._reason_phrase = reason
         self._charset = charset
         if content_type is None:

+ 22 - 2
tests/responses/tests.py

@@ -63,10 +63,30 @@ class HttpResponseTests(SimpleTestCase):
         self.assertEqual(resp.status_code, 503)
         self.assertEqual(resp.reason_phrase, "Service Unavailable")
 
+    def test_valid_status_code_string(self):
+        resp = HttpResponse(status='100')
+        self.assertEqual(resp.status_code, 100)
+        resp = HttpResponse(status='404')
+        self.assertEqual(resp.status_code, 404)
+        resp = HttpResponse(status='599')
+        self.assertEqual(resp.status_code, 599)
+
+    def test_invalid_status_code(self):
+        must_be_integer = 'HTTP status code must be an integer.'
+        must_be_integer_in_range = 'HTTP status code must be an integer from 100 to 599.'
+        with self.assertRaisesMessage(TypeError, must_be_integer):
+            HttpResponse(status=object())
+        with self.assertRaisesMessage(TypeError, must_be_integer):
+            HttpResponse(status="J'attendrai")
+        with self.assertRaisesMessage(ValueError, must_be_integer_in_range):
+            HttpResponse(status=99)
+        with self.assertRaisesMessage(ValueError, must_be_integer_in_range):
+            HttpResponse(status=600)
+
     def test_reason_phrase(self):
         reason = "I'm an anarchist coffee pot on crack."
-        resp = HttpResponse(status=814, reason=reason)
-        self.assertEqual(resp.status_code, 814)
+        resp = HttpResponse(status=419, reason=reason)
+        self.assertEqual(resp.status_code, 419)
         self.assertEqual(resp.reason_phrase, reason)
 
     def test_charset_detection(self):