Use Python 3.x compatible except construct

except x,y: was deprected and is removed in Python 3.x.
Use "except x as y:" instead which works in any Python
version >= 2.6.

Change-Id: I7008c74b807340f3457d3a0c8bd0b83f23169d14
This commit is contained in:
Dirk Mueller 2013-08-28 21:16:08 +02:00
parent 3102ad48d5
commit 3d36a76156
51 changed files with 175 additions and 175 deletions

View File

@ -347,7 +347,7 @@ class Auditor(object):
if __name__ == '__main__': if __name__ == '__main__':
try: try:
optlist, args = getopt.getopt(sys.argv[1:], 'c:r:e:d') optlist, args = getopt.getopt(sys.argv[1:], 'c:r:e:d')
except getopt.GetoptError, err: except getopt.GetoptError as err:
print str(err) print str(err)
print usage print usage
sys.exit(2) sys.exit(2)

View File

@ -96,11 +96,11 @@ def container_dispersion_report(coropool, connpool, account, container_ring,
container, error_log=error_log, retries=retries) container, error_log=error_log, retries=retries)
retries_done[0] += attempts - 1 retries_done[0] += attempts - 1
found_count += 1 found_count += 1
except ClientException, err: except ClientException as err:
if err.http_status not in (404, 507): if err.http_status not in (404, 507):
error_log('Giving up on /%s/%s/%s: %s' % (part, account, error_log('Giving up on /%s/%s/%s: %s' % (part, account,
container, err)) container, err))
except (Exception, Timeout), err: except (Exception, Timeout) as err:
error_log('Giving up on /%s/%s/%s: %s' % (part, account, error_log('Giving up on /%s/%s/%s: %s' % (part, account,
container, err)) container, err))
if output_missing_partitions and \ if output_missing_partitions and \
@ -170,7 +170,7 @@ def object_dispersion_report(coropool, connpool, account, object_ring,
try: try:
objects = [o['name'] for o in conn.get_container( objects = [o['name'] for o in conn.get_container(
container, prefix='dispersion_', full_listing=True)[1]] container, prefix='dispersion_', full_listing=True)[1]]
except ClientException, err: except ClientException as err:
if err.http_status != 404: if err.http_status != 404:
raise raise
print >>stderr, 'No objects to query. Has ' \ print >>stderr, 'No objects to query. Has ' \
@ -201,11 +201,11 @@ def object_dispersion_report(coropool, connpool, account, object_ring,
container, obj, error_log=error_log, retries=retries) container, obj, error_log=error_log, retries=retries)
retries_done[0] += attempts - 1 retries_done[0] += attempts - 1
found_count += 1 found_count += 1
except ClientException, err: except ClientException as err:
if err.http_status not in (404, 507): if err.http_status not in (404, 507):
error_log('Giving up on /%s/%s/%s/%s: %s' % (part, account, error_log('Giving up on /%s/%s/%s/%s: %s' % (part, account,
container, obj, err)) container, obj, err))
except (Exception, Timeout), err: except (Exception, Timeout) as err:
error_log('Giving up on /%s/%s/%s/%s: %s' % (part, account, error_log('Giving up on /%s/%s/%s/%s: %s' % (part, account,
container, obj, err)) container, obj, err))
if output_missing_partitions and \ if output_missing_partitions and \

View File

@ -251,7 +251,7 @@ swift-ring-builder <builder_file> create <part_power> <replicas>
backup_dir = pathjoin(dirname(argv[1]), 'backups') backup_dir = pathjoin(dirname(argv[1]), 'backups')
try: try:
mkdir(backup_dir) mkdir(backup_dir)
except OSError, err: except OSError as err:
if err.errno != EEXIST: if err.errno != EEXIST:
raise raise
builder.save(pathjoin(backup_dir, '%d.' % time() + basename(argv[1]))) builder.save(pathjoin(backup_dir, '%d.' % time() + basename(argv[1])))
@ -612,7 +612,7 @@ swift-ring-builder <builder_file> remove <search-value> [search-value ...]
for dev in devs: for dev in devs:
try: try:
builder.remove_dev(dev['id']) builder.remove_dev(dev['id'])
except exceptions.RingBuilderError, e: except exceptions.RingBuilderError as e:
print '-' * 79 print '-' * 79
print( print(
"An error occurred while removing device with id %d\n" "An error occurred while removing device with id %d\n"
@ -647,7 +647,7 @@ swift-ring-builder <builder_file> rebalance <seed>
try: try:
last_balance = builder.get_balance() last_balance = builder.get_balance()
parts, balance = builder.rebalance(seed=get_seed(3)) parts, balance = builder.rebalance(seed=get_seed(3))
except exceptions.RingBuilderError, e: except exceptions.RingBuilderError as e:
print '-' * 79 print '-' * 79
print ("An error has occurred during ring validation. Common\n" print ("An error has occurred during ring validation. Common\n"
"causes of failure are rings that are empty or do not\n" "causes of failure are rings that are empty or do not\n"
@ -672,7 +672,7 @@ swift-ring-builder <builder_file> rebalance <seed>
exit(EXIT_WARNING) exit(EXIT_WARNING)
try: try:
builder.validate() builder.validate()
except exceptions.RingValidationError, e: except exceptions.RingValidationError as e:
print '-' * 79 print '-' * 79
print ("An error has occurred during ring validation. Common\n" print ("An error has occurred during ring validation. Common\n"
"causes of failure are rings that are empty or do not\n" "causes of failure are rings that are empty or do not\n"
@ -813,7 +813,7 @@ if __name__ == '__main__':
backup_dir = pathjoin(dirname(argv[1]), 'backups') backup_dir = pathjoin(dirname(argv[1]), 'backups')
try: try:
mkdir(backup_dir) mkdir(backup_dir)
except OSError, err: except OSError as err:
if err.errno != EEXIST: if err.errno != EEXIST:
raise raise

View File

@ -331,7 +331,7 @@ class AccountReaper(Daemon):
self.stats_return_codes[2] = \ self.stats_return_codes[2] = \
self.stats_return_codes.get(2, 0) + 1 self.stats_return_codes.get(2, 0) + 1
self.logger.increment('return_codes.2') self.logger.increment('return_codes.2')
except ClientException, err: except ClientException as err:
if self.logger.getEffectiveLevel() <= DEBUG: if self.logger.getEffectiveLevel() <= DEBUG:
self.logger.exception( self.logger.exception(
_('Exception with %(ip)s:%(port)s/%(device)s'), node) _('Exception with %(ip)s:%(port)s/%(device)s'), node)
@ -374,7 +374,7 @@ class AccountReaper(Daemon):
self.stats_return_codes[2] = \ self.stats_return_codes[2] = \
self.stats_return_codes.get(2, 0) + 1 self.stats_return_codes.get(2, 0) + 1
self.logger.increment('return_codes.2') self.logger.increment('return_codes.2')
except ClientException, err: except ClientException as err:
if self.logger.getEffectiveLevel() <= DEBUG: if self.logger.getEffectiveLevel() <= DEBUG:
self.logger.exception( self.logger.exception(
_('Exception with %(ip)s:%(port)s/%(device)s'), node) _('Exception with %(ip)s:%(port)s/%(device)s'), node)
@ -433,7 +433,7 @@ class AccountReaper(Daemon):
self.stats_return_codes[2] = \ self.stats_return_codes[2] = \
self.stats_return_codes.get(2, 0) + 1 self.stats_return_codes.get(2, 0) + 1
self.logger.increment('return_codes.2') self.logger.increment('return_codes.2')
except ClientException, err: except ClientException as err:
if self.logger.getEffectiveLevel() <= DEBUG: if self.logger.getEffectiveLevel() <= DEBUG:
self.logger.exception( self.logger.exception(
_('Exception with %(ip)s:%(port)s/%(device)s'), node) _('Exception with %(ip)s:%(port)s/%(device)s'), node)

View File

@ -234,7 +234,7 @@ class AccountController(object):
return HTTPInsufficientStorage(drive=drive, request=req) return HTTPInsufficientStorage(drive=drive, request=req)
try: try:
args = json.load(req.environ['wsgi.input']) args = json.load(req.environ['wsgi.input'])
except ValueError, err: except ValueError as err:
return HTTPBadRequest(body=str(err), content_type='text/plain') return HTTPBadRequest(body=str(err), content_type='text/plain')
ret = self.replicator_rpc.dispatch(post_args, args) ret = self.replicator_rpc.dispatch(post_args, args)
ret.request = req ret.request = req

View File

@ -52,7 +52,7 @@ def delete_containers(logger, conf):
def _deleter(url, token, container): def _deleter(url, token, container):
try: try:
client.delete_container(url, token, container) client.delete_container(url, token, container)
except client.ClientException, e: except client.ClientException as e:
if e.http_status != HTTP_CONFLICT: if e.http_status != HTTP_CONFLICT:
logger.warn("Unable to delete container '%s'. " logger.warn("Unable to delete container '%s'. "
"Got http status '%d'." "Got http status '%d'."
@ -413,7 +413,7 @@ class BenchDELETE(Bench):
direct_client.direct_delete_object(node, partition, direct_client.direct_delete_object(node, partition,
self.account, self.account,
container_name, name) container_name, name)
except client.ClientException, e: except client.ClientException as e:
self.logger.debug(str(e)) self.logger.debug(str(e))
self.failures += 1 self.failures += 1
self.complete += 1 self.complete += 1
@ -442,7 +442,7 @@ class BenchGET(Bench):
direct_client.direct_get_object(node, partition, direct_client.direct_get_object(node, partition,
self.account, self.account,
container_name, name) container_name, name)
except client.ClientException, e: except client.ClientException as e:
self.logger.debug(str(e)) self.logger.debug(str(e))
self.failures += 1 self.failures += 1
self.complete += 1 self.complete += 1
@ -486,7 +486,7 @@ class BenchPUT(Bench):
container_name, name, container_name, name,
source, source,
content_length=len(source)) content_length=len(source))
except client.ClientException, e: except client.ClientException as e:
self.logger.debug(str(e)) self.logger.debug(str(e))
self.failures += 1 self.failures += 1
else: else:

View File

@ -130,7 +130,7 @@ def http_connect(ipaddr, port, device, partition, method, path,
if isinstance(path, unicode): if isinstance(path, unicode):
try: try:
path = path.encode("utf-8") path = path.encode("utf-8")
except UnicodeError, e: except UnicodeError as e:
logging.exception(_('Error encoding to UTF-8: %s'), str(e)) logging.exception(_('Error encoding to UTF-8: %s'), str(e))
path = quote('/' + device + '/' + str(partition) + path) path = quote('/' + device + '/' + str(partition) + path)
return http_connect_raw( return http_connect_raw(

View File

@ -95,7 +95,7 @@ class GreenDBConnection(sqlite3.Connection):
while True: while True:
try: try:
return call() return call()
except sqlite3.OperationalError, e: except sqlite3.OperationalError as e:
if 'locked' not in str(e): if 'locked' not in str(e):
raise raise
sleep(0.05) sleep(0.05)
@ -305,7 +305,7 @@ class DatabaseBroker(object):
os.path.basename(self.db_dir)) os.path.basename(self.db_dir))
try: try:
renamer(self.db_dir, quar_path) renamer(self.db_dir, quar_path)
except OSError, e: except OSError as e:
if e.errno not in (errno.EEXIST, errno.ENOTEMPTY): if e.errno not in (errno.EEXIST, errno.ENOTEMPTY):
raise raise
quar_path = "%s-%s" % (quar_path, uuid4().hex) quar_path = "%s-%s" % (quar_path, uuid4().hex)
@ -480,7 +480,7 @@ class DatabaseBroker(object):
with self.get() as conn: with self.get() as conn:
try: try:
curs = conn.execute(query_part1 + 'metadata' + query_part2) curs = conn.execute(query_part1 + 'metadata' + query_part2)
except sqlite3.OperationalError, err: except sqlite3.OperationalError as err:
if 'no such column: metadata' not in str(err): if 'no such column: metadata' not in str(err):
raise raise
curs = conn.execute(query_part1 + "'' as metadata" + curs = conn.execute(query_part1 + "'' as metadata" +
@ -518,7 +518,7 @@ class DatabaseBroker(object):
self.merge_items(item_list) self.merge_items(item_list)
try: try:
os.ftruncate(fp.fileno(), 0) os.ftruncate(fp.fileno(), 0)
except OSError, err: except OSError as err:
if err.errno != errno.ENOENT: if err.errno != errno.ENOENT:
raise raise
@ -605,7 +605,7 @@ class DatabaseBroker(object):
try: try:
metadata = conn.execute('SELECT metadata FROM %s_stat' % metadata = conn.execute('SELECT metadata FROM %s_stat' %
self.db_type).fetchone()[0] self.db_type).fetchone()[0]
except sqlite3.OperationalError, err: except sqlite3.OperationalError as err:
if 'no such column: metadata' not in str(err): if 'no such column: metadata' not in str(err):
raise raise
metadata = '' metadata = ''
@ -638,7 +638,7 @@ class DatabaseBroker(object):
self.db_type).fetchone()[0] self.db_type).fetchone()[0]
md = json.loads(md) if md else {} md = json.loads(md) if md else {}
utf8encodekeys(md) utf8encodekeys(md)
except sqlite3.OperationalError, err: except sqlite3.OperationalError as err:
if 'no such column: metadata' not in str(err): if 'no such column: metadata' not in str(err):
raise raise
conn.execute(""" conn.execute("""
@ -678,7 +678,7 @@ class DatabaseBroker(object):
conn.execute(''' conn.execute('''
DELETE FROM incoming_sync WHERE updated_at < ? DELETE FROM incoming_sync WHERE updated_at < ?
''', (sync_timestamp,)) ''', (sync_timestamp,))
except sqlite3.OperationalError, err: except sqlite3.OperationalError as err:
# Old dbs didn't have updated_at in the _sync tables. # Old dbs didn't have updated_at in the _sync tables.
if 'no such column: updated_at' not in str(err): if 'no such column: updated_at' not in str(err):
raise raise
@ -713,7 +713,7 @@ class DatabaseBroker(object):
conn.execute('UPDATE %s_stat SET metadata = ?' % conn.execute('UPDATE %s_stat SET metadata = ?' %
self.db_type, (json.dumps(md),)) self.db_type, (json.dumps(md),))
return True return True
except sqlite3.OperationalError, err: except sqlite3.OperationalError as err:
if 'no such column: metadata' not in str(err): if 'no such column: metadata' not in str(err):
raise raise
return False return False
@ -915,7 +915,7 @@ class ContainerBroker(DatabaseBroker):
pending_size = 0 pending_size = 0
try: try:
pending_size = os.path.getsize(self.pending_file) pending_size = os.path.getsize(self.pending_file)
except OSError, err: except OSError as err:
if err.errno != errno.ENOENT: if err.errno != errno.ENOENT:
raise raise
if pending_size > PENDING_CAP: if pending_size > PENDING_CAP:
@ -978,7 +978,7 @@ class ContainerBroker(DatabaseBroker):
id, %s id, %s
FROM container_stat FROM container_stat
''' % (trailing,)).fetchone() ''' % (trailing,)).fetchone()
except sqlite3.OperationalError, err: except sqlite3.OperationalError as err:
if 'no such column: x_container_sync_point' in str(err): if 'no such column: x_container_sync_point' in str(err):
trailing = '-1 AS x_container_sync_point1, ' \ trailing = '-1 AS x_container_sync_point1, ' \
'-1 AS x_container_sync_point2' '-1 AS x_container_sync_point2'
@ -998,7 +998,7 @@ class ContainerBroker(DatabaseBroker):
try: try:
self._set_x_container_sync_points(conn, sync_point1, self._set_x_container_sync_points(conn, sync_point1,
sync_point2) sync_point2)
except sqlite3.OperationalError, err: except sqlite3.OperationalError as err:
if 'no such column: x_container_sync_point' not in \ if 'no such column: x_container_sync_point' not in \
str(err): str(err):
raise raise
@ -1377,7 +1377,7 @@ class AccountBroker(DatabaseBroker):
pending_size = 0 pending_size = 0
try: try:
pending_size = os.path.getsize(self.pending_file) pending_size = os.path.getsize(self.pending_file)
except OSError, err: except OSError as err:
if err.errno != errno.ENOENT: if err.errno != errno.ENOENT:
raise raise
if pending_size > PENDING_CAP: if pending_size > PENDING_CAP:

View File

@ -60,7 +60,7 @@ def quarantine_db(object_file, server_type):
server_type + 's', os.path.basename(object_dir))) server_type + 's', os.path.basename(object_dir)))
try: try:
renamer(object_dir, quarantine_dir) renamer(object_dir, quarantine_dir)
except OSError, e: except OSError as e:
if e.errno not in (errno.EEXIST, errno.ENOTEMPTY): if e.errno not in (errno.EEXIST, errno.ENOTEMPTY):
raise raise
quarantine_dir = "%s-%s" % (quarantine_dir, uuid.uuid4().hex) quarantine_dir = "%s-%s" % (quarantine_dir, uuid.uuid4().hex)
@ -430,7 +430,7 @@ class Replicator(Daemon):
self.logger.error( self.logger.error(
'Found %s for %s when it should be on partition %s; will ' 'Found %s for %s when it should be on partition %s; will '
'replicate out and remove.' % (object_file, name, bpart)) 'replicate out and remove.' % (object_file, name, bpart))
except (Exception, Timeout), e: except (Exception, Timeout) as e:
if 'no such table' in str(e): if 'no such table' in str(e):
self.logger.error(_('Quarantining DB %s'), object_file) self.logger.error(_('Quarantining DB %s'), object_file)
quarantine_db(broker.db_file, broker.db_type) quarantine_db(broker.db_file, broker.db_type)
@ -495,7 +495,7 @@ class Replicator(Daemon):
shutil.rmtree(hash_dir, True) shutil.rmtree(hash_dir, True)
try: try:
os.rmdir(suf_dir) os.rmdir(suf_dir)
except OSError, err: except OSError as err:
if err.errno not in (errno.ENOENT, errno.ENOTEMPTY): if err.errno not in (errno.ENOENT, errno.ENOTEMPTY):
self.logger.exception( self.logger.exception(
_('ERROR while trying to clean up %s') % suf_dir) _('ERROR while trying to clean up %s') % suf_dir)
@ -604,7 +604,7 @@ class ReplicatorRpc(object):
timemark = time.time() timemark = time.time()
try: try:
info = broker.get_replication_info() info = broker.get_replication_info()
except (Exception, Timeout), e: except (Exception, Timeout) as e:
if 'no such table' in str(e): if 'no such table' in str(e):
self.logger.error(_("Quarantining DB %s") % broker.db_file) self.logger.error(_("Quarantining DB %s") % broker.db_file)
quarantine_db(broker.db_file, broker.db_type) quarantine_db(broker.db_file, broker.db_type)

View File

@ -469,12 +469,12 @@ def retry(func, *args, **kwargs):
attempts += 1 attempts += 1
try: try:
return attempts, func(*args, **kwargs) return attempts, func(*args, **kwargs)
except (socket.error, HTTPException, Timeout), err: except (socket.error, HTTPException, Timeout) as err:
if error_log: if error_log:
error_log(err) error_log(err)
if attempts > retries: if attempts > retries:
raise raise
except ClientException, err: except ClientException as err:
if error_log: if error_log:
error_log(err) error_log(err)
if attempts > retries or not is_server_error(err.http_status) or \ if attempts > retries or not is_server_error(err.http_status) or \

View File

@ -100,7 +100,7 @@ def watch_server_pids(server_pids, interval=1, **kwargs):
try: try:
# let pid stop if it wants to # let pid stop if it wants to
os.waitpid(pid, os.WNOHANG) os.waitpid(pid, os.WNOHANG)
except OSError, e: except OSError as e:
if e.errno not in (errno.ECHILD, errno.ESRCH): if e.errno not in (errno.ECHILD, errno.ESRCH):
raise # else no such child/process raise # else no such child/process
# check running pids for server # check running pids for server
@ -443,7 +443,7 @@ class Server():
print _('Signal %s pid: %s signal: %s') % (self.server, print _('Signal %s pid: %s signal: %s') % (self.server,
pid, sig) pid, sig)
os.kill(pid, sig) os.kill(pid, sig)
except OSError, e: except OSError as e:
if e.errno == errno.ESRCH: if e.errno == errno.ESRCH:
# pid does not exist # pid does not exist
if kwargs.get('verbose'): if kwargs.get('verbose'):
@ -611,7 +611,7 @@ class Server():
print '%s...(%s)' % (msg, conf_file) print '%s...(%s)' % (msg, conf_file)
try: try:
pid = self.spawn(conf_file, **kwargs) pid = self.spawn(conf_file, **kwargs)
except OSError, e: except OSError as e:
if e.errno == errno.ENOENT: if e.errno == errno.ENOENT:
#TODO(clayg): should I check if self.cmd exists earlier? #TODO(clayg): should I check if self.cmd exists earlier?
print _("%s does not exist") % self.cmd print _("%s does not exist") % self.cmd

View File

@ -174,7 +174,7 @@ class MemcacheRing(object):
sock.connect((host, int(port))) sock.connect((host, int(port)))
sock.settimeout(self._io_timeout) sock.settimeout(self._io_timeout)
yield server, sock.makefile(), sock yield server, sock.makefile(), sock
except Exception, e: except Exception as e:
self._exception_occurred( self._exception_occurred(
server, e, action='connecting', sock=sock) server, e, action='connecting', sock=sock)
@ -221,7 +221,7 @@ class MemcacheRing(object):
(key, flags, timeout, len(value), value)) (key, flags, timeout, len(value), value))
self._return_conn(server, fp, sock) self._return_conn(server, fp, sock)
return return
except Exception, e: except Exception as e:
self._exception_occurred(server, e, sock=sock, fp=fp) self._exception_occurred(server, e, sock=sock, fp=fp)
def get(self, key): def get(self, key):
@ -254,7 +254,7 @@ class MemcacheRing(object):
line = fp.readline().strip().split() line = fp.readline().strip().split()
self._return_conn(server, fp, sock) self._return_conn(server, fp, sock)
return value return value
except Exception, e: except Exception as e:
self._exception_occurred(server, e, sock=sock, fp=fp) self._exception_occurred(server, e, sock=sock, fp=fp)
def incr(self, key, delta=1, time=0, timeout=0): def incr(self, key, delta=1, time=0, timeout=0):
@ -306,7 +306,7 @@ class MemcacheRing(object):
ret = int(line[0].strip()) ret = int(line[0].strip())
self._return_conn(server, fp, sock) self._return_conn(server, fp, sock)
return ret return ret
except Exception, e: except Exception as e:
self._exception_occurred(server, e, sock=sock, fp=fp) self._exception_occurred(server, e, sock=sock, fp=fp)
raise MemcacheConnectionError("No Memcached connections succeeded.") raise MemcacheConnectionError("No Memcached connections succeeded.")
@ -343,7 +343,7 @@ class MemcacheRing(object):
sock.sendall('delete %s noreply\r\n' % key) sock.sendall('delete %s noreply\r\n' % key)
self._return_conn(server, fp, sock) self._return_conn(server, fp, sock)
return return
except Exception, e: except Exception as e:
self._exception_occurred(server, e, sock=sock, fp=fp) self._exception_occurred(server, e, sock=sock, fp=fp)
def set_multi(self, mapping, server_key, serialize=True, timeout=0, def set_multi(self, mapping, server_key, serialize=True, timeout=0,
@ -391,7 +391,7 @@ class MemcacheRing(object):
sock.sendall(msg) sock.sendall(msg)
self._return_conn(server, fp, sock) self._return_conn(server, fp, sock)
return return
except Exception, e: except Exception as e:
self._exception_occurred(server, e, sock=sock, fp=fp) self._exception_occurred(server, e, sock=sock, fp=fp)
def get_multi(self, keys, server_key): def get_multi(self, keys, server_key):
@ -432,5 +432,5 @@ class MemcacheRing(object):
values.append(None) values.append(None)
self._return_conn(server, fp, sock) self._return_conn(server, fp, sock)
return values return values
except Exception, e: except Exception as e:
self._exception_occurred(server, e, sock=sock, fp=fp) self._exception_occurred(server, e, sock=sock, fp=fp)

View File

@ -343,7 +343,7 @@ class Bulk(object):
resp_dict['Response Status'] = HTTPBadRequest().status resp_dict['Response Status'] = HTTPBadRequest().status
resp_dict['Response Body'] = 'Invalid bulk delete.' resp_dict['Response Body'] = 'Invalid bulk delete.'
except HTTPException, err: except HTTPException as err:
resp_dict['Response Status'] = err.status resp_dict['Response Status'] = err.status
resp_dict['Response Body'] = err.body resp_dict['Response Body'] = err.body
except Exception: except Exception:
@ -436,7 +436,7 @@ class Bulk(object):
raise HTTPBadRequest( raise HTTPBadRequest(
'More than %d containers to create ' 'More than %d containers to create '
'from tar.' % self.max_containers) 'from tar.' % self.max_containers)
except CreateContainerError, err: except CreateContainerError as err:
# the object PUT to this container still may # the object PUT to this container still may
# succeed if acls are set # succeed if acls are set
container_failure = [ container_failure = [
@ -483,10 +483,10 @@ class Bulk(object):
resp_dict['Response Status'] = HTTPBadRequest().status resp_dict['Response Status'] = HTTPBadRequest().status
resp_dict['Response Body'] = 'Invalid Tar File: No Valid Files' resp_dict['Response Body'] = 'Invalid Tar File: No Valid Files'
except HTTPException, err: except HTTPException as err:
resp_dict['Response Status'] = err.status resp_dict['Response Status'] = err.status
resp_dict['Response Body'] = err.body resp_dict['Response Body'] = err.body
except tarfile.TarError, tar_error: except tarfile.TarError as tar_error:
resp_dict['Response Status'] = HTTPBadRequest().status resp_dict['Response Status'] = HTTPBadRequest().status
resp_dict['Response Body'] = 'Invalid Tar File: %s' % tar_error resp_dict['Response Body'] = 'Invalid Tar File: %s' % tar_error
except Exception: except Exception:

View File

@ -35,7 +35,7 @@ class CatchErrorsContext(WSGIContext):
try: try:
# catch any errors in the pipeline # catch any errors in the pipeline
resp = self._app_call(env) resp = self._app_call(env)
except (Exception, Timeout), err: except (Exception, Timeout) as err:
self.logger.exception(_('Error: %s'), err) self.logger.exception(_('Error: %s'), err)
resp = HTTPServerError(request=Request(env), resp = HTTPServerError(request=Request(env),
body='An error occurred', body='An error occurred',

View File

@ -320,7 +320,7 @@ class FormPost(object):
env, attrs['boundary']) env, attrs['boundary'])
start_response(status, headers) start_response(status, headers)
return body return body
except (FormInvalid, EOFError), err: except (FormInvalid, EOFError) as err:
body = 'FormPost: %s' % err body = 'FormPost: %s' % err
start_response( start_response(
'400 Bad Request', '400 Bad Request',

View File

@ -231,7 +231,7 @@ class RateLimitMiddleware(object):
'container': container_name, 'object': obj_name}) 'container': container_name, 'object': obj_name})
if need_to_sleep > 0: if need_to_sleep > 0:
eventlet.sleep(need_to_sleep) eventlet.sleep(need_to_sleep)
except MaxSleepTimeHitError, e: except MaxSleepTimeHitError as e:
self.logger.error( self.logger.error(
_('Returning 498 for %(meth)s to %(acc)s/%(cont)s/%(obj)s ' _('Returning 498 for %(meth)s to %(acc)s/%(cont)s/%(obj)s '
'. Ratelimit (Max Sleep) %(e)s'), '. Ratelimit (Max Sleep) %(e)s'),

View File

@ -228,7 +228,7 @@ class ReconMiddleware(object):
md5sum.update(block) md5sum.update(block)
block = f.read(4096) block = f.read(4096)
sums[ringfile] = md5sum.hexdigest() sums[ringfile] = md5sum.hexdigest()
except IOError, err: except IOError as err:
sums[ringfile] = None sums[ringfile] = None
if err.errno != errno.ENOENT: if err.errno != errno.ENOENT:
self.logger.exception(_('Error reading ringfile')) self.logger.exception(_('Error reading ringfile'))

View File

@ -428,7 +428,7 @@ class StaticLargeObject(object):
body='X-Static-Large-Object is a reserved header. ' body='X-Static-Large-Object is a reserved header. '
'To create a static large object add query param ' 'To create a static large object add query param '
'multipart-manifest=put.') 'multipart-manifest=put.')
except HTTPException, err_resp: except HTTPException as err_resp:
return err_resp(env, start_response) return err_resp(env, start_response)
return self.app(env, start_response) return self.app(env, start_response)

View File

@ -1184,7 +1184,7 @@ def wsgify(func):
def _wsgify_self(self, env, start_response): def _wsgify_self(self, env, start_response):
try: try:
return func(self, Request(env))(env, start_response) return func(self, Request(env))(env, start_response)
except HTTPException, err_resp: except HTTPException as err_resp:
return err_resp(env, start_response) return err_resp(env, start_response)
return _wsgify_self return _wsgify_self
else: else:
@ -1192,7 +1192,7 @@ def wsgify(func):
def _wsgify_bare(env, start_response): def _wsgify_bare(env, start_response):
try: try:
return func(Request(env))(env, start_response) return func(Request(env))(env, start_response)
except HTTPException, err_resp: except HTTPException as err_resp:
return err_resp(env, start_response) return err_resp(env, start_response)
return _wsgify_bare return _wsgify_bare

View File

@ -447,7 +447,7 @@ def mkdirs(path):
if not os.path.isdir(path): if not os.path.isdir(path):
try: try:
os.makedirs(path) os.makedirs(path)
except OSError, err: except OSError as err:
if err.errno != errno.EEXIST or not os.path.isdir(path): if err.errno != errno.EEXIST or not os.path.isdir(path):
raise raise
@ -924,7 +924,7 @@ def get_logger(conf, name=None, log_to_console=False, log_route=None,
log_address = conf.get('log_address', '/dev/log') log_address = conf.get('log_address', '/dev/log')
try: try:
handler = SysLogHandler(address=log_address, facility=facility) handler = SysLogHandler(address=log_address, facility=facility)
except socket.error, e: except socket.error as e:
# Either /dev/log isn't a UNIX socket or it does not exist at all # Either /dev/log isn't a UNIX socket or it does not exist at all
if e.errno not in [errno.ENOTSOCK, errno.ENOENT]: if e.errno not in [errno.ENOTSOCK, errno.ENOENT]:
raise e raise e
@ -1200,7 +1200,7 @@ def lock_path(directory, timeout=10):
try: try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
break break
except IOError, err: except IOError as err:
if err.errno != errno.EAGAIN: if err.errno != errno.EAGAIN:
raise raise
sleep(0.01) sleep(0.01)
@ -1235,7 +1235,7 @@ def lock_file(filename, timeout=10, append=False, unlink=True):
try: try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
break break
except IOError, err: except IOError as err:
if err.errno != errno.EAGAIN: if err.errno != errno.EAGAIN:
raise raise
sleep(0.01) sleep(0.01)
@ -1499,7 +1499,7 @@ def write_file(path, contents):
if not os.path.exists(dirname): if not os.path.exists(dirname):
try: try:
os.makedirs(dirname) os.makedirs(dirname)
except OSError, err: except OSError as err:
if err.errno == errno.EACCES: if err.errno == errno.EACCES:
sys.exit('Unable to create %s. Running as ' sys.exit('Unable to create %s. Running as '
'non-root?' % dirname) 'non-root?' % dirname)
@ -1821,7 +1821,7 @@ def dump_recon_cache(cache_dict, cache_file, logger, lock_timeout=2):
finally: finally:
try: try:
os.unlink(tf.name) os.unlink(tf.name)
except OSError, err: except OSError as err:
if err.errno != errno.ENOENT: if err.errno != errno.ENOENT:
raise raise
except (Exception, Timeout): except (Exception, Timeout):
@ -1831,7 +1831,7 @@ def dump_recon_cache(cache_dict, cache_file, logger, lock_timeout=2):
def listdir(path): def listdir(path):
try: try:
return os.listdir(path) return os.listdir(path)
except OSError, err: except OSError as err:
if err.errno != errno.ENOENT: if err.errno != errno.ENOENT:
raise raise
return [] return []
@ -2020,7 +2020,7 @@ def tpool_reraise(func, *args, **kwargs):
def inner(): def inner():
try: try:
return func(*args, **kwargs) return func(*args, **kwargs)
except BaseException, err: except BaseException as err:
return err return err
resp = tpool.execute(inner) resp = tpool.execute(inner)
if isinstance(resp, BaseException): if isinstance(resp, BaseException):
@ -2093,7 +2093,7 @@ class ThreadPool(object):
try: try:
result = func(*args, **kwargs) result = func(*args, **kwargs)
result_queue.put((ev, True, result)) result_queue.put((ev, True, result))
except BaseException, err: except BaseException as err:
result_queue.put((ev, False, err)) result_queue.put((ev, False, err))
finally: finally:
work_queue.task_done() work_queue.task_done()

View File

@ -158,7 +158,7 @@ def get_socket(conf, default_port=8080):
warn_ssl = True warn_ssl = True
sock = ssl.wrap_socket(sock, certfile=conf['cert_file'], sock = ssl.wrap_socket(sock, certfile=conf['cert_file'],
keyfile=conf['key_file']) keyfile=conf['key_file'])
except socket.error, err: except socket.error as err:
if err.args[0] != errno.EADDRINUSE: if err.args[0] != errno.EADDRINUSE:
raise raise
sleep(0.1) sleep(0.1)
@ -225,7 +225,7 @@ def run_server(conf, logger, sock):
pool = RestrictedGreenPool(size=max_clients) pool = RestrictedGreenPool(size=max_clients)
try: try:
wsgi.server(sock, app, NullLogger(), custom_pool=pool) wsgi.server(sock, app, NullLogger(), custom_pool=pool)
except socket.error, err: except socket.error as err:
if err[0] != errno.EINVAL: if err[0] != errno.EINVAL:
raise raise
pool.waitall() pool.waitall()
@ -243,7 +243,7 @@ def run_wsgi(conf_path, app_section, *args, **kwargs):
try: try:
(conf, logger, log_name) = \ (conf, logger, log_name) = \
_initrp(conf_path, app_section, *args, **kwargs) _initrp(conf_path, app_section, *args, **kwargs)
except ConfigFileError, e: except ConfigFileError as e:
print e print e
return return
@ -303,7 +303,7 @@ def run_wsgi(conf_path, app_section, *args, **kwargs):
if os.WIFEXITED(status) or os.WIFSIGNALED(status): if os.WIFEXITED(status) or os.WIFSIGNALED(status):
logger.error('Removing dead child %s' % pid) logger.error('Removing dead child %s' % pid)
children.remove(pid) children.remove(pid)
except OSError, err: except OSError as err:
if err.errno not in (errno.EINTR, errno.ECHILD): if err.errno not in (errno.EINTR, errno.ECHILD):
raise raise
except KeyboardInterrupt: except KeyboardInterrupt:
@ -321,7 +321,7 @@ class ConfigFileError(Exception):
def _initrp(conf_path, app_section, *args, **kwargs): def _initrp(conf_path, app_section, *args, **kwargs):
try: try:
conf = appconfig(conf_path, name=app_section) conf = appconfig(conf_path, name=app_section)
except Exception, e: except Exception as e:
raise ConfigFileError("Error trying to load config from %s: %s" % raise ConfigFileError("Error trying to load config from %s: %s" %
(conf_path, e)) (conf_path, e))

View File

@ -430,7 +430,7 @@ class ContainerController(object):
return HTTPInsufficientStorage(drive=drive, request=req) return HTTPInsufficientStorage(drive=drive, request=req)
try: try:
args = json.load(req.environ['wsgi.input']) args = json.load(req.environ['wsgi.input'])
except ValueError, err: except ValueError as err:
return HTTPBadRequest(body=str(err), content_type='text/plain') return HTTPBadRequest(body=str(err), content_type='text/plain')
ret = self.replicator_rpc.dispatch(post_args, args) ret = self.replicator_rpc.dispatch(post_args, args)
ret.request = req ret.request = req

View File

@ -323,7 +323,7 @@ class ContainerSync(Daemon):
headers={'x-timestamp': row['created_at'], headers={'x-timestamp': row['created_at'],
'x-container-sync-key': sync_key}, 'x-container-sync-key': sync_key},
proxy=self.proxy) proxy=self.proxy)
except ClientException, err: except ClientException as err:
if err.http_status != HTTP_NOT_FOUND: if err.http_status != HTTP_NOT_FOUND:
raise raise
self.container_deletes += 1 self.container_deletes += 1
@ -348,14 +348,14 @@ class ContainerSync(Daemon):
timestamp = this_timestamp timestamp = this_timestamp
headers = these_headers headers = these_headers
body = this_body body = this_body
except ClientException, err: except ClientException as err:
# If any errors are not 404, make sure we report the # If any errors are not 404, make sure we report the
# non-404 one. We don't want to mistakenly assume the # non-404 one. We don't want to mistakenly assume the
# object no longer exists just because one says so and # object no longer exists just because one says so and
# the others errored for some other reason. # the others errored for some other reason.
if not exc or exc.http_status == HTTP_NOT_FOUND: if not exc or exc.http_status == HTTP_NOT_FOUND:
exc = err exc = err
except (Exception, Timeout), err: except (Exception, Timeout) as err:
exc = err exc = err
if timestamp < looking_for_timestamp: if timestamp < looking_for_timestamp:
if exc: if exc:
@ -380,7 +380,7 @@ class ContainerSync(Daemon):
self.container_puts += 1 self.container_puts += 1
self.logger.increment('puts') self.logger.increment('puts')
self.logger.timing_since('puts.timing', start_time) self.logger.timing_since('puts.timing', start_time)
except ClientException, err: except ClientException as err:
if err.http_status == HTTP_UNAUTHORIZED: if err.http_status == HTTP_UNAUTHORIZED:
self.logger.info( self.logger.info(
_('Unauth %(sync_from)r => %(sync_to)r'), _('Unauth %(sync_from)r => %(sync_to)r'),
@ -401,7 +401,7 @@ class ContainerSync(Daemon):
self.container_failures += 1 self.container_failures += 1
self.logger.increment('failures') self.logger.increment('failures')
return False return False
except (Exception, Timeout), err: except (Exception, Timeout) as err:
self.logger.exception( self.logger.exception(
_('ERROR Syncing %(db_file)s %(row)s'), _('ERROR Syncing %(db_file)s %(row)s'),
{'db_file': broker.db_file, 'row': row}) {'db_file': broker.db_file, 'row': row})

View File

@ -102,7 +102,7 @@ def quarantine_renamer(device_path, corrupted_file_path):
invalidate_hash(dirname(from_dir)) invalidate_hash(dirname(from_dir))
try: try:
renamer(from_dir, to_dir) renamer(from_dir, to_dir)
except OSError, e: except OSError as e:
if e.errno not in (errno.EEXIST, errno.ENOTEMPTY): if e.errno not in (errno.EEXIST, errno.ENOTEMPTY):
raise raise
to_dir = "%s-%s" % (to_dir, uuid.uuid4().hex) to_dir = "%s-%s" % (to_dir, uuid.uuid4().hex)
@ -156,7 +156,7 @@ def hash_suffix(path, reclaim_age):
md5 = hashlib.md5() md5 = hashlib.md5()
try: try:
path_contents = sorted(os.listdir(path)) path_contents = sorted(os.listdir(path))
except OSError, err: except OSError as err:
if err.errno in (errno.ENOTDIR, errno.ENOENT): if err.errno in (errno.ENOTDIR, errno.ENOENT):
raise PathNotDir() raise PathNotDir()
raise raise
@ -164,7 +164,7 @@ def hash_suffix(path, reclaim_age):
hsh_path = join(path, hsh) hsh_path = join(path, hsh)
try: try:
files = hash_cleanup_listdir(hsh_path, reclaim_age) files = hash_cleanup_listdir(hsh_path, reclaim_age)
except OSError, err: except OSError as err:
if err.errno == errno.ENOTDIR: if err.errno == errno.ENOTDIR:
partition_path = dirname(path) partition_path = dirname(path)
objects_path = dirname(partition_path) objects_path = dirname(partition_path)
@ -601,7 +601,7 @@ class DiskFile(object):
try: try:
if verify_file: if verify_file:
self._handle_close_quarantine() self._handle_close_quarantine()
except (Exception, Timeout), e: except (Exception, Timeout) as e:
self.logger.error(_( self.logger.error(_(
'ERROR DiskFile %(data_file)s in ' 'ERROR DiskFile %(data_file)s in '
'%(data_dir)s close failure: %(exc)s : %(stack)s'), '%(data_dir)s close failure: %(exc)s : %(stack)s'),
@ -720,7 +720,7 @@ class DiskFile(object):
'Content-Length of %s does not match file size ' 'Content-Length of %s does not match file size '
'of %s' % (metadata_size, file_size)) 'of %s' % (metadata_size, file_size))
return file_size return file_size
except OSError, err: except OSError as err:
if err.errno != errno.ENOENT: if err.errno != errno.ENOENT:
raise raise
raise DiskFileNotExist('Data File does not exist.') raise DiskFileNotExist('Data File does not exist.')

View File

@ -134,7 +134,7 @@ class ObjectExpirer(Daemon):
self.expiring_objects_account, self.expiring_objects_account,
container, container,
acceptable_statuses=(2, HTTP_NOT_FOUND, HTTP_CONFLICT)) acceptable_statuses=(2, HTTP_NOT_FOUND, HTTP_CONFLICT))
except (Exception, Timeout), err: except (Exception, Timeout) as err:
self.logger.exception( self.logger.exception(
_('Exception while deleting container %s %s') % _('Exception while deleting container %s %s') %
(container, str(err))) (container, str(err)))
@ -205,7 +205,7 @@ class ObjectExpirer(Daemon):
container, obj) container, obj)
self.report_objects += 1 self.report_objects += 1
self.logger.increment('objects') self.logger.increment('objects')
except (Exception, Timeout), err: except (Exception, Timeout) as err:
self.logger.increment('errors') self.logger.increment('errors')
self.logger.exception( self.logger.exception(
_('Exception while deleting object %s %s %s') % _('Exception while deleting object %s %s %s') %

View File

@ -64,7 +64,7 @@ class ContainerController(Controller):
req.headers[header] = \ req.headers[header] = \
req.environ['swift.clean_acl'](header, req.environ['swift.clean_acl'](header,
req.headers[header]) req.headers[header])
except ValueError, err: except ValueError as err:
return HTTPBadRequest(request=req, body=str(err)) return HTTPBadRequest(request=req, body=str(err))
return None return None

View File

@ -240,7 +240,7 @@ class SegmentedIterable(object):
self.segment_iter_swift_conn = getattr(resp, 'swift_conn', None) self.segment_iter_swift_conn = getattr(resp, 'swift_conn', None)
except StopIteration: except StopIteration:
raise raise
except SegmentError, err: except SegmentError as err:
if not getattr(err, 'swift_logged', False): if not getattr(err, 'swift_logged', False):
self.controller.app.logger.error(_( self.controller.app.logger.error(_(
'ERROR: While processing manifest ' 'ERROR: While processing manifest '
@ -251,7 +251,7 @@ class SegmentedIterable(object):
err.swift_logged = True err.swift_logged = True
self.response.status_int = HTTP_CONFLICT self.response.status_int = HTTP_CONFLICT
raise raise
except (Exception, Timeout), err: except (Exception, Timeout) as err:
if not getattr(err, 'swift_logged', False): if not getattr(err, 'swift_logged', False):
self.controller.app.logger.exception(_( self.controller.app.logger.exception(_(
'ERROR: While processing manifest ' 'ERROR: While processing manifest '
@ -298,7 +298,7 @@ class SegmentedIterable(object):
# created an invalid condition. # created an invalid condition.
yield ' ' yield ' '
raise raise
except (Exception, Timeout), err: except (Exception, Timeout) as err:
if not getattr(err, 'swift_logged', False): if not getattr(err, 'swift_logged', False):
self.controller.app.logger.exception(_( self.controller.app.logger.exception(_(
'ERROR: While processing manifest ' 'ERROR: While processing manifest '
@ -360,7 +360,7 @@ class SegmentedIterable(object):
self.segment_iter = None self.segment_iter = None
except StopIteration: except StopIteration:
raise raise
except (Exception, Timeout), err: except (Exception, Timeout) as err:
if not getattr(err, 'swift_logged', False): if not getattr(err, 'swift_logged', False):
self.controller.app.logger.exception(_( self.controller.app.logger.exception(_(
'ERROR: While processing manifest ' 'ERROR: While processing manifest '
@ -568,7 +568,7 @@ class ObjectController(Controller):
self._remaining_items(pages_iter)) self._remaining_items(pages_iter))
except ListingIterNotFound: except ListingIterNotFound:
return HTTPNotFound(request=req) return HTTPNotFound(request=req)
except ListingIterNotAuthorized, err: except ListingIterNotAuthorized as err:
return err.aresp return err.aresp
except ListingIterError: except ListingIterError:
return HTTPServerError(request=req) return HTTPServerError(request=req)
@ -1068,7 +1068,7 @@ class ObjectController(Controller):
if conn.queue.unfinished_tasks: if conn.queue.unfinished_tasks:
conn.queue.join() conn.queue.join()
conns = [conn for conn in conns if not conn.failed] conns = [conn for conn in conns if not conn.failed]
except ChunkReadTimeout, err: except ChunkReadTimeout as err:
self.app.logger.warn( self.app.logger.warn(
_('ERROR Client read timeout (%ss)'), err.seconds) _('ERROR Client read timeout (%ss)'), err.seconds)
self.app.logger.increment('client_timeouts') self.app.logger.increment('client_timeouts')
@ -1156,7 +1156,7 @@ class ObjectController(Controller):
except ListingIterNotFound: except ListingIterNotFound:
# no worries, last_item is None # no worries, last_item is None
pass pass
except ListingIterNotAuthorized, err: except ListingIterNotAuthorized as err:
return err.aresp return err.aresp
except ListingIterError: except ListingIterError:
return HTTPServerError(request=req) return HTTPServerError(request=req)

View File

@ -721,7 +721,7 @@ class File(Base):
callback(transferred, self.size) callback(transferred, self.size)
self.conn.put_end() self.conn.put_end()
except socket.timeout, err: except socket.timeout as err:
raise err raise err
if (self.conn.response.status < 200) or \ if (self.conn.response.status < 200) or \

View File

@ -100,7 +100,7 @@ def timeout(seconds, method, *args, **kwargs):
def run(self): def run(self):
try: try:
self.method(*self.args, **self.kwargs) self.method(*self.args, **self.kwargs)
except Exception, e: except Exception as e:
self.exception = e self.exception = e
t = TimeoutThread(method, *args, **kwargs) t = TimeoutThread(method, *args, **kwargs)

View File

@ -60,13 +60,13 @@ if conf:
'%s:' % conf['account2'] if 'account2' in conf else '', '%s:' % conf['account2'] if 'account2' in conf else '',
conf['username2']) conf['username2'])
swift_test_key[1] = conf['password2'] swift_test_key[1] = conf['password2']
except KeyError, err: except KeyError as err:
pass # old conf, no second account tests can be run pass # old conf, no second account tests can be run
try: try:
swift_test_user[2] = '%s%s' % ('%s:' % conf['account'] if 'account' swift_test_user[2] = '%s%s' % ('%s:' % conf['account'] if 'account'
in conf else '', conf['username3']) in conf else '', conf['username3'])
swift_test_key[2] = conf['password3'] swift_test_key[2] = conf['password3']
except KeyError, err: except KeyError as err:
pass # old conf, no third account tests can be run pass # old conf, no third account tests can be run
for _ in range(3): for _ in range(3):

View File

@ -426,7 +426,7 @@ class TestContainer(unittest.TestCase):
try: try:
resp = retry(get) resp = retry(get)
raise Exception('Should not have been able to GET') raise Exception('Should not have been able to GET')
except Exception, err: except Exception as err:
self.assert_(str(err).startswith('No result after '), err) self.assert_(str(err).startswith('No result after '), err)
def post(url, token, parsed, conn): def post(url, token, parsed, conn):
@ -453,7 +453,7 @@ class TestContainer(unittest.TestCase):
try: try:
resp = retry(get) resp = retry(get)
raise Exception('Should not have been able to GET') raise Exception('Should not have been able to GET')
except Exception, err: except Exception as err:
self.assert_(str(err).startswith('No result after '), err) self.assert_(str(err).startswith('No result after '), err)
def test_cross_account_container(self): def test_cross_account_container(self):

View File

@ -168,7 +168,7 @@ class TestObject(unittest.TestCase):
try: try:
resp = retry(get) resp = retry(get)
raise Exception('Should not have been able to GET') raise Exception('Should not have been able to GET')
except Exception, err: except Exception as err:
self.assert_(str(err).startswith('No result after ')) self.assert_(str(err).startswith('No result after '))
def post(url, token, parsed, conn): def post(url, token, parsed, conn):
@ -193,7 +193,7 @@ class TestObject(unittest.TestCase):
try: try:
resp = retry(get) resp = retry(get)
raise Exception('Should not have been able to GET') raise Exception('Should not have been able to GET')
except Exception, err: except Exception as err:
self.assert_(str(err).startswith('No result after ')) self.assert_(str(err).startswith('No result after '))
def test_private_object(self): def test_private_object(self):

View File

@ -70,7 +70,7 @@ def check_server(port, port2server, pids, timeout=CHECK_SERVER_TIMEOUT):
raise Exception( raise Exception(
'Unexpected status %s' % resp.status) 'Unexpected status %s' % resp.status)
break break
except Exception, err: except Exception as err:
if time() > try_until: if time() > try_until:
print err print err
print 'Giving up on %s:%s after %s seconds.' % ( print 'Giving up on %s:%s after %s seconds.' % (
@ -86,7 +86,7 @@ def check_server(port, port2server, pids, timeout=CHECK_SERVER_TIMEOUT):
account = url.split('/')[-1] account = url.split('/')[-1]
head_account(url, token) head_account(url, token)
return url, token, account return url, token, account
except Exception, err: except Exception as err:
if time() > try_until: if time() > try_until:
print err print err
print 'Giving up on proxy:8080 after 30 seconds.' print 'Giving up on proxy:8080 after 30 seconds.'
@ -98,7 +98,7 @@ def check_server(port, port2server, pids, timeout=CHECK_SERVER_TIMEOUT):
def kill_server(port, port2server, pids): def kill_server(port, port2server, pids):
try: try:
kill(pids[port2server[port]], SIGTERM) kill(pids[port2server[port]], SIGTERM)
except Exception, err: except Exception as err:
print err print err
try_until = time() + 30 try_until = time() + 30
while True: while True:
@ -106,7 +106,7 @@ def kill_server(port, port2server, pids):
conn = HTTPConnection('127.0.0.1', port) conn = HTTPConnection('127.0.0.1', port)
conn.request('GET', '/') conn.request('GET', '/')
conn.getresponse() conn.getresponse()
except Exception, err: except Exception as err:
break break
if time() > try_until: if time() > try_until:
raise Exception( raise Exception(

View File

@ -107,7 +107,7 @@ class TestContainerFailures(TestCase):
try: try:
direct_client.direct_get_container(cnode, cpart, self.account, direct_client.direct_get_container(cnode, cpart, self.account,
container1) container1)
except client.ClientException, err: except client.ClientException as err:
exc = err exc = err
self.assertEquals(exc.http_status, 404) self.assertEquals(exc.http_status, 404)
headers, containers = client.get_account(self.url, self.token) headers, containers = client.get_account(self.url, self.token)
@ -147,7 +147,7 @@ class TestContainerFailures(TestCase):
exc = None exc = None
try: try:
client.delete_container(self.url, self.token, container) client.delete_container(self.url, self.token, container)
except client.ClientException, err: except client.ClientException as err:
exc = err exc = err
self.assertEquals(exc.http_status, 503) self.assertEquals(exc.http_status, 503)
else: else:
@ -160,7 +160,7 @@ class TestContainerFailures(TestCase):
pool.spawn(run_test, 2, True) pool.spawn(run_test, 2, True)
pool.spawn(run_test, 3, True) pool.spawn(run_test, 3, True)
pool.waitall() pool.waitall()
except Timeout, err: except Timeout as err:
raise Exception( raise Exception(
"The server did not return a 503 on container db locks, " "The server did not return a 503 on container db locks, "
"it just hangs: %s" % err) "it just hangs: %s" % err)

View File

@ -118,7 +118,7 @@ class TestEmptyDevice(TestCase):
try: try:
direct_client.direct_get_object(onode, opart, self.account, direct_client.direct_get_object(onode, opart, self.account,
container, obj) container, obj)
except direct_client.ClientException, err: except direct_client.ClientException as err:
exc = err exc = err
self.assertEquals(exc.http_status, 404) self.assertEquals(exc.http_status, 404)
self.assertFalse(os.path.exists(obj_dir)) self.assertFalse(os.path.exists(obj_dir))
@ -147,7 +147,7 @@ class TestEmptyDevice(TestCase):
try: try:
direct_client.direct_get_object(another_onode, opart, self.account, direct_client.direct_get_object(another_onode, opart, self.account,
container, obj) container, obj)
except direct_client.ClientException, err: except direct_client.ClientException as err:
exc = err exc = err
self.assertEquals(exc.http_status, 404) self.assertEquals(exc.http_status, 404)

View File

@ -80,7 +80,7 @@ class TestObjectFailures(TestCase):
direct_client.direct_get_object(onode, opart, self.account, direct_client.direct_get_object(onode, opart, self.account,
container, obj) container, obj)
raise Exception("Did not quarantine object") raise Exception("Did not quarantine object")
except client.ClientException, err: except client.ClientException as err:
self.assertEquals(err.http_status, 404) self.assertEquals(err.http_status, 404)
def run_quarantine_range_etag(self): def run_quarantine_range_etag(self):
@ -104,7 +104,7 @@ class TestObjectFailures(TestCase):
direct_client.direct_get_object(onode, opart, self.account, direct_client.direct_get_object(onode, opart, self.account,
container, obj) container, obj)
raise Exception("Did not quarantine object") raise Exception("Did not quarantine object")
except client.ClientException, err: except client.ClientException as err:
self.assertEquals(err.http_status, 404) self.assertEquals(err.http_status, 404)
def run_quarantine_zero_byte_get(self): def run_quarantine_zero_byte_get(self):
@ -122,7 +122,7 @@ class TestObjectFailures(TestCase):
container, obj, conn_timeout=1, container, obj, conn_timeout=1,
response_timeout=1) response_timeout=1)
raise Exception("Did not quarantine object") raise Exception("Did not quarantine object")
except client.ClientException, err: except client.ClientException as err:
self.assertEquals(err.http_status, 404) self.assertEquals(err.http_status, 404)
def run_quarantine_zero_byte_head(self): def run_quarantine_zero_byte_head(self):
@ -140,7 +140,7 @@ class TestObjectFailures(TestCase):
container, obj, conn_timeout=1, container, obj, conn_timeout=1,
response_timeout=1) response_timeout=1)
raise Exception("Did not quarantine object") raise Exception("Did not quarantine object")
except client.ClientException, err: except client.ClientException as err:
self.assertEquals(err.http_status, 404) self.assertEquals(err.http_status, 404)
def run_quarantine_zero_byte_post(self): def run_quarantine_zero_byte_post(self):
@ -161,7 +161,7 @@ class TestObjectFailures(TestCase):
conn_timeout=1, conn_timeout=1,
response_timeout=1) response_timeout=1)
raise Exception("Did not quarantine object") raise Exception("Did not quarantine object")
except client.ClientException, err: except client.ClientException as err:
self.assertEquals(err.http_status, 404) self.assertEquals(err.http_status, 404)
def test_runner(self): def test_runner(self):

View File

@ -110,7 +110,7 @@ class TestObjectHandoff(TestCase):
try: try:
direct_client.direct_get_object(onode, opart, self.account, direct_client.direct_get_object(onode, opart, self.account,
container, obj) container, obj)
except direct_client.ClientException, err: except direct_client.ClientException as err:
exc = err exc = err
self.assertEquals(exc.http_status, 404) self.assertEquals(exc.http_status, 404)
# Run the extra server last so it'll remove its extra partition # Run the extra server last so it'll remove its extra partition
@ -142,7 +142,7 @@ class TestObjectHandoff(TestCase):
try: try:
direct_client.direct_get_object(another_onode, opart, self.account, direct_client.direct_get_object(another_onode, opart, self.account,
container, obj) container, obj)
except direct_client.ClientException, err: except direct_client.ClientException as err:
exc = err exc = err
self.assertEquals(exc.http_status, 404) self.assertEquals(exc.http_status, 404)
@ -151,7 +151,7 @@ class TestObjectHandoff(TestCase):
exc = None exc = None
try: try:
client.head_object(self.url, self.token, container, obj) client.head_object(self.url, self.token, container, obj)
except direct_client.ClientException, err: except direct_client.ClientException as err:
exc = err exc = err
self.assertEquals(exc.http_status, 404) self.assertEquals(exc.http_status, 404)
objs = [o['name'] for o in objs = [o['name'] for o in
@ -189,7 +189,7 @@ class TestObjectHandoff(TestCase):
try: try:
direct_client.direct_get_object(another_onode, opart, self.account, direct_client.direct_get_object(another_onode, opart, self.account,
container, obj) container, obj)
except direct_client.ClientException, err: except direct_client.ClientException as err:
exc = err exc = err
self.assertEquals(exc.http_status, 404) self.assertEquals(exc.http_status, 404)

View File

@ -41,7 +41,7 @@ class TestAccountController(unittest.TestCase):
"""Tear down for testing swift.account.server.AccountController""" """Tear down for testing swift.account.server.AccountController"""
try: try:
rmtree(self.testdir) rmtree(self.testdir)
except OSError, err: except OSError as err:
if err.errno != errno.ENOENT: if err.errno != errno.ENOENT:
raise raise

View File

@ -89,7 +89,7 @@ class TestIterRequests(unittest.TestCase):
exc = None exc = None
try: try:
it.next() it.next()
except formpost.FormInvalid, err: except formpost.FormInvalid as err:
exc = err exc = err
self.assertEquals(str(exc), 'invalid starting boundary') self.assertEquals(str(exc), 'invalid starting boundary')
@ -100,7 +100,7 @@ class TestIterRequests(unittest.TestCase):
exc = None exc = None
try: try:
it.next() it.next()
except StopIteration, err: except StopIteration as err:
exc = err exc = err
self.assertTrue(exc is not None) self.assertTrue(exc is not None)
@ -112,7 +112,7 @@ class TestIterRequests(unittest.TestCase):
exc = None exc = None
try: try:
it.next() it.next()
except StopIteration, err: except StopIteration as err:
exc = err exc = err
self.assertTrue(exc is not None) self.assertTrue(exc is not None)
@ -127,7 +127,7 @@ class TestIterRequests(unittest.TestCase):
exc = None exc = None
try: try:
it.next() it.next()
except StopIteration, err: except StopIteration as err:
exc = err exc = err
self.assertTrue(exc is not None) self.assertTrue(exc is not None)
@ -146,7 +146,7 @@ class TestIterRequests(unittest.TestCase):
exc = None exc = None
try: try:
it.next() it.next()
except StopIteration, err: except StopIteration as err:
exc = err exc = err
self.assertTrue(exc is not None) self.assertTrue(exc is not None)
@ -162,7 +162,7 @@ class TestIterRequests(unittest.TestCase):
exc = None exc = None
try: try:
it.next() it.next()
except StopIteration, err: except StopIteration as err:
exc = err exc = err
self.assertTrue(exc is not None) self.assertTrue(exc is not None)
@ -176,7 +176,7 @@ class TestIterRequests(unittest.TestCase):
exc = None exc = None
try: try:
it.next() it.next()
except StopIteration, err: except StopIteration as err:
exc = err exc = err
self.assertTrue(exc is not None) self.assertTrue(exc is not None)
@ -195,7 +195,7 @@ class TestIterRequests(unittest.TestCase):
exc = None exc = None
try: try:
it.next() it.next()
except StopIteration, err: except StopIteration as err:
exc = err exc = err
self.assertTrue(exc is not None) self.assertTrue(exc is not None)
@ -217,7 +217,7 @@ class TestIterRequests(unittest.TestCase):
exc = None exc = None
try: try:
it.next() it.next()
except StopIteration, err: except StopIteration as err:
exc = err exc = err
self.assertTrue(exc is not None) self.assertTrue(exc is not None)
finally: finally:
@ -234,7 +234,7 @@ class TestCappedFileLikeObject(unittest.TestCase):
exc = None exc = None
try: try:
formpost._CappedFileLikeObject(StringIO('abc'), 2).read() formpost._CappedFileLikeObject(StringIO('abc'), 2).read()
except EOFError, err: except EOFError as err:
exc = err exc = err
self.assertEquals(str(exc), 'max_file_size exceeded') self.assertEquals(str(exc), 'max_file_size exceeded')
@ -250,7 +250,7 @@ class TestCappedFileLikeObject(unittest.TestCase):
exc = None exc = None
try: try:
self.assertEquals(fp.readline(), 'def') self.assertEquals(fp.readline(), 'def')
except EOFError, err: except EOFError as err:
exc = err exc = err
self.assertEquals(str(exc), 'max_file_size exceeded') self.assertEquals(str(exc), 'max_file_size exceeded')

View File

@ -76,7 +76,7 @@ class TestCacheMiddleware(unittest.TestCase):
exc = None exc = None
try: try:
memcache.MemcacheMiddleware(FakeApp(), {}) memcache.MemcacheMiddleware(FakeApp(), {})
except Exception, err: except Exception as err:
exc = err exc = err
finally: finally:
memcache.ConfigParser = orig_parser memcache.ConfigParser = orig_parser
@ -91,7 +91,7 @@ class TestCacheMiddleware(unittest.TestCase):
memcache.MemcacheMiddleware( memcache.MemcacheMiddleware(
FakeApp(), {'memcache_servers': '1.2.3.4:5', FakeApp(), {'memcache_servers': '1.2.3.4:5',
'memcache_serialization_support': '2'}) 'memcache_serialization_support': '2'})
except Exception, err: except Exception as err:
exc = err exc = err
finally: finally:
memcache.ConfigParser = orig_parser memcache.ConfigParser = orig_parser

View File

@ -196,7 +196,7 @@ class TestStaticLargeObject(unittest.TestCase):
req.content_length = self.slo.max_manifest_size + 1 req.content_length = self.slo.max_manifest_size + 1
try: try:
self.slo.handle_multipart_put(req, fake_start_response) self.slo.handle_multipart_put(req, fake_start_response)
except HTTPException, e: except HTTPException as e:
pass pass
self.assertEquals(e.status_int, 413) self.assertEquals(e.status_int, 413)
@ -205,7 +205,7 @@ class TestStaticLargeObject(unittest.TestCase):
e = None e = None
try: try:
self.slo.handle_multipart_put(req, fake_start_response) self.slo.handle_multipart_put(req, fake_start_response)
except HTTPException, e: except HTTPException as e:
pass pass
self.assertEquals(e.status_int, 413) self.assertEquals(e.status_int, 413)
@ -213,14 +213,14 @@ class TestStaticLargeObject(unittest.TestCase):
req = Request.blank('/v/a/c/o', body=test_json_data) req = Request.blank('/v/a/c/o', body=test_json_data)
try: try:
self.slo.handle_multipart_put(req, fake_start_response) self.slo.handle_multipart_put(req, fake_start_response)
except HTTPException, e: except HTTPException as e:
pass pass
self.assertEquals(e.status_int, 400) self.assertEquals(e.status_int, 400)
req = Request.blank('/v/a/c/o', headers={'X-Copy-From': 'lala'}) req = Request.blank('/v/a/c/o', headers={'X-Copy-From': 'lala'})
try: try:
self.slo.handle_multipart_put(req, fake_start_response) self.slo.handle_multipart_put(req, fake_start_response)
except HTTPException, e: except HTTPException as e:
pass pass
self.assertEquals(e.status_int, 405) self.assertEquals(e.status_int, 405)
@ -346,7 +346,7 @@ class TestStaticLargeObject(unittest.TestCase):
body=bad_data) body=bad_data)
try: try:
self.slo.handle_multipart_put(req, fake_start_response) self.slo.handle_multipart_put(req, fake_start_response)
except HTTPException, e: except HTTPException as e:
self.assertEquals(self.app.calls, 4) self.assertEquals(self.app.calls, 4)
data = json.loads(e.body) data = json.loads(e.body)
errors = data['Errors'] errors = data['Errors']

View File

@ -46,7 +46,7 @@ class TestBufferedHTTP(unittest.TestCase):
self.assertEquals(headers['content-length'], '7') self.assertEquals(headers['content-length'], '7')
self.assertEquals(headers['x-header'], 'value') self.assertEquals(headers['x-header'], 'value')
self.assertEquals(fp.readline(), 'REQUEST\r\n') self.assertEquals(fp.readline(), 'REQUEST\r\n')
except BaseException, err: except BaseException as err:
return err return err
return None return None
for par in ('par', 1357): for par in ('par', 1357):

View File

@ -272,7 +272,7 @@ class TestDatabaseBroker(unittest.TestCase):
try: try:
with broker.get() as conn: with broker.get() as conn:
conn.execute('SELECT * FROM test') conn.execute('SELECT * FROM test')
except Exception, err: except Exception as err:
exc = err exc = err
self.assertEquals( self.assertEquals(
str(exc), str(exc),
@ -288,7 +288,7 @@ class TestDatabaseBroker(unittest.TestCase):
try: try:
with broker.get() as conn: with broker.get() as conn:
conn.execute('SELECT * FROM test') conn.execute('SELECT * FROM test')
except Exception, err: except Exception as err:
exc = err exc = err
self.assertEquals( self.assertEquals(
str(exc), str(exc),
@ -1727,7 +1727,7 @@ class TestContainerBrokerBeforeMetadata(TestContainerBroker):
with broker.get() as conn: with broker.get() as conn:
try: try:
conn.execute('SELECT metadata FROM container_stat') conn.execute('SELECT metadata FROM container_stat')
except BaseException, err: except BaseException as err:
exc = err exc = err
self.assert_('no such column: metadata' in str(exc)) self.assert_('no such column: metadata' in str(exc))
@ -1802,7 +1802,7 @@ class TestContainerBrokerBeforeXSync(TestContainerBroker):
try: try:
conn.execute('''SELECT x_container_sync_point1 conn.execute('''SELECT x_container_sync_point1
FROM container_stat''') FROM container_stat''')
except BaseException, err: except BaseException as err:
exc = err exc = err
self.assert_('no such column: x_container_sync_point1' in str(exc)) self.assert_('no such column: x_container_sync_point1' in str(exc))
@ -2318,7 +2318,7 @@ class TestAccountBrokerBeforeMetadata(TestAccountBroker):
with broker.get() as conn: with broker.get() as conn:
try: try:
conn.execute('SELECT metadata FROM account_stat') conn.execute('SELECT metadata FROM account_stat')
except BaseException, err: except BaseException as err:
exc = err exc = err
self.assert_('no such column: metadata' in str(exc)) self.assert_('no such column: metadata' in str(exc))

View File

@ -283,12 +283,12 @@ class TestInternalClient(unittest.TestCase):
try: try:
client.make_request('GET', '/', {}, (400,)) client.make_request('GET', '/', {}, (400,))
except Exception, err: except Exception as err:
pass pass
self.assertEquals(200, err.resp.status_int) self.assertEquals(200, err.resp.status_int)
try: try:
client.make_request('GET', '/', {}, (201,)) client.make_request('GET', '/', {}, (201,))
except Exception, err: except Exception as err:
pass pass
self.assertEquals(200, err.resp.status_int) self.assertEquals(200, err.resp.status_int)
finally: finally:
@ -323,7 +323,7 @@ class TestInternalClient(unittest.TestCase):
internal_client.sleep = not_sleep internal_client.sleep = not_sleep
try: try:
client.make_request('PUT', '/', {}, (2,), fobj) client.make_request('PUT', '/', {}, (2,), fobj)
except Exception, err: except Exception as err:
pass pass
self.assertEquals(404, err.resp.status_int) self.assertEquals(404, err.resp.status_int)
finally: finally:

View File

@ -645,11 +645,11 @@ class TestRequest(unittest.TestCase):
self.assertEquals(_test_split_path('/a/c/', 2, 3), ['a', 'c', '']) self.assertEquals(_test_split_path('/a/c/', 2, 3), ['a', 'c', ''])
try: try:
_test_split_path('o\nn e', 2) _test_split_path('o\nn e', 2)
except ValueError, err: except ValueError as err:
self.assertEquals(str(err), 'Invalid path: o%0An%20e') self.assertEquals(str(err), 'Invalid path: o%0An%20e')
try: try:
_test_split_path('o\nn e', 2, 3, True) _test_split_path('o\nn e', 2, 3, True)
except ValueError, err: except ValueError as err:
self.assertEquals(str(err), 'Invalid path: o%0An%20e') self.assertEquals(str(err), 'Invalid path: o%0An%20e')
def test_unicode_path(self): def test_unicode_path(self):

View File

@ -241,11 +241,11 @@ class TestUtils(unittest.TestCase):
self.assertEquals(utils.split_path('/a/c/', 2, 3), ['a', 'c', '']) self.assertEquals(utils.split_path('/a/c/', 2, 3), ['a', 'c', ''])
try: try:
utils.split_path('o\nn e', 2) utils.split_path('o\nn e', 2)
except ValueError, err: except ValueError as err:
self.assertEquals(str(err), 'Invalid path: o%0An%20e') self.assertEquals(str(err), 'Invalid path: o%0An%20e')
try: try:
utils.split_path('o\nn e', 2, 3, True) utils.split_path('o\nn e', 2, 3, True)
except ValueError, err: except ValueError as err:
self.assertEquals(str(err), 'Invalid path: o%0An%20e') self.assertEquals(str(err), 'Invalid path: o%0An%20e')
def test_validate_device_partition(self): def test_validate_device_partition(self):
@ -271,11 +271,11 @@ class TestUtils(unittest.TestCase):
utils.validate_device_partition, 'foo', '..') utils.validate_device_partition, 'foo', '..')
try: try:
utils.validate_device_partition('o\nn e', 'foo') utils.validate_device_partition('o\nn e', 'foo')
except ValueError, err: except ValueError as err:
self.assertEquals(str(err), 'Invalid device: o%0An%20e') self.assertEquals(str(err), 'Invalid device: o%0An%20e')
try: try:
utils.validate_device_partition('foo', 'o\nn e') utils.validate_device_partition('foo', 'o\nn e')
except ValueError, err: except ValueError as err:
self.assertEquals(str(err), 'Invalid partition: o%0An%20e') self.assertEquals(str(err), 'Invalid partition: o%0An%20e')
def test_NullLogger(self): def test_NullLogger(self):
@ -1182,7 +1182,7 @@ log_name = %(yarr)s'''
for (value, default), expected in expectations.items(): for (value, default), expected in expectations.items():
try: try:
rv = utils.config_auto_int_value(value, default) rv = utils.config_auto_int_value(value, default)
except Exception, e: except Exception as e:
if e.__class__ is not expected: if e.__class__ is not expected:
raise raise
else: else:
@ -1245,7 +1245,7 @@ log_name = %(yarr)s'''
exc = None exc = None
try: try:
fallocate(0, 1, 0, ctypes.c_uint64(0)) fallocate(0, 1, 0, ctypes.c_uint64(0))
except OSError, err: except OSError as err:
exc = err exc = err
self.assertEquals(str(exc), 'FALLOCATE_RESERVE fail 1024 <= 1024') self.assertEquals(str(exc), 'FALLOCATE_RESERVE fail 1024 <= 1024')
# Want 1024 reserved, have 512 * 2 free, so fails # Want 1024 reserved, have 512 * 2 free, so fails
@ -1255,7 +1255,7 @@ log_name = %(yarr)s'''
exc = None exc = None
try: try:
fallocate(0, 1, 0, ctypes.c_uint64(0)) fallocate(0, 1, 0, ctypes.c_uint64(0))
except OSError, err: except OSError as err:
exc = err exc = err
self.assertEquals(str(exc), 'FALLOCATE_RESERVE fail 1024 <= 1024') self.assertEquals(str(exc), 'FALLOCATE_RESERVE fail 1024 <= 1024')
# Want 2048 reserved, have 1024 * 1 free, so fails # Want 2048 reserved, have 1024 * 1 free, so fails
@ -1265,7 +1265,7 @@ log_name = %(yarr)s'''
exc = None exc = None
try: try:
fallocate(0, 1, 0, ctypes.c_uint64(0)) fallocate(0, 1, 0, ctypes.c_uint64(0))
except OSError, err: except OSError as err:
exc = err exc = err
self.assertEquals(str(exc), 'FALLOCATE_RESERVE fail 1024 <= 2048') self.assertEquals(str(exc), 'FALLOCATE_RESERVE fail 1024 <= 2048')
# Want 2048 reserved, have 512 * 2 free, so fails # Want 2048 reserved, have 512 * 2 free, so fails
@ -1275,7 +1275,7 @@ log_name = %(yarr)s'''
exc = None exc = None
try: try:
fallocate(0, 1, 0, ctypes.c_uint64(0)) fallocate(0, 1, 0, ctypes.c_uint64(0))
except OSError, err: except OSError as err:
exc = err exc = err
self.assertEquals(str(exc), 'FALLOCATE_RESERVE fail 1024 <= 2048') self.assertEquals(str(exc), 'FALLOCATE_RESERVE fail 1024 <= 2048')
# Want 1023 reserved, have 1024 * 1 free, but file size is 1, so # Want 1023 reserved, have 1024 * 1 free, but file size is 1, so
@ -1286,7 +1286,7 @@ log_name = %(yarr)s'''
exc = None exc = None
try: try:
fallocate(0, 1, 0, ctypes.c_uint64(1)) fallocate(0, 1, 0, ctypes.c_uint64(1))
except OSError, err: except OSError as err:
exc = err exc = err
self.assertEquals(str(exc), 'FALLOCATE_RESERVE fail 1023 <= 1023') self.assertEquals(str(exc), 'FALLOCATE_RESERVE fail 1023 <= 1023')
# Want 1022 reserved, have 1024 * 1 free, and file size is 1, so # Want 1022 reserved, have 1024 * 1 free, and file size is 1, so
@ -1309,7 +1309,7 @@ log_name = %(yarr)s'''
exc = None exc = None
try: try:
fallocate(0, 1, 0, ctypes.c_uint64(0)) fallocate(0, 1, 0, ctypes.c_uint64(0))
except OSError, err: except OSError as err:
exc = err exc = err
self.assertEquals(str(exc), 'FALLOCATE_RESERVE fail 1024 <= 1024') self.assertEquals(str(exc), 'FALLOCATE_RESERVE fail 1024 <= 1024')
finally: finally:
@ -2038,7 +2038,7 @@ class TestStatsdLoggingDelegation(unittest.TestCase):
if payload and 'STOP' in payload: if payload and 'STOP' in payload:
return 42 return 42
self.queue.put(payload) self.queue.put(payload)
except Exception, e: except Exception as e:
sys.stderr.write('statsd_reader thread: %r' % (e,)) sys.stderr.write('statsd_reader thread: %r' % (e,))
break break

View File

@ -458,7 +458,7 @@ class TestContainerController(unittest.TestCase):
line = inc.readline() line = inc.readline()
self.assertEquals(headers['x-put-timestamp'], self.assertEquals(headers['x-put-timestamp'],
expected_timestamp) expected_timestamp)
except BaseException, err: except BaseException as err:
return err return err
return None return None
@ -512,7 +512,7 @@ class TestContainerController(unittest.TestCase):
try: try:
with Timeout(3): with Timeout(3):
resp = req.get_response(self.controller) resp = req.get_response(self.controller)
except BaseException, err: except BaseException as err:
got_exc = True got_exc = True
finally: finally:
err = event.wait() err = event.wait()
@ -679,7 +679,7 @@ class TestContainerController(unittest.TestCase):
line = inc.readline() line = inc.readline()
self.assertEquals(headers['x-delete-timestamp'], self.assertEquals(headers['x-delete-timestamp'],
expected_timestamp) expected_timestamp)
except BaseException, err: except BaseException as err:
return err return err
return None return None
@ -742,7 +742,7 @@ class TestContainerController(unittest.TestCase):
try: try:
with Timeout(3): with Timeout(3):
resp = req.get_response(self.controller) resp = req.get_response(self.controller)
except BaseException, err: except BaseException as err:
got_exc = True got_exc = True
finally: finally:
err = event.wait() err = event.wait()

View File

@ -142,7 +142,7 @@ class TestContainerSync(unittest.TestCase):
cs = sync.ContainerSync({}, container_ring=FakeRing(), cs = sync.ContainerSync({}, container_ring=FakeRing(),
object_ring=FakeRing()) object_ring=FakeRing())
cs.run_forever() cs.run_forever()
except Exception, err: except Exception as err:
if str(err) != 'we are now done': if str(err) != 'we are now done':
raise raise
finally: finally:
@ -201,7 +201,7 @@ class TestContainerSync(unittest.TestCase):
self.assertEquals(audit_location_generator_calls, [1]) self.assertEquals(audit_location_generator_calls, [1])
self.assertEquals(cs.reported, 3602) self.assertEquals(cs.reported, 3602)
cs.run_once() cs.run_once()
except Exception, err: except Exception as err:
if str(err) != 'we are now done': if str(err) != 'we are now done':
raise raise
finally: finally:

View File

@ -129,7 +129,7 @@ class TestContainerUpdater(unittest.TestCase):
self.assert_('x-delete-timestamp' in headers) self.assert_('x-delete-timestamp' in headers)
self.assert_('x-object-count' in headers) self.assert_('x-object-count' in headers)
self.assert_('x-bytes-used' in headers) self.assert_('x-bytes-used' in headers)
except BaseException, err: except BaseException as err:
import traceback import traceback
traceback.print_exc() traceback.print_exc()
return err return err
@ -185,7 +185,7 @@ class TestContainerUpdater(unittest.TestCase):
out.write('HTTP/1.1 201 OK\r\nContent-Length: 0\r\n\r\n') out.write('HTTP/1.1 201 OK\r\nContent-Length: 0\r\n\r\n')
out.flush() out.flush()
inc.read() inc.read()
except BaseException, err: except BaseException as err:
import traceback import traceback
traceback.print_exc() traceback.print_exc()
return err return err

View File

@ -577,7 +577,7 @@ class TestObjectExpirer(TestCase):
expirer.sleep = not_sleep expirer.sleep = not_sleep
x.run_once = raise_system_exit x.run_once = raise_system_exit
x.run_forever() x.run_forever()
except SystemExit, err: except SystemExit as err:
pass pass
finally: finally:
expirer.random = orig_random expirer.random = orig_random
@ -601,7 +601,7 @@ class TestObjectExpirer(TestCase):
expirer.sleep = not_sleep expirer.sleep = not_sleep
x.run_once = raise_exceptions x.run_once = raise_exceptions
x.run_forever() x.run_forever()
except SystemExit, err: except SystemExit as err:
pass pass
finally: finally:
expirer.sleep = orig_sleep expirer.sleep = orig_sleep
@ -680,7 +680,7 @@ class TestObjectExpirer(TestCase):
exc = None exc = None
try: try:
x.delete_actual_object('/path/to/object', '1234') x.delete_actual_object('/path/to/object', '1234')
except Exception, err: except Exception as err:
exc = err exc = err
finally: finally:
pass pass

View File

@ -175,7 +175,7 @@ class TestObjectUpdater(unittest.TestCase):
line.split(':')[1].strip() line.split(':')[1].strip()
line = inc.readline() line = inc.readline()
self.assert_('x-container-timestamp' in headers) self.assert_('x-container-timestamp' in headers)
except BaseException, err: except BaseException as err:
return err return err
return None return None
@ -192,7 +192,7 @@ class TestObjectUpdater(unittest.TestCase):
err = event.wait() err = event.wait()
if err: if err:
raise err raise err
except BaseException, err: except BaseException as err:
return err return err
return None return None