Skip to content

Commit 9ec28ce

Browse files
committed
Merge pull request googleapis#90 from craigcitro/master
Fix an encoding issue, add a test.
2 parents a823225 + 75f59b2 commit 9ec28ce

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

oauth2client/client.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -409,7 +409,9 @@ def clean_headers(headers):
409409
clean = {}
410410
try:
411411
for k, v in six.iteritems(headers):
412-
clean[k.encode('ascii')] = v.encode('ascii')
412+
clean_k = k if isinstance(k, bytes) else str(k).encode('ascii')
413+
clean_v = v if isinstance(v, bytes) else str(v).encode('ascii')
414+
clean[clean_k] = clean_v
413415
except UnicodeEncodeError:
414416
raise NonAsciiHeaderError(k + ': ' + v)
415417
return clean

tests/test_oauth2client.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -598,6 +598,37 @@ def test_from_json_token_expiry(self):
598598
instance = OAuth2Credentials.from_json(json.dumps(data))
599599
self.assertTrue(isinstance(instance, OAuth2Credentials))
600600

601+
def test_unicode_header_checks(self):
602+
access_token = u'foo'
603+
client_id = u'some_client_id'
604+
client_secret = u'cOuDdkfjxxnv+'
605+
refresh_token = u'1/0/a.df219fjls0'
606+
token_expiry = str(datetime.datetime.utcnow())
607+
token_uri = str(GOOGLE_TOKEN_URI)
608+
revoke_uri = str(GOOGLE_REVOKE_URI)
609+
user_agent = u'refresh_checker/1.0'
610+
credentials = OAuth2Credentials(access_token, client_id, client_secret,
611+
refresh_token, token_expiry, token_uri,
612+
user_agent, revoke_uri=revoke_uri)
613+
614+
# First, test that we correctly encode basic objects, making sure
615+
# to include a bytes object. Note that oauth2client will normalize
616+
# everything to bytes, no matter what python version we're in.
617+
http = credentials.authorize(HttpMock(headers={'status': '200'}))
618+
headers = {u'foo': 3, b'bar': True, 'baz': b'abc'}
619+
cleaned_headers = {b'foo': b'3', b'bar': b'True', b'baz': b'abc'}
620+
http.request(u'http://example.com', method=u'GET', headers=headers)
621+
for k, v in cleaned_headers.items():
622+
self.assertTrue(k in http.headers)
623+
self.assertEqual(v, http.headers[k])
624+
625+
# Next, test that we do fail on unicode.
626+
unicode_str = six.unichr(40960) + 'abcd'
627+
self.assertRaises(
628+
NonAsciiHeaderError,
629+
http.request,
630+
u'http://example.com', method=u'GET', headers={u'foo': unicode_str})
631+
601632
def test_no_unicode_in_request_params(self):
602633
access_token = u'foo'
603634
client_id = u'some_client_id'

0 commit comments

Comments
 (0)