From 0a17badb21c2dd9ceabb82dc6f3ca30a2c8d5aad Mon Sep 17 00:00:00 2001 From: Chris Adams Date: Mon, 13 Feb 2012 10:52:25 -0500 Subject: [PATCH] header_expand: handle Unicode strings (closes #400) --- requests/utils.py | 6 +++++- test_requests.py | 13 +++++++++---- 2 files changed, 14 insertions(+), 5 deletions(-) mode change 100644 => 100755 test_requests.py diff --git a/requests/utils.py b/requests/utils.py index 0f23a52..8865ae2 100644 --- a/requests/utils.py +++ b/requests/utils.py @@ -146,9 +146,13 @@ def header_expand(headers): if isinstance(headers, dict): headers = list(headers.items()) - elif isinstance(headers, basestring): return headers + elif isinstance(headers, unicode): + # As discussed in https://github.com/kennethreitz/requests/issues/400 + # latin-1 is the most conservative encoding used on the web. Anyone + # who needs more can encode to a byte-string before calling + return headers.encode("latin-1") for i, (value, params) in enumerate(headers): diff --git a/test_requests.py b/test_requests.py old mode 100644 new mode 100755 index eda9f79..59069f3 --- a/test_requests.py +++ b/test_requests.py @@ -55,7 +55,7 @@ class TestSetup(object): class RequestsTestSuite(TestSetup, unittest.TestCase): """Requests test cases.""" - + def test_entry_points(self): requests.session @@ -111,11 +111,16 @@ class RequestsTestSuite(TestSetup, unittest.TestCase): r = get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads) self.assertEqual(r.status_code, 200) - def test_session_with_unicode_headers(self): - heads = { u'User-Agent': u'\u30cd\u30c3\u30c8\u30ef\u30fc\u30af' } - + def test_unicode_headers(self): + # Simply calling requests with a unicode instance should simply work + # when the characters are all representable using latin-1: + heads = { u'User-Agent': u'Requests Test Suite' } requests.get(url=httpbin('get'), headers=heads) + # Characters outside latin-1 should raise an exception: + heads = { u'User-Agent': u'\u30cd\u30c3\u30c8\u30ef\u30fc\u30af' } + self.assertRaises(UnicodeEncodeError, requests.get, + url=httpbin('get'), headers=heads) def test_user_agent_transfers(self): """Issue XX""" -- 2.34.1