Rename BayModel DB, Object, and internal usage to ClusterTemplate

This patch is the first of 3 patches to change the internal
usage of the terms Bay and BayModel. This patch updates
BayModel to ClusterTemplate. No functionality should be
changed by this patch, just naming and db updates.

Change-Id: I0803e81be6482962be2878a8ea2c7480f89111ac
Implements: blueprint rename-bay-to-cluster
This commit is contained in:
Jaycen Grant 2016-08-23 15:37:33 -07:00
parent 42abb07835
commit 0b7c6401dd
38 changed files with 1065 additions and 932 deletions

View File

@ -62,7 +62,7 @@ class Bay(base.APIBase):
def _set_baymodel_id(self, value): def _set_baymodel_id(self, value):
if value and self._baymodel_id != value: if value and self._baymodel_id != value:
try: try:
baymodel = api_utils.get_resource('BayModel', value) baymodel = api_utils.get_resource('ClusterTemplate', value)
self._baymodel_id = baymodel.uuid self._baymodel_id = baymodel.uuid
except exception.ClusterTemplateNotFound as e: except exception.ClusterTemplateNotFound as e:
# Change error code because 404 (NotFound) is inappropriate # Change error code because 404 (NotFound) is inappropriate
@ -364,7 +364,8 @@ class BaysController(base.Controller):
context = pecan.request.context context = pecan.request.context
policy.enforce(context, 'bay:create', policy.enforce(context, 'bay:create',
action='bay:create') action='bay:create')
baymodel = objects.BayModel.get_by_uuid(context, bay.baymodel_id) baymodel = objects.ClusterTemplate.get_by_uuid(context,
bay.baymodel_id)
attr_validator.validate_os_resources(context, baymodel.as_dict()) attr_validator.validate_os_resources(context, baymodel.as_dict())
attr_validator.validate_master_count(bay.as_dict(), baymodel.as_dict()) attr_validator.validate_master_count(bay.as_dict(), baymodel.as_dict())
bay_dict = bay.as_dict() bay_dict = bay.as_dict()

View File

@ -141,7 +141,7 @@ class BayModel(base.APIBase):
def __init__(self, **kwargs): def __init__(self, **kwargs):
self.fields = [] self.fields = []
for field in objects.BayModel.fields: for field in objects.ClusterTemplate.fields:
# Skip fields we do not expose. # Skip fields we do not expose.
if not hasattr(self, field): if not hasattr(self, field):
continue continue
@ -251,12 +251,12 @@ class BayModelsController(base.Controller):
marker_obj = None marker_obj = None
if marker: if marker:
marker_obj = objects.BayModel.get_by_uuid(pecan.request.context, marker_obj = objects.ClusterTemplate.get_by_uuid(
marker) pecan.request.context, marker)
baymodels = objects.BayModel.list(pecan.request.context, limit, baymodels = objects.ClusterTemplate.list(pecan.request.context, limit,
marker_obj, sort_key=sort_key, marker_obj, sort_key=sort_key,
sort_dir=sort_dir) sort_dir=sort_dir)
return BayModelCollection.convert_with_links(baymodels, limit, return BayModelCollection.convert_with_links(baymodels, limit,
url=resource_url, url=resource_url,
@ -311,7 +311,7 @@ class BayModelsController(base.Controller):
:param baymodel_ident: UUID or logical name of a baymodel. :param baymodel_ident: UUID or logical name of a baymodel.
""" """
context = pecan.request.context context = pecan.request.context
baymodel = api_utils.get_resource('BayModel', baymodel_ident) baymodel = api_utils.get_resource('ClusterTemplate', baymodel_ident)
if not baymodel.public: if not baymodel.public:
policy.enforce(context, 'baymodel:get', baymodel, policy.enforce(context, 'baymodel:get', baymodel,
action='baymodel:get') action='baymodel:get')
@ -350,7 +350,7 @@ class BayModelsController(base.Controller):
name = arg_name or self._generate_name_for_baymodel(context) name = arg_name or self._generate_name_for_baymodel(context)
baymodel_dict['name'] = name baymodel_dict['name'] = name
new_baymodel = objects.BayModel(context, **baymodel_dict) new_baymodel = objects.ClusterTemplate(context, **baymodel_dict)
new_baymodel.create() new_baymodel.create()
# Set the HTTP Location Header # Set the HTTP Location Header
pecan.response.location = link.build_url('baymodels', pecan.response.location = link.build_url('baymodels',
@ -368,7 +368,7 @@ class BayModelsController(base.Controller):
:param patch: a json PATCH document to apply to this baymodel. :param patch: a json PATCH document to apply to this baymodel.
""" """
context = pecan.request.context context = pecan.request.context
baymodel = api_utils.get_resource('BayModel', baymodel_ident) baymodel = api_utils.get_resource('ClusterTemplate', baymodel_ident)
policy.enforce(context, 'baymodel:update', baymodel, policy.enforce(context, 'baymodel:update', baymodel,
action='baymodel:update') action='baymodel:update')
try: try:
@ -388,7 +388,7 @@ class BayModelsController(base.Controller):
raise exception.ClusterTemplatePublishDenied() raise exception.ClusterTemplatePublishDenied()
# Update only the fields that have changed # Update only the fields that have changed
for field in objects.BayModel.fields: for field in objects.ClusterTemplate.fields:
try: try:
patch_val = getattr(new_baymodel, field) patch_val = getattr(new_baymodel, field)
except AttributeError: except AttributeError:
@ -409,7 +409,7 @@ class BayModelsController(base.Controller):
:param baymodel_ident: UUID or logical name of a baymodel. :param baymodel_ident: UUID or logical name of a baymodel.
""" """
context = pecan.request.context context = pecan.request.context
baymodel = api_utils.get_resource('BayModel', baymodel_ident) baymodel = api_utils.get_resource('ClusterTemplate', baymodel_ident)
policy.enforce(context, 'baymodel:delete', baymodel, policy.enforce(context, 'baymodel:delete', baymodel,
action='baymodel:delete') action='baymodel:delete')
baymodel.destroy() baymodel.destroy()

View File

@ -70,7 +70,8 @@ class Cluster(base.APIBase):
def _set_cluster_template_id(self, value): def _set_cluster_template_id(self, value):
if value and self._cluster_template_id != value: if value and self._cluster_template_id != value:
try: try:
cluster_template = api_utils.get_resource('BayModel', value) cluster_template = api_utils.get_resource('ClusterTemplate',
value)
self._cluster_template_id = cluster_template.uuid self._cluster_template_id = cluster_template.uuid
except exception.ClusterTemplateNotFound as e: except exception.ClusterTemplateNotFound as e:
# Change error code because 404 (NotFound) is inappropriate # Change error code because 404 (NotFound) is inappropriate
@ -400,7 +401,8 @@ class ClustersController(base.Controller):
policy.enforce(context, 'cluster:create', policy.enforce(context, 'cluster:create',
action='cluster:create') action='cluster:create')
temp_id = cluster.cluster_template_id temp_id = cluster.cluster_template_id
cluster_template = objects.BayModel.get_by_uuid(context, temp_id) cluster_template = objects.ClusterTemplate.get_by_uuid(context,
temp_id)
cluster_dict = cluster.as_dict() cluster_dict = cluster.as_dict()
attr_validator.validate_os_resources(context, attr_validator.validate_os_resources(context,

View File

@ -142,7 +142,7 @@ class ClusterTemplate(base.APIBase):
def __init__(self, **kwargs): def __init__(self, **kwargs):
self.fields = [] self.fields = []
for field in objects.BayModel.fields: for field in objects.ClusterTemplate.fields:
# Skip fields we do not expose. # Skip fields we do not expose.
if not hasattr(self, field): if not hasattr(self, field):
continue continue
@ -255,13 +255,12 @@ class ClusterTemplatesController(base.Controller):
marker_obj = None marker_obj = None
if marker: if marker:
marker_obj = objects.BayModel.get_by_uuid(pecan.request.context, marker_obj = objects.ClusterTemplate.get_by_uuid(
marker) pecan.request.context, marker)
cluster_templates = objects.BayModel.list(pecan.request.context, limit, cluster_templates = objects.ClusterTemplate.list(
marker_obj, pecan.request.context, limit, marker_obj, sort_key=sort_key,
sort_key=sort_key, sort_dir=sort_dir)
sort_dir=sort_dir)
return ClusterTemplateCollection.convert_with_links(cluster_templates, return ClusterTemplateCollection.convert_with_links(cluster_templates,
limit, limit,
@ -319,7 +318,7 @@ class ClusterTemplatesController(base.Controller):
ClusterTemplate. ClusterTemplate.
""" """
context = pecan.request.context context = pecan.request.context
cluster_template = api_utils.get_resource('BayModel', cluster_template = api_utils.get_resource('ClusterTemplate',
cluster_template_ident) cluster_template_ident)
if not cluster_template.public: if not cluster_template.public:
policy.enforce(context, 'clustertemplate:get', cluster_template, policy.enforce(context, 'clustertemplate:get', cluster_template,
@ -360,8 +359,8 @@ class ClusterTemplatesController(base.Controller):
name = arg_name or self._generate_name_for_cluster_template(context) name = arg_name or self._generate_name_for_cluster_template(context)
cluster_template_dict['name'] = name cluster_template_dict['name'] = name
new_cluster_template = objects.BayModel(context, new_cluster_template = objects.ClusterTemplate(context,
**cluster_template_dict) **cluster_template_dict)
new_cluster_template.create() new_cluster_template.create()
# Set the HTTP Location Header # Set the HTTP Location Header
pecan.response.location = link.build_url('clustertemplates', pecan.response.location = link.build_url('clustertemplates',
@ -382,7 +381,7 @@ class ClusterTemplatesController(base.Controller):
ClusterTemplate. ClusterTemplate.
""" """
context = pecan.request.context context = pecan.request.context
cluster_template = api_utils.get_resource('BayModel', cluster_template = api_utils.get_resource('ClusterTemplate',
cluster_template_ident) cluster_template_ident)
policy.enforce(context, 'clustertemplate:update', cluster_template, policy.enforce(context, 'clustertemplate:update', cluster_template,
action='clustertemplate:update') action='clustertemplate:update')
@ -404,7 +403,7 @@ class ClusterTemplatesController(base.Controller):
raise exception.ClusterTemplatePublishDenied() raise exception.ClusterTemplatePublishDenied()
# Update only the fields that have changed # Update only the fields that have changed
for field in objects.BayModel.fields: for field in objects.ClusterTemplate.fields:
try: try:
patch_val = getattr(new_cluster_template, field) patch_val = getattr(new_cluster_template, field)
except AttributeError: except AttributeError:
@ -426,7 +425,7 @@ class ClusterTemplatesController(base.Controller):
ClusterTemplate. ClusterTemplate.
""" """
context = pecan.request.context context = pecan.request.context
cluster_template = api_utils.get_resource('BayModel', cluster_template = api_utils.get_resource('ClusterTemplate',
cluster_template_ident) cluster_template_ident)
policy.enforce(context, 'clustertemplate:delete', cluster_template, policy.enforce(context, 'clustertemplate:delete', cluster_template,
action='clustertemplate:delete') action='clustertemplate:delete')

View File

@ -85,11 +85,11 @@ def enforce_bay_types(*bay_types):
else: else:
bay = objects.Bay.get_by_name(pecan.request.context, bay_ident) bay = objects.Bay.get_by_name(pecan.request.context, bay_ident)
if bay.baymodel.coe not in bay_types: if bay.cluster_template.coe not in bay_types:
raise exception.InvalidParameterValue(_( raise exception.InvalidParameterValue(_(
'Cannot fulfill request with a %(bay_type)s bay, ' 'Cannot fulfill request with a %(bay_type)s bay, '
'expecting a %(supported_bay_types)s bay.') % 'expecting a %(supported_bay_types)s bay.') %
{'bay_type': bay.baymodel.coe, {'bay_type': bay.cluster_template.coe,
'supported_bay_types': '/'.join(bay_types)}) 'supported_bay_types': '/'.join(bay_types)})
return func(*args, **kwargs) return func(*args, **kwargs)
@ -100,8 +100,8 @@ def enforce_bay_types(*bay_types):
def enforce_network_driver_types_create(): def enforce_network_driver_types_create():
@decorator.decorator @decorator.decorator
def wrapper(func, *args, **kwargs): def wrapper(func, *args, **kwargs):
baymodel = args[1] cluster_template = args[1]
_enforce_network_driver_types(baymodel) _enforce_network_driver_types(cluster_template)
return func(*args, **kwargs) return func(*args, **kwargs)
return wrapper return wrapper
@ -110,33 +110,35 @@ def enforce_network_driver_types_create():
def enforce_network_driver_types_update(): def enforce_network_driver_types_update():
@decorator.decorator @decorator.decorator
def wrapper(func, *args, **kwargs): def wrapper(func, *args, **kwargs):
baymodel_ident = args[1] cluster_template_ident = args[1]
patch = args[2] patch = args[2]
baymodel = api_utils.get_resource('BayModel', baymodel_ident) cluster_template = api_utils.get_resource('ClusterTemplate',
cluster_template_ident)
try: try:
baymodel_dict = api_utils.apply_jsonpatch(baymodel.as_dict(), cluster_template_dict = api_utils.apply_jsonpatch(
patch) cluster_template.as_dict(), patch)
except api_utils.JSONPATCH_EXCEPTIONS as e: except api_utils.JSONPATCH_EXCEPTIONS as e:
raise exception.PatchError(patch=patch, reason=e) raise exception.PatchError(patch=patch, reason=e)
baymodel = objects.BayModel(pecan.request.context, **baymodel_dict) cluster_template = objects.ClusterTemplate(pecan.request.context,
_enforce_network_driver_types(baymodel) **cluster_template_dict)
_enforce_network_driver_types(cluster_template)
return func(*args, **kwargs) return func(*args, **kwargs)
return wrapper return wrapper
def _enforce_network_driver_types(baymodel): def _enforce_network_driver_types(cluster_template):
validator = Validator.get_coe_validator(baymodel.coe) validator = Validator.get_coe_validator(cluster_template.coe)
if not baymodel.network_driver: if not cluster_template.network_driver:
baymodel.network_driver = validator.default_network_driver cluster_template.network_driver = validator.default_network_driver
validator.validate_network_driver(baymodel.network_driver) validator.validate_network_driver(cluster_template.network_driver)
def enforce_volume_driver_types_create(): def enforce_volume_driver_types_create():
@decorator.decorator @decorator.decorator
def wrapper(func, *args, **kwargs): def wrapper(func, *args, **kwargs):
baymodel = args[1] cluster_template = args[1]
_enforce_volume_driver_types(baymodel.as_dict()) _enforce_volume_driver_types(cluster_template.as_dict())
return func(*args, **kwargs) return func(*args, **kwargs)
return wrapper return wrapper
@ -145,8 +147,8 @@ def enforce_volume_driver_types_create():
def enforce_volume_storage_size_create(): def enforce_volume_storage_size_create():
@decorator.decorator @decorator.decorator
def wrapper(func, *args, **kwargs): def wrapper(func, *args, **kwargs):
baymodel = args[1] cluster_template = args[1]
_enforce_volume_storage_size(baymodel.as_dict()) _enforce_volume_storage_size(cluster_template.as_dict())
return func(*args, **kwargs) return func(*args, **kwargs)
return wrapper return wrapper
@ -155,32 +157,33 @@ def enforce_volume_storage_size_create():
def enforce_volume_driver_types_update(): def enforce_volume_driver_types_update():
@decorator.decorator @decorator.decorator
def wrapper(func, *args, **kwargs): def wrapper(func, *args, **kwargs):
baymodel_ident = args[1] cluster_template_ident = args[1]
patch = args[2] patch = args[2]
baymodel = api_utils.get_resource('BayModel', baymodel_ident) cluster_template = api_utils.get_resource('ClusterTemplate',
cluster_template_ident)
try: try:
baymodel_dict = api_utils.apply_jsonpatch(baymodel.as_dict(), cluster_template_dict = api_utils.apply_jsonpatch(
patch) cluster_template.as_dict(), patch)
except api_utils.JSONPATCH_EXCEPTIONS as e: except api_utils.JSONPATCH_EXCEPTIONS as e:
raise exception.PatchError(patch=patch, reason=e) raise exception.PatchError(patch=patch, reason=e)
_enforce_volume_driver_types(baymodel_dict) _enforce_volume_driver_types(cluster_template_dict)
return func(*args, **kwargs) return func(*args, **kwargs)
return wrapper return wrapper
def _enforce_volume_driver_types(baymodel): def _enforce_volume_driver_types(cluster_template):
validator = Validator.get_coe_validator(baymodel['coe']) validator = Validator.get_coe_validator(cluster_template['coe'])
if not baymodel.get('volume_driver'): if not cluster_template.get('volume_driver'):
return return
validator.validate_volume_driver(baymodel['volume_driver']) validator.validate_volume_driver(cluster_template['volume_driver'])
def _enforce_volume_storage_size(baymodel): def _enforce_volume_storage_size(cluster_template):
if not baymodel.get('docker_volume_size'): if not cluster_template.get('docker_volume_size'):
return return
volume_size = baymodel.get('docker_volume_size') volume_size = cluster_template.get('docker_volume_size')
storage_driver = baymodel.get('docker_storage_driver') storage_driver = cluster_template.get('docker_storage_driver')
if storage_driver == 'devicemapper': if storage_driver == 'devicemapper':
if volume_size < 3: if volume_size < 3:
raise exception.InvalidParameterValue( raise exception.InvalidParameterValue(

View File

@ -76,11 +76,11 @@ def is_docker_api_version_atleast(docker, version):
@contextlib.contextmanager @contextlib.contextmanager
def docker_for_bay(context, bay): def docker_for_bay(context, bay):
baymodel = conductor_utils.retrieve_baymodel(context, bay) cluster_template = conductor_utils.retrieve_cluster_template(context, bay)
ca_cert, magnum_key, magnum_cert = None, None, None ca_cert, magnum_key, magnum_cert = None, None, None
client_kwargs = dict() client_kwargs = dict()
if not baymodel.tls_disabled: if not cluster_template.tls_disabled:
(ca_cert, magnum_key, (ca_cert, magnum_key,
magnum_cert) = cert_manager.create_client_files(bay) magnum_cert) = cert_manager.create_client_files(bay)
client_kwargs['ca_cert'] = ca_cert.name client_kwargs['ca_cert'] = ca_cert.name

View File

@ -69,14 +69,14 @@ LOG = logging.getLogger(__name__)
def _extract_template_definition(context, bay, scale_manager=None): def _extract_template_definition(context, bay, scale_manager=None):
baymodel = conductor_utils.retrieve_baymodel(context, bay) cluster_template = conductor_utils.retrieve_cluster_template(context, bay)
cluster_distro = baymodel.cluster_distro cluster_distro = cluster_template.cluster_distro
cluster_coe = baymodel.coe cluster_coe = cluster_template.coe
cluster_server_type = baymodel.server_type cluster_server_type = cluster_template.server_type
definition = TDef.get_template_definition(cluster_server_type, definition = TDef.get_template_definition(cluster_server_type,
cluster_distro, cluster_distro,
cluster_coe) cluster_coe)
return definition.extract_definition(context, baymodel, bay, return definition.extract_definition(context, cluster_template, bay,
scale_manager=scale_manager) scale_manager=scale_manager)
@ -275,10 +275,11 @@ class HeatPoller(object):
self.context = self.openstack_client.context self.context = self.openstack_client.context
self.bay = bay self.bay = bay
self.attempts = 0 self.attempts = 0
self.baymodel = conductor_utils.retrieve_baymodel(self.context, bay) self.cluster_template = conductor_utils.retrieve_cluster_template(
self.context, bay)
self.template_def = TDef.get_template_definition( self.template_def = TDef.get_template_definition(
self.baymodel.server_type, self.cluster_template.server_type,
self.baymodel.cluster_distro, self.baymodel.coe) self.cluster_template.cluster_distro, self.cluster_template.coe)
def poll_and_check(self): def poll_and_check(self):
# TODO(yuanying): temporary implementation to update api_address, # TODO(yuanying): temporary implementation to update api_address,
@ -374,9 +375,9 @@ class HeatPoller(object):
if stack_param: if stack_param:
self.bay.coe_version = stack.parameters[stack_param] self.bay.coe_version = stack.parameters[stack_param]
tdef = TDef.get_template_definition(self.baymodel.server_type, tdef = TDef.get_template_definition(
self.baymodel.cluster_distro, self.cluster_template.server_type,
self.baymodel.coe) self.cluster_template.cluster_distro, self.cluster_template.coe)
version_module_path = tdef.driver_module_path+'.version' version_module_path = tdef.driver_module_path+'.version'
try: try:
@ -387,7 +388,8 @@ class HeatPoller(object):
self.bay.container_version = container_version self.bay.container_version = container_version
def _sync_bay_and_template_status(self, stack): def _sync_bay_and_template_status(self, stack):
self.template_def.update_outputs(stack, self.baymodel, self.bay) self.template_def.update_outputs(stack, self.cluster_template,
self.bay)
self.get_version_info(stack) self.get_version_info(stack)
self._sync_bay_status(stack) self._sync_bay_status(stack)

View File

@ -68,9 +68,11 @@ class MonitorBase(object):
def create_monitor(context, bay): def create_monitor(context, bay):
if bay.baymodel.coe in COE_CLASS_PATH: if bay.cluster_template.coe in COE_CLASS_PATH:
coe_cls = importutils.import_class(COE_CLASS_PATH[bay.baymodel.coe]) coe_cls = importutils.import_class(
COE_CLASS_PATH[bay.cluster_template.coe])
return coe_cls(context, bay) return coe_cls(context, bay)
LOG.debug("Cannot create monitor with bay type '%s'", bay.baymodel.coe) LOG.debug("Cannot create monitor with bay type '%s'",
bay.cluster_template.coe)
return None return None

View File

@ -21,7 +21,7 @@ from pycadf import resource
from magnum.common import clients from magnum.common import clients
from magnum.common import rpc from magnum.common import rpc
from magnum.objects import bay from magnum.objects import bay
from magnum.objects import baymodel from magnum.objects import cluster_template
def retrieve_bay(context, bay_ident): def retrieve_bay(context, bay_ident):
@ -31,8 +31,9 @@ def retrieve_bay(context, bay_ident):
return bay.Bay.get_by_uuid(context, bay_ident) return bay.Bay.get_by_uuid(context, bay_ident)
def retrieve_baymodel(context, bay): def retrieve_cluster_template(context, bay):
return baymodel.BayModel.get_by_uuid(context, bay.baymodel_id) return cluster_template.ClusterTemplate.get_by_uuid(context,
bay.baymodel_id)
def retrieve_bay_uuid(context, bay_ident): def retrieve_bay_uuid(context, bay_ident):

View File

@ -122,18 +122,18 @@ class Connection(object):
""" """
@abc.abstractmethod @abc.abstractmethod
def get_baymodel_list(self, context, filters=None, def get_cluster_template_list(self, context, filters=None,
limit=None, marker=None, sort_key=None, limit=None, marker=None, sort_key=None,
sort_dir=None): sort_dir=None):
"""Get matching baymodels. """Get matching ClusterTemplates.
Return a list of the specified columns for all baymodels that match the Return a list of the specified columns for all ClusterTemplates that
specified filters. match the specified filters.
:param context: The security context :param context: The security context
:param filters: Filters to apply. Defaults to None. :param filters: Filters to apply. Defaults to None.
:param limit: Maximum number of baymodels to return. :param limit: Maximum number of ClusterTemplates to return.
:param marker: the last item of the previous page; we return the next :param marker: the last item of the previous page; we return the next
result set. result set.
:param sort_key: Attribute by which results should be sorted. :param sort_key: Attribute by which results should be sorted.
@ -143,12 +143,13 @@ class Connection(object):
""" """
@abc.abstractmethod @abc.abstractmethod
def create_baymodel(self, values): def create_cluster_template(self, values):
"""Create a new baymodel. """Create a new ClusterTemplate.
:param values: A dict containing several items used to identify :param values: A dict containing several items used to identify
and track the baymodel, and several dicts which are and track the ClusterTemplate, and several dicts which
passed into the Drivers when managing this baymodel. are passed into the Drivers when managing this
ClusterTemplate.
For example: For example:
:: ::
@ -158,49 +159,49 @@ class Connection(object):
'name': 'example', 'name': 'example',
'type': 'virt' 'type': 'virt'
} }
:returns: A baymodel. :returns: A ClusterTemplate.
""" """
@abc.abstractmethod @abc.abstractmethod
def get_baymodel_by_id(self, context, baymodel_id): def get_cluster_template_by_id(self, context, cluster_template_id):
"""Return a baymodel. """Return a ClusterTemplate.
:param context: The security context :param context: The security context
:param baymodel_id: The id of a baymodel. :param cluster_template_id: The id of a ClusterTemplate.
:returns: A baymodel. :returns: A ClusterTemplate.
""" """
@abc.abstractmethod @abc.abstractmethod
def get_baymodel_by_uuid(self, context, baymodel_uuid): def get_cluster_template_by_uuid(self, context, cluster_template_uuid):
"""Return a baymodel. """Return a ClusterTemplate.
:param context: The security context :param context: The security context
:param baymodel_uuid: The uuid of a baymodel. :param cluster_template_uuid: The uuid of a ClusterTemplate.
:returns: A baymodel. :returns: A ClusterTemplate.
""" """
@abc.abstractmethod @abc.abstractmethod
def get_baymodel_by_name(self, context, baymodel_name): def get_cluster_template_by_name(self, context, cluster_template_name):
"""Return a baymodel. """Return a ClusterTemplate.
:param context: The security context :param context: The security context
:param baymodel_name: The name of a baymodel. :param cluster_template_name: The name of a ClusterTemplate.
:returns: A baymodel. :returns: A ClusterTemplate.
""" """
@abc.abstractmethod @abc.abstractmethod
def destroy_baymodel(self, baymodel_id): def destroy_cluster_template(self, cluster_template_id):
"""Destroy a baymodel and all associated interfaces. """Destroy a ClusterTemplate and all associated interfaces.
:param baymodel_id: The id or uuid of a baymodel. :param cluster_template_id: The id or uuid of a ClusterTemplate.
""" """
@abc.abstractmethod @abc.abstractmethod
def update_baymodel(self, baymodel_id, values): def update_cluster_template(self, cluster_template_id, values):
"""Update properties of a baymodel. """Update properties of a ClusterTemplate.
:param baymodel_id: The id or uuid of a baymodel. :param cluster_template_id: The id or uuid of a ClusterTemplate.
:returns: A baymodel. :returns: A ClusterTemplate.
:raises: ClusterTemplateNotFound :raises: ClusterTemplateNotFound
""" """

View File

@ -0,0 +1,28 @@
# 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.
"""rename_baymodel_to_clustertemplate
Revision ID: fb03fdef8919
Revises: fcb4efee8f8b
Create Date: 2016-08-31 12:40:31.165817
"""
# revision identifiers, used by Alembic.
revision = 'fb03fdef8919'
down_revision = 'fcb4efee8f8b'
from alembic import op
def upgrade():
op.rename_table('baymodel', 'cluster_template')

View File

@ -227,7 +227,7 @@ class Connection(api.Connection):
ref.update(values) ref.update(values)
return ref return ref
def _add_baymodels_filters(self, query, filters): def _add_cluster_template_filters(self, query, filters):
if filters is None: if filters is None:
filters = {} filters = {}
@ -242,124 +242,127 @@ class Connection(api.Connection):
return query.filter_by(**filter_dict) return query.filter_by(**filter_dict)
def get_baymodel_list(self, context, filters=None, limit=None, marker=None, def get_cluster_template_list(self, context, filters=None, limit=None,
sort_key=None, sort_dir=None): marker=None, sort_key=None, sort_dir=None):
query = model_query(models.BayModel) query = model_query(models.ClusterTemplate)
query = self._add_tenant_filters(context, query) query = self._add_tenant_filters(context, query)
query = self._add_baymodels_filters(query, filters) query = self._add_cluster_template_filters(query, filters)
# include public baymodels # include public ClusterTemplates
public_q = model_query(models.BayModel).filter_by(public=True) public_q = model_query(models.ClusterTemplate).filter_by(public=True)
query = query.union(public_q) query = query.union(public_q)
return _paginate_query(models.BayModel, limit, marker, return _paginate_query(models.ClusterTemplate, limit, marker,
sort_key, sort_dir, query) sort_key, sort_dir, query)
def create_baymodel(self, values): def create_cluster_template(self, values):
# ensure defaults are present for new baymodels # ensure defaults are present for new ClusterTemplates
if not values.get('uuid'): if not values.get('uuid'):
values['uuid'] = uuidutils.generate_uuid() values['uuid'] = uuidutils.generate_uuid()
baymodel = models.BayModel() cluster_template = models.ClusterTemplate()
baymodel.update(values) cluster_template.update(values)
try: try:
baymodel.save() cluster_template.save()
except db_exc.DBDuplicateEntry: except db_exc.DBDuplicateEntry:
raise exception.ClusterTemplateAlreadyExists(uuid=values['uuid']) raise exception.ClusterTemplateAlreadyExists(uuid=values['uuid'])
return baymodel return cluster_template
def get_baymodel_by_id(self, context, baymodel_id): def get_cluster_template_by_id(self, context, cluster_template_id):
query = model_query(models.BayModel) query = model_query(models.ClusterTemplate)
query = self._add_tenant_filters(context, query) query = self._add_tenant_filters(context, query)
public_q = model_query(models.BayModel).filter_by(public=True) public_q = model_query(models.ClusterTemplate).filter_by(public=True)
query = query.union(public_q) query = query.union(public_q)
query = query.filter_by(id=baymodel_id) query = query.filter_by(id=cluster_template_id)
try: try:
return query.one() return query.one()
except NoResultFound: except NoResultFound:
raise exception.ClusterTemplateNotFound( raise exception.ClusterTemplateNotFound(
clustertemplate=baymodel_id) clustertemplate=cluster_template_id)
def get_baymodel_by_uuid(self, context, baymodel_uuid): def get_cluster_template_by_uuid(self, context, cluster_template_uuid):
query = model_query(models.BayModel) query = model_query(models.ClusterTemplate)
query = self._add_tenant_filters(context, query) query = self._add_tenant_filters(context, query)
public_q = model_query(models.BayModel).filter_by(public=True) public_q = model_query(models.ClusterTemplate).filter_by(public=True)
query = query.union(public_q) query = query.union(public_q)
query = query.filter_by(uuid=baymodel_uuid) query = query.filter_by(uuid=cluster_template_uuid)
try: try:
return query.one() return query.one()
except NoResultFound: except NoResultFound:
raise exception.ClusterTemplateNotFound( raise exception.ClusterTemplateNotFound(
clustertemplate=baymodel_uuid) clustertemplate=cluster_template_uuid)
def get_baymodel_by_name(self, context, baymodel_name): def get_cluster_template_by_name(self, context, cluster_template_name):
query = model_query(models.BayModel) query = model_query(models.ClusterTemplate)
query = self._add_tenant_filters(context, query) query = self._add_tenant_filters(context, query)
public_q = model_query(models.BayModel).filter_by(public=True) public_q = model_query(models.ClusterTemplate).filter_by(public=True)
query = query.union(public_q) query = query.union(public_q)
query = query.filter_by(name=baymodel_name) query = query.filter_by(name=cluster_template_name)
try: try:
return query.one() return query.one()
except MultipleResultsFound: except MultipleResultsFound:
raise exception.Conflict('Multiple baymodels exist with same name.' raise exception.Conflict('Multiple ClusterTemplates exist with'
' Please use the baymodel uuid instead.') ' same name. Please use the '
'ClusterTemplate uuid instead.')
except NoResultFound: except NoResultFound:
raise exception.ClusterTemplateNotFound( raise exception.ClusterTemplateNotFound(
clustertemplate=baymodel_name) clustertemplate=cluster_template_name)
def _is_baymodel_referenced(self, session, baymodel_uuid): def _is_cluster_template_referenced(self, session, cluster_template_uuid):
"""Checks whether the baymodel is referenced by bay(s).""" """Checks whether the ClusterTemplate is referenced by cluster(s)."""
query = model_query(models.Bay, session=session) query = model_query(models.Bay, session=session)
query = self._add_bays_filters(query, {'baymodel_id': baymodel_uuid}) query = self._add_bays_filters(query, {'baymodel_id':
cluster_template_uuid})
return query.count() != 0 return query.count() != 0
def _is_publishing_baymodel(self, values): def _is_publishing_cluster_template(self, values):
if (len(values) == 1 and if (len(values) == 1 and
'public' in values and values['public'] is True): 'public' in values and values['public'] is True):
return True return True
return False return False
def destroy_baymodel(self, baymodel_id): def destroy_cluster_template(self, cluster_template_id):
session = get_session() session = get_session()
with session.begin(): with session.begin():
query = model_query(models.BayModel, session=session) query = model_query(models.ClusterTemplate, session=session)
query = add_identity_filter(query, baymodel_id) query = add_identity_filter(query, cluster_template_id)
try: try:
baymodel_ref = query.one() cluster_template_ref = query.one()
except NoResultFound: except NoResultFound:
raise exception.ClusterTemplateNotFound( raise exception.ClusterTemplateNotFound(
clustertemplate=baymodel_id) clustertemplate=cluster_template_id)
if self._is_baymodel_referenced(session, baymodel_ref['uuid']): if self._is_cluster_template_referenced(
session, cluster_template_ref['uuid']):
raise exception.ClusterTemplateReferenced( raise exception.ClusterTemplateReferenced(
clustertemplate=baymodel_id) clustertemplate=cluster_template_id)
query.delete() query.delete()
def update_baymodel(self, baymodel_id, values): def update_cluster_template(self, cluster_template_id, values):
# NOTE(dtantsur): this can lead to very strange errors # NOTE(dtantsur): this can lead to very strange errors
if 'uuid' in values: if 'uuid' in values:
msg = _("Cannot overwrite UUID for an existing BayModel.") msg = _("Cannot overwrite UUID for an existing ClusterTemplate.")
raise exception.InvalidParameterValue(err=msg) raise exception.InvalidParameterValue(err=msg)
return self._do_update_baymodel(baymodel_id, values) return self._do_update_cluster_template(cluster_template_id, values)
def _do_update_baymodel(self, baymodel_id, values): def _do_update_cluster_template(self, cluster_template_id, values):
session = get_session() session = get_session()
with session.begin(): with session.begin():
query = model_query(models.BayModel, session=session) query = model_query(models.ClusterTemplate, session=session)
query = add_identity_filter(query, baymodel_id) query = add_identity_filter(query, cluster_template_id)
try: try:
ref = query.with_lockmode('update').one() ref = query.with_lockmode('update').one()
except NoResultFound: except NoResultFound:
raise exception.ClusterTemplateNotFound( raise exception.ClusterTemplateNotFound(
clustertemplate=baymodel_id) clustertemplate=cluster_template_id)
if self._is_baymodel_referenced(session, ref['uuid']): if self._is_cluster_template_referenced(session, ref['uuid']):
# we only allow to update baymodel to be public # we only allow to update ClusterTemplate to be public
if not self._is_publishing_baymodel(values): if not self._is_publishing_cluster_template(values):
raise exception.ClusterTemplateReferenced( raise exception.ClusterTemplateReferenced(
clustertemplate=baymodel_id) clustertemplate=cluster_template_id)
ref.update(values) ref.update(values)
return ref return ref

View File

@ -141,10 +141,10 @@ class Bay(Base):
magnum_cert_ref = Column(String(512)) magnum_cert_ref = Column(String(512))
class BayModel(Base): class ClusterTemplate(Base):
"""Represents a bay model.""" """Represents a ClusterTemplate."""
__tablename__ = 'baymodel' __tablename__ = 'cluster_template'
__table_args__ = ( __table_args__ = (
schema.UniqueConstraint('uuid', name='uniq_baymodel0uuid'), schema.UniqueConstraint('uuid', name='uniq_baymodel0uuid'),
table_args() table_args()

View File

@ -13,19 +13,19 @@
# under the License. # under the License.
from magnum.objects import bay from magnum.objects import bay
from magnum.objects import baymodel
from magnum.objects import certificate from magnum.objects import certificate
from magnum.objects import cluster_template
from magnum.objects import magnum_service from magnum.objects import magnum_service
from magnum.objects import x509keypair from magnum.objects import x509keypair
Bay = bay.Bay Bay = bay.Bay
BayModel = baymodel.BayModel ClusterTemplate = cluster_template.ClusterTemplate
MagnumService = magnum_service.MagnumService MagnumService = magnum_service.MagnumService
X509KeyPair = x509keypair.X509KeyPair X509KeyPair = x509keypair.X509KeyPair
Certificate = certificate.Certificate Certificate = certificate.Certificate
__all__ = (Bay, __all__ = (Bay,
BayModel, ClusterTemplate,
MagnumService, MagnumService,
X509KeyPair, X509KeyPair,
Certificate) Certificate)

View File

@ -20,7 +20,7 @@ from oslo_versionedobjects import fields
from magnum.common import exception from magnum.common import exception
from magnum.db import api as dbapi from magnum.db import api as dbapi
from magnum.objects import base from magnum.objects import base
from magnum.objects import baymodel from magnum.objects import cluster_template
from magnum.objects import fields as m_fields from magnum.objects import fields as m_fields
@ -32,12 +32,14 @@ class Bay(base.MagnumPersistentObject, base.MagnumObject,
# Version 1.2: Add 'registry_trust_id' field # Version 1.2: Add 'registry_trust_id' field
# Version 1.3: Added 'baymodel' field # Version 1.3: Added 'baymodel' field
# Version 1.4: Added more types of status to bay's status field # Version 1.4: Added more types of status to bay's status field
# Version 1.5: Reanme 'registry_trust_id' to 'trust_id' # Version 1.5: Rename 'registry_trust_id' to 'trust_id'
# Add 'trustee_user_name', 'trustee_password', # Add 'trustee_user_name', 'trustee_password',
# 'trustee_user_id' field # 'trustee_user_id' field
# Version 1.6: Add rollback support for Bay # Version 1.6: Add rollback support for Bay
# Version 1.7: Added 'coe_version' and 'container_version' fields # Version 1.7: Added 'coe_version' and 'container_version' fields
VERSION = '1.7' # Version 1.8: Rename 'baymodel' to 'cluster_template'
VERSION = '1.8'
dbapi = dbapi.get_instance() dbapi = dbapi.get_instance()
@ -60,7 +62,7 @@ class Bay(base.MagnumPersistentObject, base.MagnumObject,
'master_addresses': fields.ListOfStringsField(nullable=True), 'master_addresses': fields.ListOfStringsField(nullable=True),
'ca_cert_ref': fields.StringField(nullable=True), 'ca_cert_ref': fields.StringField(nullable=True),
'magnum_cert_ref': fields.StringField(nullable=True), 'magnum_cert_ref': fields.StringField(nullable=True),
'baymodel': fields.ObjectField('BayModel'), 'cluster_template': fields.ObjectField('ClusterTemplate'),
'trust_id': fields.StringField(nullable=True), 'trust_id': fields.StringField(nullable=True),
'trustee_username': fields.StringField(nullable=True), 'trustee_username': fields.StringField(nullable=True),
'trustee_password': fields.StringField(nullable=True), 'trustee_password': fields.StringField(nullable=True),
@ -73,15 +75,15 @@ class Bay(base.MagnumPersistentObject, base.MagnumObject,
def _from_db_object(bay, db_bay): def _from_db_object(bay, db_bay):
"""Converts a database entity to a formal object.""" """Converts a database entity to a formal object."""
for field in bay.fields: for field in bay.fields:
if field != 'baymodel': if field != 'cluster_template':
bay[field] = db_bay[field] bay[field] = db_bay[field]
# Note(eliqiao): The following line needs to be placed outside the # Note(eliqiao): The following line needs to be placed outside the
# loop because there is a dependency from baymodel to baymodel_id. # loop because there is a dependency from cluster_template to
# The baymodel_id must be populated first in the loop before it can be # baymodel_id. The baymodel_id must be populated first in the loop
# used to find the baymodel. # before it can be used to find the cluster_template.
bay['baymodel'] = baymodel.BayModel.get_by_uuid(bay._context, bay['cluster_template'] = cluster_template.ClusterTemplate.get_by_uuid(
bay.baymodel_id) bay._context, bay.baymodel_id)
bay.obj_reset_changes() bay.obj_reset_changes()
return bay return bay

View File

@ -21,8 +21,8 @@ from magnum.objects import fields as m_fields
@base.MagnumObjectRegistry.register @base.MagnumObjectRegistry.register
class BayModel(base.MagnumPersistentObject, base.MagnumObject, class ClusterTemplate(base.MagnumPersistentObject, base.MagnumObject,
base.MagnumObjectDictCompat): base.MagnumObjectDictCompat):
# Version 1.0: Initial version # Version 1.0: Initial version
# Version 1.1: Add 'registry_enabled' field # Version 1.1: Add 'registry_enabled' field
# Version 1.2: Added 'network_driver' field # Version 1.2: Added 'network_driver' field
@ -39,7 +39,8 @@ class BayModel(base.MagnumPersistentObject, base.MagnumObject,
# Version 1.13: Added 'master_lb_enabled' field # Version 1.13: Added 'master_lb_enabled' field
# Version 1.14: Added 'fixed_subnet' field # Version 1.14: Added 'fixed_subnet' field
# Version 1.15: Added 'floating_ip_enabled' field # Version 1.15: Added 'floating_ip_enabled' field
VERSION = '1.15' # Version 1.16: Renamed the class from "BayModel' to 'ClusterTemplate'
VERSION = '1.16'
dbapi = dbapi.get_instance() dbapi = dbapi.get_instance()
@ -79,123 +80,129 @@ class BayModel(base.MagnumPersistentObject, base.MagnumObject,
} }
@staticmethod @staticmethod
def _from_db_object(baymodel, db_baymodel): def _from_db_object(cluster_template, db_cluster_template):
"""Converts a database entity to a formal object.""" """Converts a database entity to a formal object."""
for field in baymodel.fields: for field in cluster_template.fields:
baymodel[field] = db_baymodel[field] cluster_template[field] = db_cluster_template[field]
baymodel.obj_reset_changes() cluster_template.obj_reset_changes()
return baymodel return cluster_template
@staticmethod @staticmethod
def _from_db_object_list(db_objects, cls, context): def _from_db_object_list(db_objects, cls, context):
"""Converts a list of database entities to a list of formal objects.""" """Converts a list of database entities to a list of formal objects."""
return [BayModel._from_db_object(cls(context), obj) for obj in return [ClusterTemplate._from_db_object(cls(context), obj) for obj in
db_objects] db_objects]
@base.remotable_classmethod @base.remotable_classmethod
def get(cls, context, baymodel_id): def get(cls, context, cluster_template_id):
"""Find a baymodel based on its id or uuid and return a BayModel object. """Find and return ClusterTemplate object based on its id or uuid.
:param baymodel_id: the id *or* uuid of a baymodel. :param cluster_template_id: the id *or* uuid of a ClusterTemplate.
:param context: Security context :param context: Security context
:returns: a :class:`BayModel` object. :returns: a :class:`ClusterTemplate` object.
""" """
if strutils.is_int_like(baymodel_id): if strutils.is_int_like(cluster_template_id):
return cls.get_by_id(context, baymodel_id) return cls.get_by_id(context, cluster_template_id)
elif uuidutils.is_uuid_like(baymodel_id): elif uuidutils.is_uuid_like(cluster_template_id):
return cls.get_by_uuid(context, baymodel_id) return cls.get_by_uuid(context, cluster_template_id)
else: else:
raise exception.InvalidIdentity(identity=baymodel_id) raise exception.InvalidIdentity(identity=cluster_template_id)
@base.remotable_classmethod @base.remotable_classmethod
def get_by_id(cls, context, baymodel_id): def get_by_id(cls, context, cluster_template_id):
"""Find a baymodel based on its integer id and return a BayModel object. """Find and return ClusterTemplate object based on its integer id.
:param baymodel_id: the id of a baymodel. :param cluster_template_id: the id of a ClusterTemplate.
:param context: Security context :param context: Security context
:returns: a :class:`BayModel` object. :returns: a :class:`ClusterTemplate` object.
""" """
db_baymodel = cls.dbapi.get_baymodel_by_id(context, baymodel_id) db_cluster_template = cls.dbapi.get_cluster_template_by_id(
baymodel = BayModel._from_db_object(cls(context), db_baymodel) context, cluster_template_id)
return baymodel cluster_template = ClusterTemplate._from_db_object(cls(context),
db_cluster_template)
return cluster_template
@base.remotable_classmethod @base.remotable_classmethod
def get_by_uuid(cls, context, uuid): def get_by_uuid(cls, context, uuid):
"""Find a baymodel based on uuid and return a :class:`BayModel` object. """Find and return ClusterTemplate object based on uuid.
:param uuid: the uuid of a baymodel. :param uuid: the uuid of a ClusterTemplate.
:param context: Security context :param context: Security context
:returns: a :class:`BayModel` object. :returns: a :class:`ClusterTemplate` object.
""" """
db_baymodel = cls.dbapi.get_baymodel_by_uuid(context, uuid) db_cluster_template = cls.dbapi.get_cluster_template_by_uuid(
baymodel = BayModel._from_db_object(cls(context), db_baymodel) context, uuid)
return baymodel cluster_template = ClusterTemplate._from_db_object(cls(context),
db_cluster_template)
return cluster_template
@base.remotable_classmethod @base.remotable_classmethod
def get_by_name(cls, context, name): def get_by_name(cls, context, name):
"""Find a baymodel based on name and return a :class:`BayModel` object. """Find and return ClusterTemplate object based on name.
:param name: the name of a baymodel. :param name: the name of a ClusterTemplate.
:param context: Security context :param context: Security context
:returns: a :class:`BayModel` object. :returns: a :class:`ClusterTemplate` object.
""" """
db_baymodel = cls.dbapi.get_baymodel_by_name(context, name) db_cluster_template = cls.dbapi.get_cluster_template_by_name(context,
baymodel = BayModel._from_db_object(cls(context), db_baymodel) name)
return baymodel cluster_template = ClusterTemplate._from_db_object(cls(context),
db_cluster_template)
return cluster_template
@base.remotable_classmethod @base.remotable_classmethod
def list(cls, context, limit=None, marker=None, def list(cls, context, limit=None, marker=None,
sort_key=None, sort_dir=None): sort_key=None, sort_dir=None):
"""Return a list of BayModel objects. """Return a list of ClusterTemplate objects.
:param context: Security context. :param context: Security context.
:param limit: maximum number of resources to return in a single result. :param limit: maximum number of resources to return in a single result.
:param marker: pagination marker for large data sets. :param marker: pagination marker for large data sets.
:param sort_key: column to sort results by. :param sort_key: column to sort results by.
:param sort_dir: direction to sort. "asc" or "desc". :param sort_dir: direction to sort. "asc" or "desc".
:returns: a list of :class:`BayModel` object. :returns: a list of :class:`ClusterTemplate` object.
""" """
db_baymodels = cls.dbapi.get_baymodel_list(context, limit=limit, db_cluster_templates = cls.dbapi.get_cluster_template_list(
marker=marker, context, limit=limit, marker=marker, sort_key=sort_key,
sort_key=sort_key, sort_dir=sort_dir)
sort_dir=sort_dir) return ClusterTemplate._from_db_object_list(db_cluster_templates,
return BayModel._from_db_object_list(db_baymodels, cls, context) cls, context)
@base.remotable @base.remotable
def create(self, context=None): def create(self, context=None):
"""Create a BayModel record in the DB. """Create a ClusterTemplate record in the DB.
:param context: Security context. NOTE: This should only :param context: Security context. NOTE: This should only
be used internally by the indirection_api. be used internally by the indirection_api.
Unfortunately, RPC requires context as the first Unfortunately, RPC requires context as the first
argument, even though we don't use it. argument, even though we don't use it.
A context should be set when instantiating the A context should be set when instantiating the
object, e.g.: BayModel(context) object, e.g.: ClusterTemplate(context)
""" """
values = self.obj_get_changes() values = self.obj_get_changes()
db_baymodel = self.dbapi.create_baymodel(values) db_cluster_template = self.dbapi.create_cluster_template(values)
self._from_db_object(self, db_baymodel) self._from_db_object(self, db_cluster_template)
@base.remotable @base.remotable
def destroy(self, context=None): def destroy(self, context=None):
"""Delete the BayModel from the DB. """Delete the ClusterTemplate from the DB.
:param context: Security context. NOTE: This should only :param context: Security context. NOTE: This should only
be used internally by the indirection_api. be used internally by the indirection_api.
Unfortunately, RPC requires context as the first Unfortunately, RPC requires context as the first
argument, even though we don't use it. argument, even though we don't use it.
A context should be set when instantiating the A context should be set when instantiating the
object, e.g.: BayModel(context) object, e.g.: ClusterTemplate(context)
""" """
self.dbapi.destroy_baymodel(self.uuid) self.dbapi.destroy_cluster_template(self.uuid)
self.obj_reset_changes() self.obj_reset_changes()
@base.remotable @base.remotable
def save(self, context=None): def save(self, context=None):
"""Save updates to this BayModel. """Save updates to this ClusterTemplate.
Updates will be made column by column based on the result Updates will be made column by column based on the result
of self.what_changed(). of self.what_changed().
@ -205,27 +212,27 @@ class BayModel(base.MagnumPersistentObject, base.MagnumObject,
Unfortunately, RPC requires context as the first Unfortunately, RPC requires context as the first
argument, even though we don't use it. argument, even though we don't use it.
A context should be set when instantiating the A context should be set when instantiating the
object, e.g.: BayModel(context) object, e.g.: ClusterTemplate(context)
""" """
updates = self.obj_get_changes() updates = self.obj_get_changes()
self.dbapi.update_baymodel(self.uuid, updates) self.dbapi.update_cluster_template(self.uuid, updates)
self.obj_reset_changes() self.obj_reset_changes()
@base.remotable @base.remotable
def refresh(self, context=None): def refresh(self, context=None):
"""Loads updates for this BayModel. """Loads updates for this ClusterTemplate.
Loads a baymodel with the same uuid from the database and Loads a ClusterTemplate with the same uuid from the database and
checks for updated attributes. Updates are applied from checks for updated attributes. Updates are applied from
the loaded baymodel column by column, if there are any updates. the loaded ClusterTemplate column by column, if there are any updates.
:param context: Security context. NOTE: This should only :param context: Security context. NOTE: This should only
be used internally by the indirection_api. be used internally by the indirection_api.
Unfortunately, RPC requires context as the first Unfortunately, RPC requires context as the first
argument, even though we don't use it. argument, even though we don't use it.
A context should be set when instantiating the A context should be set when instantiating the
object, e.g.: BayModel(context) object, e.g.: ClusterTemplate(context)
""" """
current = self.__class__.get_by_uuid(self._context, uuid=self.uuid) current = self.__class__.get_by_uuid(self._context, uuid=self.uuid)
for field in self.fields: for field in self.fields:

View File

@ -53,7 +53,7 @@ class TestListBay(api_base.FunctionalTest):
def setUp(self): def setUp(self):
super(TestListBay, self).setUp() super(TestListBay, self).setUp()
obj_utils.create_test_baymodel(self.context) obj_utils.create_test_cluster_template(self.context)
def test_empty(self): def test_empty(self):
response = self.get_json('/bays') response = self.get_json('/bays')
@ -207,7 +207,8 @@ class TestPatch(api_base.FunctionalTest):
def setUp(self): def setUp(self):
super(TestPatch, self).setUp() super(TestPatch, self).setUp()
self.baymodel = obj_utils.create_test_baymodel(self.context) self.cluster_template = obj_utils.create_test_cluster_template(
self.context)
self.bay = obj_utils.create_test_bay(self.context, self.bay = obj_utils.create_test_bay(self.context,
name='bay_example_A', name='bay_example_A',
node_count=3) node_count=3)
@ -278,12 +279,12 @@ class TestPatch(api_base.FunctionalTest):
self.assertEqual(404, response.status_code) self.assertEqual(404, response.status_code)
def test_replace_baymodel_id_failed(self): def test_replace_baymodel_id_failed(self):
baymodel = obj_utils.create_test_baymodel( cluster_template = obj_utils.create_test_cluster_template(
self.context, self.context,
uuid=uuidutils.generate_uuid()) uuid=uuidutils.generate_uuid())
response = self.patch_json('/bays/%s' % self.bay.uuid, response = self.patch_json('/bays/%s' % self.bay.uuid,
[{'path': '/baymodel_id', [{'path': '/baymodel_id',
'value': baymodel.uuid, 'value': cluster_template.uuid,
'op': 'replace'}], 'op': 'replace'}],
expect_errors=True) expect_errors=True)
self.assertEqual('application/json', response.content_type) self.assertEqual('application/json', response.content_type)
@ -408,7 +409,8 @@ class TestPost(api_base.FunctionalTest):
def setUp(self): def setUp(self):
super(TestPost, self).setUp() super(TestPost, self).setUp()
self.baymodel = obj_utils.create_test_baymodel(self.context) self.cluster_template = obj_utils.create_test_cluster_template(
self.context)
p = mock.patch.object(rpcapi.API, 'bay_create') p = mock.patch.object(rpcapi.API, 'bay_create')
self.mock_bay_create = p.start() self.mock_bay_create = p.start()
self.mock_bay_create.side_effect = self._simulate_rpc_bay_create self.mock_bay_create.side_effect = self._simulate_rpc_bay_create
@ -487,7 +489,7 @@ class TestPost(api_base.FunctionalTest):
self.assertTrue(response.json['errors']) self.assertTrue(response.json['errors'])
def test_create_bay_with_baymodel_name(self): def test_create_bay_with_baymodel_name(self):
bdict = apiutils.bay_post_data(baymodel_id=self.baymodel.name) bdict = apiutils.bay_post_data(baymodel_id=self.cluster_template.name)
response = self.post_json('/bays', bdict, expect_errors=True) response = self.post_json('/bays', bdict, expect_errors=True)
self.assertEqual('application/json', response.content_type) self.assertEqual('application/json', response.content_type)
self.assertEqual(201, response.status_int) self.assertEqual(201, response.status_int)
@ -733,18 +735,18 @@ class TestPost(api_base.FunctionalTest):
self.assertEqual(400, response.status_int) self.assertEqual(400, response.status_int)
def test_create_bay_with_no_lb_one_node(self): def test_create_bay_with_no_lb_one_node(self):
baymodel = obj_utils.create_test_baymodel( cluster_template = obj_utils.create_test_cluster_template(
self.context, name='foo', uuid='foo', master_lb_enabled=False) self.context, name='foo', uuid='foo', master_lb_enabled=False)
bdict = apiutils.bay_post_data(baymodel_id=baymodel.name, bdict = apiutils.bay_post_data(baymodel_id=cluster_template.name,
master_count=1) master_count=1)
response = self.post_json('/bays', bdict, expect_errors=True) response = self.post_json('/bays', bdict, expect_errors=True)
self.assertEqual('application/json', response.content_type) self.assertEqual('application/json', response.content_type)
self.assertEqual(201, response.status_int) self.assertEqual(201, response.status_int)
def test_create_bay_with_no_lb_multi_node(self): def test_create_bay_with_no_lb_multi_node(self):
baymodel = obj_utils.create_test_baymodel( cluster_template = obj_utils.create_test_cluster_template(
self.context, name='foo', uuid='foo', master_lb_enabled=False) self.context, name='foo', uuid='foo', master_lb_enabled=False)
bdict = apiutils.bay_post_data(baymodel_id=baymodel.name, bdict = apiutils.bay_post_data(baymodel_id=cluster_template.name,
master_count=3) master_count=3)
response = self.post_json('/bays', bdict, expect_errors=True) response = self.post_json('/bays', bdict, expect_errors=True)
self.assertEqual('application/json', response.content_type) self.assertEqual('application/json', response.content_type)
@ -755,7 +757,8 @@ class TestDelete(api_base.FunctionalTest):
def setUp(self): def setUp(self):
super(TestDelete, self).setUp() super(TestDelete, self).setUp()
self.baymodel = obj_utils.create_test_baymodel(self.context) self.cluster_template = obj_utils.create_test_cluster_template(
self.context)
self.bay = obj_utils.create_test_bay(self.context) self.bay = obj_utils.create_test_bay(self.context)
p = mock.patch.object(rpcapi.API, 'bay_delete') p = mock.patch.object(rpcapi.API, 'bay_delete')
self.mock_bay_delete = p.start() self.mock_bay_delete = p.start()
@ -807,7 +810,7 @@ class TestBayPolicyEnforcement(api_base.FunctionalTest):
def setUp(self): def setUp(self):
super(TestBayPolicyEnforcement, self).setUp() super(TestBayPolicyEnforcement, self).setUp()
obj_utils.create_test_baymodel(self.context) obj_utils.create_test_cluster_template(self.context)
def _common_policy_check(self, rule, func, *arg, **kwarg): def _common_policy_check(self, rule, func, *arg, **kwarg):
self.policy.set_rules({rule: "project:non_fake"}) self.policy.set_rules({rule: "project:non_fake"})

View File

@ -56,20 +56,20 @@ class TestListBayModel(api_base.FunctionalTest):
self.assertEqual([], response['baymodels']) self.assertEqual([], response['baymodels'])
def test_one(self): def test_one(self):
baymodel = obj_utils.create_test_baymodel(self.context) baymodel = obj_utils.create_test_cluster_template(self.context)
response = self.get_json('/baymodels') response = self.get_json('/baymodels')
self.assertEqual(baymodel.uuid, response['baymodels'][0]["uuid"]) self.assertEqual(baymodel.uuid, response['baymodels'][0]["uuid"])
self._verify_attrs(self._baymodel_attrs, self._verify_attrs(self._baymodel_attrs,
response['baymodels'][0]) response['baymodels'][0])
def test_get_one(self): def test_get_one(self):
baymodel = obj_utils.create_test_baymodel(self.context) baymodel = obj_utils.create_test_cluster_template(self.context)
response = self.get_json('/baymodels/%s' % baymodel['uuid']) response = self.get_json('/baymodels/%s' % baymodel['uuid'])
self.assertEqual(baymodel.uuid, response['uuid']) self.assertEqual(baymodel.uuid, response['uuid'])
self._verify_attrs(self._baymodel_attrs, response) self._verify_attrs(self._baymodel_attrs, response)
def test_get_one_by_name(self): def test_get_one_by_name(self):
baymodel = obj_utils.create_test_baymodel(self.context) baymodel = obj_utils.create_test_cluster_template(self.context)
response = self.get_json('/baymodels/%s' % baymodel['name']) response = self.get_json('/baymodels/%s' % baymodel['name'])
self.assertEqual(baymodel.uuid, response['uuid']) self.assertEqual(baymodel.uuid, response['uuid'])
self._verify_attrs(self._baymodel_attrs, response) self._verify_attrs(self._baymodel_attrs, response)
@ -83,10 +83,10 @@ class TestListBayModel(api_base.FunctionalTest):
self.assertTrue(response.json['errors']) self.assertTrue(response.json['errors'])
def test_get_one_by_name_multiple_baymodel(self): def test_get_one_by_name_multiple_baymodel(self):
obj_utils.create_test_baymodel( obj_utils.create_test_cluster_template(
self.context, name='test_baymodel', self.context, name='test_baymodel',
uuid=uuidutils.generate_uuid()) uuid=uuidutils.generate_uuid())
obj_utils.create_test_baymodel( obj_utils.create_test_cluster_template(
self.context, name='test_baymodel', self.context, name='test_baymodel',
uuid=uuidutils.generate_uuid()) uuid=uuidutils.generate_uuid())
response = self.get_json( response = self.get_json(
@ -99,7 +99,7 @@ class TestListBayModel(api_base.FunctionalTest):
def test_get_all_with_pagination_marker(self): def test_get_all_with_pagination_marker(self):
bm_list = [] bm_list = []
for id_ in range(4): for id_ in range(4):
baymodel = obj_utils.create_test_baymodel( baymodel = obj_utils.create_test_cluster_template(
self.context, id=id_, self.context, id=id_,
uuid=uuidutils.generate_uuid()) uuid=uuidutils.generate_uuid())
bm_list.append(baymodel) bm_list.append(baymodel)
@ -110,7 +110,7 @@ class TestListBayModel(api_base.FunctionalTest):
self.assertEqual(bm_list[-1].uuid, response['baymodels'][0]['uuid']) self.assertEqual(bm_list[-1].uuid, response['baymodels'][0]['uuid'])
def test_detail(self): def test_detail(self):
baymodel = obj_utils.create_test_baymodel(self.context) baymodel = obj_utils.create_test_cluster_template(self.context)
response = self.get_json('/baymodels/detail') response = self.get_json('/baymodels/detail')
self.assertEqual(baymodel.uuid, response['baymodels'][0]["uuid"]) self.assertEqual(baymodel.uuid, response['baymodels'][0]["uuid"])
self._verify_attrs(self._baymodel_attrs, self._verify_attrs(self._baymodel_attrs,
@ -119,7 +119,7 @@ class TestListBayModel(api_base.FunctionalTest):
def test_detail_with_pagination_marker(self): def test_detail_with_pagination_marker(self):
bm_list = [] bm_list = []
for id_ in range(4): for id_ in range(4):
baymodel = obj_utils.create_test_baymodel( baymodel = obj_utils.create_test_cluster_template(
self.context, id=id_, self.context, id=id_,
uuid=uuidutils.generate_uuid()) uuid=uuidutils.generate_uuid())
bm_list.append(baymodel) bm_list.append(baymodel)
@ -132,7 +132,7 @@ class TestListBayModel(api_base.FunctionalTest):
response['baymodels'][0]) response['baymodels'][0])
def test_detail_against_single(self): def test_detail_against_single(self):
baymodel = obj_utils.create_test_baymodel(self.context) baymodel = obj_utils.create_test_cluster_template(self.context)
response = self.get_json('/baymodels/%s/detail' % baymodel['uuid'], response = self.get_json('/baymodels/%s/detail' % baymodel['uuid'],
expect_errors=True) expect_errors=True)
self.assertEqual(404, response.status_int) self.assertEqual(404, response.status_int)
@ -140,7 +140,7 @@ class TestListBayModel(api_base.FunctionalTest):
def test_many(self): def test_many(self):
bm_list = [] bm_list = []
for id_ in range(5): for id_ in range(5):
baymodel = obj_utils.create_test_baymodel( baymodel = obj_utils.create_test_cluster_template(
self.context, id=id_, self.context, id=id_,
uuid=uuidutils.generate_uuid()) uuid=uuidutils.generate_uuid())
bm_list.append(baymodel.uuid) bm_list.append(baymodel.uuid)
@ -151,7 +151,7 @@ class TestListBayModel(api_base.FunctionalTest):
def test_links(self): def test_links(self):
uuid = uuidutils.generate_uuid() uuid = uuidutils.generate_uuid()
obj_utils.create_test_baymodel(self.context, id=1, uuid=uuid) obj_utils.create_test_cluster_template(self.context, id=1, uuid=uuid)
response = self.get_json('/baymodels/%s' % uuid) response = self.get_json('/baymodels/%s' % uuid)
self.assertIn('links', response.keys()) self.assertIn('links', response.keys())
self.assertEqual(2, len(response['links'])) self.assertEqual(2, len(response['links']))
@ -162,8 +162,8 @@ class TestListBayModel(api_base.FunctionalTest):
def test_collection_links(self): def test_collection_links(self):
for id_ in range(5): for id_ in range(5):
obj_utils.create_test_baymodel(self.context, id=id_, obj_utils.create_test_cluster_template(
uuid=uuidutils.generate_uuid()) self.context, id=id_, uuid=uuidutils.generate_uuid())
response = self.get_json('/baymodels/?limit=3') response = self.get_json('/baymodels/?limit=3')
self.assertEqual(3, len(response['baymodels'])) self.assertEqual(3, len(response['baymodels']))
@ -173,8 +173,8 @@ class TestListBayModel(api_base.FunctionalTest):
def test_collection_links_default_limit(self): def test_collection_links_default_limit(self):
cfg.CONF.set_override('max_limit', 3, 'api') cfg.CONF.set_override('max_limit', 3, 'api')
for id_ in range(5): for id_ in range(5):
obj_utils.create_test_baymodel(self.context, id=id_, obj_utils.create_test_cluster_template(
uuid=uuidutils.generate_uuid()) self.context, id=id_, uuid=uuidutils.generate_uuid())
response = self.get_json('/baymodels') response = self.get_json('/baymodels')
self.assertEqual(3, len(response['baymodels'])) self.assertEqual(3, len(response['baymodels']))
@ -189,7 +189,7 @@ class TestPatch(api_base.FunctionalTest):
p = mock.patch.object(attr_validator, 'validate_os_resources') p = mock.patch.object(attr_validator, 'validate_os_resources')
self.mock_valid_os_res = p.start() self.mock_valid_os_res = p.start()
self.addCleanup(p.stop) self.addCleanup(p.stop)
self.baymodel = obj_utils.create_test_baymodel( self.baymodel = obj_utils.create_test_cluster_template(
self.context, self.context,
name='bay_model_example_A', name='bay_model_example_A',
image_id='nerdherd', image_id='nerdherd',
@ -218,7 +218,7 @@ class TestPatch(api_base.FunctionalTest):
self.assertTrue(response.json['errors']) self.assertTrue(response.json['errors'])
def test_update_baymodel_with_bay(self): def test_update_baymodel_with_bay(self):
baymodel = obj_utils.create_test_baymodel(self.context) baymodel = obj_utils.create_test_cluster_template(self.context)
obj_utils.create_test_bay(self.context, baymodel_id=baymodel.uuid) obj_utils.create_test_bay(self.context, baymodel_id=baymodel.uuid)
response = self.patch_json('/baymodels/%s' % baymodel.uuid, response = self.patch_json('/baymodels/%s' % baymodel.uuid,
@ -252,7 +252,7 @@ class TestPatch(api_base.FunctionalTest):
'op': 'replace'}]) 'op': 'replace'}])
def test_update_baymodel_with_bay_allow_update(self): def test_update_baymodel_with_bay_allow_update(self):
baymodel = obj_utils.create_test_baymodel(self.context) baymodel = obj_utils.create_test_cluster_template(self.context)
obj_utils.create_test_bay(self.context, baymodel_id=baymodel.uuid) obj_utils.create_test_bay(self.context, baymodel_id=baymodel.uuid)
response = self.patch_json('/baymodels/%s' % baymodel.uuid, response = self.patch_json('/baymodels/%s' % baymodel.uuid,
[{'path': '/public', [{'path': '/public',
@ -264,7 +264,7 @@ class TestPatch(api_base.FunctionalTest):
self.assertEqual(response['public'], True) self.assertEqual(response['public'], True)
def test_update_baymodel_with_bay_not_allow_update(self): def test_update_baymodel_with_bay_not_allow_update(self):
baymodel = obj_utils.create_test_baymodel(self.context) baymodel = obj_utils.create_test_cluster_template(self.context)
obj_utils.create_test_bay(self.context, baymodel_id=baymodel.uuid) obj_utils.create_test_bay(self.context, baymodel_id=baymodel.uuid)
response = self.patch_json('/baymodels/%s' % baymodel.uuid, response = self.patch_json('/baymodels/%s' % baymodel.uuid,
[{'path': '/name', [{'path': '/name',
@ -474,8 +474,9 @@ class TestPost(api_base.FunctionalTest):
@mock.patch('magnum.api.attr_validator.validate_image') @mock.patch('magnum.api.attr_validator.validate_image')
def test_create_baymodel_set_project_id_and_user_id(self, def test_create_baymodel_set_project_id_and_user_id(self,
mock_image_data): mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock: self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock:
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
bdict = apiutils.baymodel_post_data() bdict = apiutils.baymodel_post_data()
@ -489,8 +490,9 @@ class TestPost(api_base.FunctionalTest):
@mock.patch('magnum.api.attr_validator.validate_image') @mock.patch('magnum.api.attr_validator.validate_image')
def test_create_baymodel_doesnt_contain_id(self, def test_create_baymodel_doesnt_contain_id(self,
mock_image_data): mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock: self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock:
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
bdict = apiutils.baymodel_post_data(image_id='my-image') bdict = apiutils.baymodel_post_data(image_id='my-image')
@ -502,8 +504,9 @@ class TestPost(api_base.FunctionalTest):
def _create_baymodel_raises_app_error(self, **kwargs): def _create_baymodel_raises_app_error(self, **kwargs):
# Create mock for db and image data # Create mock for db and image data
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock,\ self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock,\
mock.patch('magnum.api.attr_validator.validate_image')\ mock.patch('magnum.api.attr_validator.validate_image')\
as mock_image_data: as mock_image_data:
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
@ -561,8 +564,9 @@ class TestPost(api_base.FunctionalTest):
@mock.patch('magnum.api.attr_validator.validate_image') @mock.patch('magnum.api.attr_validator.validate_image')
def test_create_baymodel_with_labels(self, mock_image_data): def test_create_baymodel_with_labels(self, mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock: self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock:
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
bdict = apiutils.baymodel_post_data(labels={'key1': 'val1', bdict = apiutils.baymodel_post_data(labels={'key1': 'val1',
@ -576,8 +580,9 @@ class TestPost(api_base.FunctionalTest):
@mock.patch('magnum.api.attr_validator.validate_image') @mock.patch('magnum.api.attr_validator.validate_image')
def test_create_baymodel_with_docker_volume_size(self, def test_create_baymodel_with_docker_volume_size(self,
mock_image_data): mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock: self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock:
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
bdict = apiutils.baymodel_post_data(docker_volume_size=99) bdict = apiutils.baymodel_post_data(docker_volume_size=99)
@ -589,8 +594,9 @@ class TestPost(api_base.FunctionalTest):
@mock.patch('magnum.api.attr_validator.validate_image') @mock.patch('magnum.api.attr_validator.validate_image')
def test_create_baymodel_with_overlay(self, mock_image_data): def test_create_baymodel_with_overlay(self, mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock: self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock:
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
bdict = apiutils.baymodel_post_data( bdict = apiutils.baymodel_post_data(
@ -617,8 +623,10 @@ class TestPost(api_base.FunctionalTest):
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
for k, v in baymodel_config_dict.items(): for k, v in baymodel_config_dict.items():
cfg.CONF.set_override(k, v, 'cluster_template') cfg.CONF.set_override(k, v, 'cluster_template')
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock: self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock:
bdict = apiutils.baymodel_post_data(**baymodel_dict) bdict = apiutils.baymodel_post_data(**baymodel_dict)
response = self.post_json('/baymodels', bdict, response = self.post_json('/baymodels', bdict,
expect_errors=expect_errors) expect_errors=expect_errors)
@ -674,8 +682,9 @@ class TestPost(api_base.FunctionalTest):
@mock.patch('magnum.api.attr_validator.validate_image') @mock.patch('magnum.api.attr_validator.validate_image')
def test_create_baymodel_with_volume_driver(self, def test_create_baymodel_with_volume_driver(self,
mock_image_data): mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock: self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock:
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
bdict = apiutils.baymodel_post_data(volume_driver='rexray') bdict = apiutils.baymodel_post_data(volume_driver='rexray')
@ -688,8 +697,9 @@ class TestPost(api_base.FunctionalTest):
@mock.patch('magnum.api.attr_validator.validate_image') @mock.patch('magnum.api.attr_validator.validate_image')
def test_create_baymodel_with_no_volume_driver(self, def test_create_baymodel_with_no_volume_driver(self,
mock_image_data): mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock: self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock:
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
bdict = apiutils.baymodel_post_data() bdict = apiutils.baymodel_post_data()
@ -703,8 +713,9 @@ class TestPost(api_base.FunctionalTest):
@mock.patch.object(magnum_policy, 'enforce') @mock.patch.object(magnum_policy, 'enforce')
def test_create_baymodel_public_success(self, mock_policy, def test_create_baymodel_public_success(self, mock_policy,
mock_image_data): mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock: self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock:
mock_policy.return_value = True mock_policy.return_value = True
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
@ -721,8 +732,8 @@ class TestPost(api_base.FunctionalTest):
@mock.patch.object(magnum_policy, 'enforce') @mock.patch.object(magnum_policy, 'enforce')
def test_create_baymodel_public_fail(self, mock_policy, def test_create_baymodel_public_fail(self, mock_policy,
mock_image_data): mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_baymodel): wraps=self.dbapi.create_cluster_template):
# make policy enforcement fail # make policy enforcement fail
mock_policy.return_value = False mock_policy.return_value = False
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
@ -734,8 +745,9 @@ class TestPost(api_base.FunctionalTest):
@mock.patch.object(magnum_policy, 'enforce') @mock.patch.object(magnum_policy, 'enforce')
def test_create_baymodel_public_not_set(self, mock_policy, def test_create_baymodel_public_not_set(self, mock_policy,
mock_image_data): mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock: self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock:
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
bdict = apiutils.baymodel_post_data(public=False) bdict = apiutils.baymodel_post_data(public=False)
@ -875,8 +887,8 @@ class TestPost(api_base.FunctionalTest):
@mock.patch('magnum.api.attr_validator.validate_image') @mock.patch('magnum.api.attr_validator.validate_image')
def test_create_baymodel_without_name(self, mock_image_data): def test_create_baymodel_without_name(self, mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_baymodel): wraps=self.dbapi.create_cluster_template):
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
bdict = apiutils.baymodel_post_data() bdict = apiutils.baymodel_post_data()
@ -889,7 +901,7 @@ class TestPost(api_base.FunctionalTest):
class TestDelete(api_base.FunctionalTest): class TestDelete(api_base.FunctionalTest):
def test_delete_baymodel(self): def test_delete_baymodel(self):
baymodel = obj_utils.create_test_baymodel(self.context) baymodel = obj_utils.create_test_cluster_template(self.context)
self.delete('/baymodels/%s' % baymodel.uuid) self.delete('/baymodels/%s' % baymodel.uuid)
response = self.get_json('/baymodels/%s' % baymodel.uuid, response = self.get_json('/baymodels/%s' % baymodel.uuid,
expect_errors=True) expect_errors=True)
@ -898,7 +910,7 @@ class TestDelete(api_base.FunctionalTest):
self.assertTrue(response.json['errors']) self.assertTrue(response.json['errors'])
def test_delete_baymodel_with_bay(self): def test_delete_baymodel_with_bay(self):
baymodel = obj_utils.create_test_baymodel(self.context) baymodel = obj_utils.create_test_cluster_template(self.context)
obj_utils.create_test_bay(self.context, baymodel_id=baymodel.uuid) obj_utils.create_test_bay(self.context, baymodel_id=baymodel.uuid)
response = self.delete('/baymodels/%s' % baymodel.uuid, response = self.delete('/baymodels/%s' % baymodel.uuid,
expect_errors=True) expect_errors=True)
@ -915,7 +927,7 @@ class TestDelete(api_base.FunctionalTest):
self.assertTrue(response.json['errors']) self.assertTrue(response.json['errors'])
def test_delete_baymodel_with_name(self): def test_delete_baymodel_with_name(self):
baymodel = obj_utils.create_test_baymodel(self.context) baymodel = obj_utils.create_test_cluster_template(self.context)
response = self.delete('/baymodels/%s' % baymodel['name'], response = self.delete('/baymodels/%s' % baymodel['name'],
expect_errors=True) expect_errors=True)
self.assertEqual(204, response.status_int) self.assertEqual(204, response.status_int)
@ -927,10 +939,10 @@ class TestDelete(api_base.FunctionalTest):
self.assertTrue(response.json['errors']) self.assertTrue(response.json['errors'])
def test_delete_multiple_baymodel_by_name(self): def test_delete_multiple_baymodel_by_name(self):
obj_utils.create_test_baymodel(self.context, name='test_baymodel', obj_utils.create_test_cluster_template(
uuid=uuidutils.generate_uuid()) self.context, name='test_baymodel', uuid=uuidutils.generate_uuid())
obj_utils.create_test_baymodel(self.context, name='test_baymodel', obj_utils.create_test_cluster_template(
uuid=uuidutils.generate_uuid()) self.context, name='test_baymodel', uuid=uuidutils.generate_uuid())
response = self.delete('/baymodels/test_baymodel', expect_errors=True) response = self.delete('/baymodels/test_baymodel', expect_errors=True)
self.assertEqual(409, response.status_int) self.assertEqual(409, response.status_int)
self.assertEqual('application/json', response.content_type) self.assertEqual('application/json', response.content_type)
@ -954,7 +966,7 @@ class TestBayModelPolicyEnforcement(api_base.FunctionalTest):
expect_errors=True) expect_errors=True)
def test_policy_disallow_get_one(self): def test_policy_disallow_get_one(self):
baymodel = obj_utils.create_test_baymodel(self.context) baymodel = obj_utils.create_test_cluster_template(self.context)
self._common_policy_check( self._common_policy_check(
"baymodel:get", self.get_json, "baymodel:get", self.get_json,
'/baymodels/%s' % baymodel.uuid, '/baymodels/%s' % baymodel.uuid,
@ -967,7 +979,7 @@ class TestBayModelPolicyEnforcement(api_base.FunctionalTest):
expect_errors=True) expect_errors=True)
def test_policy_disallow_update(self): def test_policy_disallow_update(self):
baymodel = obj_utils.create_test_baymodel( baymodel = obj_utils.create_test_cluster_template(
self.context, self.context,
name='example_A', name='example_A',
uuid=uuidutils.generate_uuid()) uuid=uuidutils.generate_uuid())
@ -984,7 +996,7 @@ class TestBayModelPolicyEnforcement(api_base.FunctionalTest):
expect_errors=True) expect_errors=True)
def test_policy_disallow_delete(self): def test_policy_disallow_delete(self):
baymodel = obj_utils.create_test_baymodel(self.context) baymodel = obj_utils.create_test_cluster_template(self.context)
self._common_policy_check( self._common_policy_check(
"baymodel:delete", self.delete, "baymodel:delete", self.delete,
'/baymodels/%s' % baymodel.uuid, expect_errors=True) '/baymodels/%s' % baymodel.uuid, expect_errors=True)
@ -999,14 +1011,14 @@ class TestBayModelPolicyEnforcement(api_base.FunctionalTest):
response.json['errors'][0]['detail']) response.json['errors'][0]['detail'])
def test_policy_only_owner_get_one(self): def test_policy_only_owner_get_one(self):
baymodel = obj_utils.create_test_baymodel(self.context, baymodel = obj_utils.create_test_cluster_template(self.context,
user_id='another') user_id='another')
self._owner_check("baymodel:get", self.get_json, self._owner_check("baymodel:get", self.get_json,
'/baymodels/%s' % baymodel.uuid, expect_errors=True) '/baymodels/%s' % baymodel.uuid, expect_errors=True)
def test_policy_only_owner_update(self): def test_policy_only_owner_update(self):
baymodel = obj_utils.create_test_baymodel(self.context, baymodel = obj_utils.create_test_cluster_template(self.context,
user_id='another') user_id='another')
self._owner_check( self._owner_check(
"baymodel:update", self.patch_json, "baymodel:update", self.patch_json,
'/baymodels/%s' % baymodel.uuid, '/baymodels/%s' % baymodel.uuid,
@ -1014,8 +1026,8 @@ class TestBayModelPolicyEnforcement(api_base.FunctionalTest):
expect_errors=True) expect_errors=True)
def test_policy_only_owner_delete(self): def test_policy_only_owner_delete(self):
baymodel = obj_utils.create_test_baymodel(self.context, baymodel = obj_utils.create_test_cluster_template(self.context,
user_id='another') user_id='another')
self._owner_check( self._owner_check(
"baymodel:delete", self.delete, '/baymodels/%s' % baymodel.uuid, "baymodel:delete", self.delete, '/baymodels/%s' % baymodel.uuid,
expect_errors=True) expect_errors=True)

View File

@ -509,8 +509,9 @@ class TestPost(api_base.FunctionalTest):
@mock.patch('magnum.api.attr_validator.validate_image') @mock.patch('magnum.api.attr_validator.validate_image')
def test_create_cluster_template_set_project_id_and_user_id( def test_create_cluster_template_set_project_id_and_user_id(
self, mock_image_data): self, mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock: self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock:
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
bdict = apiutils.cluster_template_post_data() bdict = apiutils.cluster_template_post_data()
@ -524,8 +525,9 @@ class TestPost(api_base.FunctionalTest):
@mock.patch('magnum.api.attr_validator.validate_image') @mock.patch('magnum.api.attr_validator.validate_image')
def test_create_cluster_template_doesnt_contain_id(self, def test_create_cluster_template_doesnt_contain_id(self,
mock_image_data): mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock: self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock:
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
bdict = apiutils.cluster_template_post_data(image_id='my-image') bdict = apiutils.cluster_template_post_data(image_id='my-image')
@ -537,8 +539,9 @@ class TestPost(api_base.FunctionalTest):
def _create_model_raises_app_error(self, **kwargs): def _create_model_raises_app_error(self, **kwargs):
# Create mock for db and image data # Create mock for db and image data
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock,\ self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock,\
mock.patch('magnum.api.attr_validator.validate_image')\ mock.patch('magnum.api.attr_validator.validate_image')\
as mock_image_data: as mock_image_data:
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
@ -597,8 +600,9 @@ class TestPost(api_base.FunctionalTest):
@mock.patch('magnum.api.attr_validator.validate_image') @mock.patch('magnum.api.attr_validator.validate_image')
def test_create_cluster_template_with_labels(self, mock_image_data): def test_create_cluster_template_with_labels(self, mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock: self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock:
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
bdict = apiutils.cluster_template_post_data( bdict = apiutils.cluster_template_post_data(
@ -612,8 +616,9 @@ class TestPost(api_base.FunctionalTest):
@mock.patch('magnum.api.attr_validator.validate_image') @mock.patch('magnum.api.attr_validator.validate_image')
def test_create_cluster_template_with_docker_volume_size(self, def test_create_cluster_template_with_docker_volume_size(self,
mock_image_data): mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock: self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock:
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
bdict = apiutils.cluster_template_post_data(docker_volume_size=99) bdict = apiutils.cluster_template_post_data(docker_volume_size=99)
@ -625,8 +630,9 @@ class TestPost(api_base.FunctionalTest):
@mock.patch('magnum.api.attr_validator.validate_image') @mock.patch('magnum.api.attr_validator.validate_image')
def test_create_cluster_template_with_overlay(self, mock_image_data): def test_create_cluster_template_with_overlay(self, mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock: self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock:
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
bdict = apiutils.cluster_template_post_data( bdict = apiutils.cluster_template_post_data(
@ -648,8 +654,10 @@ class TestPost(api_base.FunctionalTest):
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
for k, v in cluster_template_config_dict.items(): for k, v in cluster_template_config_dict.items():
cfg.CONF.set_override(k, v, 'cluster_template') cfg.CONF.set_override(k, v, 'cluster_template')
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock: self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock:
bdict = apiutils.cluster_template_post_data( bdict = apiutils.cluster_template_post_data(
**cluster_template_dict) **cluster_template_dict)
response = self.post_json('/clustertemplates', bdict, response = self.post_json('/clustertemplates', bdict,
@ -713,8 +721,9 @@ class TestPost(api_base.FunctionalTest):
@mock.patch('magnum.api.attr_validator.validate_image') @mock.patch('magnum.api.attr_validator.validate_image')
def test_create_cluster_template_with_volume_driver(self, def test_create_cluster_template_with_volume_driver(self,
mock_image_data): mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock: self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock:
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
bdict = apiutils.cluster_template_post_data(volume_driver='rexray') bdict = apiutils.cluster_template_post_data(volume_driver='rexray')
@ -727,8 +736,9 @@ class TestPost(api_base.FunctionalTest):
@mock.patch('magnum.api.attr_validator.validate_image') @mock.patch('magnum.api.attr_validator.validate_image')
def test_create_cluster_template_with_no_volume_driver(self, def test_create_cluster_template_with_no_volume_driver(self,
mock_image_data): mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock: self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock:
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
bdict = apiutils.cluster_template_post_data() bdict = apiutils.cluster_template_post_data()
@ -742,8 +752,9 @@ class TestPost(api_base.FunctionalTest):
@mock.patch.object(magnum_policy, 'enforce') @mock.patch.object(magnum_policy, 'enforce')
def test_create_cluster_template_public_success(self, mock_policy, def test_create_cluster_template_public_success(self, mock_policy,
mock_image_data): mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock: self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock:
mock_policy.return_value = True mock_policy.return_value = True
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
@ -761,8 +772,8 @@ class TestPost(api_base.FunctionalTest):
@mock.patch.object(magnum_policy, 'enforce') @mock.patch.object(magnum_policy, 'enforce')
def test_create_cluster_template_public_fail(self, mock_policy, def test_create_cluster_template_public_fail(self, mock_policy,
mock_image_data): mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_baymodel): wraps=self.dbapi.create_cluster_template):
# make policy enforcement fail # make policy enforcement fail
mock_policy.return_value = False mock_policy.return_value = False
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
@ -775,8 +786,9 @@ class TestPost(api_base.FunctionalTest):
@mock.patch.object(magnum_policy, 'enforce') @mock.patch.object(magnum_policy, 'enforce')
def test_create_cluster_template_public_not_set(self, mock_policy, def test_create_cluster_template_public_not_set(self, mock_policy,
mock_image_data): mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(
wraps=self.dbapi.create_baymodel) as cc_mock: self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_cluster_template) as cc_mock:
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
bdict = apiutils.cluster_template_post_data(public=False) bdict = apiutils.cluster_template_post_data(public=False)
@ -926,8 +938,8 @@ class TestPost(api_base.FunctionalTest):
@mock.patch('magnum.api.attr_validator.validate_image') @mock.patch('magnum.api.attr_validator.validate_image')
def test_create_cluster_template_without_name(self, mock_image_data): def test_create_cluster_template_without_name(self, mock_image_data):
with mock.patch.object(self.dbapi, 'create_baymodel', with mock.patch.object(self.dbapi, 'create_cluster_template',
wraps=self.dbapi.create_baymodel): wraps=self.dbapi.create_cluster_template):
mock_image_data.return_value = {'name': 'mock_name', mock_image_data.return_value = {'name': 'mock_name',
'os_distro': 'fedora-atomic'} 'os_distro': 'fedora-atomic'}
bdict = apiutils.cluster_template_post_data() bdict = apiutils.cluster_template_post_data()

View File

@ -266,7 +266,7 @@ class TestAttrValidator(base.BaseTestCase):
@mock.patch('magnum.common.clients.OpenStackClients') @mock.patch('magnum.common.clients.OpenStackClients')
def test_validate_os_resources_with_invalid_flavor(self, def test_validate_os_resources_with_invalid_flavor(self,
mock_os_cli): mock_os_cli):
mock_baymodel = {'flavor_id': 'test_flavor'} mock_cluster_template = {'flavor_id': 'test_flavor'}
mock_flavor = mock.MagicMock() mock_flavor = mock.MagicMock()
mock_flavor.name = 'test_flavor_not_equal' mock_flavor.name = 'test_flavor_not_equal'
mock_flavor.id = 'test_flavor_id_not_equal' mock_flavor.id = 'test_flavor_id_not_equal'
@ -277,22 +277,23 @@ class TestAttrValidator(base.BaseTestCase):
mock_context = mock.MagicMock() mock_context = mock.MagicMock()
self.assertRaises(exception.FlavorNotFound, self.assertRaises(exception.FlavorNotFound,
attr_validator.validate_os_resources, attr_validator.validate_os_resources,
mock_context, mock_baymodel) mock_context, mock_cluster_template)
@mock.patch('magnum.common.clients.OpenStackClients') @mock.patch('magnum.common.clients.OpenStackClients')
@mock.patch('magnum.api.attr_validator.validate_labels') @mock.patch('magnum.api.attr_validator.validate_labels')
def test_validate_os_resources_with_label(self, mock_validate_labels, def test_validate_os_resources_with_label(self, mock_validate_labels,
mock_os_cli): mock_os_cli):
mock_baymodel = {'labels': {'mesos_slave_isolation': 'abc'}} mock_cluster_template = {'labels': {'mesos_slave_isolation': 'abc'}}
mock_context = mock.MagicMock() mock_context = mock.MagicMock()
self.assertRaises(exception.InvalidParameterValue, self.assertRaises(exception.InvalidParameterValue,
attr_validator.validate_os_resources, mock_context, attr_validator.validate_os_resources, mock_context,
mock_baymodel) mock_cluster_template)
@mock.patch('magnum.common.clients.OpenStackClients') @mock.patch('magnum.common.clients.OpenStackClients')
@mock.patch('magnum.api.attr_validator.validators') @mock.patch('magnum.api.attr_validator.validators')
def test_validate_os_resources_without_validator(self, mock_validators, def test_validate_os_resources_without_validator(self, mock_validators,
mock_os_cli): mock_os_cli):
mock_baymodel = {} mock_cluster_template = {}
mock_context = mock.MagicMock() mock_context = mock.MagicMock()
attr_validator.validate_os_resources(mock_context, mock_baymodel) attr_validator.validate_os_resources(mock_context,
mock_cluster_template)

View File

@ -44,11 +44,10 @@ class TestValidation(base.BaseTestCase):
context = mock_pecan_request.context context = mock_pecan_request.context
bay = mock.MagicMock() bay = mock.MagicMock()
bay.baymodel_id = 'baymodel_id' bay.baymodel_id = 'cluster_template_id'
baymodel = obj_utils.get_test_baymodel(context, cluster_template = obj_utils.get_test_cluster_template(
uuid='baymodel_id', context, uuid='cluster_template_id', coe=bay_type)
coe=bay_type) bay.cluster_template = cluster_template
bay.baymodel = baymodel
mock_bay_get_by_uuid.return_value = bay mock_bay_get_by_uuid.return_value = bay
@ -178,17 +177,18 @@ class TestValidation(base.BaseTestCase):
assert_raised=False): assert_raised=False):
@v.enforce_network_driver_types_create() @v.enforce_network_driver_types_create()
def test(self, baymodel): def test(self, cluster_template):
pass pass
for key, val in network_driver_config_dict.items(): for key, val in network_driver_config_dict.items():
cfg.CONF.set_override(key, val, 'cluster_template') cfg.CONF.set_override(key, val, 'cluster_template')
baymodel = mock.MagicMock()
baymodel.name = 'test_cluster_template'
baymodel.network_driver = network_driver_type
baymodel.coe = coe
# Reload the validator module so that baymodel configs are cluster_template = mock.MagicMock()
cluster_template.name = 'test_cluster_template'
cluster_template.network_driver = network_driver_type
cluster_template.coe = coe
# Reload the validator module so that ClusterTemplate configs are
# re-evaluated. # re-evaluated.
reload_module(v) reload_module(v)
validator = v.K8sValidator validator = v.K8sValidator
@ -196,10 +196,10 @@ class TestValidation(base.BaseTestCase):
if assert_raised: if assert_raised:
self.assertRaises(exception.InvalidParameterValue, self.assertRaises(exception.InvalidParameterValue,
test, self, baymodel) test, self, cluster_template)
else: else:
test(self, baymodel) test(self, cluster_template)
return baymodel return cluster_template
def test_enforce_network_driver_types_one_allowed_create(self): def test_enforce_network_driver_types_one_allowed_create(self):
self._test_enforce_network_driver_types_create( self._test_enforce_network_driver_types_create(
@ -235,17 +235,17 @@ class TestValidation(base.BaseTestCase):
assert_raised=True) assert_raised=True)
def test_enforce_network_driver_types_default_create(self): def test_enforce_network_driver_types_default_create(self):
baymodel = self._test_enforce_network_driver_types_create( cluster_template = self._test_enforce_network_driver_types_create(
network_driver_type=None, network_driver_type=None,
network_driver_config_dict={}) network_driver_config_dict={})
self.assertEqual('flannel', baymodel.network_driver) self.assertEqual('flannel', cluster_template.network_driver)
def test_enforce_network_driver_types_default_config_create(self): def test_enforce_network_driver_types_default_config_create(self):
baymodel = self._test_enforce_network_driver_types_create( cluster_template = self._test_enforce_network_driver_types_create(
network_driver_type=None, network_driver_type=None,
network_driver_config_dict={ network_driver_config_dict={
'kubernetes_default_network_driver': 'type1'}) 'kubernetes_default_network_driver': 'type1'})
self.assertEqual('type1', baymodel.network_driver) self.assertEqual('type1', cluster_template.network_driver)
def test_enforce_network_driver_types_default_invalid_create(self): def test_enforce_network_driver_types_default_invalid_create(self):
self._test_enforce_network_driver_types_create( self._test_enforce_network_driver_types_create(
@ -265,22 +265,23 @@ class TestValidation(base.BaseTestCase):
assert_raised=False): assert_raised=False):
@v.enforce_network_driver_types_update() @v.enforce_network_driver_types_update()
def test(self, baymodel_ident, patch): def test(self, cluster_template_ident, patch):
pass pass
for key, val in network_driver_config_dict.items(): for key, val in network_driver_config_dict.items():
cfg.CONF.set_override(key, val, 'cluster_template') cfg.CONF.set_override(key, val, 'cluster_template')
baymodel_ident = 'test_uuid_or_name'
cluster_template_ident = 'test_uuid_or_name'
patch = [{'path': '/network_driver', 'value': network_driver_type, patch = [{'path': '/network_driver', 'value': network_driver_type,
'op': 'replace'}] 'op': 'replace'}]
context = mock_pecan_request.context context = mock_pecan_request.context
baymodel = obj_utils.get_test_baymodel(context, cluster_template = obj_utils.get_test_cluster_template(
uuid=baymodel_ident, context, uuid=cluster_template_ident, coe='kubernetes')
coe='kubernetes') cluster_template.network_driver = network_driver_type
baymodel.network_driver = network_driver_type mock_get_resource.return_value = cluster_template
mock_get_resource.return_value = baymodel
# Reload the validator module so that baymodel configs are # Reload the validator module so that ClusterTemplate configs are
# re-evaluated. # re-evaluated.
reload_module(v) reload_module(v)
validator = v.K8sValidator validator = v.K8sValidator
@ -288,11 +289,11 @@ class TestValidation(base.BaseTestCase):
if assert_raised: if assert_raised:
self.assertRaises(exception.InvalidParameterValue, self.assertRaises(exception.InvalidParameterValue,
test, self, baymodel_ident, patch) test, self, cluster_template_ident, patch)
else: else:
test(self, baymodel_ident, patch) test(self, cluster_template_ident, patch)
mock_get_resource.assert_called_once_with( mock_get_resource.assert_called_once_with(
'BayModel', baymodel_ident) 'ClusterTemplate', cluster_template_ident)
def test_enforce_network_driver_types_one_allowed_update(self): def test_enforce_network_driver_types_one_allowed_update(self):
self._test_enforce_network_driver_types_update( self._test_enforce_network_driver_types_update(
@ -327,18 +328,18 @@ class TestValidation(base.BaseTestCase):
assert_raised=False): assert_raised=False):
@v.enforce_volume_driver_types_create() @v.enforce_volume_driver_types_create()
def test(self, baymodel): def test(self, cluster_template):
pass pass
baymodel = obj_utils.get_test_baymodel( cluster_template = obj_utils.get_test_cluster_template(
{}, name='test_baymodel', coe=coe, {}, name='test_cluster_template', coe=coe,
volume_driver=volume_driver_type) volume_driver=volume_driver_type)
if assert_raised: if assert_raised:
self.assertRaises(exception.InvalidParameterValue, self.assertRaises(exception.InvalidParameterValue,
test, self, baymodel) test, self, cluster_template)
else: else:
test(self, baymodel) test(self, cluster_template)
def test_enforce_volume_driver_types_valid_create(self): def test_enforce_volume_driver_types_valid_create(self):
self._test_enforce_volume_driver_types_create( self._test_enforce_volume_driver_types_create(
@ -360,19 +361,18 @@ class TestValidation(base.BaseTestCase):
assert_raised=False): assert_raised=False):
@v.enforce_volume_driver_types_update() @v.enforce_volume_driver_types_update()
def test(self, baymodel_ident, patch): def test(self, cluster_template_ident, patch):
pass pass
baymodel_ident = 'test_uuid_or_name' cluster_template_ident = 'test_uuid_or_name'
patch = [{'path': '/volume_driver', 'value': volume_driver_type, patch = [{'path': '/volume_driver', 'value': volume_driver_type,
'op': op}] 'op': op}]
context = mock_pecan_request.context context = mock_pecan_request.context
baymodel = obj_utils.get_test_baymodel(context, cluster_template = obj_utils.get_test_cluster_template(
uuid=baymodel_ident, context, uuid=cluster_template_ident, coe='kubernetes')
coe='kubernetes') mock_get_resource.return_value = cluster_template
mock_get_resource.return_value = baymodel
# Reload the validator module so that baymodel configs are # Reload the validator module so that ClusterTemplate configs are
# re-evaluated. # re-evaluated.
reload_module(v) reload_module(v)
validator = v.K8sValidator validator = v.K8sValidator
@ -380,11 +380,11 @@ class TestValidation(base.BaseTestCase):
if assert_raised: if assert_raised:
self.assertRaises(exception.InvalidParameterValue, self.assertRaises(exception.InvalidParameterValue,
test, self, baymodel_ident, patch) test, self, cluster_template_ident, patch)
else: else:
test(self, baymodel_ident, patch) test(self, cluster_template_ident, patch)
mock_get_resource.assert_called_once_with( mock_get_resource.assert_called_once_with(
'BayModel', baymodel_ident) 'ClusterTemplate', cluster_template_ident)
def test_enforce_volume_driver_types_supported_replace_update(self): def test_enforce_volume_driver_types_supported_replace_update(self):
self._test_enforce_volume_driver_types_update( self._test_enforce_volume_driver_types_update(

View File

@ -30,13 +30,13 @@ def remove_internal(values, internal):
def baymodel_post_data(**kw): def baymodel_post_data(**kw):
baymodel = utils.get_test_baymodel(**kw) baymodel = utils.get_test_cluster_template(**kw)
internal = baymodel_controller.BayModelPatchType.internal_attrs() internal = baymodel_controller.BayModelPatchType.internal_attrs()
return remove_internal(baymodel, internal) return remove_internal(baymodel, internal)
def cluster_template_post_data(**kw): def cluster_template_post_data(**kw):
cluster_template = utils.get_test_baymodel(**kw) cluster_template = utils.get_test_cluster_template(**kw)
internal = cluster_tmp_ctrl.ClusterTemplatePatchType.internal_attrs() internal = cluster_tmp_ctrl.ClusterTemplatePatchType.internal_attrs()
return remove_internal(cluster_template, internal) return remove_internal(cluster_template, internal)

View File

@ -38,9 +38,10 @@ class TestHandler(db_base.DbTestCase):
def setUp(self): def setUp(self):
super(TestHandler, self).setUp() super(TestHandler, self).setUp()
self.handler = bay_conductor.Handler() self.handler = bay_conductor.Handler()
baymodel_dict = utils.get_test_baymodel() cluster_template_dict = utils.get_test_cluster_template()
self.baymodel = objects.BayModel(self.context, **baymodel_dict) self.cluster_template = objects.ClusterTemplate(
self.baymodel.create() self.context, **cluster_template_dict)
self.cluster_template.create()
bay_dict = utils.get_test_bay(node_count=1) bay_dict = utils.get_test_bay(node_count=1)
self.bay = objects.Bay(self.context, **bay_dict) self.bay = objects.Bay(self.context, **bay_dict)
self.bay.create() self.bay.create()
@ -196,7 +197,7 @@ class TestHandler(db_base.DbTestCase):
# baymodel_id. Here update self.bay.baymodel_id so bay.obj_get_changes # baymodel_id. Here update self.bay.baymodel_id so bay.obj_get_changes
# will get notice that baymodel_id is updated and will update it # will get notice that baymodel_id is updated and will update it
# in db. # in db.
self.bay.baymodel_id = self.baymodel.uuid self.bay.baymodel_id = self.cluster_template.uuid
bay = self.handler.bay_create(self.context, bay = self.handler.bay_create(self.context,
self.bay, timeout) self.bay, timeout)
@ -378,7 +379,7 @@ class TestHandler(db_base.DbTestCase):
mock_process_mult, mock_process_mult,
mock_heat_poller_class): mock_heat_poller_class):
timeout = 15 timeout = 15
self.bay.baymodel_id = self.baymodel.uuid self.bay.baymodel_id = self.cluster_template.uuid
bay_name = self.bay.name bay_name = self.bay.name
mock_short_id.generate_id.return_value = 'short_id' mock_short_id.generate_id.return_value = 'short_id'
mock_poller = mock.MagicMock() mock_poller = mock.MagicMock()
@ -487,20 +488,23 @@ class TestHandler(db_base.DbTestCase):
class TestHeatPoller(base.TestCase): class TestHeatPoller(base.TestCase):
@patch('magnum.conductor.utils.retrieve_baymodel') @patch('magnum.conductor.utils.retrieve_cluster_template')
@patch('oslo_config.cfg') @patch('oslo_config.cfg')
@patch('magnum.common.clients.OpenStackClients') @patch('magnum.common.clients.OpenStackClients')
def setup_poll_test(self, mock_openstack_client, cfg, def setup_poll_test(self, mock_openstack_client, cfg,
mock_retrieve_baymodel): mock_retrieve_cluster_template):
cfg.CONF.cluster_heat.max_attempts = 10 cfg.CONF.cluster_heat.max_attempts = 10
bay = mock.MagicMock() bay = mock.MagicMock()
baymodel_dict = utils.get_test_baymodel(coe='kubernetes') cluster_template_dict = utils.get_test_cluster_template(
coe='kubernetes')
mock_heat_stack = mock.MagicMock() mock_heat_stack = mock.MagicMock()
mock_heat_client = mock.MagicMock() mock_heat_client = mock.MagicMock()
mock_heat_client.stacks.get.return_value = mock_heat_stack mock_heat_client.stacks.get.return_value = mock_heat_stack
mock_openstack_client.heat.return_value = mock_heat_client mock_openstack_client.heat.return_value = mock_heat_client
baymodel = objects.BayModel(self.context, **baymodel_dict) cluster_template = objects.ClusterTemplate(self.context,
mock_retrieve_baymodel.return_value = baymodel **cluster_template_dict)
mock_retrieve_cluster_template.return_value = cluster_template
poller = bay_conductor.HeatPoller(mock_openstack_client, bay) poller = bay_conductor.HeatPoller(mock_openstack_client, bay)
poller.get_version_info = mock.MagicMock() poller.get_version_info = mock.MagicMock()
return (mock_heat_stack, bay, poller) return (mock_heat_stack, bay, poller)

View File

@ -24,7 +24,7 @@ from magnum.tests import base
class TestBayConductorWithK8s(base.TestCase): class TestBayConductorWithK8s(base.TestCase):
def setUp(self): def setUp(self):
super(TestBayConductorWithK8s, self).setUp() super(TestBayConductorWithK8s, self).setUp()
self.baymodel_dict = { self.cluster_template_dict = {
'image_id': 'image_id', 'image_id': 'image_id',
'flavor_id': 'flavor_id', 'flavor_id': 'flavor_id',
'master_flavor_id': 'master_flavor_id', 'master_flavor_id': 'master_flavor_id',
@ -85,25 +85,27 @@ class TestBayConductorWithK8s(base.TestCase):
self.mock_osc_class.return_value = self.mock_osc self.mock_osc_class.return_value = self.mock_osc
@patch('requests.get') @patch('requests.get')
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition( def test_extract_template_definition(
self, self,
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get): mock_get):
self._test_extract_template_definition( self._test_extract_template_definition(
mock_objects_baymodel_get_by_uuid, mock_get) mock_objects_cluster_template_get_by_uuid, mock_get)
def _test_extract_template_definition( def _test_extract_template_definition(
self, self,
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get, mock_get,
missing_attr=None): missing_attr=None):
if missing_attr in self.baymodel_dict: if missing_attr in self.cluster_template_dict:
self.baymodel_dict[missing_attr] = None self.cluster_template_dict[missing_attr] = None
elif missing_attr in self.bay_dict: elif missing_attr in self.bay_dict:
self.bay_dict[missing_attr] = None self.bay_dict[missing_attr] = None
baymodel = objects.BayModel(self.context, **self.baymodel_dict) cluster_template = objects.ClusterTemplate(
mock_objects_baymodel_get_by_uuid.return_value = baymodel self.context, **self.cluster_template_dict)
mock_objects_cluster_template_get_by_uuid.return_value = \
cluster_template
expected_result = str('{"action":"get","node":{"key":"test","value":' expected_result = str('{"action":"get","node":{"key":"test","value":'
'"1","modifiedIndex":10,"createdIndex":10}}') '"1","modifiedIndex":10,"createdIndex":10}}')
mock_resp = mock.MagicMock() mock_resp = mock.MagicMock()
@ -186,14 +188,16 @@ class TestBayConductorWithK8s(base.TestCase):
env_files) env_files)
@patch('requests.get') @patch('requests.get')
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_with_registry( def test_extract_template_definition_with_registry(
self, self,
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get): mock_get):
self.baymodel_dict['registry_enabled'] = True self.cluster_template_dict['registry_enabled'] = True
baymodel = objects.BayModel(self.context, **self.baymodel_dict) cluster_template = objects.ClusterTemplate(
mock_objects_baymodel_get_by_uuid.return_value = baymodel self.context, **self.cluster_template_dict)
mock_objects_cluster_template_get_by_uuid.return_value = \
cluster_template
expected_result = str('{"action":"get","node":{"key":"test","value":' expected_result = str('{"action":"get","node":{"key":"test","value":'
'"1","modifiedIndex":10,"createdIndex":10}}') '"1","modifiedIndex":10,"createdIndex":10}}')
mock_resp = mock.MagicMock() mock_resp = mock.MagicMock()
@ -256,14 +260,16 @@ class TestBayConductorWithK8s(base.TestCase):
env_files) env_files)
@patch('requests.get') @patch('requests.get')
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_coreos_with_disovery( def test_extract_template_definition_coreos_with_disovery(
self, self,
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get): mock_get):
self.baymodel_dict['cluster_distro'] = 'coreos' self.cluster_template_dict['cluster_distro'] = 'coreos'
baymodel = objects.BayModel(self.context, **self.baymodel_dict) cluster_template = objects.ClusterTemplate(
mock_objects_baymodel_get_by_uuid.return_value = baymodel self.context, **self.cluster_template_dict)
mock_objects_cluster_template_get_by_uuid.return_value = \
cluster_template
expected_result = str('{"action":"get","node":{"key":"test","value":' expected_result = str('{"action":"get","node":{"key":"test","value":'
'"1","modifiedIndex":10,"createdIndex":10}}') '"1","modifiedIndex":10,"createdIndex":10}}')
mock_resp = mock.MagicMock() mock_resp = mock.MagicMock()
@ -313,17 +319,19 @@ class TestBayConductorWithK8s(base.TestCase):
env_files) env_files)
@patch('requests.get') @patch('requests.get')
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_coreos_no_discoveryurl( def test_extract_template_definition_coreos_no_discoveryurl(
self, self,
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
reqget): reqget):
self.baymodel_dict['cluster_distro'] = 'coreos' self.cluster_template_dict['cluster_distro'] = 'coreos'
self.bay_dict['discovery_url'] = None self.bay_dict['discovery_url'] = None
mock_req = mock.MagicMock(text='http://tokentest/h1/h2/h3') mock_req = mock.MagicMock(text='http://tokentest/h1/h2/h3')
reqget.return_value = mock_req reqget.return_value = mock_req
baymodel = objects.BayModel(self.context, **self.baymodel_dict) cluster_template = objects.ClusterTemplate(
mock_objects_baymodel_get_by_uuid.return_value = baymodel self.context, **self.cluster_template_dict)
mock_objects_cluster_template_get_by_uuid.return_value = \
cluster_template
bay = objects.Bay(self.context, **self.bay_dict) bay = objects.Bay(self.context, **self.bay_dict)
(template_path, (template_path,
@ -368,112 +376,114 @@ class TestBayConductorWithK8s(base.TestCase):
env_files) env_files)
@patch('requests.get') @patch('requests.get')
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_without_dns( def test_extract_template_definition_without_dns(
self, self,
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get): mock_get):
self._test_extract_template_definition( self._test_extract_template_definition(
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get, mock_get,
missing_attr='dns_nameserver') missing_attr='dns_nameserver')
@patch('requests.get') @patch('requests.get')
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_without_server_image( def test_extract_template_definition_without_server_image(
self, self,
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get): mock_get):
self._test_extract_template_definition( self._test_extract_template_definition(
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get, mock_get,
missing_attr='image_id') missing_attr='image_id')
@patch('requests.get') @patch('requests.get')
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_without_minion_flavor( def test_extract_template_definition_without_minion_flavor(
self, self,
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get): mock_get):
self._test_extract_template_definition( self._test_extract_template_definition(
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get, mock_get,
missing_attr='flavor_id') missing_attr='flavor_id')
@patch('requests.get') @patch('requests.get')
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_without_docker_volume_size( def test_extract_template_definition_without_docker_volume_size(
self, self,
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get): mock_get):
self._test_extract_template_definition( self._test_extract_template_definition(
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get, mock_get,
missing_attr='docker_volume_size') missing_attr='docker_volume_size')
@patch('requests.get') @patch('requests.get')
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_without_docker_storage_driver( def test_extract_template_definition_without_docker_storage_driver(
self, self,
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get): mock_get):
self._test_extract_template_definition( self._test_extract_template_definition(
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get, mock_get,
missing_attr='docker_storage_driver') missing_attr='docker_storage_driver')
@patch('requests.get') @patch('requests.get')
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_without_master_flavor( def test_extract_template_definition_without_master_flavor(
self, self,
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get): mock_get):
self._test_extract_template_definition( self._test_extract_template_definition(
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get, mock_get,
missing_attr='master_flavor_id') missing_attr='master_flavor_id')
@patch('requests.get') @patch('requests.get')
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_without_apiserver_port( def test_extract_template_definition_without_apiserver_port(
self, self,
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get): mock_get):
self._test_extract_template_definition( self._test_extract_template_definition(
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get, mock_get,
missing_attr='apiserver_port') missing_attr='apiserver_port')
@patch('requests.get') @patch('requests.get')
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_without_node_count( def test_extract_template_definition_without_node_count(
self, self,
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get): mock_get):
self._test_extract_template_definition( self._test_extract_template_definition(
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get, mock_get,
missing_attr='node_count') missing_attr='node_count')
@patch('requests.get') @patch('requests.get')
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_without_master_count( def test_extract_template_definition_without_master_count(
self, self,
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get): mock_get):
self._test_extract_template_definition( self._test_extract_template_definition(
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get, mock_get,
missing_attr='master_count') missing_attr='master_count')
@patch('requests.get') @patch('requests.get')
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_without_discovery_url( def test_extract_template_definition_without_discovery_url(
self, self,
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
reqget): reqget):
baymodel = objects.BayModel(self.context, **self.baymodel_dict) cluster_template = objects.ClusterTemplate(
mock_objects_baymodel_get_by_uuid.return_value = baymodel self.context, **self.cluster_template_dict)
mock_objects_cluster_template_get_by_uuid.return_value = \
cluster_template
bay_dict = self.bay_dict bay_dict = self.bay_dict
bay_dict['discovery_url'] = None bay_dict['discovery_url'] = None
bay = objects.Bay(self.context, **bay_dict) bay = objects.Bay(self.context, **bay_dict)

View File

@ -25,7 +25,7 @@ from magnum.tests import base
class TestBayConductorWithMesos(base.TestCase): class TestBayConductorWithMesos(base.TestCase):
def setUp(self): def setUp(self):
super(TestBayConductorWithMesos, self).setUp() super(TestBayConductorWithMesos, self).setUp()
self.baymodel_dict = { self.cluster_template_dict = {
'image_id': 'image_id', 'image_id': 'image_id',
'flavor_id': 'flavor_id', 'flavor_id': 'flavor_id',
'master_flavor_id': 'master_flavor_id', 'master_flavor_id': 'master_flavor_id',
@ -77,12 +77,14 @@ class TestBayConductorWithMesos(base.TestCase):
self.mock_osc.keystone.return_value = self.mock_keystone self.mock_osc.keystone.return_value = self.mock_keystone
self.mock_osc_class.return_value = self.mock_osc self.mock_osc_class.return_value = self.mock_osc
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_all_values( def test_extract_template_definition_all_values(
self, self,
mock_objects_baymodel_get_by_uuid): mock_objects_cluster_template_get_by_uuid):
baymodel = objects.BayModel(self.context, **self.baymodel_dict) cluster_template = objects.ClusterTemplate(
mock_objects_baymodel_get_by_uuid.return_value = baymodel self.context, **self.cluster_template_dict)
mock_objects_cluster_template_get_by_uuid.return_value = \
cluster_template
bay = objects.Bay(self.context, **self.bay_dict) bay = objects.Bay(self.context, **self.bay_dict)
(template_path, (template_path,
@ -125,18 +127,20 @@ class TestBayConductorWithMesos(base.TestCase):
['../../common/templates/environments/no_master_lb.yaml'], ['../../common/templates/environments/no_master_lb.yaml'],
env_files) env_files)
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_only_required( def test_extract_template_definition_only_required(
self, self,
mock_objects_baymodel_get_by_uuid): mock_objects_cluster_template_get_by_uuid):
not_required = ['image_id', 'master_flavor_id', 'flavor_id', not_required = ['image_id', 'master_flavor_id', 'flavor_id',
'dns_nameserver', 'fixed_network', 'http_proxy', 'dns_nameserver', 'fixed_network', 'http_proxy',
'https_proxy', 'no_proxy', 'volume_driver'] 'https_proxy', 'no_proxy', 'volume_driver']
for key in not_required: for key in not_required:
self.baymodel_dict[key] = None self.cluster_template_dict[key] = None
baymodel = objects.BayModel(self.context, **self.baymodel_dict) cluster_template = objects.ClusterTemplate(
mock_objects_baymodel_get_by_uuid.return_value = baymodel self.context, **self.cluster_template_dict)
mock_objects_cluster_template_get_by_uuid.return_value = \
cluster_template
bay = objects.Bay(self.context, **self.bay_dict) bay = objects.Bay(self.context, **self.bay_dict)
(template_path, (template_path,
@ -171,13 +175,15 @@ class TestBayConductorWithMesos(base.TestCase):
['../../common/templates/environments/no_master_lb.yaml'], ['../../common/templates/environments/no_master_lb.yaml'],
env_files) env_files)
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_with_lb( def test_extract_template_definition_with_lb(
self, self,
mock_objects_baymodel_get_by_uuid): mock_objects_cluster_template_get_by_uuid):
self.baymodel_dict['master_lb_enabled'] = True self.cluster_template_dict['master_lb_enabled'] = True
baymodel = objects.BayModel(self.context, **self.baymodel_dict) cluster_template = objects.ClusterTemplate(
mock_objects_baymodel_get_by_uuid.return_value = baymodel self.context, **self.cluster_template_dict)
mock_objects_cluster_template_get_by_uuid.return_value = \
cluster_template
bay = objects.Bay(self.context, **self.bay_dict) bay = objects.Bay(self.context, **self.bay_dict)
(template_path, (template_path,
@ -220,14 +226,16 @@ class TestBayConductorWithMesos(base.TestCase):
['../../common/templates/environments/with_master_lb.yaml'], ['../../common/templates/environments/with_master_lb.yaml'],
env_files) env_files)
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_multi_master( def test_extract_template_definition_multi_master(
self, self,
mock_objects_baymodel_get_by_uuid): mock_objects_cluster_template_get_by_uuid):
self.baymodel_dict['master_lb_enabled'] = True self.cluster_template_dict['master_lb_enabled'] = True
self.bay_dict['master_count'] = 2 self.bay_dict['master_count'] = 2
baymodel = objects.BayModel(self.context, **self.baymodel_dict) cluster_template = objects.ClusterTemplate(
mock_objects_baymodel_get_by_uuid.return_value = baymodel self.context, **self.cluster_template_dict)
mock_objects_cluster_template_get_by_uuid.return_value = \
cluster_template
bay = objects.Bay(self.context, **self.bay_dict) bay = objects.Bay(self.context, **self.bay_dict)
(template_path, (template_path,
@ -270,19 +278,21 @@ class TestBayConductorWithMesos(base.TestCase):
['../../common/templates/environments/with_master_lb.yaml'], ['../../common/templates/environments/with_master_lb.yaml'],
env_files) env_files)
@patch('magnum.conductor.utils.retrieve_baymodel') @patch('magnum.conductor.utils.retrieve_cluster_template')
@patch('oslo_config.cfg') @patch('oslo_config.cfg')
@patch('magnum.common.clients.OpenStackClients') @patch('magnum.common.clients.OpenStackClients')
def setup_poll_test(self, mock_openstack_client, cfg, def setup_poll_test(self, mock_openstack_client, cfg,
mock_retrieve_baymodel): mock_retrieve_cluster_template):
cfg.CONF.cluster_heat.max_attempts = 10 cfg.CONF.cluster_heat.max_attempts = 10
bay = mock.MagicMock() bay = mock.MagicMock()
mock_heat_stack = mock.MagicMock() mock_heat_stack = mock.MagicMock()
mock_heat_client = mock.MagicMock() mock_heat_client = mock.MagicMock()
mock_heat_client.stacks.get.return_value = mock_heat_stack mock_heat_client.stacks.get.return_value = mock_heat_stack
mock_openstack_client.heat.return_value = mock_heat_client mock_openstack_client.heat.return_value = mock_heat_client
baymodel = objects.BayModel(self.context, **self.baymodel_dict) cluster_template = objects.ClusterTemplate(
mock_retrieve_baymodel.return_value = baymodel self.context, **self.cluster_template_dict)
mock_retrieve_cluster_template.return_value = cluster_template
poller = bay_conductor.HeatPoller(mock_openstack_client, bay) poller = bay_conductor.HeatPoller(mock_openstack_client, bay)
poller.get_version_info = mock.MagicMock() poller.get_version_info = mock.MagicMock()
return (mock_heat_stack, bay, poller) return (mock_heat_stack, bay, poller)

View File

@ -26,7 +26,7 @@ from magnum.tests import base
class TestBayConductorWithSwarm(base.TestCase): class TestBayConductorWithSwarm(base.TestCase):
def setUp(self): def setUp(self):
super(TestBayConductorWithSwarm, self).setUp() super(TestBayConductorWithSwarm, self).setUp()
self.baymodel_dict = { self.cluster_template_dict = {
'image_id': 'image_id', 'image_id': 'image_id',
'flavor_id': 'flavor_id', 'flavor_id': 'flavor_id',
'master_flavor_id': 'master_flavor_id', 'master_flavor_id': 'master_flavor_id',
@ -78,13 +78,15 @@ class TestBayConductorWithSwarm(base.TestCase):
self.context.auth_url = 'http://192.168.10.10:5000/v3' self.context.auth_url = 'http://192.168.10.10:5000/v3'
@patch('requests.get') @patch('requests.get')
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_all_values( def test_extract_template_definition_all_values(
self, self,
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get): mock_get):
baymodel = objects.BayModel(self.context, **self.baymodel_dict) cluster_template = objects.ClusterTemplate(
mock_objects_baymodel_get_by_uuid.return_value = baymodel self.context, **self.cluster_template_dict)
mock_objects_cluster_template_get_by_uuid.return_value = \
cluster_template
expected_result = str('{"action":"get","node":{"key":"test","value":' expected_result = str('{"action":"get","node":{"key":"test","value":'
'"1","modifiedIndex":10,"createdIndex":10}}') '"1","modifiedIndex":10,"createdIndex":10}}')
mock_resp = mock.MagicMock() mock_resp = mock.MagicMock()
@ -134,14 +136,16 @@ class TestBayConductorWithSwarm(base.TestCase):
env_files) env_files)
@patch('requests.get') @patch('requests.get')
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_with_registry( def test_extract_template_definition_with_registry(
self, self,
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get): mock_get):
self.baymodel_dict['registry_enabled'] = True self.cluster_template_dict['registry_enabled'] = True
baymodel = objects.BayModel(self.context, **self.baymodel_dict) cluster_template = objects.ClusterTemplate(
mock_objects_baymodel_get_by_uuid.return_value = baymodel self.context, **self.cluster_template_dict)
mock_objects_cluster_template_get_by_uuid.return_value = \
cluster_template
expected_result = str('{"action":"get","node":{"key":"test","value":' expected_result = str('{"action":"get","node":{"key":"test","value":'
'"1","modifiedIndex":10,"createdIndex":10}}') '"1","modifiedIndex":10,"createdIndex":10}}')
mock_resp = mock.MagicMock() mock_resp = mock.MagicMock()
@ -197,10 +201,10 @@ class TestBayConductorWithSwarm(base.TestCase):
env_files) env_files)
@patch('requests.get') @patch('requests.get')
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_only_required( def test_extract_template_definition_only_required(
self, self,
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get): mock_get):
not_required = ['image_id', 'flavor_id', 'dns_nameserver', not_required = ['image_id', 'flavor_id', 'dns_nameserver',
@ -208,11 +212,13 @@ class TestBayConductorWithSwarm(base.TestCase):
'https_proxy', 'no_proxy', 'network_driver', 'https_proxy', 'no_proxy', 'network_driver',
'master_flavor_id', 'docker_storage_driver'] 'master_flavor_id', 'docker_storage_driver']
for key in not_required: for key in not_required:
self.baymodel_dict[key] = None self.cluster_template_dict[key] = None
self.bay_dict['discovery_url'] = 'https://discovery.etcd.io/test' self.bay_dict['discovery_url'] = 'https://discovery.etcd.io/test'
baymodel = objects.BayModel(self.context, **self.baymodel_dict) cluster_template = objects.ClusterTemplate(
mock_objects_baymodel_get_by_uuid.return_value = baymodel self.context, **self.cluster_template_dict)
mock_objects_cluster_template_get_by_uuid.return_value = \
cluster_template
expected_result = str('{"action":"get","node":{"key":"test","value":' expected_result = str('{"action":"get","node":{"key":"test","value":'
'"1","modifiedIndex":10,"createdIndex":10}}') '"1","modifiedIndex":10,"createdIndex":10}}')
mock_resp = mock.MagicMock() mock_resp = mock.MagicMock()
@ -252,14 +258,16 @@ class TestBayConductorWithSwarm(base.TestCase):
env_files) env_files)
@patch('requests.get') @patch('requests.get')
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_with_lb( def test_extract_template_definition_with_lb(
self, self,
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get): mock_get):
self.baymodel_dict['master_lb_enabled'] = True self.cluster_template_dict['master_lb_enabled'] = True
baymodel = objects.BayModel(self.context, **self.baymodel_dict) cluster_template = objects.ClusterTemplate(
mock_objects_baymodel_get_by_uuid.return_value = baymodel self.context, **self.cluster_template_dict)
mock_objects_cluster_template_get_by_uuid.return_value = \
cluster_template
expected_result = str('{"action":"get","node":{"key":"test","value":' expected_result = str('{"action":"get","node":{"key":"test","value":'
'"1","modifiedIndex":10,"createdIndex":10}}') '"1","modifiedIndex":10,"createdIndex":10}}')
mock_resp = mock.MagicMock() mock_resp = mock.MagicMock()
@ -309,15 +317,17 @@ class TestBayConductorWithSwarm(base.TestCase):
env_files) env_files)
@patch('requests.get') @patch('requests.get')
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_extract_template_definition_multi_master( def test_extract_template_definition_multi_master(
self, self,
mock_objects_baymodel_get_by_uuid, mock_objects_cluster_template_get_by_uuid,
mock_get): mock_get):
self.baymodel_dict['master_lb_enabled'] = True self.cluster_template_dict['master_lb_enabled'] = True
self.bay_dict['master_count'] = 2 self.bay_dict['master_count'] = 2
baymodel = objects.BayModel(self.context, **self.baymodel_dict) cluster_template = objects.ClusterTemplate(
mock_objects_baymodel_get_by_uuid.return_value = baymodel self.context, **self.cluster_template_dict)
mock_objects_cluster_template_get_by_uuid.return_value = \
cluster_template
expected_result = str('{"action":"get","node":{"key":"test","value":' expected_result = str('{"action":"get","node":{"key":"test","value":'
'"2","modifiedIndex":10,"createdIndex":10}}') '"2","modifiedIndex":10,"createdIndex":10}}')
mock_resp = mock.MagicMock() mock_resp = mock.MagicMock()
@ -366,19 +376,22 @@ class TestBayConductorWithSwarm(base.TestCase):
['../../common/templates/environments/with_master_lb.yaml'], ['../../common/templates/environments/with_master_lb.yaml'],
env_files) env_files)
@patch('magnum.conductor.utils.retrieve_baymodel') @patch('magnum.conductor.utils.retrieve_cluster_template')
@patch('oslo_config.cfg') @patch('oslo_config.cfg')
@patch('magnum.common.clients.OpenStackClients') @patch('magnum.common.clients.OpenStackClients')
def setup_poll_test(self, mock_openstack_client, cfg, def setup_poll_test(self, mock_openstack_client, cfg,
mock_retrieve_baymodel): mock_retrieve_cluster_template):
cfg.CONF.cluster_heat.max_attempts = 10 cfg.CONF.cluster_heat.max_attempts = 10
bay = mock.MagicMock() bay = mock.MagicMock()
mock_heat_stack = mock.MagicMock() mock_heat_stack = mock.MagicMock()
mock_heat_client = mock.MagicMock() mock_heat_client = mock.MagicMock()
mock_heat_client.stacks.get.return_value = mock_heat_stack mock_heat_client.stacks.get.return_value = mock_heat_stack
mock_openstack_client.heat.return_value = mock_heat_client mock_openstack_client.heat.return_value = mock_heat_client
baymodel = objects.BayModel(self.context, **self.baymodel_dict) cluster_template = objects.ClusterTemplate(
mock_retrieve_baymodel.return_value = baymodel self.context, **self.cluster_template_dict)
mock_retrieve_cluster_template.return_value = \
cluster_template
poller = bay_conductor.HeatPoller(mock_openstack_client, bay) poller = bay_conductor.HeatPoller(mock_openstack_client, bay)
poller.get_version_info = mock.MagicMock() poller.get_version_info = mock.MagicMock()
return (mock_heat_stack, bay, poller) return (mock_heat_stack, bay, poller)

View File

@ -57,19 +57,19 @@ class MonitorsTestCase(base.TestCase):
self.addCleanup(p.stop) self.addCleanup(p.stop)
def test_create_monitor_success(self): def test_create_monitor_success(self):
self.bay.baymodel = obj_utils.get_test_baymodel( self.bay.cluster_template = obj_utils.get_test_cluster_template(
self.context, uuid=self.bay.baymodel_id, coe='swarm') self.context, uuid=self.bay.baymodel_id, coe='swarm')
monitor = monitors.create_monitor(self.context, self.bay) monitor = monitors.create_monitor(self.context, self.bay)
self.assertIsInstance(monitor, swarm_monitor.SwarmMonitor) self.assertIsInstance(monitor, swarm_monitor.SwarmMonitor)
def test_create_monitor_k8s_bay(self): def test_create_monitor_k8s_bay(self):
self.bay.baymodel = obj_utils.get_test_baymodel( self.bay.cluster_template = obj_utils.get_test_cluster_template(
self.context, uuid=self.bay.baymodel_id, coe='kubernetes') self.context, uuid=self.bay.baymodel_id, coe='kubernetes')
monitor = monitors.create_monitor(self.context, self.bay) monitor = monitors.create_monitor(self.context, self.bay)
self.assertIsInstance(monitor, k8s_monitor.K8sMonitor) self.assertIsInstance(monitor, k8s_monitor.K8sMonitor)
def test_create_monitor_mesos_bay(self): def test_create_monitor_mesos_bay(self):
self.bay.baymodel = obj_utils.get_test_baymodel( self.bay.cluster_template = obj_utils.get_test_cluster_template(
self.context, uuid=self.bay.baymodel_id, coe='mesos') self.context, uuid=self.bay.baymodel_id, coe='mesos')
monitor = monitors.create_monitor(self.context, self.bay) monitor = monitors.create_monitor(self.context, self.bay)
self.assertIsInstance(monitor, mesos_monitor.MesosMonitor) self.assertIsInstance(monitor, mesos_monitor.MesosMonitor)

View File

@ -34,19 +34,20 @@ class TestConductorUtils(base.TestCase):
def _get_type_uri(self): def _get_type_uri(self):
return 'service/security/account/user' return 'service/security/account/user'
@patch('magnum.objects.BayModel.get_by_uuid') @patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_retrieve_baymodel(self, mock_baymodel_get_by_uuid): def test_retrieve_cluster_template(self,
mock_cluster_template_get_by_uuid):
expected_context = 'context' expected_context = 'context'
expected_baymodel_uuid = 'baymodel_uuid' expected_cluster_template_uuid = 'ClusterTemplate_uuid'
bay = objects.Bay({}) bay = objects.Bay({})
bay.baymodel_id = expected_baymodel_uuid bay.baymodel_id = expected_cluster_template_uuid
utils.retrieve_baymodel(expected_context, bay) utils.retrieve_cluster_template(expected_context, bay)
mock_baymodel_get_by_uuid.assert_called_once_with( mock_cluster_template_get_by_uuid.assert_called_once_with(
expected_context, expected_context,
expected_baymodel_uuid) expected_cluster_template_uuid)
@patch('oslo_utils.uuidutils.is_uuid_like') @patch('oslo_utils.uuidutils.is_uuid_like')
@patch('magnum.objects.Bay.get_by_name') @patch('magnum.objects.Bay.get_by_name')

View File

@ -23,24 +23,24 @@ from magnum.tests.unit.db import base
class SqlAlchemyCustomTypesTestCase(base.DbTestCase): class SqlAlchemyCustomTypesTestCase(base.DbTestCase):
def test_JSONEncodedDict_default_value(self): def test_JSONEncodedDict_default_value(self):
# Create baymodel w/o labels # Create ClusterTemplate w/o labels
baymodel1_id = uuidutils.generate_uuid() cluster_template1_id = uuidutils.generate_uuid()
self.dbapi.create_baymodel({'uuid': baymodel1_id}) self.dbapi.create_cluster_template({'uuid': cluster_template1_id})
baymodel1 = sa_api.model_query( cluster_template1 = sa_api.model_query(
models.BayModel).filter_by(uuid=baymodel1_id).one() models.ClusterTemplate).filter_by(uuid=cluster_template1_id).one()
self.assertEqual({}, baymodel1.labels) self.assertEqual({}, cluster_template1.labels)
# Create baymodel with labels # Create ClusterTemplate with labels
baymodel2_id = uuidutils.generate_uuid() cluster_template2_id = uuidutils.generate_uuid()
self.dbapi.create_baymodel( self.dbapi.create_cluster_template(
{'uuid': baymodel2_id, 'labels': {'bar': 'foo'}}) {'uuid': cluster_template2_id, 'labels': {'bar': 'foo'}})
baymodel2 = sa_api.model_query( cluster_template2 = sa_api.model_query(
models.BayModel).filter_by(uuid=baymodel2_id).one() models.ClusterTemplate).filter_by(uuid=cluster_template2_id).one()
self.assertEqual('foo', baymodel2.labels['bar']) self.assertEqual('foo', cluster_template2.labels['bar'])
def test_JSONEncodedDict_type_check(self): def test_JSONEncodedDict_type_check(self):
self.assertRaises(db_exc.DBError, self.assertRaises(db_exc.DBError,
self.dbapi.create_baymodel, self.dbapi.create_cluster_template,
{'labels': {'labels':
['this is not a dict']}) ['this is not a dict']})

View File

@ -88,20 +88,22 @@ class DbBayTestCase(base.DbTestCase):
sort_key='foo') sort_key='foo')
def test_get_bay_list_with_filters(self): def test_get_bay_list_with_filters(self):
bm1 = utils.get_test_baymodel(id=1, uuid=uuidutils.generate_uuid()) ct1 = utils.get_test_cluster_template(id=1,
bm2 = utils.get_test_baymodel(id=2, uuid=uuidutils.generate_uuid()) uuid=uuidutils.generate_uuid())
self.dbapi.create_baymodel(bm1) ct2 = utils.get_test_cluster_template(id=2,
self.dbapi.create_baymodel(bm2) uuid=uuidutils.generate_uuid())
self.dbapi.create_cluster_template(ct1)
self.dbapi.create_cluster_template(ct2)
bay1 = utils.create_test_bay( bay1 = utils.create_test_bay(
name='bay-one', name='bay-one',
uuid=uuidutils.generate_uuid(), uuid=uuidutils.generate_uuid(),
baymodel_id=bm1['uuid'], baymodel_id=ct1['uuid'],
status=bay_status.CREATE_IN_PROGRESS) status=bay_status.CREATE_IN_PROGRESS)
bay2 = utils.create_test_bay( bay2 = utils.create_test_bay(
name='bay-two', name='bay-two',
uuid=uuidutils.generate_uuid(), uuid=uuidutils.generate_uuid(),
baymodel_id=bm2['uuid'], baymodel_id=ct2['uuid'],
node_count=1, node_count=1,
master_count=1, master_count=1,
status=bay_status.UPDATE_IN_PROGRESS) status=bay_status.UPDATE_IN_PROGRESS)
@ -112,11 +114,11 @@ class DbBayTestCase(base.DbTestCase):
status=bay_status.DELETE_IN_PROGRESS) status=bay_status.DELETE_IN_PROGRESS)
res = self.dbapi.get_bay_list(self.context, res = self.dbapi.get_bay_list(self.context,
filters={'baymodel_id': bm1['uuid']}) filters={'baymodel_id': ct1['uuid']})
self.assertEqual([bay1.id], [r.id for r in res]) self.assertEqual([bay1.id], [r.id for r in res])
res = self.dbapi.get_bay_list(self.context, res = self.dbapi.get_bay_list(self.context,
filters={'baymodel_id': bm2['uuid']}) filters={'baymodel_id': ct2['uuid']})
self.assertEqual([bay2.id], [r.id for r in res]) self.assertEqual([bay2.id], [r.id for r in res])
res = self.dbapi.get_bay_list(self.context, res = self.dbapi.get_bay_list(self.context,

View File

@ -1,182 +0,0 @@
# Copyright 2015 OpenStack Foundation
# All Rights Reserved.
#
# 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.
"""Tests for manipulating Baymodel via the DB API"""
from oslo_utils import uuidutils
import six
from magnum.common import exception
from magnum.tests.unit.db import base
from magnum.tests.unit.db import utils
class DbBaymodelTestCase(base.DbTestCase):
def test_create_baymodel(self):
utils.create_test_baymodel()
def test_get_baymodel_list(self):
uuids = []
for i in range(1, 6):
bm = utils.create_test_baymodel(id=i,
uuid=uuidutils.generate_uuid())
uuids.append(six.text_type(bm['uuid']))
res = self.dbapi.get_baymodel_list(self.context)
res_uuids = [r.uuid for r in res]
self.assertEqual(sorted(uuids), sorted(res_uuids))
def test_get_baymodel_list_sorted(self):
uuids = []
for _ in range(5):
bm = utils.create_test_baymodel(uuid=uuidutils.generate_uuid())
uuids.append(six.text_type(bm['uuid']))
res = self.dbapi.get_baymodel_list(self.context, sort_key='uuid')
res_uuids = [r.uuid for r in res]
self.assertEqual(sorted(uuids), res_uuids)
self.assertRaises(exception.InvalidParameterValue,
self.dbapi.get_baymodel_list,
self.context,
sort_key='foo')
def test_get_baymodel_list_with_filters(self):
bm1 = utils.create_test_baymodel(
id=1,
name='bm-one',
uuid=uuidutils.generate_uuid(),
image_id='image1')
bm2 = utils.create_test_baymodel(
id=2,
name='bm-two',
uuid=uuidutils.generate_uuid(),
image_id='image2')
res = self.dbapi.get_baymodel_list(self.context,
filters={'name': 'bm-one'})
self.assertEqual([bm1['id']], [r.id for r in res])
res = self.dbapi.get_baymodel_list(self.context,
filters={'name': 'bad-name'})
self.assertEqual([], [r.id for r in res])
res = self.dbapi.get_baymodel_list(self.context,
filters={'image_id': 'image1'})
self.assertEqual([bm1['id']], [r.id for r in res])
res = self.dbapi.get_baymodel_list(self.context,
filters={'image_id': 'image2'})
self.assertEqual([bm2['id']], [r.id for r in res])
def test_get_baymodel_by_id(self):
bm = utils.create_test_baymodel()
baymodel = self.dbapi.get_baymodel_by_id(self.context, bm['id'])
self.assertEqual(bm['uuid'], baymodel.uuid)
def test_get_baymodel_by_id_public(self):
bm = utils.create_test_baymodel(user_id='not_me', public=True)
baymodel = self.dbapi.get_baymodel_by_id(self.context, bm['id'])
self.assertEqual(bm['uuid'], baymodel.uuid)
def test_get_baymodel_by_uuid(self):
bm = utils.create_test_baymodel()
baymodel = self.dbapi.get_baymodel_by_uuid(self.context, bm['uuid'])
self.assertEqual(bm['id'], baymodel.id)
def test_get_baymodel_by_uuid_public(self):
bm = utils.create_test_baymodel(user_id='not_me', public=True)
baymodel = self.dbapi.get_baymodel_by_uuid(self.context, bm['uuid'])
self.assertEqual(bm['id'], baymodel.id)
def test_get_baymodel_that_does_not_exist(self):
self.assertRaises(exception.ClusterTemplateNotFound,
self.dbapi.get_baymodel_by_id, self.context, 666)
def test_get_baymodel_by_name(self):
bm = utils.create_test_baymodel()
res = self.dbapi.get_baymodel_by_name(self.context, bm['name'])
self.assertEqual(bm['id'], res.id)
self.assertEqual(bm['uuid'], res.uuid)
def test_get_baymodel_by_name_public(self):
bm = utils.create_test_baymodel(user_id='not_me', public=True)
res = self.dbapi.get_baymodel_by_name(self.context, bm['name'])
self.assertEqual(bm['id'], res.id)
self.assertEqual(bm['uuid'], res.uuid)
def test_get_baymodel_by_name_multiple_baymodel(self):
utils.create_test_baymodel(
id=1, name='bm',
uuid=uuidutils.generate_uuid(),
image_id='image1')
utils.create_test_baymodel(
id=2, name='bm',
uuid=uuidutils.generate_uuid(),
image_id='image2')
self.assertRaises(exception.Conflict, self.dbapi.get_baymodel_by_name,
self.context, 'bm')
def test_get_baymodel_by_name_not_found(self):
self.assertRaises(exception.ClusterTemplateNotFound,
self.dbapi.get_baymodel_by_name,
self.context, 'not_found')
def test_update_baymodel(self):
bm = utils.create_test_baymodel()
res = self.dbapi.update_baymodel(bm['id'], {'name': 'updated-model'})
self.assertEqual('updated-model', res.name)
def test_update_baymodel_that_does_not_exist(self):
self.assertRaises(exception.ClusterTemplateNotFound,
self.dbapi.update_baymodel, 666, {'name': ''})
def test_update_baymodel_uuid(self):
bm = utils.create_test_baymodel()
self.assertRaises(exception.InvalidParameterValue,
self.dbapi.update_baymodel, bm['id'],
{'uuid': 'hello'})
def test_destroy_baymodel(self):
bm = utils.create_test_baymodel()
self.dbapi.destroy_baymodel(bm['id'])
self.assertRaises(exception.ClusterTemplateNotFound,
self.dbapi.get_baymodel_by_id,
self.context, bm['id'])
def test_destroy_baymodel_by_uuid(self):
uuid = uuidutils.generate_uuid()
utils.create_test_baymodel(uuid=uuid)
self.assertIsNotNone(self.dbapi.get_baymodel_by_uuid(self.context,
uuid))
self.dbapi.destroy_baymodel(uuid)
self.assertRaises(exception.ClusterTemplateNotFound,
self.dbapi.get_baymodel_by_uuid, self.context, uuid)
def test_destroy_baymodel_that_does_not_exist(self):
self.assertRaises(exception.ClusterTemplateNotFound,
self.dbapi.destroy_baymodel, 666)
def test_destroy_baymodel_that_referenced_by_bays(self):
bm = utils.create_test_baymodel()
bay = utils.create_test_bay(baymodel_id=bm['uuid'])
self.assertEqual(bm['uuid'], bay.baymodel_id)
self.assertRaises(exception.ClusterTemplateReferenced,
self.dbapi.destroy_baymodel, bm['id'])
def test_create_baymodel_already_exists(self):
uuid = uuidutils.generate_uuid()
utils.create_test_baymodel(id=1, uuid=uuid)
self.assertRaises(exception.ClusterTemplateAlreadyExists,
utils.create_test_baymodel,
id=2, uuid=uuid)

View File

@ -0,0 +1,193 @@
# Copyright 2015 OpenStack Foundation
# All Rights Reserved.
#
# 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.
"""Tests for manipulating ClusterTemplate via the DB API"""
from oslo_utils import uuidutils
import six
from magnum.common import exception
from magnum.tests.unit.db import base
from magnum.tests.unit.db import utils
class DbClusterTemplateTestCase(base.DbTestCase):
def test_create_cluster_template(self):
utils.create_test_cluster_template()
def test_get_cluster_template_list(self):
uuids = []
for i in range(1, 6):
ct = utils.create_test_cluster_template(
id=i, uuid=uuidutils.generate_uuid())
uuids.append(six.text_type(ct['uuid']))
res = self.dbapi.get_cluster_template_list(self.context)
res_uuids = [r.uuid for r in res]
self.assertEqual(sorted(uuids), sorted(res_uuids))
def test_get_cluster_template_list_sorted(self):
uuids = []
for _ in range(5):
ct = utils.create_test_cluster_template(
uuid=uuidutils.generate_uuid())
uuids.append(six.text_type(ct['uuid']))
res = self.dbapi.get_cluster_template_list(self.context,
sort_key='uuid')
res_uuids = [r.uuid for r in res]
self.assertEqual(sorted(uuids), res_uuids)
self.assertRaises(exception.InvalidParameterValue,
self.dbapi.get_cluster_template_list,
self.context,
sort_key='foo')
def test_get_cluster_template_list_with_filters(self):
ct1 = utils.create_test_cluster_template(
id=1,
name='ct-one',
uuid=uuidutils.generate_uuid(),
image_id='image1')
ct2 = utils.create_test_cluster_template(
id=2,
name='ct-two',
uuid=uuidutils.generate_uuid(),
image_id='image2')
res = self.dbapi.get_cluster_template_list(self.context,
filters={'name': 'ct-one'})
self.assertEqual([ct1['id']], [r.id for r in res])
res = self.dbapi.get_cluster_template_list(
self.context, filters={'name': 'bad-name'})
self.assertEqual([], [r.id for r in res])
res = self.dbapi.get_cluster_template_list(
self.context, filters={'image_id': 'image1'})
self.assertEqual([ct1['id']], [r.id for r in res])
res = self.dbapi.get_cluster_template_list(
self.context, filters={'image_id': 'image2'})
self.assertEqual([ct2['id']], [r.id for r in res])
def test_get_cluster_template_by_id(self):
ct = utils.create_test_cluster_template()
cluster_template = self.dbapi.get_cluster_template_by_id(
self.context, ct['id'])
self.assertEqual(ct['uuid'], cluster_template.uuid)
def test_get_cluster_template_by_id_public(self):
ct = utils.create_test_cluster_template(user_id='not_me', public=True)
cluster_template = self.dbapi.get_cluster_template_by_id(
self.context, ct['id'])
self.assertEqual(ct['uuid'], cluster_template.uuid)
def test_get_cluster_template_by_uuid(self):
ct = utils.create_test_cluster_template()
cluster_template = self.dbapi.get_cluster_template_by_uuid(
self.context, ct['uuid'])
self.assertEqual(ct['id'], cluster_template.id)
def test_get_cluster_template_by_uuid_public(self):
ct = utils.create_test_cluster_template(user_id='not_me', public=True)
cluster_template = self.dbapi.get_cluster_template_by_uuid(
self.context, ct['uuid'])
self.assertEqual(ct['id'], cluster_template.id)
def test_get_cluster_template_that_does_not_exist(self):
self.assertRaises(exception.ClusterTemplateNotFound,
self.dbapi.get_cluster_template_by_id,
self.context, 666)
def test_get_cluster_template_by_name(self):
ct = utils.create_test_cluster_template()
res = self.dbapi.get_cluster_template_by_name(self.context, ct['name'])
self.assertEqual(ct['id'], res.id)
self.assertEqual(ct['uuid'], res.uuid)
def test_get_cluster_template_by_name_public(self):
ct = utils.create_test_cluster_template(user_id='not_me', public=True)
res = self.dbapi.get_cluster_template_by_name(self.context, ct['name'])
self.assertEqual(ct['id'], res.id)
self.assertEqual(ct['uuid'], res.uuid)
def test_get_cluster_template_by_name_multiple_cluster_template(self):
utils.create_test_cluster_template(
id=1, name='ct',
uuid=uuidutils.generate_uuid(),
image_id='image1')
utils.create_test_cluster_template(
id=2, name='ct',
uuid=uuidutils.generate_uuid(),
image_id='image2')
self.assertRaises(exception.Conflict,
self.dbapi.get_cluster_template_by_name,
self.context, 'ct')
def test_get_cluster_template_by_name_not_found(self):
self.assertRaises(exception.ClusterTemplateNotFound,
self.dbapi.get_cluster_template_by_name,
self.context, 'not_found')
def test_update_cluster_template(self):
ct = utils.create_test_cluster_template()
res = self.dbapi.update_cluster_template(ct['id'],
{'name': 'updated-model'})
self.assertEqual('updated-model', res.name)
def test_update_cluster_template_that_does_not_exist(self):
self.assertRaises(exception.ClusterTemplateNotFound,
self.dbapi.update_cluster_template, 666,
{'name': ''})
def test_update_cluster_template_uuid(self):
ct = utils.create_test_cluster_template()
self.assertRaises(exception.InvalidParameterValue,
self.dbapi.update_cluster_template, ct['id'],
{'uuid': 'hello'})
def test_destroy_cluster_template(self):
ct = utils.create_test_cluster_template()
self.dbapi.destroy_cluster_template(ct['id'])
self.assertRaises(exception.ClusterTemplateNotFound,
self.dbapi.get_cluster_template_by_id,
self.context, ct['id'])
def test_destroy_cluster_template_by_uuid(self):
uuid = uuidutils.generate_uuid()
utils.create_test_cluster_template(uuid=uuid)
self.assertIsNotNone(self.dbapi.get_cluster_template_by_uuid(
self.context, uuid))
self.dbapi.destroy_cluster_template(uuid)
self.assertRaises(exception.ClusterTemplateNotFound,
self.dbapi.get_cluster_template_by_uuid,
self.context, uuid)
def test_destroy_cluster_template_that_does_not_exist(self):
self.assertRaises(exception.ClusterTemplateNotFound,
self.dbapi.destroy_cluster_template, 666)
def test_destroy_cluster_template_that_referenced_by_bays(self):
ct = utils.create_test_cluster_template()
bay = utils.create_test_bay(cluster_template_id=ct['uuid'])
self.assertEqual(ct['uuid'], bay.baymodel_id)
self.assertRaises(exception.ClusterTemplateReferenced,
self.dbapi.destroy_cluster_template, ct['id'])
def test_create_cluster_template_already_exists(self):
uuid = uuidutils.generate_uuid()
utils.create_test_cluster_template(id=1, uuid=uuid)
self.assertRaises(exception.ClusterTemplateAlreadyExists,
utils.create_test_cluster_template,
id=2, uuid=uuid)

View File

@ -18,7 +18,7 @@
from magnum.db import api as db_api from magnum.db import api as db_api
def get_test_baymodel(**kw): def get_test_cluster_template(**kw):
return { return {
'id': kw.get('id', 32), 'id': kw.get('id', 32),
'project_id': kw.get('project_id', 'fake_project'), 'project_id': kw.get('project_id', 'fake_project'),
@ -58,19 +58,19 @@ def get_test_baymodel(**kw):
} }
def create_test_baymodel(**kw): def create_test_cluster_template(**kw):
"""Create test baymodel entry in DB and return BayModel DB object. """Create and return test ClusterTemplate DB object.
Function to be used to create test BayModel objects in the database. Function to be used to create test ClusterTemplate objects in the database.
:param kw: kwargs with overriding values for baymodel's attributes. :param kw: kwargs with overriding values for ClusterTemplate's attributes.
:returns: Test BayModel DB object. :returns: Test ClusterTemplate DB object.
""" """
baymodel = get_test_baymodel(**kw) cluster_template = get_test_cluster_template(**kw)
# Let DB generate ID if it isn't specified explicitly # Let DB generate ID if it isn't specified explicitly
if 'id' not in kw: if 'id' not in kw:
del baymodel['id'] del cluster_template['id']
dbapi = db_api.get_instance() dbapi = db_api.get_instance()
return dbapi.create_baymodel(baymodel) return dbapi.create_cluster_template(cluster_template)
def get_test_bay(**kw): def get_test_bay(**kw):

View File

@ -34,68 +34,70 @@ class TestBayObject(base.DbTestCase):
self.fake_bay['trustee_password'] = 'password' self.fake_bay['trustee_password'] = 'password'
self.fake_bay['coe_version'] = 'fake-coe-version' self.fake_bay['coe_version'] = 'fake-coe-version'
self.fake_bay['container_version'] = 'fake-container-version' self.fake_bay['container_version'] = 'fake-container-version'
baymodel_id = self.fake_bay['baymodel_id'] cluster_template_id = self.fake_bay['baymodel_id']
self.fake_baymodel = objects.BayModel(uuid=baymodel_id) self.fake_cluster_template = objects.ClusterTemplate(
uuid=cluster_template_id)
@mock.patch('magnum.objects.BayModel.get_by_uuid') @mock.patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_get_by_id(self, mock_baymodel_get): def test_get_by_id(self, mock_cluster_template_get):
bay_id = self.fake_bay['id'] bay_id = self.fake_bay['id']
with mock.patch.object(self.dbapi, 'get_bay_by_id', with mock.patch.object(self.dbapi, 'get_bay_by_id',
autospec=True) as mock_get_bay: autospec=True) as mock_get_bay:
mock_baymodel_get.return_value = self.fake_baymodel mock_cluster_template_get.return_value = self.fake_cluster_template
mock_get_bay.return_value = self.fake_bay mock_get_bay.return_value = self.fake_bay
bay = objects.Bay.get(self.context, bay_id) bay = objects.Bay.get(self.context, bay_id)
mock_get_bay.assert_called_once_with(self.context, bay_id) mock_get_bay.assert_called_once_with(self.context, bay_id)
self.assertEqual(self.context, bay._context) self.assertEqual(self.context, bay._context)
self.assertEqual(bay.baymodel_id, bay.baymodel.uuid) self.assertEqual(bay.baymodel_id, bay.cluster_template.uuid)
@mock.patch('magnum.objects.BayModel.get_by_uuid') @mock.patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_get_by_uuid(self, mock_baymodel_get): def test_get_by_uuid(self, mock_cluster_template_get):
uuid = self.fake_bay['uuid'] uuid = self.fake_bay['uuid']
with mock.patch.object(self.dbapi, 'get_bay_by_uuid', with mock.patch.object(self.dbapi, 'get_bay_by_uuid',
autospec=True) as mock_get_bay: autospec=True) as mock_get_bay:
mock_baymodel_get.return_value = self.fake_baymodel mock_cluster_template_get.return_value = self.fake_cluster_template
mock_get_bay.return_value = self.fake_bay mock_get_bay.return_value = self.fake_bay
bay = objects.Bay.get(self.context, uuid) bay = objects.Bay.get(self.context, uuid)
mock_get_bay.assert_called_once_with(self.context, uuid) mock_get_bay.assert_called_once_with(self.context, uuid)
self.assertEqual(self.context, bay._context) self.assertEqual(self.context, bay._context)
self.assertEqual(bay.baymodel_id, bay.baymodel.uuid) self.assertEqual(bay.baymodel_id, bay.cluster_template.uuid)
@mock.patch('magnum.objects.BayModel.get_by_uuid') @mock.patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_get_by_name(self, mock_baymodel_get): def test_get_by_name(self, mock_cluster_template_get):
name = self.fake_bay['name'] name = self.fake_bay['name']
with mock.patch.object(self.dbapi, 'get_bay_by_name', with mock.patch.object(self.dbapi, 'get_bay_by_name',
autospec=True) as mock_get_bay: autospec=True) as mock_get_bay:
mock_baymodel_get.return_value = self.fake_baymodel mock_cluster_template_get.return_value = self.fake_cluster_template
mock_get_bay.return_value = self.fake_bay mock_get_bay.return_value = self.fake_bay
bay = objects.Bay.get_by_name(self.context, name) bay = objects.Bay.get_by_name(self.context, name)
mock_get_bay.assert_called_once_with(self.context, name) mock_get_bay.assert_called_once_with(self.context, name)
self.assertEqual(self.context, bay._context) self.assertEqual(self.context, bay._context)
self.assertEqual(bay.baymodel_id, bay.baymodel.uuid) self.assertEqual(bay.baymodel_id, bay.cluster_template.uuid)
def test_get_bad_id_and_uuid(self): def test_get_bad_id_and_uuid(self):
self.assertRaises(exception.InvalidIdentity, self.assertRaises(exception.InvalidIdentity,
objects.Bay.get, self.context, 'not-a-uuid') objects.Bay.get, self.context, 'not-a-uuid')
@mock.patch('magnum.objects.BayModel.get_by_uuid') @mock.patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_list(self, mock_baymodel_get): def test_list(self, mock_cluster_template_get):
with mock.patch.object(self.dbapi, 'get_bay_list', with mock.patch.object(self.dbapi, 'get_bay_list',
autospec=True) as mock_get_list: autospec=True) as mock_get_list:
mock_get_list.return_value = [self.fake_bay] mock_get_list.return_value = [self.fake_bay]
mock_baymodel_get.return_value = self.fake_baymodel mock_cluster_template_get.return_value = self.fake_cluster_template
bays = objects.Bay.list(self.context) bays = objects.Bay.list(self.context)
self.assertEqual(1, mock_get_list.call_count) self.assertEqual(1, mock_get_list.call_count)
self.assertThat(bays, HasLength(1)) self.assertThat(bays, HasLength(1))
self.assertIsInstance(bays[0], objects.Bay) self.assertIsInstance(bays[0], objects.Bay)
self.assertEqual(self.context, bays[0]._context) self.assertEqual(self.context, bays[0]._context)
self.assertEqual(bays[0].baymodel_id, bays[0].baymodel.uuid) self.assertEqual(bays[0].baymodel_id,
bays[0].cluster_template.uuid)
@mock.patch('magnum.objects.BayModel.get_by_uuid') @mock.patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_list_all(self, mock_baymodel_get): def test_list_all(self, mock_cluster_template_get):
with mock.patch.object(self.dbapi, 'get_bay_list', with mock.patch.object(self.dbapi, 'get_bay_list',
autospec=True) as mock_get_list: autospec=True) as mock_get_list:
mock_get_list.return_value = [self.fake_bay] mock_get_list.return_value = [self.fake_bay]
mock_baymodel_get.return_value = self.fake_baymodel mock_cluster_template_get.return_value = self.fake_cluster_template
self.context.all_tenants = True self.context.all_tenants = True
bays = objects.Bay.list(self.context) bays = objects.Bay.list(self.context)
mock_get_list.assert_called_once_with( mock_get_list.assert_called_once_with(
@ -106,12 +108,12 @@ class TestBayObject(base.DbTestCase):
self.assertIsInstance(bays[0], objects.Bay) self.assertIsInstance(bays[0], objects.Bay)
self.assertEqual(self.context, bays[0]._context) self.assertEqual(self.context, bays[0]._context)
@mock.patch('magnum.objects.BayModel.get_by_uuid') @mock.patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_list_with_filters(self, mock_baymodel_get): def test_list_with_filters(self, mock_cluster_template_get):
with mock.patch.object(self.dbapi, 'get_bay_list', with mock.patch.object(self.dbapi, 'get_bay_list',
autospec=True) as mock_get_list: autospec=True) as mock_get_list:
mock_get_list.return_value = [self.fake_bay] mock_get_list.return_value = [self.fake_bay]
mock_baymodel_get.return_value = self.fake_baymodel mock_cluster_template_get.return_value = self.fake_cluster_template
filters = {'name': 'bay1'} filters = {'name': 'bay1'}
bays = objects.Bay.list(self.context, filters=filters) bays = objects.Bay.list(self.context, filters=filters)
@ -124,24 +126,24 @@ class TestBayObject(base.DbTestCase):
self.assertIsInstance(bays[0], objects.Bay) self.assertIsInstance(bays[0], objects.Bay)
self.assertEqual(self.context, bays[0]._context) self.assertEqual(self.context, bays[0]._context)
@mock.patch('magnum.objects.BayModel.get_by_uuid') @mock.patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_create(self, mock_baymodel_get): def test_create(self, mock_cluster_template_get):
with mock.patch.object(self.dbapi, 'create_bay', with mock.patch.object(self.dbapi, 'create_bay',
autospec=True) as mock_create_bay: autospec=True) as mock_create_bay:
mock_baymodel_get.return_value = self.fake_baymodel mock_cluster_template_get.return_value = self.fake_cluster_template
mock_create_bay.return_value = self.fake_bay mock_create_bay.return_value = self.fake_bay
bay = objects.Bay(self.context, **self.fake_bay) bay = objects.Bay(self.context, **self.fake_bay)
bay.create() bay.create()
mock_create_bay.assert_called_once_with(self.fake_bay) mock_create_bay.assert_called_once_with(self.fake_bay)
self.assertEqual(self.context, bay._context) self.assertEqual(self.context, bay._context)
@mock.patch('magnum.objects.BayModel.get_by_uuid') @mock.patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_destroy(self, mock_baymodel_get): def test_destroy(self, mock_cluster_template_get):
uuid = self.fake_bay['uuid'] uuid = self.fake_bay['uuid']
with mock.patch.object(self.dbapi, 'get_bay_by_uuid', with mock.patch.object(self.dbapi, 'get_bay_by_uuid',
autospec=True) as mock_get_bay: autospec=True) as mock_get_bay:
mock_get_bay.return_value = self.fake_bay mock_get_bay.return_value = self.fake_bay
mock_baymodel_get.return_value = self.fake_baymodel mock_cluster_template_get.return_value = self.fake_cluster_template
with mock.patch.object(self.dbapi, 'destroy_bay', with mock.patch.object(self.dbapi, 'destroy_bay',
autospec=True) as mock_destroy_bay: autospec=True) as mock_destroy_bay:
bay = objects.Bay.get_by_uuid(self.context, uuid) bay = objects.Bay.get_by_uuid(self.context, uuid)
@ -150,12 +152,12 @@ class TestBayObject(base.DbTestCase):
mock_destroy_bay.assert_called_once_with(uuid) mock_destroy_bay.assert_called_once_with(uuid)
self.assertEqual(self.context, bay._context) self.assertEqual(self.context, bay._context)
@mock.patch('magnum.objects.BayModel.get_by_uuid') @mock.patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_save(self, mock_baymodel_get): def test_save(self, mock_cluster_template_get):
uuid = self.fake_bay['uuid'] uuid = self.fake_bay['uuid']
with mock.patch.object(self.dbapi, 'get_bay_by_uuid', with mock.patch.object(self.dbapi, 'get_bay_by_uuid',
autospec=True) as mock_get_bay: autospec=True) as mock_get_bay:
mock_baymodel_get.return_value = self.fake_baymodel mock_cluster_template_get.return_value = self.fake_cluster_template
mock_get_bay.return_value = self.fake_bay mock_get_bay.return_value = self.fake_bay
with mock.patch.object(self.dbapi, 'update_bay', with mock.patch.object(self.dbapi, 'update_bay',
autospec=True) as mock_update_bay: autospec=True) as mock_update_bay:
@ -167,11 +169,11 @@ class TestBayObject(base.DbTestCase):
mock_get_bay.assert_called_once_with(self.context, uuid) mock_get_bay.assert_called_once_with(self.context, uuid)
mock_update_bay.assert_called_once_with( mock_update_bay.assert_called_once_with(
uuid, {'node_count': 10, 'master_count': 5, uuid, {'node_count': 10, 'master_count': 5,
'baymodel': self.fake_baymodel}) 'cluster_template': self.fake_cluster_template})
self.assertEqual(self.context, bay._context) self.assertEqual(self.context, bay._context)
@mock.patch('magnum.objects.BayModel.get_by_uuid') @mock.patch('magnum.objects.ClusterTemplate.get_by_uuid')
def test_refresh(self, mock_baymodel_get): def test_refresh(self, mock_cluster_template_get):
uuid = self.fake_bay['uuid'] uuid = self.fake_bay['uuid']
new_uuid = uuidutils.generate_uuid() new_uuid = uuidutils.generate_uuid()
returns = [dict(self.fake_bay, uuid=uuid), returns = [dict(self.fake_bay, uuid=uuid),
@ -181,7 +183,7 @@ class TestBayObject(base.DbTestCase):
with mock.patch.object(self.dbapi, 'get_bay_by_uuid', with mock.patch.object(self.dbapi, 'get_bay_by_uuid',
side_effect=returns, side_effect=returns,
autospec=True) as mock_get_bay: autospec=True) as mock_get_bay:
mock_baymodel_get.return_value = self.fake_baymodel mock_cluster_template_get.return_value = self.fake_cluster_template
bay = objects.Bay.get_by_uuid(self.context, uuid) bay = objects.Bay.get_by_uuid(self.context, uuid)
self.assertEqual(uuid, bay.uuid) self.assertEqual(uuid, bay.uuid)
bay.refresh() bay.refresh()

View File

@ -1,127 +0,0 @@
# Copyright 2015 OpenStack Foundation
# All Rights Reserved.
#
# 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.
import mock
from oslo_utils import uuidutils
from testtools.matchers import HasLength
from magnum.common import exception
from magnum import objects
from magnum.tests.unit.db import base
from magnum.tests.unit.db import utils
class TestBayModelObject(base.DbTestCase):
def setUp(self):
super(TestBayModelObject, self).setUp()
self.fake_baymodel = utils.get_test_baymodel()
def test_get_by_id(self):
baymodel_id = self.fake_baymodel['id']
with mock.patch.object(self.dbapi, 'get_baymodel_by_id',
autospec=True) as mock_get_baymodel:
mock_get_baymodel.return_value = self.fake_baymodel
baymodel = objects.BayModel.get(self.context, baymodel_id)
mock_get_baymodel.assert_called_once_with(self.context,
baymodel_id)
self.assertEqual(self.context, baymodel._context)
def test_get_by_uuid(self):
uuid = self.fake_baymodel['uuid']
with mock.patch.object(self.dbapi, 'get_baymodel_by_uuid',
autospec=True) as mock_get_baymodel:
mock_get_baymodel.return_value = self.fake_baymodel
baymodel = objects.BayModel.get(self.context, uuid)
mock_get_baymodel.assert_called_once_with(self.context, uuid)
self.assertEqual(self.context, baymodel._context)
def test_get_bad_id_and_uuid(self):
self.assertRaises(exception.InvalidIdentity,
objects.BayModel.get, self.context, 'not-a-uuid')
def test_get_by_name(self):
name = self.fake_baymodel['name']
with mock.patch.object(self.dbapi, 'get_baymodel_by_name',
autospec=True) as mock_get_baymodel:
mock_get_baymodel.return_value = self.fake_baymodel
baymodel = objects.BayModel.get_by_name(self.context, name)
mock_get_baymodel.assert_called_once_with(self.context, name)
self.assertEqual(self.context, baymodel._context)
def test_list(self):
with mock.patch.object(self.dbapi, 'get_baymodel_list',
autospec=True) as mock_get_list:
mock_get_list.return_value = [self.fake_baymodel]
baymodels = objects.BayModel.list(self.context)
self.assertEqual(1, mock_get_list.call_count)
self.assertThat(baymodels, HasLength(1))
self.assertIsInstance(baymodels[0], objects.BayModel)
self.assertEqual(self.context, baymodels[0]._context)
def test_create(self):
with mock.patch.object(self.dbapi, 'create_baymodel',
autospec=True) as mock_create_baymodel:
mock_create_baymodel.return_value = self.fake_baymodel
baymodel = objects.BayModel(self.context, **self.fake_baymodel)
baymodel.create()
mock_create_baymodel.assert_called_once_with(self.fake_baymodel)
self.assertEqual(self.context, baymodel._context)
def test_destroy(self):
uuid = self.fake_baymodel['uuid']
with mock.patch.object(self.dbapi, 'get_baymodel_by_uuid',
autospec=True) as mock_get_baymodel:
mock_get_baymodel.return_value = self.fake_baymodel
with mock.patch.object(self.dbapi, 'destroy_baymodel',
autospec=True) as mock_destroy_baymodel:
bm = objects.BayModel.get_by_uuid(self.context, uuid)
bm.destroy()
mock_get_baymodel.assert_called_once_with(self.context, uuid)
mock_destroy_baymodel.assert_called_once_with(uuid)
self.assertEqual(self.context, bm._context)
def test_save(self):
uuid = self.fake_baymodel['uuid']
with mock.patch.object(self.dbapi, 'get_baymodel_by_uuid',
autospec=True) as mock_get_baymodel:
mock_get_baymodel.return_value = self.fake_baymodel
with mock.patch.object(self.dbapi, 'update_baymodel',
autospec=True) as mock_update_baymodel:
bm = objects.BayModel.get_by_uuid(self.context, uuid)
bm.image_id = 'test-image'
bm.save()
mock_get_baymodel.assert_called_once_with(self.context, uuid)
mock_update_baymodel.assert_called_once_with(
uuid, {'image_id': 'test-image'})
self.assertEqual(self.context, bm._context)
def test_refresh(self):
uuid = self.fake_baymodel['uuid']
new_uuid = uuidutils.generate_uuid()
returns = [dict(self.fake_baymodel, uuid=uuid),
dict(self.fake_baymodel, uuid=new_uuid)]
expected = [mock.call(self.context, uuid),
mock.call(self.context, uuid)]
with mock.patch.object(self.dbapi, 'get_baymodel_by_uuid',
side_effect=returns,
autospec=True) as mock_get_baymodel:
bm = objects.BayModel.get_by_uuid(self.context, uuid)
self.assertEqual(uuid, bm.uuid)
bm.refresh()
self.assertEqual(new_uuid, bm.uuid)
self.assertEqual(expected, mock_get_baymodel.call_args_list)
self.assertEqual(self.context, bm._context)

View File

@ -0,0 +1,144 @@
# Copyright 2015 OpenStack Foundation
# All Rights Reserved.
#
# 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.
import mock
from oslo_utils import uuidutils
from testtools.matchers import HasLength
from magnum.common import exception
from magnum import objects
from magnum.tests.unit.db import base
from magnum.tests.unit.db import utils
class TestClusterTemplateObject(base.DbTestCase):
def setUp(self):
super(TestClusterTemplateObject, self).setUp()
self.fake_cluster_template = utils.get_test_cluster_template()
def test_get_by_id(self):
cluster_template_id = self.fake_cluster_template['id']
with mock.patch.object(self.dbapi, 'get_cluster_template_by_id',
autospec=True) as mock_get_cluster_template:
mock_get_cluster_template.return_value = self.fake_cluster_template
cluster_template = objects.ClusterTemplate.get(self.context,
cluster_template_id)
mock_get_cluster_template.assert_called_once_with(
self.context, cluster_template_id)
self.assertEqual(self.context, cluster_template._context)
def test_get_by_uuid(self):
uuid = self.fake_cluster_template['uuid']
with mock.patch.object(self.dbapi, 'get_cluster_template_by_uuid',
autospec=True) as mock_get_cluster_template:
mock_get_cluster_template.return_value = self.fake_cluster_template
cluster_template = objects.ClusterTemplate.get(self.context, uuid)
mock_get_cluster_template.assert_called_once_with(self.context,
uuid)
self.assertEqual(self.context, cluster_template._context)
def test_get_bad_id_and_uuid(self):
self.assertRaises(exception.InvalidIdentity,
objects.ClusterTemplate.get, self.context,
'not-a-uuid')
def test_get_by_name(self):
name = self.fake_cluster_template['name']
with mock.patch.object(self.dbapi, 'get_cluster_template_by_name',
autospec=True) as mock_get_cluster_template:
mock_get_cluster_template.return_value = self.fake_cluster_template
cluster_template = objects.ClusterTemplate.get_by_name(
self.context, name)
mock_get_cluster_template.assert_called_once_with(self.context,
name)
self.assertEqual(self.context, cluster_template._context)
def test_list(self):
with mock.patch.object(self.dbapi, 'get_cluster_template_list',
autospec=True) as mock_get_list:
mock_get_list.return_value = [self.fake_cluster_template]
cluster_templates = objects.ClusterTemplate.list(self.context)
self.assertEqual(1, mock_get_list.call_count)
self.assertThat(cluster_templates, HasLength(1))
self.assertIsInstance(cluster_templates[0],
objects.ClusterTemplate)
self.assertEqual(self.context, cluster_templates[0]._context)
def test_create(self):
with mock.patch.object(self.dbapi, 'create_cluster_template',
autospec=True) as mock_create_cluster_template:
mock_create_cluster_template.return_value = \
self.fake_cluster_template
cluster_template = objects.ClusterTemplate(
self.context, **self.fake_cluster_template)
cluster_template.create()
mock_create_cluster_template.assert_called_once_with(
self.fake_cluster_template)
self.assertEqual(self.context, cluster_template._context)
def test_destroy(self):
uuid = self.fake_cluster_template['uuid']
with mock.patch.object(self.dbapi, 'get_cluster_template_by_uuid',
autospec=True) as mock_get_cluster_template:
mock_get_cluster_template.return_value = self.fake_cluster_template
with mock.patch.object(
self.dbapi, 'destroy_cluster_template', autospec=True)\
as mock_destroy_cluster_template:
cluster_template = objects.ClusterTemplate.get_by_uuid(
self.context, uuid)
cluster_template.destroy()
mock_get_cluster_template.assert_called_once_with(self.context,
uuid)
mock_destroy_cluster_template.assert_called_once_with(uuid)
self.assertEqual(self.context, cluster_template._context)
def test_save(self):
uuid = self.fake_cluster_template['uuid']
with mock.patch.object(self.dbapi, 'get_cluster_template_by_uuid',
autospec=True) as mock_get_cluster_template:
mock_get_cluster_template.return_value = self.fake_cluster_template
with mock.patch.object(self.dbapi, 'update_cluster_template',
autospec=True) \
as mock_update_cluster_template:
cluster_template = objects.ClusterTemplate.get_by_uuid(
self.context, uuid)
cluster_template.image_id = 'test-image'
cluster_template.save()
mock_get_cluster_template.assert_called_once_with(self.context,
uuid)
mock_update_cluster_template.assert_called_once_with(
uuid, {'image_id': 'test-image'})
self.assertEqual(self.context, cluster_template._context)
def test_refresh(self):
uuid = self.fake_cluster_template['uuid']
new_uuid = uuidutils.generate_uuid()
returns = [dict(self.fake_cluster_template, uuid=uuid),
dict(self.fake_cluster_template, uuid=new_uuid)]
expected = [mock.call(self.context, uuid),
mock.call(self.context, uuid)]
with mock.patch.object(self.dbapi, 'get_cluster_template_by_uuid',
side_effect=returns,
autospec=True) as mock_get_cluster_template:
cluster_template = objects.ClusterTemplate.get_by_uuid(
self.context, uuid)
self.assertEqual(uuid, cluster_template.uuid)
cluster_template.refresh()
self.assertEqual(new_uuid, cluster_template.uuid)
self.assertEqual(expected,
mock_get_cluster_template.call_args_list)
self.assertEqual(self.context, cluster_template._context)

View File

@ -362,8 +362,8 @@ class TestObject(test_base.TestCase, _TestObject):
# For more information on object version testing, read # For more information on object version testing, read
# http://docs.openstack.org/developer/magnum/objects.html # http://docs.openstack.org/developer/magnum/objects.html
object_data = { object_data = {
'Bay': '1.7-88cb12f991721fe31602dc3fd7acd654', 'Bay': '1.8-a6109e08d32dc59d3ad100697e06d8da',
'BayModel': '1.15-9b961246b348aa380783dae14014e423', 'ClusterTemplate': '1.16-29dfb88bff54a412b05f9a651f4758a6',
'Certificate': '1.1-1924dc077daa844f0f9076332ef96815', 'Certificate': '1.1-1924dc077daa844f0f9076332ef96815',
'MyObj': '1.0-b43567e512438205e32f4e95ca616697', 'MyObj': '1.0-b43567e512438205e32f4e95ca616697',
'MyObj': '1.0-34c4b1aadefd177b13f9a2f894cc23cd', 'MyObj': '1.0-34c4b1aadefd177b13f9a2f894cc23cd',

View File

@ -28,34 +28,36 @@ from magnum import objects
from magnum.tests.unit.db import utils as db_utils from magnum.tests.unit.db import utils as db_utils
def get_test_baymodel(context, **kw): def get_test_cluster_template(context, **kw):
"""Return a BayModel object with appropriate attributes. """Return a ClusterTemplate object with appropriate attributes.
NOTE: The object leaves the attributes marked as changed, such NOTE: The object leaves the attributes marked as changed, such
that a create() could be used to commit it to the DB. that a create() could be used to commit it to the DB.
""" """
db_baymodel = db_utils.get_test_baymodel(**kw) db_cluster_template = db_utils.get_test_cluster_template(**kw)
cluster_template = objects.ClusterTemplate(context)
# Let DB generate ID if it isn't specified explicitly # Let DB generate ID if it isn't specified explicitly
if 'id' not in kw: if 'id' not in kw:
del db_baymodel['id'] del db_cluster_template['id']
baymodel = objects.BayModel(context)
for key in db_baymodel: for key in db_cluster_template:
setattr(baymodel, key, db_baymodel[key]) setattr(cluster_template, key, db_cluster_template[key])
return baymodel return cluster_template
def create_test_baymodel(context, **kw): def create_test_cluster_template(context, **kw):
"""Create and return a test baymodel object. """Create and return a test ClusterTemplate object.
Create a baymodel in the DB and return a BayModel object with appropriate Create a ClusterTemplate in the DB and return a ClusterTemplate object
attributes. with appropriate attributes.
""" """
baymodel = get_test_baymodel(context, **kw) cluster_template = get_test_cluster_template(context, **kw)
try: try:
baymodel.create() cluster_template.create()
except exception.ClusterTemplateAlreadyExists: except exception.ClusterTemplateAlreadyExists:
baymodel = objects.BayModel.get(context, baymodel.uuid) cluster_template = objects.ClusterTemplate.get(context,
return baymodel cluster_template.uuid)
return cluster_template
def get_test_bay(context, **kw): def get_test_bay(context, **kw):
@ -81,30 +83,12 @@ def create_test_bay(context, **kw):
attributes. attributes.
""" """
bay = get_test_bay(context, **kw) bay = get_test_bay(context, **kw)
create_test_baymodel(context, uuid=bay['baymodel_id'], create_test_cluster_template(context, uuid=bay['baymodel_id'],
coe=kw.get('coe', 'swarm')) coe=kw.get('coe', 'swarm'))
bay.create() bay.create()
return bay return bay
def get_test_cluster_template(context, **kw):
"""Return a ClusterTemplate object with appropriate attributes.
NOTE: Object model is the same for ClusterTemplate and
BayModel
"""
return get_test_baymodel(context, **kw)
def create_test_cluster_template(context, **kw):
"""Create and return a test ClusterTemplate object.
NOTE: Object model is the same for ClusterTemplate and
BayModel
"""
return create_test_baymodel(context, **kw)
def get_test_cluster(context, **kw): def get_test_cluster(context, **kw):
"""Return a Cluster object with appropriate attributes. """Return a Cluster object with appropriate attributes.