feat(testing.Result): Default to UTF-8 when charset is missing (#824)

The requests library attempts to auto-detect the charset using chardet,
but we just assume UTF-8 to avoid having to pull in another dependency.
This commit is contained in:
Kurt Griffiths
2016-08-05 09:50:11 -06:00
committed by John Vrbanac
parent ebc2d143de
commit 8266ff60d7
2 changed files with 11 additions and 9 deletions

View File

@@ -55,8 +55,8 @@ class Result(object):
response body was empty.
text (str): Decoded response body of type ``unicode``
under Python 2.6 and 2.7, and of type ``str`` otherwise.
Raises an error if the response encoding can not be
determined.
If the content type does not specify an encoding, UTF-8 is
assumed.
json (dict): Deserialized JSON body. Raises an error if the
response is not JSON.
"""
@@ -101,10 +101,11 @@ class Result(object):
self._text = u''
else:
if self.encoding is None:
msg = 'Response did not specify a content encoding'
raise RuntimeError(msg)
encoding = 'UTF-8'
else:
encoding = self.encoding
self._text = self.content.decode(self.encoding)
self._text = self.content.decode(encoding)
return self._text

View File

@@ -268,15 +268,16 @@ class TestHeaders(testing.TestCase):
self.assertEqual(result.headers['Content-Type'], content_type)
def test_override_default_media_type_missing_encoding(self):
body = b'{}'
body = u'{"msg": "Hello Unicode! \U0001F638"}'
self.api = falcon.API(media_type='application/json')
self.api.add_route('/', testing.SimpleTestResource(body=body))
result = self.simulate_get()
self.assertEqual(result.content, body)
self.assertRaises(RuntimeError, lambda: result.text)
self.assertRaises(RuntimeError, lambda: result.json)
self.assertEqual(result.content, body.encode('utf-8'))
self.assertIsInstance(result.text, six.text_type)
self.assertEqual(result.text, body)
self.assertEqual(result.json, {u'msg': u'Hello Unicode! \U0001F638'})
def test_response_header_helpers_on_get(self):
last_modified = datetime(2013, 1, 1, 10, 30, 30)