From fd77e7cd13caaf823abf3bad2ebfdd6bab5f1bd1 Mon Sep 17 00:00:00 2001 From: David Kerkeslager Date: Tue, 22 Oct 2019 15:03:04 -0400 Subject: [PATCH] Add some more response types --- phial.py | 27 +++++++++++++++++++++++++++ test_phial.py | 23 +++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/phial.py b/phial.py index f76a5dc..f4da0dd 100644 --- 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, diff --git a/test_phial.py b/test_phial.py index df7e771..6ff27d9 100644 --- a/test_phial.py +++ b/test_phial.py @@ -35,6 +35,29 @@ class ResponseTests(unittest.TestCase): ), ) +class HTMLResponseTests(unittest.TestCase): + def test_sets_content_type(self): + response = phial.HTMLResponse('Hello, world') + 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') -- 2.20.1