Move all exception objects in the same place

- Follow what other OpenStack projects are doing
- Respect the OpenStack guidelines about import
- Remove common packages

Change-Id: I4a3f598537ed5f54edab79471d074a46fa99ab52
This commit is contained in:
Frédéric Guillot 2016-10-07 14:40:35 -04:00
parent 22c6251c2a
commit a180ee30f8
31 changed files with 170 additions and 254 deletions

View File

@ -21,12 +21,7 @@ import jsonpickle
from oslo_serialization import jsonutils
from werkzeug import wrappers
from almanach.common.exceptions import almanach_entity_not_found_exception
from almanach.common.exceptions import almanach_exception
from almanach.common.exceptions import authentication_failure_exception
from almanach.common.exceptions import date_format_exception
from almanach.common.exceptions import multiple_entities_matching_query
from almanach.common.exceptions import validation_exception
from almanach.core import exception
api = flask.Blueprint("api", __name__)
controller = None
@ -43,7 +38,7 @@ def to_json(api_call):
result = api_call(*args, **kwargs)
return result if isinstance(result, wrappers.BaseResponse) \
else flask.Response(encode(result), 200, {"Content-Type": "application/json"})
except date_format_exception.DateFormatException as e:
except exception.DateFormatException as e:
logging.warning(e.message)
return flask.Response(encode({"error": e.message}), 400, {"Content-Type": "application/json"})
except KeyError as e:
@ -54,17 +49,17 @@ def to_json(api_call):
message = "The request you have made must have data. None was given."
logging.warning(message)
return encode({"error": message}), 400, {"Content-Type": "application/json"}
except validation_exception.InvalidAttributeException as e:
except exception.InvalidAttributeException as e:
logging.warning(e.get_error_message())
return encode({"error": e.get_error_message()}), 400, {"Content-Type": "application/json"}
except multiple_entities_matching_query.MultipleEntitiesMatchingQuery as e:
except exception.MultipleEntitiesMatchingQuery as e:
logging.warning(e.message)
return encode({"error": "Multiple entities found while updating closed"}), 400, {
"Content-Type": "application/json"}
except almanach_entity_not_found_exception.AlmanachEntityNotFoundException as e:
except exception.AlmanachEntityNotFoundException as e:
logging.warning(e.message)
return encode({"error": "Entity not found"}), 404, {"Content-Type": "application/json"}
except almanach_exception.AlmanachException as e:
except exception.AlmanachException as e:
logging.exception(e)
return flask.Response(encode({"error": e.message}), 500, {"Content-Type": "application/json"})
except Exception as e:
@ -80,7 +75,7 @@ def authenticated(api_call):
try:
auth_adapter.validate(flask.request.headers.get('X-Auth-Token'))
return api_call(*args, **kwargs)
except authentication_failure_exception.AuthenticationFailureException as e:
except exception.AuthenticationFailureException as e:
logging.error("Authentication failure: {0}".format(e))
return flask.Response('Unauthorized', 401)

View File

@ -17,9 +17,8 @@ import logging
import pymongo
from pymongo import errors
from almanach.common.exceptions import almanach_exception
from almanach.common.exceptions import volume_type_not_found_exception
from almanach import config
from almanach.core import exception
from almanach.core import model
from almanach.core.model import build_entity_from_dict
@ -34,7 +33,7 @@ def database(function):
return function(self, *args, **kwargs)
except KeyError as e:
raise e
except volume_type_not_found_exception.VolumeTypeNotFoundException as e:
except exception.VolumeTypeNotFoundException as e:
raise e
except NotImplementedError as e:
raise e
@ -124,7 +123,7 @@ class DatabaseAdapter(object):
volume_type = self.db.volume_type.find_one({"volume_type_id": volume_type_id})
if not volume_type:
logging.error("Trying to get a volume type not in the database.")
raise volume_type_not_found_exception.VolumeTypeNotFoundException(volume_type_id=volume_type_id)
raise exception.VolumeTypeNotFoundException(volume_type_id=volume_type_id)
return model.VolumeType(volume_type_id=volume_type["volume_type_id"],
volume_type_name=volume_type["volume_type_name"])
@ -134,14 +133,14 @@ class DatabaseAdapter(object):
if volume_type_id is None:
error = "Trying to delete all volume types which is not permitted."
logging.error(error)
raise almanach_exception.AlmanachException(error)
raise exception.AlmanachException(error)
returned_value = self.db.volume_type.remove({"volume_type_id": volume_type_id})
if returned_value['n'] == 1:
logging.info("Deleted volume type with id '%s' successfully." % volume_type_id)
else:
error = "Volume type with id '%s' doesn't exist in the database." % volume_type_id
logging.error(error)
raise almanach_exception.AlmanachException(error)
raise exception.AlmanachException(error)
@database
def list_volume_types(self):

View File

@ -16,7 +16,7 @@ from keystoneclient.v2_0 import client as keystone_client
from keystoneclient.v2_0 import tokens
from almanach.auth import base_auth
from almanach.common.exceptions import authentication_failure_exception
from almanach.core import exception
class KeystoneTokenManagerFactory(object):
@ -41,11 +41,11 @@ class KeystoneAuthentication(base_auth.BaseAuth):
def validate(self, token):
if token is None:
raise authentication_failure_exception.AuthenticationFailureException("No token provided")
raise exception.AuthenticationFailureException("No token provided")
try:
self.token_manager_factory.get_manager().validate(token)
except Exception as e:
raise authentication_failure_exception.AuthenticationFailureException(e)
raise exception.AuthenticationFailureException(e)
return True

View File

@ -11,10 +11,11 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from almanach.auth import base_auth
from almanach.common.exceptions import authentication_failure_exception
from almanach.core import exception
class MixedAuthentication(base_auth.BaseAuth):
@ -28,6 +29,6 @@ class MixedAuthentication(base_auth.BaseAuth):
if valid:
logging.debug('Validated token with auth {0}'.format(method.__class__))
return True
except authentication_failure_exception.AuthenticationFailureException:
except exception.AuthenticationFailureException:
logging.debug('Failed to validate with auth {0}'.format(method.__class__))
raise authentication_failure_exception.AuthenticationFailureException('No valid auth method matching token')
raise exception.AuthenticationFailureException('No valid auth method matching token')

View File

@ -13,7 +13,7 @@
# limitations under the License.
from almanach.auth import base_auth
from almanach.common.exceptions import authentication_failure_exception
from almanach.core import exception
class PrivateKeyAuthentication(base_auth.BaseAuth):
@ -22,5 +22,5 @@ class PrivateKeyAuthentication(base_auth.BaseAuth):
def validate(self, token):
if token is None or self.private_key != token:
raise authentication_failure_exception.AuthenticationFailureException("Invalid Token")
raise exception.AuthenticationFailureException("Invalid Token")
return True

View File

@ -1,18 +0,0 @@
# Copyright 2016 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from almanach.common.exceptions import almanach_exception
class AlmanachEntityNotFoundException(almanach_exception.AlmanachException):
pass

View File

@ -1,18 +0,0 @@
# Copyright 2016 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class AlmanachException(Exception):
def __init__(self, message=None):
self.message = message

View File

@ -1,17 +0,0 @@
# Copyright 2016 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class AuthenticationFailureException(Exception):
pass

View File

@ -1,23 +0,0 @@
# Copyright 2016 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from almanach.common.exceptions import almanach_exception
class DateFormatException(almanach_exception.AlmanachException):
def __init__(self, message=None):
if not message:
message = "The provided date has an invalid format. Format should be of yyyy-mm-ddThh:mm:ss.msZ, " \
"ex: 2015-01-31T18:24:34.1523Z"
super(DateFormatException, self).__init__(message)

View File

@ -1,18 +0,0 @@
# Copyright 2016 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from almanach.common.exceptions import almanach_exception
class MultipleEntitiesMatchingQuery(almanach_exception.AlmanachException):
pass

View File

@ -1,26 +0,0 @@
# Copyright 2016 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from almanach.common.exceptions import almanach_exception
class InvalidAttributeException(almanach_exception.AlmanachException):
def __init__(self, errors):
self.errors = errors
def get_error_message(self):
messages = {}
for error in self.errors:
messages[error.path[0]] = error.msg
return messages

View File

@ -1,22 +0,0 @@
# Copyright 2016 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from almanach.common.exceptions import almanach_exception
class VolumeTypeNotFoundException(almanach_exception.AlmanachException):
def __init__(self, volume_type_id, message=None):
if not message:
message = "Unable to find volume_type id '{volume_type_id}'".format(volume_type_id=volume_type_id)
super(VolumeTypeNotFoundException, self).__init__(message)

View File

@ -16,7 +16,7 @@ import os
import os.path as os_path
import six
from almanach.common.exceptions import almanach_exception
from almanach.core import exception
if six.PY2:
from ConfigParser import RawConfigParser
@ -28,7 +28,7 @@ configuration = RawConfigParser()
def read(filename):
if not os_path.isfile(filename):
raise almanach_exception.AlmanachException("Config file '{0}' not found".format(filename))
raise exception.AlmanachException("Config file '{0}' not found".format(filename))
print("Loading configuration file {0}".format(filename))
configuration.read(filename)

View File

@ -19,10 +19,8 @@ from pkg_resources import get_distribution
import pytz
from almanach.common.exceptions import almanach_entity_not_found_exception
from almanach.common.exceptions import date_format_exception
from almanach.common.exceptions import multiple_entities_matching_query
from almanach import config
from almanach.core import exception
from almanach.core import model
from almanach.validators import instance_validator
@ -59,7 +57,7 @@ class Controller(object):
def delete_instance(self, instance_id, delete_date):
if not self.database_adapter.has_active_entity(instance_id):
raise almanach_entity_not_found_exception.AlmanachEntityNotFoundException(
raise exception.AlmanachEntityNotFoundException(
"InstanceId: {0} Not Found".format(instance_id))
delete_date = self._validate_and_parse_date(delete_date)
@ -102,9 +100,9 @@ class Controller(object):
def update_inactive_entity(self, instance_id, start, end, **kwargs):
inactive_entities = self.database_adapter.list_entities_by_id(instance_id, start, end)
if len(inactive_entities) > 1:
raise multiple_entities_matching_query.MultipleEntitiesMatchingQuery()
raise exception.MultipleEntitiesMatchingQuery()
if len(inactive_entities) < 1:
raise almanach_entity_not_found_exception.AlmanachEntityNotFoundException(
raise exception.AlmanachEntityNotFoundException(
"InstanceId: {0} Not Found with start".format(instance_id))
entity = inactive_entities[0]
entity_update = self._transform_attribute_to_match_entity_attribute(**kwargs)
@ -129,7 +127,7 @@ class Controller(object):
def get_all_entities_by_id(self, entity_id):
if not self.entity_exists(entity_id=entity_id):
raise almanach_entity_not_found_exception.AlmanachEntityNotFoundException("Entity not found")
raise exception.AlmanachEntityNotFoundException("Entity not found")
return self.database_adapter.get_all_entities_by_id(entity_id=entity_id)
def attach_volume(self, volume_id, date, attachments):
@ -300,7 +298,7 @@ class Controller(object):
date = date_parser.parse(date)
return self._localize_date(date)
except TypeError:
raise date_format_exception.DateFormatException()
raise exception.DateFormatException()
@staticmethod
def _localize_date(date):

View File

@ -0,0 +1,59 @@
# Copyright 2016 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class AlmanachException(Exception):
def __init__(self, message=None):
self.message = message
class AlmanachEntityNotFoundException(AlmanachException):
pass
class AuthenticationFailureException(AlmanachException):
pass
class DateFormatException(AlmanachException):
def __init__(self, message=None):
if not message:
message = "The provided date has an invalid format. Format should be of yyyy-mm-ddThh:mm:ss.msZ, " \
"ex: 2015-01-31T18:24:34.1523Z"
super(DateFormatException, self).__init__(message)
class MultipleEntitiesMatchingQuery(AlmanachException):
pass
class InvalidAttributeException(AlmanachException):
def __init__(self, errors):
self.errors = errors
def get_error_message(self):
messages = {}
for error in self.errors:
messages[error.path[0]] = error.msg
return messages
class VolumeTypeNotFoundException(AlmanachException):
def __init__(self, volume_type_id, message=None):
if not message:
message = "Unable to find volume_type id '{volume_type_id}'".format(volume_type_id=volume_type_id)
super(VolumeTypeNotFoundException, self).__init__(message)

View File

@ -11,6 +11,7 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import six

View File

@ -11,10 +11,11 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import six
import voluptuous
from almanach.common.exceptions import validation_exception
from almanach.core import exception
class InstanceValidator(object):
@ -36,4 +37,4 @@ class InstanceValidator(object):
try:
return self.schema(payload)
except voluptuous.MultipleInvalid as e:
raise validation_exception.InvalidAttributeException(e.errors)
raise exception.InvalidAttributeException(e.errors)

View File

@ -20,7 +20,7 @@ from flexmock import flexmock_teardown
import pytz
from almanach.adapters.bus_adapter import BusAdapter
from almanach.common.exceptions.almanach_entity_not_found_exception import AlmanachEntityNotFoundException
from almanach.core import exception
from integration_tests.builders import messages
@ -247,7 +247,8 @@ class BusAdapterTest(unittest.TestCase):
message = flexmock()
(flexmock(message).should_receive("ack"))
self.controller.should_receive('delete_instance').and_raise(AlmanachEntityNotFoundException("Entity not found"))
self.controller.should_receive('delete_instance')\
.and_raise(exception.AlmanachEntityNotFoundException("Entity not found"))
self.retry.should_receive('publish_to_dead_letter').with_args(message).once()
self.bus_adapter.on_message(notification, message)

View File

@ -25,10 +25,9 @@ from pymongo import MongoClient
import pytz
from almanach.adapters.database_adapter import DatabaseAdapter
from almanach.common.exceptions.almanach_exception import AlmanachException
from almanach.common.exceptions.volume_type_not_found_exception import VolumeTypeNotFoundException
from almanach import config
from almanach.core.model import todict
from almanach.core import exception
from almanach.core import model
from tests.builder import a
from tests.builder import instance
from tests.builder import volume
@ -66,7 +65,7 @@ class DatabaseAdapterTest(unittest.TestCase):
def test_get_instance_entity(self):
fake_entity = a(instance().with_metadata({}))
self.db.entity.insert(todict(fake_entity))
self.db.entity.insert(model.todict(fake_entity))
self.assertEqual(self.adapter.get_active_entity(fake_entity.entity_id), fake_entity)
@ -74,7 +73,7 @@ class DatabaseAdapterTest(unittest.TestCase):
fake_entity = a(instance().with_metadata({"a_metadata_not_sanitize": "not.sanitize",
"a_metadata^to_sanitize": "this.sanitize"}))
self.db.entity.insert(todict(fake_entity))
self.db.entity.insert(model.todict(fake_entity))
entity = self.adapter.get_active_entity(fake_entity.entity_id)
@ -95,7 +94,7 @@ class DatabaseAdapterTest(unittest.TestCase):
fake_entity = a(instance())
fake_entity.entity_type = "will_raise_excepion"
self.db.entity.insert(todict(fake_entity))
self.db.entity.insert(model.todict(fake_entity))
with self.assertRaises(NotImplementedError):
self.adapter.get_active_entity(fake_entity.entity_id)
@ -109,7 +108,9 @@ class DatabaseAdapterTest(unittest.TestCase):
a(instance().with_id("id1").with_start(2014, 1, 1, 7, 0, 0).with_end(2014, 1, 1, 8, 0, 0)),
a(volume().with_id("id2").with_start(2014, 1, 1, 1, 0, 0).with_end(2014, 1, 1, 8, 0, 0)),
]
[self.db.entity.insert(todict(fake_entity)) for fake_entity in fake_active_entities + fake_inactive_entities]
all_entities = fake_active_entities + fake_inactive_entities
[self.db.entity.insert(model.todict(fake_entity)) for fake_entity in all_entities]
self.assertEqual(4, self.adapter.count_entities())
self.assertEqual(2, self.adapter.count_active_entities())
@ -118,7 +119,7 @@ class DatabaseAdapterTest(unittest.TestCase):
def test_get_entity(self):
fake_entity = a(instance().with_id("id1").with_start(2014, 1, 1, 8, 0, 0).with_no_end())
self.db.entity.insert(todict(fake_entity))
self.db.entity.insert(model.todict(fake_entity))
entries = self.adapter.get_all_entities_by_id(entity_id="id1")
self.assertEqual(1, len(entries))
@ -142,7 +143,7 @@ class DatabaseAdapterTest(unittest.TestCase):
a(volume().with_id("id2").with_start(2014, 1, 1, 1, 0, 0).with_no_end().with_project_id("project_id")),
a(volume().with_id("id3").with_start(2014, 1, 1, 8, 0, 0).with_no_end().with_project_id("project_id")),
]
[self.db.entity.insert(todict(fake_entity)) for fake_entity in fake_instances + fake_volumes]
[self.db.entity.insert(model.todict(fake_entity)) for fake_entity in fake_instances + fake_volumes]
entities = self.adapter.list_entities("project_id", datetime(
2014, 1, 1, 0, 0, 0, tzinfo=pytz.utc), datetime(2014, 1, 1, 12, 0, 0, tzinfo=pytz.utc), "instance")
@ -181,7 +182,7 @@ class DatabaseAdapterTest(unittest.TestCase):
.with_metadata({"a_metadata.to_sanitize": "this.sanitize"})),
]
[self.db.entity.insert(todict(fake_entity)) for fake_entity in fake_instances]
[self.db.entity.insert(model.todict(fake_entity)) for fake_entity in fake_instances]
entities = self.adapter.list_entities("project_id", datetime(
2014, 1, 1, 0, 0, 0, tzinfo=pytz.utc), datetime(2014, 1, 1, 12, 0, 0, tzinfo=pytz.utc), "instance")
@ -208,7 +209,7 @@ class DatabaseAdapterTest(unittest.TestCase):
a(instance().with_id("running_has_started_after").with_start(
2014, 1, 1, 10, 0, 0).with_no_end().with_project_id("project_id")),
]
[self.db.entity.insert(todict(fake_entity))
[self.db.entity.insert(model.todict(fake_entity))
for fake_entity in fake_entities_in_period + fake_entities_out_period]
entities = self.adapter.list_entities("project_id", datetime(
@ -226,7 +227,7 @@ class DatabaseAdapterTest(unittest.TestCase):
.with_start(2016, 3, 2, 0, 0, 0)
.with_no_end()),
]
[self.db.entity.insert(todict(fake_instance)) for fake_instance in instances]
[self.db.entity.insert(model.todict(fake_instance)) for fake_instance in instances]
instance_list = self.adapter.list_entities_by_id("id1", start, end)
@ -236,7 +237,7 @@ class DatabaseAdapterTest(unittest.TestCase):
fake_entity = a(instance())
end_date = datetime(2015, 10, 21, 16, 29, 0)
self.db.entity.insert(todict(fake_entity))
self.db.entity.insert(model.todict(fake_entity))
self.adapter.close_active_entity(fake_entity.entity_id, end_date)
self.assertEqual(self.db.entity.find_one({"entity_id": fake_entity.entity_id})["end"], end_date)
@ -244,7 +245,7 @@ class DatabaseAdapterTest(unittest.TestCase):
def test_update_closed_entity(self):
fake_entity = a(instance().with_end(2016, 3, 2, 0, 0, 0))
self.db.entity.insert(todict(fake_entity))
self.db.entity.insert(model.todict(fake_entity))
fake_entity.flavor = "my_new_flavor"
self.adapter.update_closed_entity(fake_entity, data={"flavor": fake_entity.flavor})
@ -256,7 +257,7 @@ class DatabaseAdapterTest(unittest.TestCase):
fake_entity = a(instance())
fake_entity.os.distro = "Centos"
self.db.entity.insert(todict(fake_entity))
self.db.entity.insert(model.todict(fake_entity))
fake_entity.os.distro = "Windows"
self.adapter.update_active_entity(fake_entity)
@ -275,7 +276,7 @@ class DatabaseAdapterTest(unittest.TestCase):
def test_delete_active_entity(self):
fake_entity = a(volume())
self.db.entity.insert(todict(fake_entity))
self.db.entity.insert(model.todict(fake_entity))
self.assertEqual(1, self.db.entity.count())
self.adapter.delete_active_entity(fake_entity.entity_id)
@ -290,35 +291,35 @@ class DatabaseAdapterTest(unittest.TestCase):
def test_get_volume_type(self):
fake_volume_type = a(volume_type())
self.db.volume_type.insert(todict(fake_volume_type))
self.db.volume_type.insert(model.todict(fake_volume_type))
self.assertEqual(self.adapter.get_volume_type(fake_volume_type.volume_type_id), fake_volume_type)
def test_get_volume_type_not_exist(self):
fake_volume_type = a(volume_type())
with self.assertRaises(VolumeTypeNotFoundException):
with self.assertRaises(exception.VolumeTypeNotFoundException):
self.adapter.get_volume_type(fake_volume_type.volume_type_id)
def test_delete_volume_type(self):
fake_volume_type = a(volume_type())
self.db.volume_type.insert(todict(fake_volume_type))
self.db.volume_type.insert(model.todict(fake_volume_type))
self.assertEqual(1, self.db.volume_type.count())
self.adapter.delete_volume_type(fake_volume_type.volume_type_id)
self.assertEqual(0, self.db.volume_type.count())
def test_delete_volume_type_not_in_database(self):
with self.assertRaises(AlmanachException):
with self.assertRaises(exception.AlmanachException):
self.adapter.delete_volume_type("not_in_database_id")
def test_delete_all_volume_types_not_permitted(self):
with self.assertRaises(AlmanachException):
with self.assertRaises(exception.AlmanachException):
self.adapter.delete_volume_type(None)
def test_list_volume_types(self):
fake_volume_types = [a(volume_type()), a(volume_type())]
for fake_volume_type in fake_volume_types:
self.db.volume_type.insert(todict(fake_volume_type))
self.db.volume_type.insert(model.todict(fake_volume_type))
self.assertEqual(len(self.adapter.list_volume_types()), 2)

View File

@ -22,8 +22,8 @@ from flexmock import flexmock_teardown
import oslo_serialization
from almanach.adapters import api_route_v1 as api_route
from almanach.common.exceptions.authentication_failure_exception import AuthenticationFailureException
from almanach import config
from almanach.core import exception
class BaseApi(TestCase):
@ -55,7 +55,8 @@ class BaseApi(TestCase):
def prepare_with_failed_authentication(self):
self.having_config('auth_private_key', 'some token value')
self.auth_adapter.should_receive("validate").and_raise(AuthenticationFailureException("Wrong credentials"))
self.auth_adapter.should_receive("validate")\
.and_raise(exception.AuthenticationFailureException("Wrong credentials"))
def api_get(self, url, query_string=None, headers=None, accept='application/json'):
return self._api_call(url, "get", None, query_string, headers, accept)

View File

@ -19,7 +19,7 @@ from hamcrest import has_key
from hamcrest import is_
from voluptuous import Invalid
from almanach.common.exceptions.validation_exception import InvalidAttributeException
from almanach.core import exception
from tests.api.base_api import BaseApi
from tests.builder import a
from tests.builder import instance
@ -68,7 +68,7 @@ class ApiEntityTest(BaseApi):
self.controller.should_receive('update_active_instance_entity') \
.with_args(instance_id=instance_id, **data) \
.once() \
.and_raise(InvalidAttributeException(errors))
.and_raise(exception.InvalidAttributeException(errors))
code, result = self.api_put(
'/entity/instance/INSTANCE_ID',

View File

@ -19,7 +19,7 @@ from hamcrest import has_key
from hamcrest import has_length
from hamcrest import is_
from almanach.common.exceptions.date_format_exception import DateFormatException
from almanach.core import exception
from tests.api.base_api import a_date_matching
from tests.api.base_api import BaseApi
from tests.builder import a
@ -149,7 +149,7 @@ class ApiInstanceTest(BaseApi):
name=data['name'],
metadata={}) \
.once() \
.and_raise(DateFormatException)
.and_raise(exception.DateFormatException)
code, result = self.api_post(
'/project/PROJECT_ID/instance',
@ -219,7 +219,7 @@ class ApiInstanceTest(BaseApi):
.with_args(instance_id="INSTANCE_ID",
delete_date=data['date']) \
.once() \
.and_raise(DateFormatException)
.and_raise(exception.DateFormatException)
code, result = self.api_delete('/instance/INSTANCE_ID', data=data, headers={'X-Auth-Token': 'some token value'})
assert_that(result, has_entries(
@ -253,7 +253,7 @@ class ApiInstanceTest(BaseApi):
flavor=data['flavor'],
resize_date=data['date']) \
.once() \
.and_raise(DateFormatException)
.and_raise(exception.DateFormatException)
code, result = self.api_put(
'/instance/INSTANCE_ID/resize',
@ -322,7 +322,7 @@ class ApiInstanceTest(BaseApi):
self.controller.should_receive('rebuild_instance') \
.with_args(instance_id=instance_id, **data) \
.once() \
.and_raise(DateFormatException)
.and_raise(exception.DateFormatException)
code, result = self.api_put(
'/instance/INSTANCE_ID/rebuild',

View File

@ -18,7 +18,7 @@ from hamcrest import assert_that
from hamcrest import equal_to
from hamcrest import has_entries
from almanach.common.exceptions.date_format_exception import DateFormatException
from almanach.core import exception
from tests.api.base_api import BaseApi
@ -76,7 +76,7 @@ class ApiVolumeTest(BaseApi):
.with_args(project_id="PROJECT_ID",
**data) \
.once() \
.and_raise(DateFormatException)
.and_raise(exception.DateFormatException)
code, result = self.api_post(
'/project/PROJECT_ID/volume',
@ -125,7 +125,7 @@ class ApiVolumeTest(BaseApi):
.with_args(volume_id="VOLUME_ID",
delete_date=data['date']) \
.once() \
.and_raise(DateFormatException)
.and_raise(exception.DateFormatException)
code, result = self.api_delete('/volume/VOLUME_ID', data=data, headers={'X-Auth-Token': 'some token value'})
assert_that(result, has_entries(
@ -168,7 +168,7 @@ class ApiVolumeTest(BaseApi):
size=data['size'],
update_date=data['date']) \
.once() \
.and_raise(DateFormatException)
.and_raise(exception.DateFormatException)
code, result = self.api_put('/volume/VOLUME_ID/resize', data=data, headers={'X-Auth-Token': 'some token value'})
assert_that(result, has_entries(
@ -218,7 +218,7 @@ class ApiVolumeTest(BaseApi):
attachments=data['attachments'],
date=data['date']) \
.once() \
.and_raise(DateFormatException)
.and_raise(exception.DateFormatException)
code, result = self.api_put('/volume/VOLUME_ID/attach', data=data, headers={'X-Auth-Token': 'some token value'})
assert_that(result, has_entries(
@ -264,7 +264,7 @@ class ApiVolumeTest(BaseApi):
attachments=data['attachments'],
date=data['date']) \
.once() \
.and_raise(DateFormatException)
.and_raise(exception.DateFormatException)
code, result = self.api_put('/volume/VOLUME_ID/detach', data=data, headers={'X-Auth-Token': 'some token value'})
assert_that(result, has_entries(

View File

@ -19,7 +19,7 @@ from hamcrest import has_entry
from hamcrest import has_key
from hamcrest import has_length
from almanach.common.exceptions.almanach_exception import AlmanachException
from almanach.core import exception
from tests.api.base_api import BaseApi
from tests.builder import a
from tests.builder import volume_type
@ -74,7 +74,7 @@ class ApiVolumeTypeTest(BaseApi):
def test_volume_type_delete_not_in_database(self):
self.controller.should_receive('delete_volume_type') \
.with_args('A_VOLUME_TYPE_ID') \
.and_raise(AlmanachException("An exception occurred")) \
.and_raise(exception.AlmanachException("An exception occurred")) \
.once()
code, result = self.api_delete('/volume_type/A_VOLUME_TYPE_ID', headers={'X-Auth-Token': 'some token value'})

View File

@ -22,7 +22,7 @@ from hamcrest import equal_to
from hamcrest import raises
from almanach.auth.keystone_auth import KeystoneAuthentication
from almanach.common.exceptions.authentication_failure_exception import AuthenticationFailureException
from almanach.core import exception
class KeystoneAuthenticationTest(unittest.TestCase):
@ -44,7 +44,9 @@ class KeystoneAuthenticationTest(unittest.TestCase):
token = "bad token"
self.token_manager_factory.should_receive("get_manager").and_return(self.keystone_token_manager)
self.keystone_token_manager.should_receive("validate").with_args(token).and_raise(Exception)
assert_that(calling(self.auth_backend.validate).with_args(token), raises(AuthenticationFailureException))
assert_that(calling(self.auth_backend.validate)
.with_args(token), raises(exception.AuthenticationFailureException))
def test_with_empty_token(self):
assert_that(calling(self.auth_backend.validate).with_args(None), raises(AuthenticationFailureException))
assert_that(calling(self.auth_backend.validate)
.with_args(None), raises(exception.AuthenticationFailureException))

View File

@ -22,7 +22,7 @@ from hamcrest import equal_to
from hamcrest import raises
from almanach.auth.mixed_auth import MixedAuthentication
from almanach.common.exceptions.authentication_failure_exception import AuthenticationFailureException
from almanach.core import exception
class MixedAuthenticationTest(unittest.TestCase):
@ -41,12 +41,13 @@ class MixedAuthenticationTest(unittest.TestCase):
def test_with_token_valid_with_auth_two(self):
token = "my token"
self.auth_one.should_receive("validate").and_raise(AuthenticationFailureException)
self.auth_one.should_receive("validate").and_raise(exception.AuthenticationFailureException)
self.auth_two.should_receive("validate").and_return(True)
assert_that(self.auth_backend.validate(token), equal_to(True))
def test_with_token_valid_with_auth_twos(self):
token = "bad token"
self.auth_one.should_receive("validate").and_raise(AuthenticationFailureException)
self.auth_two.should_receive("validate").and_raise(AuthenticationFailureException)
assert_that(calling(self.auth_backend.validate).with_args(token), raises(AuthenticationFailureException))
self.auth_one.should_receive("validate").and_raise(exception.AuthenticationFailureException)
self.auth_two.should_receive("validate").and_raise(exception.AuthenticationFailureException)
assert_that(calling(self.auth_backend.validate)
.with_args(token), raises(exception.AuthenticationFailureException))

View File

@ -20,7 +20,7 @@ from hamcrest import equal_to
from hamcrest import raises
from almanach.auth.private_key_auth import PrivateKeyAuthentication
from almanach.common.exceptions.authentication_failure_exception import AuthenticationFailureException
from almanach.core import exception
class PrivateKeyAuthenticationTest(unittest.TestCase):
@ -31,7 +31,9 @@ class PrivateKeyAuthenticationTest(unittest.TestCase):
assert_that(self.auth_backend.validate("my token"), equal_to(True))
def test_with_invalid_token(self):
assert_that(calling(self.auth_backend.validate).with_args("bad token"), raises(AuthenticationFailureException))
assert_that(calling(self.auth_backend.validate)
.with_args("bad token"), raises(exception.AuthenticationFailureException))
def test_with_empty_token(self):
assert_that(calling(self.auth_backend.validate).with_args(None), raises(AuthenticationFailureException))
assert_that(calling(self.auth_backend.validate)
.with_args(None), raises(exception.AuthenticationFailureException))

View File

@ -29,14 +29,10 @@ from hamcrest import raises
from nose.tools import assert_raises
import pytz
from almanach.common.exceptions.almanach_entity_not_found_exception import AlmanachEntityNotFoundException
from almanach.common.exceptions.date_format_exception import DateFormatException
from almanach.common.exceptions.multiple_entities_matching_query import MultipleEntitiesMatchingQuery
from almanach.common.exceptions.validation_exception import InvalidAttributeException
from almanach import config
from almanach.core.controller import Controller
from almanach.core.model import Instance
from almanach.core.model import Volume
from almanach.core import exception
from almanach.core import model
from tests.builder import a
from tests.builder import instance
from tests.builder import volume
@ -147,7 +143,7 @@ class ControllerTest(unittest.TestCase):
start=fake_instances[0].start,
end=fake_instances[0].end,
flavor=fake_instances[0].flavor),
raises(MultipleEntitiesMatchingQuery)
raises(exception.MultipleEntitiesMatchingQuery)
)
def test_update_one_close_entity_return_no_entity(self):
@ -164,7 +160,7 @@ class ControllerTest(unittest.TestCase):
start=fake_instances.start,
end=fake_instances.end,
flavor=fake_instances.flavor),
raises(AlmanachEntityNotFoundException)
raises(exception.AlmanachEntityNotFoundException)
)
def test_update_active_instance_entity_with_a_new_flavor(self):
@ -249,7 +245,7 @@ class ControllerTest(unittest.TestCase):
assert_that(
calling(self.controller.update_active_instance_entity).with_args(instance_id=fake_instance1.entity_id,
wrong_attribute="this is wrong"),
raises(InvalidAttributeException))
raises(exception.InvalidAttributeException))
def test_instance_created_but_its_an_old_event(self):
fake_instance = a(instance()
@ -310,7 +306,7 @@ class ControllerTest(unittest.TestCase):
.and_return(False)
.once())
with self.assertRaises(AlmanachEntityNotFoundException):
with self.assertRaises(exception.AlmanachEntityNotFoundException):
self.controller.delete_instance("id1", "2015-10-21T16:25:00.000000Z")
def test_volume_deleted(self):
@ -385,7 +381,7 @@ class ControllerTest(unittest.TestCase):
def test_list_instances(self):
(flexmock(self.database_adapter)
.should_receive("list_entities")
.with_args("project_id", "start", "end", Instance.TYPE)
.with_args("project_id", "start", "end", model.Instance.TYPE)
.and_return(["instance1", "instance2"])
.once())
@ -394,7 +390,7 @@ class ControllerTest(unittest.TestCase):
def test_list_volumes(self):
(flexmock(self.database_adapter)
.should_receive("list_entities")
.with_args("project_id", "start", "end", Volume.TYPE)
.with_args("project_id", "start", "end", model.Volume.TYPE)
.and_return(["volume2", "volume3"]))
self.assertEqual(self.controller.list_volumes("project_id", "start", "end"), ["volume2", "volume3"])
@ -443,7 +439,7 @@ class ControllerTest(unittest.TestCase):
some_volume = a(volume())
assert_raises(
DateFormatException,
exception.DateFormatException,
self.controller.create_volume,
some_volume.entity_id,
some_volume.project_id,
@ -777,7 +773,7 @@ class ControllerTest(unittest.TestCase):
assert_that(
calling(self.controller.get_all_entities_by_id).with_args(entity_id),
raises(AlmanachEntityNotFoundException)
raises(exception.AlmanachEntityNotFoundException)
)
def test_rename_volume(self):

View File

@ -19,7 +19,7 @@ from hamcrest import calling
from hamcrest import is_
from hamcrest import raises
from almanach.common.exceptions.validation_exception import InvalidAttributeException
from almanach.core import exception
from almanach.validators.instance_validator import InstanceValidator
@ -28,7 +28,7 @@ class InstanceValidatorTests(unittest.TestCase):
instance_validator = InstanceValidator()
payload = {"invalid attribute": ".."}
assert_that(calling(instance_validator.validate_update).with_args(payload),
raises(InvalidAttributeException))
raises(exception.InvalidAttributeException))
def test_validate_update_with_valid_name_attribute(self):
instance_validator = InstanceValidator()
@ -41,7 +41,7 @@ class InstanceValidatorTests(unittest.TestCase):
payload = {"name": 123}
assert_that(calling(instance_validator.validate_update).with_args(payload),
raises(InvalidAttributeException))
raises(exception.InvalidAttributeException))
def test_validate_update_with_valid_flavor_attribute(self):
instance_validator = InstanceValidator()
@ -54,7 +54,7 @@ class InstanceValidatorTests(unittest.TestCase):
payload = {"flavor": 123}
assert_that(calling(instance_validator.validate_update).with_args(payload),
raises(InvalidAttributeException))
raises(exception.InvalidAttributeException))
def test_validate_update_with_valid_start_date(self):
instance_validator = InstanceValidator()
@ -68,7 +68,7 @@ class InstanceValidatorTests(unittest.TestCase):
payload = {"start_date": "2015-10-21"}
assert_that(calling(instance_validator.validate_update).with_args(payload),
raises(InvalidAttributeException))
raises(exception.InvalidAttributeException))
def test_validate_update_with_valid_end_date(self):
instance_validator = InstanceValidator()
@ -82,7 +82,7 @@ class InstanceValidatorTests(unittest.TestCase):
payload = {"end_date": "2016"}
assert_that(calling(instance_validator.validate_update).with_args(payload),
raises(InvalidAttributeException))
raises(exception.InvalidAttributeException))
def test_validate_update_with_valid_os_attribute(self):
instance_validator = InstanceValidator()
@ -106,7 +106,7 @@ class InstanceValidatorTests(unittest.TestCase):
}
assert_that(calling(instance_validator.validate_update).with_args(payload),
raises(InvalidAttributeException))
raises(exception.InvalidAttributeException))
def test_validate_update_with_valid_metadata_attribute(self):
instance_validator = InstanceValidator()
@ -132,4 +132,4 @@ class InstanceValidatorTests(unittest.TestCase):
}
assert_that(calling(instance_validator.validate_update).with_args(payload),
raises(InvalidAttributeException))
raises(exception.InvalidAttributeException))