Add some more response types
authorDavid Kerkeslager <kerkeslager@gmail.com>
Tue, 22 Oct 2019 19:03:04 +0000 (15:03 -0400)
committerDavid Kerkeslager <kerkeslager@gmail.com>
Tue, 22 Oct 2019 19:03:04 +0000 (15:03 -0400)
phial.py
test_phial.py

index f76a5dc..f4da0dd 100644 (file)
--- a/phial.py
+++ b/phial.py
@@ -1,4 +1,5 @@
 import collections
+import json
 
 Request = collections.namedtuple(
     'Request',
@@ -44,9 +45,35 @@ class Response(_Response):
             ('Content-Type', self.content_type),
         )
 
+class HTMLResponse(Response):
+    def __new__(cls, content, **kwargs):
+        assert 'content_type' not in kwargs
+
+        return super().__new__(
+            cls,
+            content,
+            content_type='text/html',
+            **kwargs,
+        )
+
+class JSONResponse(Response):
+    def __new__(cls, content_json, **kwargs):
+        assert 'content_type' not in kwargs
+        assert 'content' not in kwargs
+
+        self = super().__new__(
+            cls,
+            content=json.dumps(content_json),
+            content_type='application/json',
+            **kwargs,
+        )
+        self.content_json = content_json
+        return self
+
 class TextResponse(Response):
     def __new__(cls, content, **kwargs):
         assert 'content_type' not in kwargs
+
         return super().__new__(
             cls,
             content,
index df7e771..6ff27d9 100644 (file)
@@ -35,6 +35,29 @@ class ResponseTests(unittest.TestCase):
             ),
         )
 
+class HTMLResponseTests(unittest.TestCase):
+    def test_sets_content_type(self):
+        response = phial.HTMLResponse('<html><body>Hello, world</body></html>')
+        self.assertEqual(response.content_type, 'text/html')
+
+class JSONResponseTests(unittest.TestCase):
+    def test_sets_content_type(self):
+        response = phial.JSONResponse({ 'foo': 'bar', 'baz': 42 })
+        self.assertEqual(response.content_type, 'application/json')
+
+    def test_sets_content(self):
+        response = phial.JSONResponse({ 'foo': 'bar', 'baz': 42 })
+        self.assertEqual(response.content, '{"foo": "bar", "baz": 42}')
+
+    def test_sets_content_json(self):
+        response = phial.JSONResponse({ 'foo': 'bar', 'baz': 42 })
+        self.assertEqual(response.content_json, {"foo": "bar", "baz": 42})
+
+class TextResponseTests(unittest.TestCase):
+    def test_sets_content_type(self):
+        response = phial.TextResponse('Hello, world\n')
+        self.assertEqual(response.content_type, 'text/plain')
+
 class _get_status_Tests(unittest.TestCase):
     def test_basic(self):
         self.assertEqual(phial._get_status(mock.MagicMock(status=200)), '200 OK')