Skip to content

Commit dcc11df

Browse files
author
Philip Langdale
committed
Revert "[py] Make scripts Python 3 compatible"
This reverts commit 73829ba.
1 parent 27499aa commit dcc11df

File tree

14 files changed

+140
-146
lines changed

14 files changed

+140
-146
lines changed

python/Makefile

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,6 @@ test:
2929
@echo 'Running tests...'
3030
PYTHONPATH=src python -m unittest discover src/cm_api_tests
3131

32-
.PHONY: test_py3
33-
test_py3:
34-
@echo 'Running tests...'
35-
PYTHONPATH=src python3 -m unittest discover src/cm_api_tests
36-
3732
.PHONY: dist
3833
dist: test
3934
git rev-parse HEAD > .git-hash

python/src/cm_api/endpoints/services.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1472,14 +1472,14 @@ def create_replication_schedule(self,
14721472

14731473
if self.type == 'HDFS':
14741474
if not isinstance(arguments, ApiHdfsReplicationArguments):
1475-
raise TypeError('Unexpected type for HDFS replication argument.')
1475+
raise TypeError, 'Unexpected type for HDFS replication argument.'
14761476
schedule.hdfsArguments = arguments
14771477
elif self.type == 'HIVE':
14781478
if not isinstance(arguments, ApiHiveReplicationArguments):
1479-
raise TypeError('Unexpected type for Hive replication argument.')
1479+
raise TypeError, 'Unexpected type for Hive replication argument.'
14801480
schedule.hiveArguments = arguments
14811481
else:
1482-
raise TypeError('Replication is not supported for service type ' + self.type)
1482+
raise TypeError, 'Replication is not supported for service type ' + self.type
14831483

14841484
return self._post("replications", ApiReplicationSchedule, True, [schedule],
14851485
api_version=3)[0]

python/src/cm_api/endpoints/types.py

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121

2222
import copy
2323
import datetime
24-
import six
2524
import time
2625

2726
__docformat__ = "epytext"
@@ -132,7 +131,7 @@ def call(method, path, ret_type,
132131
@param params: Optional query parameters for the call.
133132
@param api_version: minimum API version for the call.
134133
"""
135-
check_api_version(method.__self__, api_version)
134+
check_api_version(method.im_self, api_version)
136135
if data is not None:
137136
data = json.dumps(Attr(is_api_list=True).to_json(data, False))
138137
ret = method(path, data=data, params=params)
@@ -141,11 +140,11 @@ def call(method, path, ret_type,
141140
if ret_type is None:
142141
return
143142
elif ret_is_list:
144-
return ApiList.from_json_dict(ret, method.__self__, ret_type)
143+
return ApiList.from_json_dict(ret, method.im_self, ret_type)
145144
elif isinstance(ret, list):
146-
return [ ret_type.from_json_dict(x, method.__self__) for x in ret ]
145+
return [ ret_type.from_json_dict(x, method.im_self) for x in ret ]
147146
else:
148-
return ret_type.from_json_dict(ret, method.__self__)
147+
return ret_type.from_json_dict(ret, method.im_self)
149148

150149
class BaseApiObject(object):
151150
"""
@@ -192,7 +191,7 @@ def init(obj, resource_root, attrs=None):
192191
# We use unicode strings as keys in kwargs.
193192
str_attrs = { }
194193
if attrs:
195-
for k, v in six.iteritems(attrs):
194+
for k, v in attrs.iteritems():
196195
if k not in ('self', 'resource_root'):
197196
str_attrs[k] = v
198197
BaseApiObject.__init__(obj, resource_root, **str_attrs)
@@ -209,7 +208,7 @@ def __init__(self, resource_root, **attrs):
209208
"""
210209
self._resource_root = resource_root
211210

212-
for name, attr in six.iteritems(self._get_attributes()):
211+
for name, attr in self._get_attributes().iteritems():
213212
object.__setattr__(self, name, None)
214213
if attrs:
215214
self._set_attrs(attrs, from_json=False)
@@ -220,7 +219,7 @@ def _set_attrs(self, attrs, allow_ro=False, from_json=True):
220219
read-only attributes (e.g. when deserializing from JSON) and skipping
221220
JSON deserialization of values.
222221
"""
223-
for k, v in six.iteritems(attrs):
222+
for k, v in attrs.iteritems():
224223
attr = self._check_attr(k, allow_ro)
225224
if attr and from_json:
226225
v = attr.from_json(self._get_resource_root(), v)
@@ -255,12 +254,12 @@ def _update(self, api_obj):
255254
try:
256255
val = getattr(api_obj, name)
257256
setattr(self, name, val)
258-
except AttributeError as ignored:
257+
except AttributeError, ignored:
259258
pass
260259

261260
def to_json_dict(self, preserve_ro=False):
262261
dic = { }
263-
for name, attr in six.iteritems(self._get_attributes()):
262+
for name, attr in self._get_attributes().iteritems():
264263
if not preserve_ro and attr and not attr.rw:
265264
continue
266265
try:
@@ -486,7 +485,7 @@ class ApiCommand(BaseApiObject):
486485

487486
@classmethod
488487
def _get_attributes(cls):
489-
if '_ATTRIBUTES' not in cls.__dict__:
488+
if not cls.__dict__.has_key('_ATTRIBUTES'):
490489
cls._ATTRIBUTES = {
491490
'id' : ROAttr(),
492491
'name' : ROAttr(),
@@ -761,7 +760,7 @@ class ApiHiveReplicationResult(BaseApiObject):
761760
class ApiReplicationCommand(ApiCommand):
762761
@classmethod
763762
def _get_attributes(cls):
764-
if '_ATTRIBUTES' not in cls.__dict__:
763+
if not cls.__dict__.has_key('_ATTRIBUTES'):
765764
attrs = {
766765
'hdfsResult' : ROAttr(ApiHdfsReplicationResult),
767766
'hiveResult' : ROAttr(ApiHiveReplicationResult),
@@ -1114,7 +1113,7 @@ def config_to_api_list(dic):
11141113
@return: JSON dictionary of an ApiConfig list (*not* an ApiList).
11151114
"""
11161115
config = [ ]
1117-
for k, v in six.iteritems(dic):
1116+
for k, v in dic.iteritems():
11181117
config.append({ 'name' : k, 'value': v })
11191118
return { ApiList.LIST_KEY : config }
11201119

python/src/cm_api/http_client.py

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,12 @@
1414
# See the License for the specific language governing permissions and
1515
# limitations under the License.
1616

17-
import logging
1817
import os
18+
import cookielib
19+
import logging
1920
import posixpath
2021
import types
21-
from six.moves import http_cookiejar
22-
from six.moves import urllib
22+
import urllib
2323

2424
try:
2525
import socks
@@ -32,6 +32,8 @@
3232
except ImportError:
3333
pass
3434

35+
import urllib2
36+
3537
__docformat__ = "epytext"
3638

3739
LOG = logging.getLogger(__name__)
@@ -45,7 +47,7 @@ def __init__(self, error):
4547
self._error = error
4648
self._code = None
4749
self._message = str(error)
48-
# See if there is a code or a message. (For urllib.error.HTTPError.)
50+
# See if there is a code or a message. (For urllib2.HTTPError.)
4951
try:
5052
self._code = error.code
5153
self._message = error.read()
@@ -89,15 +91,15 @@ def __init__(self, base_url, exc_class=None, logger=None):
8991
self._headers = { }
9092

9193
# Make a basic auth handler that does nothing. Set credentials later.
92-
self._passmgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
93-
authhandler = urllib.request.HTTPBasicAuthHandler(self._passmgr)
94+
self._passmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
95+
authhandler = urllib2.HTTPBasicAuthHandler(self._passmgr)
9496

9597
# Make a cookie processor
96-
cookiejar = http_cookiejar.CookieJar()
98+
cookiejar = cookielib.CookieJar()
9799

98-
self._opener = urllib.request.build_opener(
100+
self._opener = urllib2.build_opener(
99101
HTTPErrorProcessor(),
100-
urllib.request.HTTPCookieProcessor(cookiejar),
102+
urllib2.HTTPCookieProcessor(cookiejar),
101103
authhandler)
102104

103105

@@ -145,7 +147,7 @@ def execute(self, http_method, path, params=None, data=None, headers=None):
145147
@param data: The data to attach to the body of the request.
146148
@param headers: The headers to set for this request.
147149
148-
@return: The result of urllib.request.urlopen()
150+
@return: The result of urllib2.urlopen()
149151
"""
150152
# Prepare URL and params
151153
url = self._make_url(path, params)
@@ -156,8 +158,8 @@ def execute(self, http_method, path, params=None, data=None, headers=None):
156158
data = None
157159

158160
# Setup the request
159-
request = urllib.request.Request(url, data)
160-
# Hack/workaround because urllib only does GET and POST
161+
request = urllib2.Request(url, data)
162+
# Hack/workaround because urllib2 only does GET and POST
161163
request.get_method = lambda: http_method
162164

163165
headers = self._get_headers(headers)
@@ -168,28 +170,28 @@ def execute(self, http_method, path, params=None, data=None, headers=None):
168170
self.logger.debug("%s %s" % (http_method, url))
169171
try:
170172
return self._opener.open(request)
171-
except urllib.error.HTTPError as ex:
173+
except urllib2.HTTPError, ex:
172174
raise self._exc_class(ex)
173175

174176
def _make_url(self, path, params):
175177
res = self._base_url
176178
if path:
177179
res += posixpath.normpath('/' + path.lstrip('/'))
178180
if params:
179-
param_str = urllib.parse.urlencode(params, True)
181+
param_str = urllib.urlencode(params, True)
180182
res += '?' + param_str
181183
return iri_to_uri(res)
182184

183185

184-
class HTTPErrorProcessor(urllib.request.HTTPErrorProcessor):
186+
class HTTPErrorProcessor(urllib2.HTTPErrorProcessor):
185187
"""
186188
Python 2.4 only recognize 200 and 206 as success. It's broken. So we install
187189
the following processor to catch the bug.
188190
"""
189191
def http_response(self, request, response):
190192
if 200 <= response.code < 300:
191193
return response
192-
return urllib.request.HTTPErrorProcessor.http_response(self, request, response)
194+
return urllib2.HTTPErrorProcessor.http_response(self, request, response)
193195

194196
https_response = http_response
195197

@@ -214,14 +216,14 @@ def iri_to_uri(iri):
214216
# sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
215217
# / "*" / "+" / "," / ";" / "="
216218
# unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
217-
# Of the unreserved characters, urllib.parse.quote already considers all but
219+
# Of the unreserved characters, urllib.quote already considers all but
218220
# the ~ safe.
219221
# The % character is also added to the list of safe characters here, as the
220222
# end of section 3.1 of RFC 3987 specifically mentions that % must not be
221223
# converted.
222224
if iri is None:
223225
return iri
224-
return urllib.parse.quote(smart_str(iri), safe="/#%[]=:;$&()+,!?*@'~")
226+
return urllib.quote(smart_str(iri), safe="/#%[]=:;$&()+,!?*@'~")
225227

226228
#
227229
# Method copied from Django

python/src/cm_api/resource.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,18 +14,15 @@
1414
# See the License for the specific language governing permissions and
1515
# limitations under the License.
1616

17+
import os
1718
try:
1819
import json
1920
except ImportError:
2021
import simplejson as json
2122
import logging
22-
import os
2323
import posixpath
2424
import time
2525
import socket
26-
import six
27-
from six.moves import urllib
28-
2926
try:
3027
import socks
3128
socks_server = os.environ.get("SOCKS_SERVER", None)
@@ -35,6 +32,7 @@
3532
socket.socket = socks.socksocket
3633
except ImportError:
3734
pass
35+
import urllib2
3836

3937
LOG = logging.getLogger(__name__)
4038

@@ -75,7 +73,7 @@ def invoke(self, method, relpath=None, params=None, data=None, headers=None):
7573
headers=headers)
7674
try:
7775
body = resp.read()
78-
except Exception as ex:
76+
except Exception, ex:
7977
raise Exception("Command '%s %s' failed: %s" %
8078
(method, path, ex))
8179

@@ -90,7 +88,7 @@ def invoke(self, method, relpath=None, params=None, data=None, headers=None):
9088
try:
9189
json_dict = json.loads(body)
9290
return json_dict
93-
except Exception as ex:
91+
except Exception, ex:
9492
self._client.logger.exception('JSON decode error: %s' % (body,))
9593
raise ex
9694
else:
@@ -105,12 +103,12 @@ def get(self, relpath=None, params=None):
105103
106104
@return: A dictionary of the JSON result.
107105
"""
108-
for retry in six.moves.xrange(self.retries + 1):
106+
for retry in xrange(self.retries + 1):
109107
if retry:
110108
time.sleep(self.retry_sleep)
111109
try:
112110
return self.invoke("GET", relpath, params)
113-
except (socket.error, urllib.error.URLError) as e:
111+
except (socket.error, urllib2.URLError) as e:
114112
if "timed out" in str(e).lower():
115113
log_message = "Timeout issuing GET request for %s." \
116114
% (self._join_uri(relpath), )

python/src/cm_api_tests/test_baseapiobject.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ def test_serde(self):
8989
}
9090
'''
9191
obj = utils.deserialize(JSON, Parent)
92-
self.assertEqual([], obj.children)
92+
self.assertEquals([], obj.children)
9393

9494
def test_init(self):
9595
obj = Parent(None)
@@ -106,4 +106,4 @@ def test_empty_property(self):
106106
dummy.foo = 'foo'
107107
json = dummy.to_json_dict()
108108
self.assertEqual('foo', json['foo'])
109-
self.assertFalse('bar' in json)
109+
self.assertFalse(json.has_key('bar'))

python/src/cm_api_tests/test_batch.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,4 @@ def test_execute_batch(self):
3838
self.assertIsInstance(ret, ApiBatchResponseList)
3939
self.assertIsInstance(ret.success, bool)
4040
self.assertFalse(ret.success)
41-
self.assertEqual(0, len(ret))
41+
self.assertEquals(0, len(ret))

python/src/cm_api_tests/test_dashboards.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def test_create_dashboards(self):
5757
data=[dashboard])
5858

5959
resp = create_dashboards(resource, [dashboard])
60-
self.assertEqual(1, len(resp))
60+
self.assertEquals(1, len(resp))
6161

6262
def test_delete_dashboard(self):
6363
resource = utils.MockResource(self)

python/src/cm_api_tests/test_impala.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def test_get_queries(self):
3434
params={ 'from':time.isoformat(), 'to':time.isoformat(), \
3535
'filter':'', 'limit':100, 'offset':0 })
3636
resp = service.get_impala_queries(time, time)
37-
self.assertEqual(0, len(resp.queries))
37+
self.assertEquals(0, len(resp.queries))
3838

3939
def test_get_details(self):
4040
resource = utils.MockResource(self)
@@ -44,7 +44,7 @@ def test_get_details(self):
4444
retdata={ 'details': '' },
4545
params={ 'format':'text' } )
4646
resp = service.get_query_details('randomId')
47-
self.assertEqual('', resp.details)
47+
self.assertEquals('', resp.details)
4848

4949
def test_cancel_query(self):
5050
resource = utils.MockResource(self)
@@ -53,7 +53,7 @@ def test_cancel_query(self):
5353
resource.expect("POST", "/cm/service/impalaQueries/randomId/cancel",
5454
retdata={ 'warning' : 'test' })
5555
resp = service.cancel_impala_query('randomId')
56-
self.assertEqual('test', resp.warning)
56+
self.assertEquals('test', resp.warning)
5757

5858
def test_attributes(self):
5959
resource = utils.MockResource(self)
@@ -66,7 +66,7 @@ def test_attributes(self):
6666
'supportsHistograms' : True,
6767
'description' : 'testDescription' }])
6868
resp = service.get_impala_query_attributes()
69-
self.assertEqual(1, len(resp))
69+
self.assertEquals(1, len(resp))
7070
attr = resp[0]
7171
self.assertIsInstance(attr, ApiImpalaQueryAttribute)
72-
self.assertEqual('test', attr.name)
72+
self.assertEquals('test', attr.name)

0 commit comments

Comments
 (0)