From a542c3f6cc00584840f9bb1c24be3ca5d45ac286 Mon Sep 17 00:00:00 2001 From: Richard Mitchell Date: Mon, 3 Dec 2012 13:55:40 +0000 Subject: [PATCH 1/3] Initial Py3k compatibility. --- oauth2/__init__.py | 114 ++++++++++++++++++++++++++++----------- setup.py | 7 +-- tests/test_oauth.py | 129 +++++++++++++++++++++++++++----------------- 3 files changed, 169 insertions(+), 81 deletions(-) diff --git a/oauth2/__init__.py b/oauth2/__init__.py index 36f5726c..3b43dc22 100644 --- a/oauth2/__init__.py +++ b/oauth2/__init__.py @@ -26,17 +26,34 @@ import urllib import time import random -import urlparse +try: + import urllib.parse as urlparse + from urllib.parse import quote + from urllib.parse import splithost + from urllib.parse import splittype + from urllib.parse import unquote + from urllib.parse import urlencode +except ImportError: + import urlparse + from urllib import quote + from urllib import splithost + from urllib import splittype + from urllib import unquote + from urllib import urlencode import hmac import binascii import httplib2 +import sys try: - from urlparse import parse_qs - parse_qs # placate pyflakes + from urllib.parse import parse_qs except ImportError: - # fall back for Python 2.5 - from cgi import parse_qs + try: + from urlparse import parse_qs + parse_qs # placate pyflakes + except ImportError: + # fall back for Python 2.5 + from cgi import parse_qs try: from hashlib import sha1 @@ -52,6 +69,35 @@ OAUTH_VERSION = '1.0' # Hi Blaine! HTTP_METHOD = 'GET' SIGNATURE_METHOD = 'PLAINTEXT' +PY3 = sys.version > '3' + + +try: + basestring +except NameError: + basestring = str +try: + unicode +except NameError: + unicode = str + + +def b(string): + if PY3: + return string.encode('ascii') + return string + + +def s(bytes): + if PY3: + return bytes.decode('ascii') + return bytes + + +def iteritems(d): + if PY3: + return d.items() + return d.iteritems() class Error(RuntimeError): @@ -87,7 +133,7 @@ def build_xoauth_string(url, consumer, token=None): request.sign_request(signing_method, consumer, token) params = [] - for k, v in sorted(request.iteritems()): + for k, v in sorted(iteritems(request)): if v is not None: params.append('%s="%s"' % (k, escape(v))) @@ -102,7 +148,8 @@ def to_unicode(s): raise TypeError('You are required to pass either unicode or string here, not: %r (%s)' % (type(s), s)) try: s = s.decode('utf-8') - except UnicodeDecodeError, le: + except UnicodeDecodeError: + le = sys.exc_info()[1] raise TypeError('You are required to pass either a unicode object or a utf-8 string here. You passed a Python string object which contained non-utf-8: %r. The UnicodeDecodeError that resulted from attempting to interpret it as utf-8 was: %s' % (s, le,)) return s @@ -131,7 +178,8 @@ def to_unicode_optional_iterator(x): try: l = list(x) - except TypeError, e: + except TypeError: + e = sys.exc_info()[1] assert 'is not iterable' in str(e) return x else: @@ -147,7 +195,8 @@ def to_utf8_optional_iterator(x): try: l = list(x) - except TypeError, e: + except TypeError: + e = sys.exc_info()[1] assert 'is not iterable' in str(e) return x else: @@ -155,7 +204,9 @@ def to_utf8_optional_iterator(x): def escape(s): """Escape a URL including any /.""" - return urllib.quote(s.encode('utf-8'), safe='~') + if not PY3: + s = s.encode('utf-8') + return quote(s, safe='~') def generate_timestamp(): """Get seconds since epoch (UTC).""" @@ -206,7 +257,7 @@ def __str__(self): data = {'oauth_consumer_key': self.key, 'oauth_consumer_secret': self.secret} - return urllib.urlencode(data) + return urlencode(data) class Token(object): @@ -274,7 +325,7 @@ def to_string(self): if self.callback_confirmed is not None: data['oauth_callback_confirmed'] = self.callback_confirmed - return urllib.urlencode(data) + return urlencode(data) @staticmethod def from_string(s): @@ -345,7 +396,7 @@ def __init__(self, method=HTTP_METHOD, url=None, parameters=None, self.url = to_unicode(url) self.method = method if parameters is not None: - for k, v in parameters.iteritems(): + for k, v in iteritems(parameters): k = to_unicode(k) v = to_unicode_optional_iterator(v) self[k] = v @@ -382,7 +433,7 @@ def _get_timestamp_nonce(self): def get_nonoauth_parameters(self): """Get any non-OAuth parameters.""" - return dict([(k, v) for k, v in self.iteritems() + return dict([(k, v) for k, v in iteritems(self) if not k.startswith('oauth_')]) def to_header(self, realm=''): @@ -402,13 +453,13 @@ def to_header(self, realm=''): def to_postdata(self): """Serialize as post data for a POST request.""" d = {} - for k, v in self.iteritems(): + for k, v in iteritems(self): d[k.encode('utf-8')] = to_utf8_optional_iterator(v) # tell urlencode to deal with sequence values and map them correctly # to resulting querystring. for example self["k"] = ["v1", "v2"] will # result in 'k=v1&k=v2' and not k=%5B%27v1%27%2C+%27v2%27%5D - return urllib.urlencode(d, True).replace('+', '%20') + return urlencode(d, True).replace('+', '%20') def to_url(self): """Serialize as a URL for a GET request.""" @@ -437,7 +488,7 @@ def to_url(self): fragment = to_utf8(base_url[5]) url = (scheme, netloc, path, params, - urllib.urlencode(query, True), fragment) + urlencode(query, True), fragment) return urlparse.urlunparse(url) def get_parameter(self, parameter): @@ -450,7 +501,7 @@ def get_parameter(self, parameter): def get_normalized_parameters(self): """Return a string that contains the parameters that must be signed.""" items = [] - for key, value in self.iteritems(): + for key, value in iteritems(self): if key == 'oauth_signature': continue # 1.0a/9.1.1 states that kvp must be sorted by key, then by value, @@ -460,7 +511,8 @@ def get_normalized_parameters(self): else: try: value = list(value) - except TypeError, e: + except TypeError: + e = sys.exc_info()[1] assert 'is not iterable' in str(e) items.append((to_utf8_if_string(key), to_utf8_if_string(value))) else: @@ -474,7 +526,7 @@ def get_normalized_parameters(self): items.extend(url_items) items.sort() - encoded_str = urllib.urlencode(items, True) + encoded_str = urlencode(items, True) # Encode signature parameters per Oauth Core 1.0 protocol # spec draft 7, section 3.6 # (http://tools.ietf.org/html/draft-hammer-oauth-07#section-3.6) @@ -490,7 +542,7 @@ def sign_request(self, signature_method, consumer, token): # section 4.1.1 "OAuth Consumers MUST NOT include an # oauth_body_hash parameter on requests with form-encoded # request bodies." - self['oauth_body_hash'] = base64.b64encode(sha(self.body).digest()) + self['oauth_body_hash'] = s(base64.b64encode(sha(b(self.body)).digest())) if 'oauth_consumer_key' not in self: self['oauth_consumer_key'] = consumer.key @@ -605,18 +657,20 @@ def _split_header(header): # Split key-value. param_parts = param.split('=', 1) # Remove quotes and unescape the value. - params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"')) + params[param_parts[0]] = unquote(param_parts[1].strip('\"')) return params @staticmethod def _split_url_string(param_str): """Turn URL string into parameters.""" - parameters = parse_qs(param_str.encode('utf-8'), keep_blank_values=True) - for k, v in parameters.iteritems(): + if not PY3: + param_str = param_str.encode('utf8') + parameters = parse_qs(param_str, keep_blank_values=True) + for k, v in iteritems(parameters): if len(v) == 1: - parameters[k] = urllib.unquote(v[0]) + parameters[k] = unquote(v[0]) else: - parameters[k] = sorted([urllib.unquote(s) for s in v]) + parameters[k] = sorted([unquote(s) for s in v]) return parameters @@ -668,12 +722,12 @@ def request(self, uri, method="GET", body='', headers=None, req.sign_request(self.method, self.consumer, self.token) - schema, rest = urllib.splittype(uri) + schema, rest = splittype(uri) if rest.startswith('//'): hierpart = '//' else: hierpart = '' - host, rest = urllib.splithost(rest) + host, rest = splithost(rest) realm = schema + ':' + hierpart + host @@ -844,10 +898,10 @@ def sign(self, request, consumer, token): """Builds the base signature string.""" key, raw = self.signing_base(request, consumer, token) - hashed = hmac.new(key, raw, sha) + hashed = hmac.new(b(key), b(raw), sha) # Calculate the digest base 64. - return binascii.b2a_base64(hashed.digest())[:-1] + return s(binascii.b2a_base64(hashed.digest())[:-1]) class SignatureMethod_PLAINTEXT(SignatureMethod): diff --git a/setup.py b/setup.py index 78119d69..0cdc4a6e 100755 --- a/setup.py +++ b/setup.py @@ -1,6 +1,7 @@ #!/usr/bin/env python -from setuptools import setup -import os, re +import os, re, sys + +from setuptools import setup, find_packages PKG='oauth2' VERSIONFILE = os.path.join('oauth2', '_version.py') @@ -15,7 +16,7 @@ if mo: mverstr = mo.group(1) else: - print "unable to find version in %s" % (VERSIONFILE,) + sys.stdout.write("unable to find version in %s\n" % (VERSIONFILE,)) raise RuntimeError("if %s.py exists, it must be well-formed" % (VERSIONFILE,)) AVSRE = r"^auto_build_num *= *['\"]([^'\"]*)['\"]" mo = re.search(AVSRE, verstrline, re.M) diff --git a/tests/test_oauth.py b/tests/test_oauth.py index bae3e514..8f64e004 100644 --- a/tests/test_oauth.py +++ b/tests/test_oauth.py @@ -30,15 +30,43 @@ import random import time import urllib -import urlparse -import mock +try: + import urllib.parse as urlparse + from urllib.parse import unquote + from urllib.parse import urlencode +except ImportError: + import urlparse + from urllib import unquote + from urllib import urlencode +try: + from unittest import mock +except ImportError: + import mock + import httplib2 -# Fix for python2.5 compatibility try: - from urlparse import parse_qs, parse_qsl + from urllib.parse import parse_qs + from urllib.parse import parse_qsl except ImportError: - from cgi import parse_qs, parse_qsl + try: + from urlparse import parse_qs + from urlparse import parse_qsl + parse_qsl # placate pyflakes + except ImportError: + # fall back for Python 2.5 + from cgi import parse_qs + from cgi import parse_qsl + + +PY3 = sys.version_info >= (3,) +iteritems = oauth.iteritems + + +def _u(string): + if PY3: + return string + return eval('u"""%s"""' % (string,)) sys.path[0:0] = [os.path.join(os.path.dirname(__file__), "..")] @@ -48,19 +76,22 @@ class TestError(unittest.TestCase): def test_message(self): try: raise oauth.Error - except oauth.Error, e: + except oauth.Error: + e = sys.exc_info()[1] self.assertEqual(e.message, 'OAuth error occurred.') msg = 'OMG THINGS BROKE!!!!' try: raise oauth.Error(msg) - except oauth.Error, e: + except oauth.Error: + e = sys.exc_info()[1] self.assertEqual(e.message, msg) def test_str(self): try: raise oauth.Error - except oauth.Error, e: + except oauth.Error: + e = sys.exc_info()[1] self.assertEquals(str(e), 'OAuth error occurred.') class TestGenerateFunctions(unittest.TestCase): @@ -205,7 +236,7 @@ def test_get_callback_url(self): verifier_str = '?oauth_verifier=%s' % v self.assertEqual(url, '%s%s' % (cb, verifier_str)) - def test_to_string(self): + def test_to_string_callback(self): string = 'oauth_token_secret=%s&oauth_token=%s' % (self.secret, self.key) self.assertEqual(self.token.to_string(), string) @@ -260,11 +291,11 @@ def test_to_unicode(self): self.failUnlessRaises(TypeError, oauth.to_unicode_optional_iterator, '\xae') self.failUnlessRaises(TypeError, oauth.to_unicode_optional_iterator, ['\xae']) - self.failUnlessEqual(oauth.to_unicode(':-)'), u':-)') - self.failUnlessEqual(oauth.to_unicode(u'\u00ae'), u'\u00ae') - self.failUnlessEqual(oauth.to_unicode('\xc2\xae'), u'\u00ae') - self.failUnlessEqual(oauth.to_unicode_optional_iterator([':-)']), [u':-)']) - self.failUnlessEqual(oauth.to_unicode_optional_iterator([u'\u00ae']), [u'\u00ae']) + self.failUnlessEqual(oauth.to_unicode(':-)'), _u(':-)')) + self.failUnlessEqual(oauth.to_unicode(_u('\u00ae'), _u('\u00ae'))) + self.failUnlessEqual(oauth.to_unicode('\xc2\xae'), _u('\u00ae')) + self.failUnlessEqual(oauth.to_unicode_optional_iterator([':-)']), [_u(':-)')]) + self.failUnlessEqual(oauth.to_unicode_optional_iterator([_u('\u00ae')]), [_u('\u00ae')]) class TestRequest(unittest.TestCase, ReallyEqualMixin): def test_setter(self): @@ -285,7 +316,8 @@ def test_deleter(self): self.fail("AttributeError should have been raised on empty url.") except AttributeError: pass - except Exception, e: + except Exception: + e = sys.exc_info()[1] self.fail(str(e)) def test_url(self): @@ -360,12 +392,12 @@ def test_get_nonoauth_parameters(self): } other_params = { - u'foo': u'baz', - u'bar': u'foo', - u'multi': [u'FOO',u'BAR'], - u'uni_utf8': u'\xae', - u'uni_unicode': u'\u00ae', - u'uni_unicode_2': u'åÅøØ', + _u('foo'): _u('baz'), + _u('bar'): _u('foo'), + _u('multi'): [_u('FOO'), _u('BAR')], + _u('uni_utf8'): _u('\xae'), + _u('uni_unicode'): _u('\u00ae'), + _u('uni_unicode_2'): _u('åÅøØ'), } params = oauth_params @@ -441,7 +473,7 @@ def test_to_header(self): } req = oauth.Request("GET", realm, params) - header, value = req.to_header(realm).items()[0] + header, value = list(req.to_header(realm).items())[0] parts = value.split('OAuth ') vars = parts[1].split(', ') @@ -450,7 +482,7 @@ def test_to_header(self): res = {} for v in vars: var, val = v.split('=') - res[var] = urllib.unquote(val.strip('"')) + res[var] = unquote(val.strip('"')) self.assertEquals(realm, res['realm']) del res['realm'] @@ -464,7 +496,7 @@ def test_to_postdata_nonascii(self): realm = "http://sp.example.com/" params = { - 'nonasciithing': u'q\xbfu\xe9 ,aasp u?..a.s', + 'nonasciithing': _u('q\xbfu\xe9 ,aasp u?..a.s'), 'oauth_version': "1.0", 'oauth_nonce': "4572616e48616d6d65724c61686176", 'oauth_timestamp': "137131200", @@ -514,7 +546,7 @@ def test_to_url(self): } req = oauth.Request("GET", url, params) - exp = urlparse.urlparse("%s?%s" % (url, urllib.urlencode(params))) + exp = urlparse.urlparse("%s?%s" % (url, urlencode(params))) res = urlparse.urlparse(req.to_url()) self.assertEquals(exp.scheme, res.scheme) self.assertEquals(exp.netloc, res.netloc) @@ -539,7 +571,7 @@ def test_to_url_with_query(self): req = oauth.Request("GET", url, params) # Note: the url above already has query parameters, so append new ones with & - exp = urlparse.urlparse("%s&%s" % (url, urllib.urlencode(params))) + exp = urlparse.urlparse("%s&%s" % (url, urlencode(params))) res = urlparse.urlparse(req.to_url()) self.assertEquals(exp.scheme, res.scheme) self.assertEquals(exp.netloc, res.netloc) @@ -556,27 +588,27 @@ def test_to_url_with_query(self): def test_signature_base_string_nonascii_nonutf8(self): consumer = oauth.Consumer('consumer_token', 'consumer_secret') - url = u'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc\u2766,+CA' + url = _u('http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc\u2766,+CA') req = oauth.Request("GET", url) - self.failUnlessReallyEqual(req.normalized_url, u'http://api.simplegeo.com/1.0/places/address.json') + self.failUnlessReallyEqual(req.normalized_url, _u('http://api.simplegeo.com/1.0/places/address.json')) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, None) self.failUnlessReallyEqual(req['oauth_signature'], 'WhufgeZKyYpKsI70GZaiDaYwl6g=') url = 'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc\xe2\x9d\xa6,+CA' req = oauth.Request("GET", url) - self.failUnlessReallyEqual(req.normalized_url, u'http://api.simplegeo.com/1.0/places/address.json') + self.failUnlessReallyEqual(req.normalized_url, _u('http://api.simplegeo.com/1.0/places/address.json')) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, None) self.failUnlessReallyEqual(req['oauth_signature'], 'WhufgeZKyYpKsI70GZaiDaYwl6g=') url = 'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc%E2%9D%A6,+CA' req = oauth.Request("GET", url) - self.failUnlessReallyEqual(req.normalized_url, u'http://api.simplegeo.com/1.0/places/address.json') + self.failUnlessReallyEqual(req.normalized_url, _u('http://api.simplegeo.com/1.0/places/address.json')) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, None) self.failUnlessReallyEqual(req['oauth_signature'], 'WhufgeZKyYpKsI70GZaiDaYwl6g=') - url = u'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc%E2%9D%A6,+CA' + url = _u('http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc%E2%9D%A6,+CA') req = oauth.Request("GET", url) - self.failUnlessReallyEqual(req.normalized_url, u'http://api.simplegeo.com/1.0/places/address.json') + self.failUnlessReallyEqual(req.normalized_url, _u('http://api.simplegeo.com/1.0/places/address.json')) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, None) self.failUnlessReallyEqual(req['oauth_signature'], 'WhufgeZKyYpKsI70GZaiDaYwl6g=') @@ -597,7 +629,7 @@ def test_signature_base_string_with_query(self): normalized_params = parse_qsl(req.get_normalized_parameters()) self.assertTrue(len(normalized_params), len(params) + 2) normalized_params = dict(normalized_params) - for key, value in params.iteritems(): + for key, value in iteritems(params): if key == 'oauth_signature': continue self.assertEquals(value, normalized_params[key]) @@ -680,10 +712,10 @@ def test_get_normalized_parameters(self): 'oauth_consumer_key': "0685bd9184jfhq22", 'oauth_signature_method': "HMAC-SHA1", 'oauth_token': "ad180jjd733klru7", - 'multi': ['FOO','BAR', u'\u00ae', '\xc2\xae'], + 'multi': ['FOO','BAR', _u('\u00ae'), '\xc2\xae'], 'multi_same': ['FOO','FOO'], 'uni_utf8_bytes': '\xc2\xae', - 'uni_unicode_object': u'\u00ae' + 'uni_unicode_object': _u('\u00ae') } req = oauth.Request("GET", url, params) @@ -711,17 +743,18 @@ def test_get_normalized_parameters_ignores_auth_signature(self): res = req.get_normalized_parameters() - self.assertNotEquals(urllib.urlencode(sorted(params.items())), res) + self.assertNotEquals(urlencode(sorted(params.items())), res) foo = params.copy() del foo["oauth_signature"] - self.assertEqual(urllib.urlencode(sorted(foo.items())), res) + self.assertEqual(urlencode(sorted(foo.items())), res) def test_signature_base_string_with_matrix_params(self): url = "http://social.yahooapis.com/v1/user/6677/connections;start=0;count=20" req = oauth.Request("GET", url, None) self.assertEquals(req.normalized_url, 'http://social.yahooapis.com/v1/user/6677/connections;start=0;count=20') self.assertEquals(req.url, 'http://social.yahooapis.com/v1/user/6677/connections;start=0;count=20') + self.assertEqual(urlencode(sorted(foo.items())), res) def test_set_signature_method(self): consumer = oauth.Consumer('key', 'secret') @@ -749,7 +782,7 @@ def test_get_normalized_string_escapes_spaces_properly(self): req = oauth.Request("GET", url, params) res = req.get_normalized_parameters() - expected = urllib.urlencode(sorted(params.items())).replace('+', '%20') + expected = urlencode(sorted(params.items())).replace('+', '%20') self.assertEqual(expected, res) @mock.patch('oauth2.Request.make_timestamp') @@ -774,7 +807,7 @@ def test_request_nonutf8_bytes(self, mock_make_nonce, mock_make_timestamp): self.assertRaises(TypeError, oauth.Request, method="GET", url=url, parameters=params) # And if they pass an unicode, then we'll use it. - url = u'http://sp.example.com/\u2019' + url = _u('http://sp.example.com/\u2019') req = oauth.Request(method="GET", url=url, parameters=params) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, None) self.failUnlessReallyEqual(req['oauth_signature'], 'cMzvCkhvLL57+sTIxLITTHfkqZk=') @@ -795,7 +828,7 @@ def test_request_nonutf8_bytes(self, mock_make_nonce, mock_make_timestamp): self.assertRaises(TypeError, oauth.Request, method="GET", url=url, parameters=params) # And if they pass a unicode, then we'll use it. - params['non_oauth_thing'] = u'\u2019' + params['non_oauth_thing'] = _u('\u2019') req = oauth.Request(method="GET", url=url, parameters=params) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, None) self.failUnlessReallyEqual(req['oauth_signature'], '0GU50m0v60CVDB5JnoBXnvvvKx4=') @@ -828,7 +861,7 @@ def test_request_hash_of_body(self): 'oauth_consumer_key': con.key } - url = u"http://www.example.com/resource" + url = _u("http://www.example.com/resource") req = oauth.Request(method="PUT", url=url, parameters=params, body="Hello World!", is_form_encoded=False) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, None) self.failUnlessReallyEqual(req['oauth_body_hash'], 'Lve95gjOVATpfV8EL5X4nxwjKHE=') @@ -898,7 +931,7 @@ def test_sign_request(self): req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, tok) self.assertEquals(req['oauth_signature'], 'loFvp5xC7YbOgd9exIO6TxB7H4s=') - url = u'http://sp.example.com/\u2019' # Python unicode object + url = _u('http://sp.example.com/\u2019') # Python unicode object req = oauth.Request(method="GET", url=url, parameters=params) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, tok) self.assertEquals(req['oauth_signature'], 'loFvp5xC7YbOgd9exIO6TxB7H4s=') @@ -909,7 +942,7 @@ def test_sign_request(self): req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, tok) self.assertEquals(req['oauth_signature'], 'IBw5mfvoCsDjgpcsVKbyvsDqQaU=') - url = u'http://sp.example.com/?q=\u2019' # Python unicode object + url = _u('http://sp.example.com/?q=\u2019') # Python unicode object req = oauth.Request(method="GET", url=url, parameters=params) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, tok) self.assertEquals(req['oauth_signature'], 'IBw5mfvoCsDjgpcsVKbyvsDqQaU=') @@ -1003,12 +1036,12 @@ def test_from_request(self): url, bad_headers) # Test getting from query string - qs = urllib.urlencode(params) + qs = urlencode(params) req = oauth.Request.from_request("GET", url, query_string=qs) exp = parse_qs(qs, keep_blank_values=False) - for k, v in exp.iteritems(): - exp[k] = urllib.unquote(v[0]) + for k, v in iteritems(exp): + exp[k] = unquote(v[0]) self.assertEquals(exp, req.copy()) @@ -1292,7 +1325,7 @@ def create_simple_multipart_data(self, data): boundary = '---Boundary-%d' % random.randint(1,1000) crlf = '\r\n' items = [] - for key, value in data.iteritems(): + for key, value in iteritems(data): items += [ '--'+boundary, 'Content-Disposition: form-data; name="%s"'%str(key), @@ -1354,7 +1387,7 @@ def _two_legged(self, method): client = oauth.Client(self.consumer, None) return client.request(self._uri('two_legged'), method, - body=urllib.urlencode(self.body)) + body=urlencode(self.body)) def test_two_legged_post(self): """A test of a two-legged OAuth POST request.""" From d0c91306a032844ebc27e9f01cee199079cd1021 Mon Sep 17 00:00:00 2001 From: Richard Mitchell Date: Mon, 3 Dec 2012 15:05:38 +0000 Subject: [PATCH 2/3] Fix tests for Python 3. --- tests/test_oauth.py | 264 +++++++++++++++++++++++--------------------- 1 file changed, 139 insertions(+), 125 deletions(-) diff --git a/tests/test_oauth.py b/tests/test_oauth.py index 8f64e004..d32b6c66 100644 --- a/tests/test_oauth.py +++ b/tests/test_oauth.py @@ -92,7 +92,7 @@ def test_str(self): raise oauth.Error except oauth.Error: e = sys.exc_info()[1] - self.assertEquals(str(e), 'OAuth error occurred.') + self.assertEqual(str(e), 'OAuth error occurred.') class TestGenerateFunctions(unittest.TestCase): def test_build_auth_header(self): @@ -122,16 +122,16 @@ def test_build_xoauth_string(self): var, val = part.split('=') returned[var] = val.strip('"') - self.assertEquals('HMAC-SHA1', returned['oauth_signature_method']) - self.assertEquals('user_token', returned['oauth_token']) - self.assertEquals('consumer_token', returned['oauth_consumer_key']) + self.assertEqual('HMAC-SHA1', returned['oauth_signature_method']) + self.assertEqual('user_token', returned['oauth_token']) + self.assertEqual('consumer_token', returned['oauth_consumer_key']) self.assertTrue('oauth_signature' in returned, 'oauth_signature') def test_escape(self): string = 'http://whatever.com/~someuser/?test=test&other=other' - self.assert_('~' in oauth.escape(string)) + self.assertTrue('~' in oauth.escape(string)) string = '../../../../../../../etc/passwd' - self.assert_('../' not in oauth.escape(string)) + self.assertTrue('../' not in oauth.escape(string)) def test_gen_nonce(self): nonce = oauth.generate_nonce() @@ -169,8 +169,8 @@ def test_str(self): res = dict(parse_qsl(str(self.consumer))) self.assertTrue('oauth_consumer_key' in res) self.assertTrue('oauth_consumer_secret' in res) - self.assertEquals(res['oauth_consumer_key'], self.consumer.key) - self.assertEquals(res['oauth_consumer_secret'], self.consumer.secret) + self.assertEqual(res['oauth_consumer_key'], self.consumer.key) + self.assertEqual(res['oauth_consumer_secret'], self.consumer.secret) class TestToken(unittest.TestCase): def setUp(self): @@ -282,20 +282,21 @@ def test_from_string(self): class ReallyEqualMixin: def failUnlessReallyEqual(self, a, b, msg=None): - self.failUnlessEqual(a, b, msg=msg) - self.failUnlessEqual(type(a), type(b), msg="a :: %r, b :: %r, %r" % (a, b, msg)) + self.assertEqual(a, b, msg=msg) + self.assertEqual(type(a), type(b), msg="a :: %r, b :: %r, %r" % (a, b, msg)) class TestFuncs(unittest.TestCase): def test_to_unicode(self): - self.failUnlessRaises(TypeError, oauth.to_unicode, '\xae') - self.failUnlessRaises(TypeError, oauth.to_unicode_optional_iterator, '\xae') - self.failUnlessRaises(TypeError, oauth.to_unicode_optional_iterator, ['\xae']) + if not PY3: + self.assertRaises(TypeError, oauth.to_unicode, '\xae') + self.assertRaises(TypeError, oauth.to_unicode_optional_iterator, '\xae') + self.assertRaises(TypeError, oauth.to_unicode_optional_iterator, ['\xae']) + self.assertEqual(oauth.to_unicode('\xc2\xae'), _u('\u00ae')) - self.failUnlessEqual(oauth.to_unicode(':-)'), _u(':-)')) - self.failUnlessEqual(oauth.to_unicode(_u('\u00ae'), _u('\u00ae'))) - self.failUnlessEqual(oauth.to_unicode('\xc2\xae'), _u('\u00ae')) - self.failUnlessEqual(oauth.to_unicode_optional_iterator([':-)']), [_u(':-)')]) - self.failUnlessEqual(oauth.to_unicode_optional_iterator([_u('\u00ae')]), [_u('\u00ae')]) + self.assertEqual(oauth.to_unicode(':-)'), _u(':-)')) + self.assertEqual(oauth.to_unicode(_u('\u00ae')), _u('\u00ae')) + self.assertEqual(oauth.to_unicode_optional_iterator([':-)']), [_u(':-)')]) + self.assertEqual(oauth.to_unicode_optional_iterator([_u('\u00ae')]), [_u('\u00ae')]) class TestRequest(unittest.TestCase, ReallyEqualMixin): def test_setter(self): @@ -328,12 +329,12 @@ def test_url(self): method = "GET" req = oauth.Request(method, url1) - self.assertEquals(req.normalized_url, exp1) - self.assertEquals(req.url, url1) + self.assertEqual(req.normalized_url, exp1) + self.assertEqual(req.url, url1) req = oauth.Request(method, url2) - self.assertEquals(req.normalized_url, exp2) - self.assertEquals(req.url, url2) + self.assertEqual(req.normalized_url, exp2) + self.assertEqual(req.url, url2) def test_bad_url(self): request = oauth.Request() @@ -350,8 +351,8 @@ def test_unset_consumer_and_token(self): request.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, token) - self.assertEquals(consumer.key, request['oauth_consumer_key']) - self.assertEquals(token.key, request['oauth_token']) + self.assertEqual(consumer.key, request['oauth_consumer_key']) + self.assertEqual(token.key, request['oauth_token']) def test_no_url_set(self): consumer = oauth.Consumer('my_consumer_key', 'my_consumer_secret') @@ -373,8 +374,8 @@ def test_url_query(self): method = "GET" req = oauth.Request(method, url) - self.assertEquals(req.url, url) - self.assertEquals(req.normalized_url, normalized_url) + self.assertEqual(req.url, url) + self.assertEqual(req.normalized_url, normalized_url) def test_get_parameter(self): url = "http://example.com" @@ -382,7 +383,7 @@ def test_get_parameter(self): params = {'oauth_consumer' : 'asdf'} req = oauth.Request(method, url, parameters=params) - self.assertEquals(req.get_parameter('oauth_consumer'), 'asdf') + self.assertEqual(req.get_parameter('oauth_consumer'), 'asdf') self.assertRaises(oauth.Error, req.get_parameter, 'blah') def test_get_nonoauth_parameters(self): @@ -404,7 +405,7 @@ def test_get_nonoauth_parameters(self): params.update(other_params) req = oauth.Request("GET", "http://example.com", params) - self.assertEquals(other_params, req.get_nonoauth_parameters()) + self.assertEqual(other_params, req.get_nonoauth_parameters()) def test_to_url_nonascii(self): url = "http://sp.example.com/" @@ -484,13 +485,13 @@ def test_to_header(self): var, val = v.split('=') res[var] = unquote(val.strip('"')) - self.assertEquals(realm, res['realm']) + self.assertEqual(realm, res['realm']) del res['realm'] self.assertTrue(len(res), len(params)) for key, val in res.items(): - self.assertEquals(val, params.get(key)) + self.assertEqual(val, params.get(key)) def test_to_postdata_nonascii(self): realm = "http://sp.example.com/" @@ -530,7 +531,7 @@ def test_to_postdata(self): del params['multi'] flat.extend(params.items()) kf = lambda x: x[0] - self.assertEquals(sorted(flat, key=kf), sorted(parse_qsl(req.to_postdata()), key=kf)) + self.assertEqual(sorted(flat, key=kf), sorted(parse_qsl(req.to_postdata()), key=kf)) def test_to_url(self): url = "http://sp.example.com/" @@ -548,13 +549,13 @@ def test_to_url(self): req = oauth.Request("GET", url, params) exp = urlparse.urlparse("%s?%s" % (url, urlencode(params))) res = urlparse.urlparse(req.to_url()) - self.assertEquals(exp.scheme, res.scheme) - self.assertEquals(exp.netloc, res.netloc) - self.assertEquals(exp.path, res.path) + self.assertEqual(exp.scheme, res.scheme) + self.assertEqual(exp.netloc, res.netloc) + self.assertEqual(exp.path, res.path) a = parse_qs(exp.query) b = parse_qs(res.query) - self.assertEquals(a, b) + self.assertEqual(a, b) def test_to_url_with_query(self): url = "https://www.google.com/m8/feeds/contacts/default/full/?alt=json&max-contacts=10" @@ -573,17 +574,17 @@ def test_to_url_with_query(self): # Note: the url above already has query parameters, so append new ones with & exp = urlparse.urlparse("%s&%s" % (url, urlencode(params))) res = urlparse.urlparse(req.to_url()) - self.assertEquals(exp.scheme, res.scheme) - self.assertEquals(exp.netloc, res.netloc) - self.assertEquals(exp.path, res.path) + self.assertEqual(exp.scheme, res.scheme) + self.assertEqual(exp.netloc, res.netloc) + self.assertEqual(exp.path, res.path) a = parse_qs(exp.query) b = parse_qs(res.query) self.assertTrue('alt' in b) self.assertTrue('max-contacts' in b) - self.assertEquals(b['alt'], ['json']) - self.assertEquals(b['max-contacts'], ['10']) - self.assertEquals(a, b) + self.assertEqual(b['alt'], ['json']) + self.assertEqual(b['max-contacts'], ['10']) + self.assertEqual(a, b) def test_signature_base_string_nonascii_nonutf8(self): consumer = oauth.Consumer('consumer_token', 'consumer_secret') @@ -594,11 +595,12 @@ def test_signature_base_string_nonascii_nonutf8(self): req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, None) self.failUnlessReallyEqual(req['oauth_signature'], 'WhufgeZKyYpKsI70GZaiDaYwl6g=') - url = 'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc\xe2\x9d\xa6,+CA' - req = oauth.Request("GET", url) - self.failUnlessReallyEqual(req.normalized_url, _u('http://api.simplegeo.com/1.0/places/address.json')) - req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, None) - self.failUnlessReallyEqual(req['oauth_signature'], 'WhufgeZKyYpKsI70GZaiDaYwl6g=') + if not PY3: + url = 'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc\xe2\x9d\xa6,+CA' + req = oauth.Request("GET", url) + self.failUnlessReallyEqual(req.normalized_url, _u('http://api.simplegeo.com/1.0/places/address.json')) + req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, None) + self.failUnlessReallyEqual(req['oauth_signature'], 'WhufgeZKyYpKsI70GZaiDaYwl6g=') url = 'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc%E2%9D%A6,+CA' req = oauth.Request("GET", url) @@ -624,17 +626,17 @@ def test_signature_base_string_with_query(self): 'oauth_signature': "wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D", } req = oauth.Request("GET", url, params) - self.assertEquals(req.normalized_url, 'https://www.google.com/m8/feeds/contacts/default/full/') - self.assertEquals(req.url, 'https://www.google.com/m8/feeds/contacts/default/full/?alt=json&max-contacts=10') + self.assertEqual(req.normalized_url, 'https://www.google.com/m8/feeds/contacts/default/full/') + self.assertEqual(req.url, 'https://www.google.com/m8/feeds/contacts/default/full/?alt=json&max-contacts=10') normalized_params = parse_qsl(req.get_normalized_parameters()) self.assertTrue(len(normalized_params), len(params) + 2) normalized_params = dict(normalized_params) for key, value in iteritems(params): if key == 'oauth_signature': continue - self.assertEquals(value, normalized_params[key]) - self.assertEquals(normalized_params['alt'], 'json') - self.assertEquals(normalized_params['max-contacts'], '10') + self.assertEqual(value, normalized_params[key]) + self.assertEqual(normalized_params['alt'], 'json') + self.assertEqual(normalized_params['max-contacts'], '10') def test_get_normalized_parameters_empty(self): url = "http://sp.example.com/?empty=" @@ -645,7 +647,7 @@ def test_get_normalized_parameters_empty(self): expected='empty=' - self.assertEquals(expected, res) + self.assertEqual(expected, res) def test_get_normalized_parameters_duplicate(self): url = "http://example.com/v2/search/videos?oauth_nonce=79815175&oauth_timestamp=1295397962&oauth_consumer_key=mykey&oauth_signature_method=HMAC-SHA1&q=car&oauth_version=1.0&offset=10&oauth_signature=spWLI%2FGQjid7sQVd5%2FarahRxzJg%3D" @@ -656,7 +658,7 @@ def test_get_normalized_parameters_duplicate(self): expected='oauth_consumer_key=mykey&oauth_nonce=79815175&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1295397962&oauth_version=1.0&offset=10&q=car' - self.assertEquals(expected, res) + self.assertEqual(expected, res) def test_get_normalized_parameters_multiple(self): url = "http://example.com/v2/search/videos?oauth_nonce=79815175&oauth_timestamp=1295397962&oauth_consumer_key=mykey&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&offset=10&oauth_signature=spWLI%2FGQjid7sQVd5%2FarahRxzJg%3D&tag=one&tag=two" @@ -683,7 +685,7 @@ def test_get_normalized_parameters_from_url(self): expected = 'file=vacation.jpg&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_nonce=kllo9940pd9333jh&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1191242096&oauth_token=nnch734d00sl2jdk&oauth_version=1.0&size=original' - self.assertEquals(expected, res) + self.assertEqual(expected, res) def test_signing_base(self): # example copied from @@ -700,7 +702,7 @@ def test_signing_base(self): key, raw = sm.signing_base(req, consumer, None) expected = 'GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal' - self.assertEquals(expected, raw) + self.assertEqual(expected, raw) def test_get_normalized_parameters(self): url = "http://sp.example.com/" @@ -722,9 +724,11 @@ def test_get_normalized_parameters(self): res = req.get_normalized_parameters() - expected='multi=BAR&multi=FOO&multi=%C2%AE&multi=%C2%AE&multi_same=FOO&multi_same=FOO&oauth_consumer_key=0685bd9184jfhq22&oauth_nonce=4572616e48616d6d65724c61686176&oauth_signature_method=HMAC-SHA1&oauth_timestamp=137131200&oauth_token=ad180jjd733klru7&oauth_version=1.0&uni_unicode_object=%C2%AE&uni_utf8_bytes=%C2%AE' + expected = 'multi=BAR&multi=FOO&multi=%C2%AE&multi=%C2%AE&multi_same=FOO&multi_same=FOO&oauth_consumer_key=0685bd9184jfhq22&oauth_nonce=4572616e48616d6d65724c61686176&oauth_signature_method=HMAC-SHA1&oauth_timestamp=137131200&oauth_token=ad180jjd733klru7&oauth_version=1.0&uni_unicode_object=%C2%AE&uni_utf8_bytes=%C2%AE' + if PY3: + expected = 'multi=BAR&multi=FOO&multi=%C2%AE&multi=%C3%82%C2%AE&multi_same=FOO&multi_same=FOO&oauth_consumer_key=0685bd9184jfhq22&oauth_nonce=4572616e48616d6d65724c61686176&oauth_signature_method=HMAC-SHA1&oauth_timestamp=137131200&oauth_token=ad180jjd733klru7&oauth_version=1.0&uni_unicode_object=%C2%AE&uni_utf8_bytes=%C3%82%C2%AE' - self.assertEquals(expected, res) + self.assertEqual(expected, res) def test_get_normalized_parameters_ignores_auth_signature(self): url = "http://sp.example.com/" @@ -743,7 +747,7 @@ def test_get_normalized_parameters_ignores_auth_signature(self): res = req.get_normalized_parameters() - self.assertNotEquals(urlencode(sorted(params.items())), res) + self.assertNotEqual(urlencode(sorted(params.items())), res) foo = params.copy() del foo["oauth_signature"] @@ -771,7 +775,7 @@ class Blah: m = oauth.SignatureMethod_HMAC_SHA1() client.set_signature_method(m) - self.assertEquals(m, client.method) + self.assertEqual(m, client.method) def test_get_normalized_string_escapes_spaces_properly(self): url = "http://sp.example.com/" @@ -801,10 +805,11 @@ def test_request_nonutf8_bytes(self, mock_make_nonce, mock_make_timestamp): 'oauth_consumer_key': con.key } - # If someone passes a sequence of bytes which is not ascii for - # url, we'll raise an exception as early as possible. - url = "http://sp.example.com/\x92" # It's actually cp1252-encoding... - self.assertRaises(TypeError, oauth.Request, method="GET", url=url, parameters=params) + if not PY3: + # If someone passes a sequence of bytes which is not ascii for + # url, we'll raise an exception as early as possible. + url = "http://sp.example.com/\x92" # It's actually cp1252-encoding... + self.assertRaises(TypeError, oauth.Request, method="GET", url=url, parameters=params) # And if they pass an unicode, then we'll use it. url = _u('http://sp.example.com/\u2019') @@ -822,10 +827,11 @@ def test_request_nonutf8_bytes(self, mock_make_nonce, mock_make_timestamp): # Same thing with the params. url = "http://sp.example.com/" - # If someone passes a sequence of bytes which is not ascii in - # params, we'll raise an exception as early as possible. - params['non_oauth_thing'] = '\xae', # It's actually cp1252-encoding... - self.assertRaises(TypeError, oauth.Request, method="GET", url=url, parameters=params) + if not PY3: + # If someone passes a sequence of bytes which is not ascii in + # params, we'll raise an exception as early as possible. + params['non_oauth_thing'] = '\xae', # It's actually cp1252-encoding... + self.assertRaises(TypeError, oauth.Request, method="GET", url=url, parameters=params) # And if they pass a unicode, then we'll use it. params['non_oauth_thing'] = _u('\u2019') @@ -838,12 +844,16 @@ def test_request_nonutf8_bytes(self, mock_make_nonce, mock_make_timestamp): params['non_oauth_thing'] = '\xc2\xae' req = oauth.Request(method="GET", url=url, parameters=params) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, None) - self.failUnlessReallyEqual(req['oauth_signature'], 'pqOCu4qvRTiGiXB8Z61Jsey0pMM=') + expected = 'pqOCu4qvRTiGiXB8Z61Jsey0pMM=' + if PY3: + expected = 'zHfzdfpczALRdfMO2u6x+2M4ibk=' + self.failUnlessReallyEqual(req['oauth_signature'], expected) - # Also if there are non-utf8 bytes in the query args. - url = "http://sp.example.com/?q=\x92" # cp1252 - self.assertRaises(TypeError, oauth.Request, method="GET", url=url, parameters=params) + if not PY3: + # Also if there are non-utf8 bytes in the query args. + url = "http://sp.example.com/?q=\x92" # cp1252 + self.assertRaises(TypeError, oauth.Request, method="GET", url=url, parameters=params) def test_request_hash_of_body(self): tok = oauth.Token(key="token", secret="tok-test-secret") @@ -922,30 +932,32 @@ def test_sign_request(self): for exp, method in methods.items(): req.sign_request(method, con, tok) - self.assertEquals(req['oauth_signature_method'], method.name) - self.assertEquals(req['oauth_signature'], exp) + self.assertEqual(req['oauth_signature_method'], method.name) + self.assertEqual(req['oauth_signature'], exp) - # Also if there are non-ascii chars in the URL. - url = "http://sp.example.com/\xe2\x80\x99" # utf-8 bytes - req = oauth.Request(method="GET", url=url, parameters=params) - req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, tok) - self.assertEquals(req['oauth_signature'], 'loFvp5xC7YbOgd9exIO6TxB7H4s=') + if not PY3: + # Also if there are non-ascii chars in the URL. + url = "http://sp.example.com/\xe2\x80\x99" # utf-8 bytes + req = oauth.Request(method="GET", url=url, parameters=params) + req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, tok) + self.assertEqual(req['oauth_signature'], 'loFvp5xC7YbOgd9exIO6TxB7H4s=') url = _u('http://sp.example.com/\u2019') # Python unicode object req = oauth.Request(method="GET", url=url, parameters=params) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, tok) - self.assertEquals(req['oauth_signature'], 'loFvp5xC7YbOgd9exIO6TxB7H4s=') + self.assertEqual(req['oauth_signature'], 'loFvp5xC7YbOgd9exIO6TxB7H4s=') - # Also if there are non-ascii chars in the query args. - url = "http://sp.example.com/?q=\xe2\x80\x99" # utf-8 bytes - req = oauth.Request(method="GET", url=url, parameters=params) - req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, tok) - self.assertEquals(req['oauth_signature'], 'IBw5mfvoCsDjgpcsVKbyvsDqQaU=') + if not PY3: + # Also if there are non-ascii chars in the query args. + url = "http://sp.example.com/?q=\xe2\x80\x99" # utf-8 bytes + req = oauth.Request(method="GET", url=url, parameters=params) + req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, tok) + self.assertEqual(req['oauth_signature'], 'IBw5mfvoCsDjgpcsVKbyvsDqQaU=') url = _u('http://sp.example.com/?q=\u2019') # Python unicode object req = oauth.Request(method="GET", url=url, parameters=params) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, tok) - self.assertEquals(req['oauth_signature'], 'IBw5mfvoCsDjgpcsVKbyvsDqQaU=') + self.assertEqual(req['oauth_signature'], 'IBw5mfvoCsDjgpcsVKbyvsDqQaU=') def test_from_request_works_with_wsgi(self): @@ -1022,10 +1034,10 @@ def test_from_request(self): # Test from the headers req = oauth.Request.from_request("GET", url, headers) - self.assertEquals(req.method, "GET") - self.assertEquals(req.url, url) + self.assertEqual(req.method, "GET") + self.assertEqual(req.url, url) - self.assertEquals(params, req.copy()) + self.assertEqual(params, req.copy()) # Test with bad OAuth headers bad_headers = { @@ -1043,11 +1055,11 @@ def test_from_request(self): for k, v in iteritems(exp): exp[k] = unquote(v[0]) - self.assertEquals(exp, req.copy()) + self.assertEqual(exp, req.copy()) # Test that a boned from_request() call returns None req = oauth.Request.from_request("GET", url) - self.assertEquals(None, req) + self.assertEqual(None, req) def test_from_token_and_callback(self): url = "http://sp.example.com/" @@ -1065,11 +1077,11 @@ def test_from_token_and_callback(self): tok = oauth.Token(key="tok-test-key", secret="tok-test-secret") req = oauth.Request.from_token_and_callback(tok) self.assertFalse('oauth_callback' in req) - self.assertEquals(req['oauth_token'], tok.key) + self.assertEqual(req['oauth_token'], tok.key) req = oauth.Request.from_token_and_callback(tok, callback=url) self.assertTrue('oauth_callback' in req) - self.assertEquals(req['oauth_callback'], url) + self.assertEqual(req['oauth_callback'], url) def test_from_consumer_and_token(self): url = "http://sp.example.com/" @@ -1080,9 +1092,9 @@ def test_from_consumer_and_token(self): req = oauth.Request.from_consumer_and_token(con, token=tok, http_method="GET", http_url=url) - self.assertEquals(req['oauth_token'], tok.key) - self.assertEquals(req['oauth_consumer_key'], con.key) - self.assertEquals(tok.verifier, req['oauth_verifier']) + self.assertEqual(req['oauth_token'], tok.key) + self.assertEqual(req['oauth_consumer_key'], con.key) + self.assertEqual(tok.verifier, req['oauth_verifier']) class SignatureMethod_Bad(oauth.SignatureMethod): name = "BAD" @@ -1125,7 +1137,7 @@ def test_init(self): oauth.SignatureMethod_HMAC_SHA1)) server = oauth.Server() - self.assertEquals(server.signature_methods, {}) + self.assertEqual(server.signature_methods, {}) def test_add_signature_method(self): server = oauth.Server() @@ -1151,15 +1163,15 @@ def test_verify_request(self): self.assertTrue('bar' in parameters) self.assertTrue('foo' in parameters) self.assertTrue('multi' in parameters) - self.assertEquals(parameters['bar'], 'blerg') - self.assertEquals(parameters['foo'], 59) - self.assertEquals(parameters['multi'], ['FOO','BAR']) + self.assertEqual(parameters['bar'], 'blerg') + self.assertEqual(parameters['foo'], 59) + self.assertEqual(parameters['multi'], ['FOO','BAR']) def test_build_authenticate_header(self): server = oauth.Server() headers = server.build_authenticate_header('example.com') self.assertTrue('WWW-Authenticate' in headers) - self.assertEquals('OAuth realm="example.com"', + self.assertEqual('OAuth realm="example.com"', headers['WWW-Authenticate']) def test_no_version(self): @@ -1370,15 +1382,17 @@ def test_access_token_get(self): client = oauth.Client(self.consumer, None) resp, content = client.request(self._uri('request_token'), "GET") - self.assertEquals(int(resp['status']), 200) + self.assertEqual(int(resp['status']), 200) def test_access_token_post(self): """Test getting an access token via POST.""" client = oauth.Client(self.consumer, None) resp, content = client.request(self._uri('request_token'), "POST") - self.assertEquals(int(resp['status']), 200) + self.assertEqual(int(resp['status']), 200) + if PY3: + content = content.decode('utf8') res = dict(parse_qsl(content)) self.assertTrue('oauth_token' in res) self.assertTrue('oauth_token_secret' in res) @@ -1393,12 +1407,12 @@ def test_two_legged_post(self): """A test of a two-legged OAuth POST request.""" resp, content = self._two_legged("POST") - self.assertEquals(int(resp['status']), 200) + self.assertEqual(int(resp['status']), 200) def test_two_legged_get(self): """A test of a two-legged OAuth GET request.""" resp, content = self._two_legged("GET") - self.assertEquals(int(resp['status']), 200) + self.assertEqual(int(resp['status']), 200) @mock.patch('httplib2.Http.request') def test_multipart_post_does_not_alter_body(self, mockHttpRequest): @@ -1413,14 +1427,14 @@ def test_multipart_post_does_not_alter_body(self, mockHttpRequest): uri = self._uri('two_legged') def mockrequest(cl, ur, **kw): - self.failUnless(cl is client) - self.failUnless(ur is uri) - self.failUnlessEqual(frozenset(kw.keys()), frozenset(['method', 'body', 'redirections', 'connection_type', 'headers'])) - self.failUnlessEqual(kw['body'], body) - self.failUnlessEqual(kw['connection_type'], None) - self.failUnlessEqual(kw['method'], 'POST') - self.failUnlessEqual(kw['redirections'], httplib2.DEFAULT_MAX_REDIRECTS) - self.failUnless(isinstance(kw['headers'], dict)) + self.assertTrue(cl is client) + self.assertTrue(ur is uri) + self.assertEqual(frozenset(kw.keys()), frozenset(['method', 'body', 'redirections', 'connection_type', 'headers'])) + self.assertEqual(kw['body'], body) + self.assertEqual(kw['connection_type'], None) + self.assertEqual(kw['method'], 'POST') + self.assertEqual(kw['redirections'], httplib2.DEFAULT_MAX_REDIRECTS) + self.assertTrue(isinstance(kw['headers'], dict)) return random_result @@ -1436,24 +1450,24 @@ def test_url_with_query_string(self, mockHttpRequest): random_result = random.randint(1,100) def mockrequest(cl, ur, **kw): - self.failUnless(cl is client) - self.failUnlessEqual(frozenset(kw.keys()), frozenset(['method', 'body', 'redirections', 'connection_type', 'headers'])) - self.failUnlessEqual(kw['body'], '') - self.failUnlessEqual(kw['connection_type'], None) - self.failUnlessEqual(kw['method'], 'GET') - self.failUnlessEqual(kw['redirections'], httplib2.DEFAULT_MAX_REDIRECTS) - self.failUnless(isinstance(kw['headers'], dict)) + self.assertTrue(cl is client) + self.assertEqual(frozenset(kw.keys()), frozenset(['method', 'body', 'redirections', 'connection_type', 'headers'])) + self.assertEqual(kw['body'], '') + self.assertEqual(kw['connection_type'], None) + self.assertEqual(kw['method'], 'GET') + self.assertEqual(kw['redirections'], httplib2.DEFAULT_MAX_REDIRECTS) + self.assertTrue(isinstance(kw['headers'], dict)) req = oauth.Request.from_consumer_and_token(self.consumer, None, http_method='GET', http_url=uri, parameters={}) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), self.consumer, None) expected = parse_qsl(urlparse.urlparse(req.to_url()).query) actual = parse_qsl(urlparse.urlparse(ur).query) - self.failUnlessEqual(len(expected), len(actual)) + self.assertEqual(len(expected), len(actual)) actual = dict(actual) for key, value in expected: if key not in ('oauth_signature', 'oauth_nonce', 'oauth_timestamp'): - self.failUnlessEqual(actual[key], value) + self.assertEqual(actual[key], value) return random_result @@ -1471,11 +1485,11 @@ def test_multiple_values_for_a_key(self, mockReqConstructor, mockHttpRequest): client.request('http://whatever', 'POST', body='multi=1&multi=2') - self.failUnlessEqual(mockReqConstructor.call_count, 1) - self.failUnlessEqual(mockReqConstructor.call_args[1]['parameters'], {'multi': ['1', '2']}) + self.assertEqual(mockReqConstructor.call_count, 1) + self.assertEqual(mockReqConstructor.call_args[1]['parameters'], {'multi': ['1', '2']}) - self.failUnless('multi=1' in mockHttpRequest.call_args[1]['body']) - self.failUnless('multi=2' in mockHttpRequest.call_args[1]['body']) + self.assertTrue('multi=1' in mockHttpRequest.call_args[1]['body']) + self.assertTrue('multi=2' in mockHttpRequest.call_args[1]['body']) if __name__ == "__main__": unittest.main() From 750be672483fc0dbd1b538e8f6f1b11ff92e6411 Mon Sep 17 00:00:00 2001 From: Richard Mitchell Date: Tue, 4 Aug 2015 15:09:10 +0100 Subject: [PATCH 3/3] Fix tests after merge/rebase. --- tests/test_oauth.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/test_oauth.py b/tests/test_oauth.py index d32b6c66..9d3368e5 100644 --- a/tests/test_oauth.py +++ b/tests/test_oauth.py @@ -758,7 +758,6 @@ def test_signature_base_string_with_matrix_params(self): req = oauth.Request("GET", url, None) self.assertEquals(req.normalized_url, 'http://social.yahooapis.com/v1/user/6677/connections;start=0;count=20') self.assertEquals(req.url, 'http://social.yahooapis.com/v1/user/6677/connections;start=0;count=20') - self.assertEqual(urlencode(sorted(foo.items())), res) def test_set_signature_method(self): consumer = oauth.Consumer('key', 'secret')