From ded0a4376184594b435c9144d08956d98124535a Mon Sep 17 00:00:00 2001 From: fspreck <f.spreckelsen@indiscale.com> Date: Thu, 14 Jan 2021 18:40:56 +0100 Subject: [PATCH] MAINT: Rename Exceptions to Errors --- examples/set_permissions.py | 14 ++-- src/caosdb/common/administration.py | 58 ++++++++-------- src/caosdb/common/models.py | 18 ++--- .../connection/authentication/auth_token.py | 12 ++-- .../connection/authentication/interface.py | 8 +-- .../connection/authentication/keyring.py | 10 +-- src/caosdb/connection/authentication/pass.py | 10 +-- .../authentication/unauthenticated.py | 12 ++-- src/caosdb/connection/connection.py | 68 +++++++++---------- src/caosdb/exceptions.py | 36 +++++----- src/caosdb/utils/caosdb_admin.py | 4 +- unittests/test_authentication_auth_token.py | 4 +- .../test_authentication_unauthenticated.py | 4 +- unittests/test_connection.py | 14 ++-- unittests/test_connection_utils.py | 8 ++- unittests/test_error_handling.py | 7 +- 16 files changed, 144 insertions(+), 143 deletions(-) diff --git a/examples/set_permissions.py b/examples/set_permissions.py index 3637f89e..dfc0a151 100755 --- a/examples/set_permissions.py +++ b/examples/set_permissions.py @@ -51,26 +51,26 @@ out : tuple try: human_user = admin._retrieve_user("jane") _activate_user("jane") - except db.ResourceNotFoundException: + except db.ResourceNotFoundError: human_user = admin._insert_user( "jane", password="Human_Rememberable_Password_1234", status="ACTIVE") try: alien_user = admin._retrieve_user("xaxys") _activate_user("xaxys") - except db.ResourceNotFoundException: + except db.ResourceNotFoundError: alien_user = admin._insert_user("xaxys", password="4321_Syxax", status="ACTIVE") # At the moment, the return value is only "ok" for successful insertions. try: human_role = admin._retrieve_role("human") - except db.ResourceNotFoundException: + except db.ResourceNotFoundError: human_role = admin._insert_role("human", "An Earthling.") try: alien_role = admin._retrieve_role("alien") - except db.ResourceNotFoundException: + except db.ResourceNotFoundError: alien_role = admin._insert_role("alien", "An Extra-terrestrial.") admin._set_roles("jane", ["human"]) @@ -193,7 +193,7 @@ None ent.retrieve() print("Successfully retrieved all entities.") except db.TransactionError as te: - if te.has_error(db.AuthorizationException): + if te.has_error(db.AuthorizationError): print(ent) print("Could not retrieve this entity although it should have been possible!") else: @@ -214,8 +214,8 @@ None print("Could retrieve this entity although it should not have been possible!") except db.TransactionError as te: # Only do something if an error wasn't caused by an - # AuthorizationException - if not te.has_error(db.AuthorizationException): + # AuthorizationError + if not te.has_error(db.AuthorizationError): raise te if denied_all: print("Retrieval of all entities was successfully denied.") diff --git a/src/caosdb/common/administration.py b/src/caosdb/common/administration.py index 4d5f633d..f88119eb 100644 --- a/src/caosdb/common/administration.py +++ b/src/caosdb/common/administration.py @@ -30,9 +30,9 @@ from lxml import etree from caosdb.common.utils import xml2str from caosdb.connection.connection import get_connection -from caosdb.exceptions import (ClientErrorException, - HTTPAuthorizationException, - ResourceNotFoundException) +from caosdb.exceptions import (HTTPClientError, + HTTPAuthorizationError, + ResourceNotFoundError) def set_server_property(key, value): @@ -107,10 +107,10 @@ def _retrieve_user(name, realm=None, **kwargs): con = get_connection() try: return con._http_request(method="GET", path="User/" + (realm + "/" + name if realm is not None else name), **kwargs).read() - except HTTPAuthorizationException as e: + except HTTPAuthorizationError as e: e.msg = "You are not permitted to retrieve this user." raise - except ResourceNotFoundException as e: + except ResourceNotFoundError as e: e.msg = "User does not exist." raise @@ -119,10 +119,10 @@ def _delete_user(name, **kwargs): con = get_connection() try: return con._http_request(method="DELETE", path="User/" + name, **kwargs).read() - except HTTPAuthorizationException as e: + except HTTPAuthorizationError as e: e.msg = "You are not permitted to delete this user." raise - except ResourceNotFoundException as e: + except ResourceNotFoundError as e: e.msg = "User does not exist." raise @@ -145,13 +145,13 @@ def _update_user(name, realm=None, password=None, status=None, params["entity"] = str(entity) try: return con.put_form_data(entity_uri_segment="User/" + (realm + "/" + name if realm is not None else name), params=params, **kwargs).read() - except ResourceNotFoundException as e: + except ResourceNotFoundError as e: e.msg = "User does not exist." raise - except HTTPAuthorizationException as e: + except HTTPAuthorizationError as e: e.msg = "You are not permitted to update this user." raise - except ClientErrorException as e: + except HTTPClientError as e: if e.status == 409: e.msg = "Entity does not exist." raise @@ -174,10 +174,10 @@ def _insert_user(name, password=None, status=None, email=None, entity=None, **kw params["entity"] = entity try: return con.post_form_data(entity_uri_segment="User", params=params, **kwargs).read() - except HTTPAuthorizationException as e: + except HTTPAuthorizationError as e: e.msg = "You are not permitted to insert a new user." raise e - except ClientErrorException as e: + except HTTPClientError as e: if e.status == 409: e.msg = "User name is already in use." @@ -190,10 +190,10 @@ def _insert_role(name, description, **kwargs): con = get_connection() try: return con.post_form_data(entity_uri_segment="Role", params={"role_name": name, "role_description": description}, **kwargs).read() - except HTTPAuthorizationException as e: + except HTTPAuthorizationError as e: e.msg = "You are not permitted to insert a new role." raise - except ClientErrorException as e: + except HTTPClientError as e: if e.status == 409: e.msg = "Role name is already in use. Choose a different name." raise @@ -203,10 +203,10 @@ def _update_role(name, description, **kwargs): con = get_connection() try: return con.put_form_data(entity_uri_segment="Role/" + name, params={"role_description": description}, **kwargs).read() - except HTTPAuthorizationException as e: + except HTTPAuthorizationError as e: e.msg = "You are not permitted to update this role." raise - except ResourceNotFoundException as e: + except ResourceNotFoundError as e: e.msg = "Role does not exist." raise @@ -215,10 +215,10 @@ def _retrieve_role(name, **kwargs): con = get_connection() try: return con._http_request(method="GET", path="Role/" + name, **kwargs).read() - except HTTPAuthorizationException as e: + except HTTPAuthorizationError as e: e.msg = "You are not permitted to retrieve this role." raise - except ResourceNotFoundException as e: + except ResourceNotFoundError as e: e.msg = "Role does not exist." raise @@ -227,10 +227,10 @@ def _delete_role(name, **kwargs): con = get_connection() try: return con._http_request(method="DELETE", path="Role/" + name, **kwargs).read() - except HTTPAuthorizationException as e: + except HTTPAuthorizationError as e: e.msg = "You are not permitted to delete this role." raise - except ResourceNotFoundException as e: + except ResourceNotFoundError as e: e.msg = "Role does not exist." raise @@ -246,13 +246,13 @@ def _set_roles(username, roles, realm=None, **kwargs): try: body = con._http_request(method="PUT", path="UserRoles/" + (realm + "/" + username if realm is not None else username), body=body, **kwargs).read() - except HTTPAuthorizationException as e: + except HTTPAuthorizationError as e: e.msg = "You are not permitted to set this user's roles." raise - except ResourceNotFoundException as e: + except ResourceNotFoundError as e: e.msg = "User does not exist." raise - except ClientErrorException as e: + except HTTPClientError as e: if e.status == 409: e.msg = "Role does not exist." raise @@ -270,10 +270,10 @@ def _get_roles(username, realm=None, **kwargs): try: body = con._http_request(method="GET", path="UserRoles/" + ( realm + "/" + username if realm is not None else username), **kwargs).read() - except HTTPAuthorizationException as e: + except HTTPAuthorizationError as e: e.msg = "You are not permitted to retrieve this user's roles." raise - except ResourceNotFoundException as e: + except ResourceNotFoundError as e: e.msg = "User does not exist." raise ret = set() @@ -313,10 +313,10 @@ Returns con = get_connection() try: return con._http_request(method="PUT", path="PermissionRules/" + role, body=body, **kwargs).read() - except HTTPAuthorizationException as e: + except HTTPAuthorizationError as e: e.msg = "You are not permitted to set this role's permissions." raise - except ResourceNotFoundException as e: + except ResourceNotFoundError as e: e.msg = "Role does not exist." raise @@ -325,10 +325,10 @@ def _get_permissions(role, **kwargs): con = get_connection() try: return PermissionRule._parse_body(con._http_request(method="GET", path="PermissionRules/" + role, **kwargs).read()) - except HTTPAuthorizationException as e: + except HTTPAuthorizationError as e: e.msg = "You are not permitted to retrieve this role's permissions." raise - except ResourceNotFoundException as e: + except ResourceNotFoundError as e: e.msg = "Role does not exist." raise diff --git a/src/caosdb/common/models.py b/src/caosdb/common/models.py index faec8476..1cdbe6fb 100644 --- a/src/caosdb/common/models.py +++ b/src/caosdb/common/models.py @@ -48,9 +48,9 @@ from caosdb.common.utils import uuid, xml2str from caosdb.configuration import get_config from caosdb.connection.connection import get_connection from caosdb.connection.encode import MultipartParam, multipart_encode -from caosdb.exceptions import (AmbiguityException, - AuthorizationException, - CaosDBException, ConnectionException, +from caosdb.exceptions import (AmbiguityError, + AuthorizationError, + CaosDBException, ConnectionError, ConsistencyError, EmptyUniqueQueryError, EntityDoesNotExistError, EntityError, @@ -60,7 +60,7 @@ from caosdb.exceptions import (AmbiguityException, UniqueNamesError, UnqualifiedParentsError, UnqualifiedPropertiesError, - URITooLongException) + URITooLongError) from lxml import etree from .datatype import is_reference @@ -998,7 +998,7 @@ class Entity(object): if len(c == 1): e = c[0] else: - raise AmbiguityException( + raise AmbiguityError( "Could not determine the desired Entity which is to be updated by its name.") else: e = Container().retrieve(query=self.id, sync=False)[0] @@ -2943,7 +2943,7 @@ class Container(list): "&".join(entities))], query_dict=flags) return Container._response_to_entities(http_response) - except URITooLongException as uri_e: + except URITooLongError as uri_e: try: # split up uri1, uri2 = Container._split_uri_string(entities) @@ -3758,7 +3758,7 @@ class Info(): c = get_connection() try: http_response = c.retrieve(["Info"]) - except ConnectionException as conn_e: + except ConnectionError as conn_e: print(conn_e) return @@ -3937,8 +3937,8 @@ def _evaluate_and_add_error(parent_error, ent): new_exc = EntityHasNoDatatypeError(entity=ent, error=err) elif int(err.code) == 403: # no permission - new_exc = AuthorizationException(entity=ent, - error=err) + new_exc = AuthorizationError(entity=ent, + error=err) elif int(err.code) == 152: # name wasn't unique new_exc = UniqueNamesError(entity=ent, error=err) elif int(err.code) == 114: # unqualified properties diff --git a/src/caosdb/connection/authentication/auth_token.py b/src/caosdb/connection/authentication/auth_token.py index fbce78fb..68812386 100644 --- a/src/caosdb/connection/authentication/auth_token.py +++ b/src/caosdb/connection/authentication/auth_token.py @@ -30,7 +30,7 @@ An Authentictor which only uses only a pre-supplied authentication token. from __future__ import absolute_import, unicode_literals, print_function from .interface import AbstractAuthenticator, CaosDBServerConnection from caosdb.connection.utils import auth_token_to_cookie -from caosdb.exceptions import LoginFailedException +from caosdb.exceptions import LoginFailedError def get_authentication_provider(): @@ -68,11 +68,11 @@ class AuthTokenAuthenticator(AbstractAuthenticator): self._login() def _login(self): - raise LoginFailedException("The authentication token is expired or you " - "have been logged out otherwise. The " - "auth_token authenticator cannot log in " - "again. You must provide a new " - "authentication token.") + raise LoginFailedError("The authentication token is expired or you " + "have been logged out otherwise. The " + "auth_token authenticator cannot log in " + "again. You must provide a new " + "authentication token.") def logout(self): self._logout() diff --git a/src/caosdb/connection/authentication/interface.py b/src/caosdb/connection/authentication/interface.py index d9a9b430..a364aeb5 100644 --- a/src/caosdb/connection/authentication/interface.py +++ b/src/caosdb/connection/authentication/interface.py @@ -31,7 +31,7 @@ import logging from caosdb.connection.utils import urlencode from caosdb.connection.interface import CaosDBServerConnection from caosdb.connection.utils import parse_auth_token, auth_token_to_cookie -from caosdb.exceptions import LoginFailedException +from caosdb.exceptions import LoginFailedError # meta class compatible with Python 2 *and* 3: ABC = ABCMeta('ABC', (object, ), {'__slots__': ()}) @@ -197,9 +197,9 @@ class CredentialsAuthenticator(AbstractAuthenticator): # we need a username for this: if username is None: - raise LoginFailedException("No username was given.") + raise LoginFailedError("No username was given.") if password is None: - raise LoginFailedException("No password was given") + raise LoginFailedError("No password was given") headers = {} headers["Content-Type"] = "application/x-www-form-urlencoded" @@ -210,7 +210,7 @@ class CredentialsAuthenticator(AbstractAuthenticator): response.read() # clear socket if response.status != 200: - raise LoginFailedException("LOGIN WAS NOT SUCCESSFUL") + raise LoginFailedError("LOGIN WAS NOT SUCCESSFUL") self.on_response(response) return response diff --git a/src/caosdb/connection/authentication/keyring.py b/src/caosdb/connection/authentication/keyring.py index 1dc98617..d8be7ddf 100644 --- a/src/caosdb/connection/authentication/keyring.py +++ b/src/caosdb/connection/authentication/keyring.py @@ -30,7 +30,7 @@ retrieve the password. import sys import imp from getpass import getpass -from caosdb.exceptions import ConfigurationException +from caosdb.exceptions import ConfigurationError from .external_credentials_provider import ExternalCredentialsProvider from .interface import CredentialsAuthenticator @@ -67,10 +67,10 @@ def _get_external_keyring(): def _call_keyring(**config): if "username" not in config: - raise ConfigurationException("Your configuration did not provide a " - "`username` which is needed by the " - "`KeyringCaller` to retrieve the " - "password in question.") + raise ConfigurationError("Your configuration did not provide a " + "`username` which is needed by the " + "`KeyringCaller` to retrieve the " + "password in question.") url = config.get("url") username = config.get("username") app = "caosdb — {}".format(url) diff --git a/src/caosdb/connection/authentication/pass.py b/src/caosdb/connection/authentication/pass.py index 9399fc4f..853cdf0e 100644 --- a/src/caosdb/connection/authentication/pass.py +++ b/src/caosdb/connection/authentication/pass.py @@ -28,7 +28,7 @@ password. """ from subprocess import check_output, CalledProcessError -from caosdb.exceptions import ConfigurationException +from caosdb.exceptions import ConfigurationError from .interface import CredentialsAuthenticator from .external_credentials_provider import ExternalCredentialsProvider @@ -50,10 +50,10 @@ def get_authentication_provider(): def _call_pass(**config): if "password_identifier" not in config: - raise ConfigurationException("Your configuration did not provide a " - "`password_identifier` which is needed " - "by the `PassCaller` to retrieve the " - "password in question.") + raise ConfigurationError("Your configuration did not provide a " + "`password_identifier` which is needed " + "by the `PassCaller` to retrieve the " + "password in question.") try: return check_output( diff --git a/src/caosdb/connection/authentication/unauthenticated.py b/src/caosdb/connection/authentication/unauthenticated.py index 53a2756e..65febae8 100644 --- a/src/caosdb/connection/authentication/unauthenticated.py +++ b/src/caosdb/connection/authentication/unauthenticated.py @@ -30,7 +30,7 @@ cookies. """ from __future__ import absolute_import, unicode_literals, print_function from .interface import AbstractAuthenticator, CaosDBServerConnection -from caosdb.exceptions import LoginFailedException +from caosdb.exceptions import LoginFailedError def get_authentication_provider(): @@ -70,11 +70,11 @@ class Unauthenticated(AbstractAuthenticator): self._login() def _login(self): - raise LoginFailedException("This caosdb client is configured to stay " - "unauthenticated. Change your " - "`password_method` and provide an " - "`auth_token` or credentials if you want " - "to authenticate this client.") + raise LoginFailedError("This caosdb client is configured to stay " + "unauthenticated. Change your " + "`password_method` and provide an " + "`auth_token` or credentials if you want " + "to authenticate this client.") def logout(self): self._logout() diff --git a/src/caosdb/connection/connection.py b/src/caosdb/connection/connection.py index 460d0f41..0445f93b 100644 --- a/src/caosdb/connection/connection.py +++ b/src/caosdb/connection/connection.py @@ -33,14 +33,14 @@ from errno import EPIPE as BrokenPipe from socket import error as SocketError from caosdb.configuration import get_config -from caosdb.exceptions import (CaosDBException, ClientErrorException, - ConfigurationException, - ConnectionException, - HTTPAuthorizationException, - LoginFailedException, - ResourceNotFoundException, - ServerErrorException, - URITooLongException) +from caosdb.exceptions import (CaosDBException, HTTPClientError, + ConfigurationError, + ConnectionError, + HTTPAuthorizationError, + LoginFailedError, + ResourceNotFoundError, + HTTPServerError, + URITooLongError) from caosdb.version import version from pkg_resources import resource_filename @@ -136,7 +136,7 @@ class _DefaultCaosDBServerConnection(CaosDBServerConnection): self._http_con.request(method=method, url=self._base_path + path, headers=headers, body=body) except SocketError as socket_err: - raise ConnectionException( + raise ConnectionError( "Connection failed. Network or server down? " + str(socket_err) ) @@ -160,7 +160,7 @@ class _DefaultCaosDBServerConnection(CaosDBServerConnection): Raises ------ - ConnectionException + ConnectionError If no url has been specified, or if the CA certificate cannot be loaded. """ @@ -197,9 +197,9 @@ class _DefaultCaosDBServerConnection(CaosDBServerConnection): try: context.load_verify_locations(config["cacert"]) except Exception as exc: - raise ConnectionException("Could not load the cacert in" - "`{}`: {}".format(config["cacert"], - exc)) + raise ConnectionError("Could not load the cacert in" + "`{}`: {}".format(config["cacert"], + exc)) context.load_default_certs() @@ -208,7 +208,7 @@ class _DefaultCaosDBServerConnection(CaosDBServerConnection): host = parsed_url.netloc self._base_path = parsed_url.path else: - raise ConnectionException( + raise ConnectionError( "No connection url specified. Please " "do so via caosdb.configure_connection(...) or in a config " "file.") @@ -280,7 +280,7 @@ def _get_authenticator(**config): Raises ------ - ConnectionException + ConnectionError If the password_method string cannot be resolved to a CaosAuthenticator class. """ @@ -296,10 +296,10 @@ def _get_authenticator(**config): return auth_provider except ImportError: - raise ConfigurationException("Password method \"{}\" not implemented. " - "Try `plain`, `pass`, `keyring`, or " - "`auth_token`." - .format(config["password_method"])) + raise ConfigurationError("Password method \"{}\" not implemented. " + "Try `plain`, `pass`, `keyring`, or " + "`auth_token`." + .format(config["password_method"])) def configure_connection(**kwargs): @@ -403,24 +403,24 @@ def _handle_response_status(http_response): body = http_response.read() if status == 401: - raise LoginFailedException( + raise LoginFailedError( "Request failed. The response returned with status " "{}.".format(status)) elif status == 403: - raise HTTPAuthorizationException( + raise HTTPAuthorizationError( "Request failed. The response returned with status " "{}.".format(status)) elif status == 404: - raise ResourceNotFoundException("This entity does not exist.") + raise ResourceNotFoundError("This entity does not exist.") elif status in (413, 414): - raise URITooLongException( + raise URITooLongError( "Request failed. The response returned with status " "{}.".format(status)) elif 399 < status < 500: - raise ClientErrorException(msg=("Request failed. The response returned " - "with status {}.").format(status), status=status, body=body) + raise HTTPClientError(msg=("Request failed. The response returned " + "with status {}.").format(status), status=status, body=body) elif status > 499: - raise ServerErrorException(body=body) + raise HTTPServerError(body=body) else: raise CaosDBException( "Request failed. The response returned with status " @@ -458,7 +458,7 @@ class _Connection(object): # pylint: disable=useless-object-inheritance self.is_configured = True if "implementation" not in config: - raise ConfigurationException( + raise ConfigurationError( "Missing CaosDBServerConnection implementation. You did not " "specify an `implementation` for the connection.") try: @@ -469,7 +469,7 @@ class _Connection(object): # pylint: disable=useless-object-inheritance raise TypeError("The `implementation` callable did not return " "an instance of CaosDBServerConnection.") except TypeError as type_err: - raise ConfigurationException( + raise ConfigurationError( "Bad CaosDBServerConnection implementation. The " "implementation must be a callable object which returns an " "instance of `CaosDBServerConnection` (e.g. a constructor " @@ -480,9 +480,9 @@ class _Connection(object): # pylint: disable=useless-object-inheritance # deprecated, needed for older scripts config["password_method"] = "auth_token" if "password_method" not in config: - raise ConfigurationException("Missing password_method. You did " - "not specify a `password_method` for" - "the connection.") + raise ConfigurationError("Missing password_method. You did " + "not specify a `password_method` for" + "the connection.") self._authenticator = _get_authenticator( connection=self._delegate_connection, **config) @@ -558,8 +558,8 @@ class _Connection(object): # pylint: disable=useless-object-inheritance uri_segments.extend(path.split("/")) return self.retrieve(entity_uri_segments=uri_segments) - except ResourceNotFoundException: - raise ResourceNotFoundException("This file does not exist.") + except ResourceNotFoundError: + raise ResourceNotFoundError("This file does not exist.") def _login(self): self._authenticator.login() @@ -580,7 +580,7 @@ class _Connection(object): # pylint: disable=useless-object-inheritance headers=headers, body=body, reconnect=False, **kwargs) - except LoginFailedException: + except LoginFailedError: if kwargs.get("reconnect", True) is True: self._login() diff --git a/src/caosdb/exceptions.py b/src/caosdb/exceptions.py index 43dde185..8eb07f34 100644 --- a/src/caosdb/exceptions.py +++ b/src/caosdb/exceptions.py @@ -39,8 +39,8 @@ class CaosDBException(Exception): self.msg = msg -class ConfigurationException(CaosDBException): - """ConfigurationException. +class ConfigurationError(CaosDBException): + """ConfigurationError. Indicates a misconfiguration. @@ -57,8 +57,8 @@ class ConfigurationException(CaosDBException): """ def __init__(self, msg): - super(ConfigurationException, self).__init__(msg + - ConfigurationException._INFO) + super(ConfigurationError, self).__init__(msg + + ConfigurationError._INFO) _INFO = ("\n\nPlease check your ~/.pycaosdb.ini and your $PWD/" ".pycaosdb.ini. Do at least one of them exist and are they correct?") @@ -67,8 +67,8 @@ class ConfigurationException(CaosDBException): # to their HTTP codes as children of client/server exception. -class ClientErrorException(CaosDBException): - """ClientErrorException represents 4xx HTTP client errors.""" +class HTTPClientError(CaosDBException): + """HTTPClientError represents 4xx HTTP client errors.""" def __init__(self, msg, status, body): self.status = status @@ -76,8 +76,8 @@ class ClientErrorException(CaosDBException): CaosDBException.__init__(self, msg) -class ServerErrorException(CaosDBException): - """ServerErrorException represents 5xx HTTP server errors.""" +class HTTPServerError(CaosDBException): + """HTTPServerError represents 5xx HTTP server errors.""" def __init__(self, body): xml = etree.fromstring(body) @@ -89,21 +89,21 @@ class ServerErrorException(CaosDBException): CaosDBException.__init__(self, msg) -class ConnectionException(CaosDBException): +class ConnectionError(CaosDBException): """Connection is not configured or the network is down.""" def __init__(self, msg=None): CaosDBException.__init__(self, msg) -class URITooLongException(ClientErrorException): +class URITooLongError(HTTPClientError): """The URI of the last request was too long.""" def __init__(self, msg=None): - ClientErrorException.__init__(self, msg=msg, status=414, body=None) + HTTPClientError.__init__(self, msg=msg, status=414, body=None) -class AmbiguityException(CaosDBException): +class AmbiguityError(CaosDBException): """A retrieval of an entity that was supposed to be uniquely identifiable returned two or more entities.""" @@ -111,7 +111,7 @@ class AmbiguityException(CaosDBException): CaosDBException.__init__(self, msg) -class LoginFailedException(CaosDBException): +class LoginFailedError(CaosDBException): """Login failed. Probably, your username/password pair is wrong. @@ -121,24 +121,24 @@ class LoginFailedException(CaosDBException): CaosDBException.__init__(self, msg=msg) -class HTTPAuthorizationException(ClientErrorException): +class HTTPAuthorizationError(HTTPClientError): """You're lacking the required permissions. Corresponds to HTTP status 403. """ def __init__(self, msg=None): - ClientErrorException.__init__(self, msg=msg, status=403, body=None) + HTTPClientError.__init__(self, msg=msg, status=403, body=None) -class ResourceNotFoundException(ClientErrorException): +class ResourceNotFoundError(HTTPClientError): """The requested resource doesn't exist; corresponds to HTTP status 404. """ def __init__(self, msg=None): - ClientErrorException.__init__(self, msg=msg, status=404, body=None) + HTTPClientError.__init__(self, msg=msg, status=404, body=None) class MismatchingEntitiesError(CaosDBException): @@ -347,7 +347,7 @@ class ConsistencyError(EntityError): """The transaction violates database consistecy.""" -class AuthorizationException(EntityError): +class AuthorizationError(EntityError): """You are not allowed to do what ever you tried to do. Maybe you need more privileges or a user account at all. diff --git a/src/caosdb/utils/caosdb_admin.py b/src/caosdb/utils/caosdb_admin.py index 250c2878..4f329822 100755 --- a/src/caosdb/utils/caosdb_admin.py +++ b/src/caosdb/utils/caosdb_admin.py @@ -33,7 +33,7 @@ from argparse import ArgumentParser, RawDescriptionHelpFormatter import caosdb as db from caosdb import administration as admin -from caosdb.exceptions import ClientErrorException +from caosdb.exceptions import HTTPClientError __all__ = [] __version__ = 0.3 @@ -123,7 +123,7 @@ def do_create_user(args): try: admin._insert_user(name=args.user_name, email=args.user_email, password=password) - except ClientErrorException as e: + except HTTPClientError as e: print(e.msg) diff --git a/unittests/test_authentication_auth_token.py b/unittests/test_authentication_auth_token.py index 1eaf0918..15e54121 100644 --- a/unittests/test_authentication_auth_token.py +++ b/unittests/test_authentication_auth_token.py @@ -32,7 +32,7 @@ from unittest.mock import Mock from caosdb.connection.authentication import auth_token as at from caosdb.connection.mockup import MockUpServerConnection, MockUpResponse from caosdb.connection.utils import parse_auth_token -from caosdb.exceptions import LoginFailedException +from caosdb.exceptions import LoginFailedError from caosdb import configure_connection @@ -73,7 +73,7 @@ def test_login_raises(): c = configure_connection(url="https://example.com", password_method="auth_token", auth_token="[auth_token]") - with raises(LoginFailedException): + with raises(LoginFailedError): c._login() diff --git a/unittests/test_authentication_unauthenticated.py b/unittests/test_authentication_unauthenticated.py index 9ea864a9..52146b08 100644 --- a/unittests/test_authentication_unauthenticated.py +++ b/unittests/test_authentication_unauthenticated.py @@ -32,7 +32,7 @@ from unittest.mock import Mock from caosdb.connection.authentication import unauthenticated from caosdb.connection.mockup import MockUpServerConnection, MockUpResponse from caosdb.connection.utils import parse_auth_token -from caosdb.exceptions import LoginFailedException +from caosdb.exceptions import LoginFailedError from caosdb import configure_connection from .test_authentication_auth_token import response_with_auth_token @@ -67,5 +67,5 @@ def test_configure_connection(): def test_login_raises(): c = configure_connection(url="https://example.com", password_method="unauthenticated") - with raises(LoginFailedException): + with raises(LoginFailedError): c._login() diff --git a/unittests/test_connection.py b/unittests/test_connection.py index 657fd5aa..16370f00 100644 --- a/unittests/test_connection.py +++ b/unittests/test_connection.py @@ -37,7 +37,7 @@ from caosdb.connection.connection import (CaosDBServerConnection, from caosdb.connection.mockup import (MockUpResponse, MockUpServerConnection, _request_log_message) from caosdb.connection.utils import make_uri_path, quote, urlencode -from caosdb.exceptions import ConfigurationException, LoginFailedException +from caosdb.exceptions import ConfigurationError, LoginFailedError from nose.tools import assert_equal as eq from nose.tools import assert_false as falz from nose.tools import assert_is_not_none as there @@ -234,7 +234,7 @@ def test_test_request_with_two_responses(): def test_missing_implementation(): connection = configure_connection() - with raises(ConfigurationException) as exc_info: + with raises(ConfigurationError) as exc_info: connection.configure() assert exc_info.value.args[0].startswith( "Missing CaosDBServerConnection implementation.") @@ -242,7 +242,7 @@ def test_missing_implementation(): def test_bad_implementation_not_callable(): connection = configure_connection() - with raises(ConfigurationException) as exc_info: + with raises(ConfigurationError) as exc_info: connection.configure(implementation=None) assert exc_info.value.args[0].startswith( "Bad CaosDBServerConnection implementation.") @@ -251,7 +251,7 @@ def test_bad_implementation_not_callable(): def test_bad_implementation_wrong_class(): connection = configure_connection() - with raises(ConfigurationException) as exc_info: + with raises(ConfigurationError) as exc_info: connection.configure(implementation=dict) assert exc_info.value.args[0].startswith( "Bad CaosDBServerConnection implementation.") @@ -261,7 +261,7 @@ def test_bad_implementation_wrong_class(): def test_missing_auth_method(): connection = configure_connection() - with raises(ConfigurationException) as exc_info: + with raises(ConfigurationError) as exc_info: connection.configure(implementation=MockUpServerConnection) assert exc_info.value.args[0].startswith("Missing password_method.") @@ -276,7 +276,7 @@ def test_missing_password(): connection.configure(implementation=setup_two_resources, password_method="plain") - with raises(LoginFailedException): + with raises(LoginFailedError): connection.delete(["401"]) @@ -288,7 +288,7 @@ def test_auth_token_connection(): ["some"]).headers["Cookie"] == "SessionToken=blablabla;" connection._logout() - with raises(LoginFailedException) as cm: + with raises(LoginFailedError) as cm: connection.retrieve( ["some"]).headers["Cookie"] == "SessionToken=blablabla;" assert cm.value.args[0] == ("The authentication token is expired or you " diff --git a/unittests/test_connection_utils.py b/unittests/test_connection_utils.py index c21b453e..3890ae05 100644 --- a/unittests/test_connection_utils.py +++ b/unittests/test_connection_utils.py @@ -28,7 +28,7 @@ from pytest import raises from nose.tools import (assert_equal as eq, assert_raises as raiz, assert_true as tru, assert_is_not_none as there, assert_false as falz) -from caosdb.exceptions import ConfigurationException, LoginFailedException +from caosdb.exceptions import ConfigurationError, LoginFailedError from caosdb.connection.utils import parse_auth_token, auth_token_to_cookie from caosdb.connection.connection import ( configure_connection, CaosDBServerConnection, @@ -45,8 +45,10 @@ def setup_module(): def test_parse_auth_token(): - assert parse_auth_token("SessionToken=%5Bblablabla%5D; expires=bla; ...") == "[blablabla]" + assert parse_auth_token( + "SessionToken=%5Bblablabla%5D; expires=bla; ...") == "[blablabla]" def test_auth_token_to_cookie(): - assert auth_token_to_cookie("[blablabla]") == "SessionToken=%5Bblablabla%5D;" + assert auth_token_to_cookie( + "[blablabla]") == "SessionToken=%5Bblablabla%5D;" diff --git a/unittests/test_error_handling.py b/unittests/test_error_handling.py index 998766c7..a65430d9 100644 --- a/unittests/test_error_handling.py +++ b/unittests/test_error_handling.py @@ -28,8 +28,7 @@ children. """ import caosdb as db from caosdb.common.models import raise_errors -from caosdb.exceptions import (AmbiguityException, - AuthorizationException, +from caosdb.exceptions import (AuthorizationError, EntityDoesNotExistError, EntityError, EntityHasNoDatatypeError, TransactionError, UniqueNamesError, @@ -116,7 +115,7 @@ def test_authorization_exception(): raise_errors(ent) assert len(e.value.errors) == 1 err = e.value.errors[0] - assert isinstance(err, AuthorizationException) + assert isinstance(err, AuthorizationError) assert err.entity.name == ent.name @@ -311,7 +310,7 @@ def test_container_with_faulty_elements(): if err.entity.name == rec_name.name: assert isinstance(err, UniqueNamesError) elif err.entity.name == rec_auth.name: - assert isinstance(err, AuthorizationException) + assert isinstance(err, AuthorizationError) elif err.entity.name == rec_par_prop.name: # record raises both of them assert (isinstance(err, UnqualifiedParentsError) or -- GitLab