Commit 497ec2ba authored by Martijn Pieters's avatar Martijn Pieters

Massive style cleanup: Move to new raise exception style; for motivation, see:

    
  http://permalink.gmane.org/gmane.comp.web.zope.zope3/13884
parent 57b2a116
......@@ -417,7 +417,7 @@ class ClientStorage(object):
def doAuth(self, protocol, stub):
if not (self._username and self._password):
raise AuthError, "empty username or password"
raise AuthError("empty username or password")
module = get_module(protocol)
if not module:
......@@ -430,7 +430,7 @@ class ClientStorage(object):
if not client:
log2("%s: %s isn't a valid protocol, must have a Client class" %
(self.__class__.__name__, protocol), level=logging.WARNING)
raise AuthError, "invalid protocol"
raise AuthError("invalid protocol")
c = client(stub)
......@@ -472,7 +472,7 @@ class ClientStorage(object):
conn.setSessionKey(skey)
else:
log2("Authentication failed")
raise AuthError, "Authentication failed"
raise AuthError("Authentication failed")
try:
stub.register(str(self._storage), self._is_read_only)
......
......@@ -206,15 +206,15 @@ class ZEOStorage:
immediately after authentication is finished.
"""
if self.auth_realm and not self.authenticated:
raise AuthError, "Client was never authenticated with server!"
raise AuthError("Client was never authenticated with server!")
if self.storage is not None:
self.log("duplicate register() call")
raise ValueError, "duplicate register() call"
raise ValueError("duplicate register() call")
storage = self.server.storages.get(storage_id)
if storage is None:
self.log("unknown storage_id: %s" % storage_id)
raise ValueError, "unknown storage: %s" % storage_id
raise ValueError("unknown storage: %s" % storage_id)
if not read_only and (self.read_only or storage.isReadOnly()):
raise ReadOnlyError()
......
......@@ -26,5 +26,5 @@ def get_module(name):
def register_module(name, storage_class, client, db):
if _auth_modules.has_key(name):
raise TypeError, "%s is already registred" % name
raise TypeError("%s is already registred" % name)
_auth_modules[name] = storage_class, client, db
......@@ -112,7 +112,7 @@ class StorageClass(ZEOStorage):
# we sent to the client. It will need to generate a new
# nonce for a new connection anyway.
if self._challenge != challenge:
raise ValueError, "invalid challenge"
raise ValueError("invalid challenge")
# lookup user in database
h_up = self.database.get_password(user)
......
......@@ -62,7 +62,7 @@ class Database:
self.load()
if realm:
if self.realm and self.realm != realm:
raise ValueError, ("Specified realm %r differs from database "
raise ValueError("Specified realm %r differs from database "
"realm %r" % (realm or '', self.realm))
else:
self.realm = realm
......@@ -109,7 +109,7 @@ class Database:
Callers must check for LookupError, which is raised in
the case of a non-existent user specified."""
if not self._users.has_key(username):
raise LookupError, "No such user: %s" % username
raise LookupError("No such user: %s" % username)
return self._users[username]
def hash(self, s):
......@@ -117,15 +117,15 @@ class Database:
def add_user(self, username, password):
if self._users.has_key(username):
raise LookupError, "User %s already exists" % username
raise LookupError("User %s already exists" % username)
self._store_password(username, password)
def del_user(self, username):
if not self._users.has_key(username):
raise LookupError, "No such user: %s" % username
raise LookupError("No such user: %s" % username)
del self._users[username]
def change_password(self, username, password):
if not self._users.has_key(username):
raise LookupError, "No such user: %s" % username
raise LookupError("No such user: %s" % username)
self._store_password(username, password)
......@@ -48,7 +48,7 @@ class HMAC:
self.update(msg)
## def clear(self):
## raise NotImplementedError, "clear() method not available in HMAC."
## raise NotImplementedError("clear() method not available in HMAC.")
def update(self, msg):
"""Update this hashing object with the string msg.
......
......@@ -98,7 +98,7 @@ def get_port():
return port
finally:
s.close()
raise RuntimeError, "Can't find port"
raise RuntimeError("Can't find port")
class GenericTests(
# Base class for all ZODB tests
......
......@@ -112,7 +112,7 @@ def main(args=None, dbclass=None):
# dbclass is used for testing tests.auth_plaintext, see testAuth.py
Database = dbclass
else:
raise ValueError, "Unknown database type %r" % p
raise ValueError("Unknown database type %r" % p)
if auth_db is None:
usage("Error: configuration does not specify auth database")
db = Database(auth_db, auth_realm)
......
......@@ -55,7 +55,7 @@ class HMAC:
self.update(msg)
## def clear(self):
## raise NotImplementedError, "clear() method not available in HMAC."
## raise NotImplementedError("clear() method not available in HMAC.")
def update(self, msg):
"""Update this hashing object with the string msg.
......
......@@ -66,8 +66,7 @@ class ConnectionManager(object):
for addr in addrs:
addr_type = self._guess_type(addr)
if addr_type is None:
raise ValueError, (
"unknown address in list: %s" % repr(addr))
raise ValueError("unknown address in list: %s" % repr(addr))
addrlist.append((addr_type, addr))
return addrlist
......
......@@ -288,7 +288,7 @@ class BaseStorage(UndoLogCompatible):
def undo(self, transaction_id, txn):
if self._is_read_only:
raise POSException.ReadOnlyError()
raise POSException.UndoError, 'non-undoable transaction'
raise POSException.UndoError('non-undoable transaction')
def undoLog(self, first, last, filter=None):
return ()
......@@ -313,7 +313,7 @@ class BaseStorage(UndoLogCompatible):
self._lock_release()
def loadSerial(self, oid, serial):
raise POSException.Unsupported, (
raise POSException.Unsupported(
"Retrieval of historical revisions is not supported")
def loadBefore(self, oid, tid):
......
......@@ -64,7 +64,7 @@ class PersistentReference:
return "PR(%s %s)" % (id(self), self.data)
def __getstate__(self):
raise PicklingError, "Can't pickle PersistentReference"
raise PicklingError("Can't pickle PersistentReference")
class PersistentReferenceFactory:
......
......@@ -103,7 +103,7 @@ class DemoStorage(BaseStorage):
self._ltid = None
self._clear_temp()
if base is not None and base.versions():
raise POSException.StorageError, (
raise POSException.StorageError(
"Demo base storage has version data")
# While we officially don't support wrapping a non-read-only base
......@@ -213,7 +213,7 @@ class DemoStorage(BaseStorage):
except KeyError:
if self._base:
return self._base.load(oid, '')
raise KeyError, oid
raise KeyError(oid)
ver = ""
if vdata:
......@@ -224,11 +224,11 @@ class DemoStorage(BaseStorage):
# data.
oid, pre, vdata, p, skiptid = nv
else:
raise KeyError, oid
raise KeyError(oid)
ver = oversion
if p is None:
raise KeyError, oid
raise KeyError(oid)
return p, tid, ver
finally: self._lock_release()
......@@ -269,7 +269,7 @@ class DemoStorage(BaseStorage):
if vdata:
if vdata[0] != version:
raise POSException.VersionLockError, oid
raise POSException.VersionLockError(oid)
nv=vdata[1]
else:
......@@ -287,7 +287,7 @@ class DemoStorage(BaseStorage):
if version: s=s+32+len(version)
if self._quota is not None and s > self._quota:
raise POSException.StorageError, (
raise POSException.StorageError(
'''<b>Quota Exceeded</b><br>
The maximum quota for this demonstration storage
has been exceeded.<br>Have a nice day.''')
......
......@@ -1322,7 +1322,7 @@ class FileStorage(BaseStorage.BaseStorage,
raise POSException.ReadOnlyError()
stop=`TimeStamp(*time.gmtime(t)[:5]+(t%60,))`
if stop==z64: raise FileStorageError, 'Invalid pack time'
if stop==z64: raise FileStorageError('Invalid pack time')
# If the storage is empty, there's nothing to do.
if not self._index:
......@@ -1331,7 +1331,7 @@ class FileStorage(BaseStorage.BaseStorage,
self._lock_acquire()
try:
if self._pack_is_in_progress:
raise FileStorageError, 'Already packing'
raise FileStorageError('Already packing')
self._pack_is_in_progress = True
current_size = self.getSize()
finally:
......@@ -1624,10 +1624,10 @@ def read_index(file, name, index, vindex, tindex, stop='\377'*8,
if file_size:
if file_size < start:
raise FileStorageFormatError, file.name
raise FileStorageFormatError(file.name)
seek(0)
if read(4) != packed_version:
raise FileStorageFormatError, name
raise FileStorageFormatError(name)
else:
if not read_only:
file.write(packed_version)
......@@ -1791,8 +1791,7 @@ def _truncate(file, name, pos):
except:
logger.error("couldn\'t write truncated data for %s", name,
exc_info=True)
raise POSException.StorageSystemError, (
"Couldn't save truncated data")
raise POSException.StorageSystemError("Couldn't save truncated data")
file.seek(pos)
file.truncate()
......@@ -1824,7 +1823,7 @@ class FileIterator(Iterator, FileStorageFormatter):
file = open(file, 'rb')
self._file = file
if file.read(4) != packed_version:
raise FileStorageFormatError, file.name
raise FileStorageFormatError(file.name)
file.seek(0,2)
self._file_size = file.tell()
self._pos = 4L
......@@ -1887,7 +1886,7 @@ class FileIterator(Iterator, FileStorageFormatter):
if self._file is None:
# A closed iterator. Is IOError the best we can do? For
# now, mimic a read on a closed file.
raise IOError, 'iterator is closed'
raise IOError('iterator is closed')
pos = self._pos
while 1:
......@@ -1906,11 +1905,11 @@ class FileIterator(Iterator, FileStorageFormatter):
self._ltid = h.tid
if self._stop is not None and h.tid > self._stop:
raise IndexError, index
raise IndexError(index)
if h.status == "c":
# Assume we've hit the last, in-progress transaction
raise IndexError, index
raise IndexError(index)
if pos + h.tlen + 8 > self._file_size:
# Hm, the data were truncated or the checkpoint flag wasn't
......@@ -1974,7 +1973,7 @@ class FileIterator(Iterator, FileStorageFormatter):
return result
raise IndexError, index
raise IndexError(index)
class RecordIterator(Iterator, BaseStorage.TransactionRecord,
FileStorageFormatter):
......@@ -2023,7 +2022,7 @@ class RecordIterator(Iterator, BaseStorage.TransactionRecord,
r = Record(h.oid, h.tid, h.version, data, prev_txn, pos)
return r
raise IndexError, index
raise IndexError(index)
class Record(BaseStorage.DataRecord):
"""An abstract database record."""
......
......@@ -215,12 +215,12 @@ class MountPoint(persistent.Persistent, Acquisition.Implicit):
try:
app = root['Application']
except:
raise MountedStorageError, (
raise MountedStorageError(
"No 'Application' object exists in the mountable database.")
try:
return app.unrestrictedTraverse(self._path)
except:
raise MountedStorageError, (
raise MountedStorageError(
"The path '%s' was not found in the mountable database."
% self._path)
......
......@@ -54,14 +54,14 @@ class _p_DataDescr(object):
return self
if '__global_persistent_class_not_stored_in_DB__' in inst.__dict__:
raise AttributeError, self.__name__
raise AttributeError(self.__name__)
return inst._p_class_dict.get(self.__name__)
def __set__(self, inst, v):
inst._p_class_dict[self.__name__] = v
def __delete__(self, inst):
raise AttributeError, self.__name__
raise AttributeError(self.__name__)
class _p_oid_or_jar_Descr(_p_DataDescr):
# Special descr for _p_oid and _p_jar that loads
......@@ -112,10 +112,10 @@ class _p_MethodDescr(object):
return self.func.__get__(inst, cls)
def __set__(self, inst, v):
raise AttributeError, self.__name__
raise AttributeError(self.__name__)
def __delete__(self, inst):
raise AttributeError, self.__name__
raise AttributeError(self.__name__)
special_class_descrs = '__dict__', '__weakref__'
......
......@@ -47,11 +47,11 @@ class PCounter2(PCounter):
class PCounter3(PCounter):
def _p_resolveConflict(self, oldState, savedState, newState):
raise AttributeError, "no attribute (testing conflict resolution)"
raise AttributeError("no attribute (testing conflict resolution)")
class PCounter4(PCounter):
def _p_resolveConflict(self, oldState, savedState):
raise RuntimeError, "Can't get here; not enough args"
raise RuntimeError("Can't get here; not enough args")
class ConflictResolvingStorage:
......
......@@ -99,7 +99,7 @@ def zodb_unpickle(data):
print >> sys.stderr, "can't find %s in %r" % (klassname, ns)
inst = klass()
else:
raise ValueError, "expected class info: %s" % repr(klass_info)
raise ValueError("expected class info: %s" % repr(klass_info))
state = u.load()
inst.__setstate__(state)
return inst
......
......@@ -86,7 +86,7 @@ class RecoverTest(unittest.TestCase):
ZODB.fsrecover.recover(self.path, self.dest,
verbose=0, partial=True, force=False, pack=1)
except SystemExit:
raise RuntimeError, "recover tried to exit"
raise RuntimeError("recover tried to exit")
finally:
sys.stdout = orig_stdout
return faux_stdout.getvalue()
......
......@@ -102,7 +102,7 @@ class SerializerTestCase(unittest.TestCase):
if name == "error":
raise ValueError("whee!")
else:
raise AttributeError, name
raise AttributeError(name)
class NewStyle(object):
bar = "bar"
......
......@@ -123,7 +123,7 @@ class MinimalMemoryStorage(BaseStorage, object):
try:
tids = [tid for oid, tid in self._index if oid == the_oid]
if not tids:
raise KeyError, the_oid
raise KeyError(the_oid)
tids.sort()
i = bisect.bisect_left(tids, the_tid) - 1
if i == -1:
......
......@@ -54,5 +54,5 @@ def transact(f, note=None, retries=5):
raise
continue
return r
raise RuntimeError, "couldn't commit transaction"
raise RuntimeError("couldn't commit transaction")
return g
......@@ -73,7 +73,7 @@ class SampleOverridingGetattr(Persistent):
"""
# Don't pretend we have any special attributes.
if name.startswith("__") and name.endswrith("__"):
raise AttributeError, name
raise AttributeError(name)
else:
return name.upper(), self._p_changed
......@@ -178,7 +178,7 @@ class SampleOverridingGetattributeSetattrAndDelattr(Persistent):
# Maybe it's a method:
meth = getattr(self.__class__, name, None)
if meth is None:
raise AttributeError, name
raise AttributeError(name)
return meth.__get__(self, self.__class__)
......
......@@ -52,7 +52,7 @@ def main():
opts, args = getopt.getopt(sys.argv[1:], 'f:')
if not args:
usage()
raise ValueError, "Must specify a FileStorage"
raise ValueError("Must specify a FileStorage")
path = None
for k, v in opts:
if k == '-f':
......
......@@ -209,7 +209,7 @@ if __name__ == "__main__":
try:
opts, args = getopt.getopt(sys.argv[1:], 'v')
if len(args) != 1:
raise ValueError, "expected one argument"
raise ValueError("expected one argument")
for k, v in opts:
if k == '-v':
VERBOSE = VERBOSE + 1
......
......@@ -197,7 +197,7 @@ def which(program):
if not os.path.isabs(path):
path = os.path.abspath(path)
return path
raise IOError, "can't find %r on path %r" % (program, strpath)
raise IOError("can't find %r on path %r" % (program, strpath))
def makedir(*args):
path = ""
......
......@@ -45,7 +45,7 @@ def connect(storage):
storage._call.connect()
if storage._connected:
return
raise RuntimeError, "Unable to connect to ZEO server"
raise RuntimeError("Unable to connect to ZEO server")
def pack1(addr, storage, days, wait):
cs = ClientStorage(addr, storage=storage,
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment