Replace oslo_utils.encodeutils.exception_to_unicode

The function is deprecated because it is equivalent to str(ex) in
Python 3.

Note that %s implies conversion by str so we don't have to even call
str for most of cases. However a few explicit str calls are kept to
simplify unit tests.

Depends-on: https://review.opendev.org/c/openstack/oslo.utils/+/938929
Change-Id: Ie04bf64a22781c95d24222c96eee7865b0712312
Signed-off-by: Takashi Kajinami <kajinamit@oss.nttdata.com>
This commit is contained in:
Takashi Kajinami
2025-02-03 21:28:16 +09:00
parent 32f8343da1
commit 0bdc50ba99
39 changed files with 135 additions and 232 deletions

View File

@@ -20,7 +20,6 @@ from glance_store import backend
from glance_store import location
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
import webob.exc
@@ -67,7 +66,7 @@ class ImageDataController(object):
except Exception as e:
msg = (_LE("Unable to restore image %(image_id)s: %(e)s") %
{'image_id': image.image_id,
'e': encodeutils.exception_to_unicode(e)})
'e': e})
LOG.exception(msg)
def _unstage(self, image_repo, image, staging_store):
@@ -154,7 +153,7 @@ class ImageDataController(object):
except Exception as e:
LOG.info(_LI("Unable to create trust: %s "
"Use the existing user token."),
encodeutils.exception_to_unicode(e))
e)
image_repo.save(image, from_state='queued')
ks_quota.enforce_image_count_uploading(req.context,
@@ -176,9 +175,9 @@ class ImageDataController(object):
if refresher is not None:
refresher.release_resources()
except Exception as e:
LOG.info(_LI("Unable to delete trust %(trust)s: %(msg)s"),
LOG.info(_LI("Unable to delete trust %(trust)s: %(err)s"),
{"trust": refresher.trust_id,
"msg": encodeutils.exception_to_unicode(e)})
"err": e})
except (glance_store.NotFound,
exception.ImageNotFound,
@@ -213,10 +212,10 @@ class ImageDataController(object):
except ValueError as e:
LOG.debug("Cannot save data for image %(id)s: %(e)s",
{'id': image_id,
'e': encodeutils.exception_to_unicode(e)})
'e': e})
self._restore(image_repo, image)
raise webob.exc.HTTPBadRequest(
explanation=encodeutils.exception_to_unicode(e))
explanation=str(e))
except glance_store.StoreAddDisabled:
msg = _("Error in store configuration. Adding images to store "
@@ -227,8 +226,7 @@ class ImageDataController(object):
content_type='text/plain')
except exception.InvalidImageStatusTransition as e:
msg = encodeutils.exception_to_unicode(e)
LOG.exception(msg)
LOG.exception(str(e))
raise webob.exc.HTTPConflict(explanation=e.msg, request=req)
except exception.Forbidden:
@@ -241,24 +239,21 @@ class ImageDataController(object):
raise webob.exc.HTTPNotFound(explanation=e.msg)
except glance_store.StorageFull as e:
msg = _("Image storage media "
"is full: %s") % encodeutils.exception_to_unicode(e)
msg = _("Image storage media is full: %s") % e
LOG.error(msg)
self._restore(image_repo, image)
raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg,
request=req)
except exception.StorageQuotaFull as e:
msg = _("Image exceeds the storage "
"quota: %s") % encodeutils.exception_to_unicode(e)
msg = _("Image exceeds the storage quota: %s") % e
LOG.error(msg)
self._restore(image_repo, image)
raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg,
request=req)
except exception.ImageSizeLimitExceeded as e:
msg = _("The incoming image is "
"too large: %s") % encodeutils.exception_to_unicode(e)
msg = _("The incoming image is too large: %s") % e
LOG.error(msg)
self._restore(image_repo, image)
raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg,
@@ -277,8 +272,7 @@ class ImageDataController(object):
request=req)
except glance_store.StorageWriteDenied as e:
msg = _("Insufficient permissions on image "
"storage media: %s") % encodeutils.exception_to_unicode(e)
msg = _("Insufficient permissions on image storage media: %s") % e
LOG.error(msg)
self._restore(image_repo, image)
raise webob.exc.HTTPServiceUnavailable(explanation=msg,
@@ -286,8 +280,7 @@ class ImageDataController(object):
except cursive_exception.SignatureVerificationError as e:
msg = (_LE("Signature verification failed for image %(id)s: %(e)s")
% {'id': image_id,
'e': encodeutils.exception_to_unicode(e)})
% {'id': image_id, 'e': e})
LOG.error(msg)
self._restore(image_repo, image)
raise webob.exc.HTTPBadRequest(explanation=msg)
@@ -395,24 +388,21 @@ class ImageDataController(object):
raise webob.exc.HTTPNotFound(explanation=e.msg)
except glance_store.StorageFull as e:
msg = _("Image storage media "
"is full: %s") % encodeutils.exception_to_unicode(e)
msg = _("Image storage media is full: %s") % e
LOG.error(msg)
self._unstage(image_repo, image, staging_store)
raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg,
request=req)
except exception.StorageQuotaFull as e:
msg = _("Image exceeds the storage "
"quota: %s") % encodeutils.exception_to_unicode(e)
msg = _("Image exceeds the storage quota: %s") % e
LOG.debug(msg)
self._unstage(image_repo, image, staging_store)
raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg,
request=req)
except exception.ImageSizeLimitExceeded as e:
msg = _("The incoming image is "
"too large: %s") % encodeutils.exception_to_unicode(e)
msg = _("The incoming image is too large: %s") % e
LOG.debug(msg)
self._unstage(image_repo, image, staging_store)
raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg,
@@ -426,15 +416,14 @@ class ImageDataController(object):
except glance_store.StorageWriteDenied as e:
msg = _("Insufficient permissions on image "
"storage media: %s") % encodeutils.exception_to_unicode(e)
"storage media: %s") % e
LOG.error(msg)
self._unstage(image_repo, image, staging_store)
raise webob.exc.HTTPServiceUnavailable(explanation=msg,
request=req)
except exception.InvalidImageStatusTransition as e:
msg = encodeutils.exception_to_unicode(e)
LOG.debug(msg)
LOG.debug(str(e))
raise webob.exc.HTTPConflict(explanation=e.msg, request=req)
except Exception:

View File

@@ -20,7 +20,6 @@ import glance_store
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import encodeutils
import webob
from glance.api import policy
@@ -179,7 +178,7 @@ class ImageMembersController(object):
except exception.ImageMemberLimitExceeded as e:
msg = (_("Image member limit exceeded for image %(id)s: %(e)s:")
% {"id": image_id,
"e": encodeutils.exception_to_unicode(e)})
"e": e})
LOG.warning(msg)
raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg)
@@ -228,8 +227,7 @@ class ImageMembersController(object):
LOG.warning(msg)
raise webob.exc.HTTPForbidden(explanation=msg)
except ValueError as e:
msg = (_("Incorrect request: %s")
% encodeutils.exception_to_unicode(e))
msg = (_("Incorrect request: %s") % e)
LOG.warning(msg)
raise webob.exc.HTTPBadRequest(explanation=msg)

View File

@@ -16,7 +16,6 @@ import http.client as http
import glance_store
from oslo_log import log as logging
from oslo_utils import encodeutils
import webob.exc
from glance.api import policy
@@ -62,14 +61,13 @@ class Controller(object):
LOG.warning(msg)
raise webob.exc.HTTPForbidden(explanation=msg)
except exception.Invalid as e:
msg = (_("Could not update image: %s")
% encodeutils.exception_to_unicode(e))
msg = (_("Could not update image: %s") % e)
LOG.warning(msg)
raise webob.exc.HTTPBadRequest(explanation=msg)
except exception.ImageTagLimitExceeded as e:
msg = (_("Image tag limit exceeded for image %(id)s: %(e)s:")
% {"id": image_id,
"e": encodeutils.exception_to_unicode(e)})
"e": e})
LOG.warning(msg)
raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg)

View File

@@ -27,7 +27,6 @@ from glance_store import location
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import jsonutils as json
from oslo_utils import encodeutils
from oslo_utils import timeutils as oslo_timeutils
import requests
import webob.exc
@@ -116,7 +115,7 @@ class ImagesController(object):
LOG.debug("User not permitted to create image")
raise webob.exc.HTTPForbidden(explanation=e.msg)
except exception.LimitExceeded as e:
LOG.warning(encodeutils.exception_to_unicode(e))
LOG.warning(str(e))
raise webob.exc.HTTPRequestEntityTooLarge(
explanation=e.msg, request=req, content_type='text/plain')
except exception.Duplicate as e:
@@ -124,7 +123,7 @@ class ImagesController(object):
except exception.NotAuthenticated as e:
raise webob.exc.HTTPUnauthorized(explanation=e.msg)
except TypeError as e:
LOG.debug(encodeutils.exception_to_unicode(e))
LOG.debug(str(e))
raise webob.exc.HTTPBadRequest(explanation=e)
return image
@@ -505,9 +504,9 @@ class ImagesController(object):
except ValueError as e:
LOG.debug("Cannot import data for image %(id)s: %(e)s",
{'id': image_id,
'e': encodeutils.exception_to_unicode(e)})
'e': e})
raise webob.exc.HTTPBadRequest(
explanation=encodeutils.exception_to_unicode(e))
explanation=str(e))
return image_id
@@ -634,12 +633,12 @@ class ImagesController(object):
raise webob.exc.HTTPForbidden(explanation=e.msg)
except exception.StorageQuotaFull as e:
msg = (_("Denying attempt to upload image because it exceeds the"
" quota: %s") % encodeutils.exception_to_unicode(e))
" quota: %s") % e)
LOG.warning(msg)
raise webob.exc.HTTPRequestEntityTooLarge(
explanation=msg, request=req, content_type='text/plain')
except exception.LimitExceeded as e:
LOG.exception(encodeutils.exception_to_unicode(e))
LOG.exception(str(e))
raise webob.exc.HTTPRequestEntityTooLarge(
explanation=e.msg, request=req, content_type='text/plain')
except exception.NotAuthenticated as e:
@@ -806,7 +805,7 @@ class ImagesController(object):
raise webob.exc.HTTPConflict(explanation=msg)
except Exception as e:
raise webob.exc.HTTPInternalServerError(
explanation=encodeutils.exception_to_unicode(e))
explanation=str(e))
image_repo.save(image)
@@ -1073,8 +1072,7 @@ class ImagesController(object):
except (exception.BadStoreUri, exception.DuplicateLocation) as e:
raise webob.exc.HTTPBadRequest(explanation=e.msg)
except ValueError as ve: # update image status failed.
raise webob.exc.HTTPBadRequest(
explanation=encodeutils.exception_to_unicode(ve))
raise webob.exc.HTTPBadRequest(explanation=str(ve))
def _do_add_locations(self, image, path_pos, value, context):
if CONF.show_multiple_locations == False:
@@ -1108,8 +1106,7 @@ class ImagesController(object):
except (exception.BadStoreUri, exception.DuplicateLocation) as e:
raise webob.exc.HTTPBadRequest(explanation=e.msg)
except ValueError as e: # update image status failed.
raise webob.exc.HTTPBadRequest(
explanation=encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPBadRequest(explanation=str(e))
def _do_remove_locations(self, image, path_pos):
if CONF.show_multiple_locations == False:
@@ -1139,8 +1136,7 @@ class ImagesController(object):
# TODO(jokke): Fix this, we should catch what store throws and
# provide definitely something else than IternalServerError to user.
except Exception as e:
raise webob.exc.HTTPInternalServerError(
explanation=encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPInternalServerError(explanation=str(e))
def add_location(self, req, image_id, body):
url = body.get('url')
@@ -1225,8 +1221,7 @@ class ImagesController(object):
except exception.NotAuthenticated as e:
raise webob.exc.HTTPUnauthorized(explanation=e.msg)
except ValueError as e:
raise webob.exc.HTTPBadRequest(
explanation=encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPBadRequest(explanation=str(e))
return image_id

View File

@@ -19,7 +19,6 @@ import urllib.parse as urlparse
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import encodeutils
import webob.exc
from wsme.rest import json
@@ -214,8 +213,7 @@ class NamespaceController(object):
))
prop_repo.add(new_property_type)
except exception.Invalid as e:
msg = (_("Couldn't create metadata namespace: %s")
% encodeutils.exception_to_unicode(e))
msg = (_("Couldn't create metadata namespace: %s") % e)
raise webob.exc.HTTPBadRequest(explanation=msg)
except exception.Forbidden as e:
self._cleanup_namespace(ns_repo, namespace, namespace_created)
@@ -257,7 +255,7 @@ class NamespaceController(object):
msg = (_LE("Failed to delete namespace %(namespace)s."
"Exception: %(exception)s"),
{'namespace': namespace.namespace,
'exception': encodeutils.exception_to_unicode(e)})
'exception': str(e)})
LOG.error(msg)
def show(self, req, namespace, filters=None):
@@ -373,8 +371,7 @@ class NamespaceController(object):
wsme_utils._get_value(user_ns.owner) or req.context.owner)
updated_namespace = namespace_repo.save(ns_obj)
except exception.Invalid as e:
msg = (_("Couldn't update metadata namespace: %s")
% encodeutils.exception_to_unicode(e))
msg = (_("Couldn't update metadata namespace: %s") % e)
raise webob.exc.HTTPBadRequest(explanation=msg)
except exception.Forbidden as e:
LOG.debug("User not permitted to update metadata namespace "

View File

@@ -17,7 +17,6 @@ import http.client as http
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import encodeutils
import webob.exc
from wsme.rest import json
@@ -81,8 +80,7 @@ class MetadefObjectsController(object):
"'%s' namespace", namespace)
raise webob.exc.HTTPForbidden(explanation=e.msg)
except exception.Invalid as e:
msg = (_("Couldn't create metadata object: %s")
% encodeutils.exception_to_unicode(e))
msg = (_("Couldn't create metadata object: %s") % e)
raise webob.exc.HTTPBadRequest(explanation=msg)
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
@@ -207,8 +205,7 @@ class MetadefObjectsController(object):
metadata_object.properties)
updated_metadata_obj = meta_repo.save(metadef_object)
except exception.Invalid as e:
msg = (_("Couldn't update metadata object: %s")
% encodeutils.exception_to_unicode(e))
msg = (_("Couldn't update metadata object: %s") % e)
raise webob.exc.HTTPBadRequest(explanation=msg)
except exception.Forbidden as e:
LOG.debug("User not permitted to update metadata object '%s' "

View File

@@ -17,7 +17,6 @@ import http.client as http
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import encodeutils
import webob.exc
from wsme.rest import json
@@ -175,8 +174,7 @@ class NamespacePropertiesController(object):
"'%s' namespace", namespace)
raise webob.exc.HTTPForbidden(explanation=e.msg)
except exception.Invalid as e:
msg = (_("Couldn't create metadata property: %s")
% encodeutils.exception_to_unicode(e))
msg = (_("Couldn't create metadata property: %s") % e)
raise webob.exc.HTTPBadRequest(explanation=msg)
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
@@ -210,8 +208,7 @@ class NamespacePropertiesController(object):
db_property_type.schema = (self._to_dict(property_type))['schema']
updated_property_type = prop_repo.save(db_property_type)
except exception.Invalid as e:
msg = (_("Couldn't update metadata property: %s")
% encodeutils.exception_to_unicode(e))
msg = (_("Couldn't update metadata property: %s") % e)
raise webob.exc.HTTPBadRequest(explanation=msg)
except exception.Forbidden as e:
LOG.debug("User not permitted to update metadata property '%s' "

View File

@@ -17,7 +17,6 @@ import http.client as http
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import encodeutils
from oslo_utils import strutils
import webob.exc
from wsme.rest import json
@@ -80,8 +79,7 @@ class TagsController(object):
**tag_name_as_dict)
tag_repo.add(new_meta_tag)
except exception.Invalid as e:
msg = (_("Couldn't create metadata tag: %s")
% encodeutils.exception_to_unicode(e))
msg = (_("Couldn't create metadata tag: %s") % e)
raise webob.exc.HTTPBadRequest(explanation=msg)
except exception.Forbidden as e:
LOG.debug("User not permitted to create metadata tag within "
@@ -239,8 +237,7 @@ class TagsController(object):
metadata_tag.name)
updated_metadata_tag = meta_repo.save(metadef_tag)
except exception.Invalid as e:
msg = (_("Couldn't update metadata tag: %s")
% encodeutils.exception_to_unicode(e))
msg = (_("Couldn't update metadata tag: %s") % e)
raise webob.exc.HTTPBadRequest(explanation=msg)
except exception.Forbidden as e:
LOG.debug("User not permitted to update metadata tag '%s' "

View File

@@ -23,7 +23,6 @@ import glance_store
from oslo_config import cfg
from oslo_log import log as logging
import oslo_serialization.jsonutils as json
from oslo_utils import encodeutils
from oslo_utils import uuidutils
import webob.exc
@@ -87,7 +86,7 @@ class TasksController(object):
pool.spawn(new_task.run, task_executor)
except exception.Forbidden as e:
msg = (_LW("Forbidden to create task. Reason: %(reason)s")
% {'reason': encodeutils.exception_to_unicode(e)})
% {'reason': e})
LOG.warning(msg)
raise webob.exc.HTTPForbidden(explanation=e.msg)
return new_task
@@ -114,10 +113,10 @@ class TasksController(object):
result['next_marker'] = tasks[-1].task_id
except (exception.NotFound, exception.InvalidSortKey,
exception.InvalidFilterRangeValue) as e:
LOG.warning(encodeutils.exception_to_unicode(e))
LOG.warning(str(e))
raise webob.exc.HTTPBadRequest(explanation=e.msg)
except exception.Forbidden as e:
LOG.warning(encodeutils.exception_to_unicode(e))
LOG.warning(str(e))
raise webob.exc.HTTPForbidden(explanation=e.msg)
result['tasks'] = tasks
return result
@@ -131,14 +130,14 @@ class TasksController(object):
except exception.NotFound as e:
msg = (_LW("Failed to find task %(task_id)s. Reason: %(reason)s")
% {'task_id': task_id,
'reason': encodeutils.exception_to_unicode(e)})
'reason': e})
LOG.warning(msg)
raise webob.exc.HTTPNotFound(explanation=e.msg)
except exception.Forbidden as e:
msg = (_LW("Forbidden to get task %(task_id)s. Reason:"
" %(reason)s")
% {'task_id': task_id,
'reason': encodeutils.exception_to_unicode(e)})
'reason': e})
LOG.warning(msg)
raise webob.exc.HTTPForbidden(explanation=e.msg)
return task

View File

@@ -17,7 +17,6 @@ import urllib.request
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
from taskflow.patterns import linear_flow as lf
@@ -71,7 +70,7 @@ class _DownloadGlanceImage(base_download.BaseDownload):
with excutils.save_and_reraise_exception():
LOG.error(
_LE("Task %(task_id)s failed with exception %(error)s"), {
"error": encodeutils.exception_to_unicode(e),
"error": e,
"task_id": self.task_id
})

View File

@@ -16,7 +16,6 @@
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
from taskflow.patterns import linear_flow as lf
@@ -53,7 +52,7 @@ class _WebDownload(base_download.BaseDownload):
except Exception as e:
with excutils.save_and_reraise_exception():
LOG.error("Task %(task_id)s failed with exception %(error)s",
{"error": encodeutils.exception_to_unicode(e),
{"error": e,
"task_id": self.task_id})
self._path, bytes_written = self.store.add(self.image_id, data, 0)[0:2]

View File

@@ -23,7 +23,6 @@ from glance_store import backend
from glance_store import exceptions as store_exceptions
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
from oslo_utils import timeutils
from oslo_utils import units
@@ -748,12 +747,11 @@ class _CompleteTask(task.Task):
log_msg = _LE("Task ID %(task_id)s failed. Error: %(exc_type)s: "
"%(e)s")
LOG.exception(log_msg, {'exc_type': str(type(e)),
'e': encodeutils.exception_to_unicode(e),
'e': e,
'task_id': task.task_id})
err_msg = _("Error: %(exc_type)s: %(e)s")
task.fail(err_msg % {'exc_type': str(type(e)),
'e': encodeutils.exception_to_unicode(e)})
task.fail(err_msg % {'exc_type': str(type(e)), 'e': e})
finally:
self.task_repo.save(task)
@@ -854,7 +852,7 @@ class _ImportMetadata(task.Task):
with excutils.save_and_reraise_exception():
LOG.error(
"Task %(task_id)s failed with exception %(error)s", {
"error": encodeutils.exception_to_unicode(e),
"error": e,
"task_id": self.task_id
})

View File

@@ -21,7 +21,6 @@ from glance_store import backend
from oslo_concurrency import processutils as putils
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
from stevedore import named
from taskflow.patterns import linear_flow as lf
@@ -167,10 +166,9 @@ class _ImportToFS(task.Task):
log_errors=putils.LOG_ALL_ERRORS)
except OSError as exc:
with excutils.save_and_reraise_exception():
exc_message = encodeutils.exception_to_unicode(exc)
msg = _LE('Failed to execute security checks on the image '
'%(task_id)s: %(exc)s')
LOG.error(msg, {'task_id': self.task_id, 'exc': exc_message})
LOG.error(msg, {'task_id': self.task_id, 'exc': exc})
metadata = json.loads(stdout)
@@ -336,9 +334,9 @@ class _ImportToStore(task.Task):
image_import.set_image_data(image,
file_path or self.uri, self.task_id,
backend=self.backend)
except IOError as e:
except IOError as exc:
msg = (_('Uploading the image failed due to: %(exc)s') %
{'exc': encodeutils.exception_to_unicode(e)})
{'exc': exc})
LOG.error(msg)
raise exception.UploadException(message=msg)
# NOTE(flaper87): We need to save the image again after the locations
@@ -389,21 +387,20 @@ class _CompleteTask(task.Task):
return
try:
task.succeed({'image_id': image_id})
except Exception as e:
except Exception as exc:
# Note: The message string contains Error in it to indicate
# in the task.message that it's a error message for the user.
# TODO(nikhil): need to bring back save_and_reraise_exception when
# necessary
log_msg = _LE("Task ID %(task_id)s failed. Error: %(exc_type)s: "
"%(e)s")
LOG.exception(log_msg, {'exc_type': str(type(e)),
'e': encodeutils.exception_to_unicode(e),
"%(exc)s")
LOG.exception(log_msg, {'exc_type': str(type(exc)),
'exc': exc,
'task_id': task.task_id})
err_msg = _("Error: %(exc_type)s: %(e)s")
task.fail(err_msg % {'exc_type': str(type(e)),
'e': encodeutils.exception_to_unicode(e)})
err_msg = _("Error: %(exc_type)s: %(exc)s")
task.fail(err_msg % {'exc_type': str(type(exc)), 'exc': exc})
finally:
self.task_repo.save(task)

View File

@@ -17,7 +17,6 @@ import json
from oslo_concurrency import processutils as putils
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
from taskflow.patterns import linear_flow as lf
@@ -57,11 +56,10 @@ class _Introspect(utils.OptionalTask):
# tasks.
if exc.errno != 2:
with excutils.save_and_reraise_exception():
exc_message = encodeutils.exception_to_unicode(exc)
msg = _LE('Failed to execute introspection '
'%(task_id)s: %(exc)s')
LOG.error(msg, {'task_id': self.task_id,
'exc': exc_message})
'exc': exc})
return
if stderr:

View File

@@ -17,7 +17,6 @@ import hashlib
import glance_store as store
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
from taskflow.patterns import linear_flow as lf
from taskflow import retry
@@ -90,12 +89,10 @@ class _CalculateHash(task.Task):
self.image_repo.save(image)
except _HashCalculationCanceled as e:
with excutils.save_and_reraise_exception():
LOG.debug('Hash calculation cancelled: %s',
encodeutils.exception_to_unicode(e))
LOG.debug('Hash calculation cancelled: %s', e)
except IOError as e:
LOG.debug('[%i/%i] Hash calculation failed due to %s',
retries, CONF.http_retries,
encodeutils.exception_to_unicode(e))
retries, CONF.http_retries, str(e))
if retries == CONF.http_retries:
if image.status != 'active':
# NOTE(pdeore): The image location add operation

View File

@@ -19,7 +19,6 @@ import os
from oslo_concurrency import processutils as putils
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
from oslo_utils.imageutils import format_inspector
from taskflow.patterns import linear_flow as lf
@@ -157,10 +156,9 @@ class _ConvertImage(task.Task):
log_errors=putils.LOG_ALL_ERRORS,)
except OSError as exc:
with excutils.save_and_reraise_exception():
exc_message = encodeutils.exception_to_unicode(exc)
msg = ("Failed to do introspection as part of image "
"conversion for %(iid)s: %(err)s")
LOG.error(msg, {'iid': self.image_id, 'err': exc_message})
LOG.error(msg, {'iid': self.image_id, 'err': exc})
if stderr:
raise RuntimeError(stderr)
@@ -218,9 +216,8 @@ class _ConvertImage(task.Task):
log_errors=putils.LOG_ALL_ERRORS)
except OSError as exc:
with excutils.save_and_reraise_exception():
exc_message = encodeutils.exception_to_unicode(exc)
msg = "Failed to do image conversion for %(iid)s: %(err)s"
LOG.error(msg, {'iid': self.image_id, 'err': exc_message})
LOG.error(msg, {'iid': self.image_id, 'err': exc})
if stderr:
raise RuntimeError(stderr)

View File

@@ -19,7 +19,6 @@ import shutil
import zipfile
from oslo_log import log as logging
from oslo_utils import encodeutils
from taskflow.patterns import linear_flow as lf
from taskflow import task
@@ -60,9 +59,9 @@ def _zipfile(src_path, dest_path, image_id):
else:
zfd.extract(content[0], dest_path)
except Exception as e:
LOG.debug("ZIP: Error decompressing image %(iid)s: %(msg)s", {
LOG.debug("ZIP: Error decompressing image %(iid)s: %(exc)s", {
"iid": image_id,
"msg": encodeutils.exception_to_unicode(e)})
"exc": e})
raise
@@ -77,9 +76,9 @@ def _lhafile(src_path, dest_path, image_id):
else:
lfd.extract(content[0], dest_path)
except Exception as e:
LOG.debug("LHA: Error decompressing image %(iid)s: %(msg)s", {
LOG.debug("LHA: Error decompressing image %(iid)s: %(exc)s", {
"iid": image_id,
"msg": encodeutils.exception_to_unicode(e)})
"exc": e})
raise
@@ -90,13 +89,13 @@ def _gzipfile(src_path, dest_path, image_id):
shutil.copyfileobj(gzfd, fd)
except gzip.BadGzipFile as e:
LOG.debug("ZIP: Error decompressing image %(iid)s: Bad GZip file: "
"%(msg)s", {"iid": image_id,
"msg": encodeutils.exception_to_unicode(e)})
"%(exc)s", {"iid": image_id,
"exc": e})
raise
except Exception as e:
LOG.debug("GZIP: Error decompressing image %(iid)s: %(msg)s", {
LOG.debug("GZIP: Error decompressing image %(iid)s: %(exc)s", {
"iid": image_id,
"msg": encodeutils.exception_to_unicode(e)})
"exc": e})
raise

View File

@@ -17,7 +17,6 @@ import urllib
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
from stevedore import driver
from taskflow import engines
@@ -183,13 +182,12 @@ class TaskExecutor(glance.async_.TaskExecutor):
with llistener.DynamicLoggingListener(engine, log=LOG):
engine.run()
except exception.UploadException as exc:
task.fail(encodeutils.exception_to_unicode(exc))
task.fail(str(exc))
self.task_repo.save(task)
except Exception as exc:
with excutils.save_and_reraise_exception():
LOG.error(_LE('Failed to execute task %(task_id)s: %(exc)s'),
{'task_id': task_id,
'exc': encodeutils.exception_to_unicode(exc)})
{'task_id': task_id, 'exc': exc})
# TODO(sabari): Check for specific exceptions and update the
# task failure message.
task.fail(_('Task failed due to Internal Error'))

View File

@@ -15,7 +15,6 @@
from oslo_concurrency import processutils as putils
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import units
from taskflow import task
@@ -74,8 +73,7 @@ class OptionalTask(task.Task):
return func(*args, **kwargs)
except Exception as exc:
msg = (_LW("An optional task has failed, "
"the failure was: %s") %
encodeutils.exception_to_unicode(exc))
"the failure was: %s") % exc)
LOG.warning(msg)
return wrapper

View File

@@ -28,7 +28,6 @@ import eventlet
eventlet.patcher.monkey_patch()
from oslo_reports import guru_meditation_report as gmr
from oslo_utils import encodeutils
# If ../glance/__init__.py exists, add ../ to Python search path, so that
# it will override what happens to be installed in /usr/(local/)lib/python...
@@ -65,7 +64,7 @@ ERROR_CODE_MAP = {RuntimeError: 1,
def fail(e):
sys.stderr.write("ERROR: %s\n" % encodeutils.exception_to_unicode(e))
sys.stderr.write("ERROR: %s\n" % e)
return_code = ERROR_CODE_MAP.get(type(e), 99)
sys.exit(return_code)

View File

@@ -28,7 +28,6 @@ import sys
import time
import uuid
from oslo_utils import encodeutils
import prettytable
# If ../glance/__init__.py exists, add ../ to Python search path, so that
@@ -90,7 +89,7 @@ def catch_error(action):
if options.debug:
raise
print("Failed to %s. Got error:" % action)
pieces = encodeutils.exception_to_unicode(e).split('\n')
pieces = str(e).split('\n')
for piece in pieces:
print(piece)
return FAILURE

View File

@@ -569,7 +569,7 @@ def main():
for arg in CONF.command.action_args]
return CONF.command.action_fn(*func_args, **func_kwargs)
except exception.GlanceException as e:
sys.exit("ERROR: %s" % encodeutils.exception_to_unicode(e))
sys.exit("ERROR: %s" % e)
if __name__ == '__main__':

View File

@@ -24,7 +24,6 @@ import urllib.parse as urlparse
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import encodeutils
from oslo_utils import uuidutils
from webob import exc
@@ -735,7 +734,7 @@ def main():
try:
config.parse_args()
except RuntimeError as e:
sys.exit("ERROR: %s" % encodeutils.exception_to_unicode(e))
sys.exit("ERROR: %s" % e)
except SystemExit:
sys.exit("Please specify one command")
@@ -752,10 +751,10 @@ def main():
command(CONF, CONF.args)
except TypeError as e:
LOG.error(_LE(command.__doc__) % {'prog': command.__name__}) # noqa
sys.exit("ERROR: %s" % encodeutils.exception_to_unicode(e))
sys.exit("ERROR: %s" % e)
except ValueError as e:
LOG.error(_LE(command.__doc__) % {'prog': command.__name__}) # noqa
sys.exit("ERROR: %s" % encodeutils.exception_to_unicode(e))
sys.exit("ERROR: %s" % e)
if __name__ == '__main__':

View File

@@ -19,7 +19,6 @@ __all__ = [
from oslo_concurrency import lockutils
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
from glance.api.v2 import images as v2_api
@@ -62,8 +61,7 @@ def _execute(t_id, task_repo, image_repo, image_factory):
# TODO(nikhil): need to bring back save_and_reraise_exception when
# necessary
err_msg = ("Error: " + str(type(e)) + ': ' +
encodeutils.exception_to_unicode(e))
err_msg = ("Error: " + str(type(e)) + ': ' + str(e))
log_msg = err_msg + ("Task ID %s" % task.task_id)
LOG.exception(log_msg)
@@ -125,7 +123,7 @@ def set_image_data(image, uri, task_id, backend=None):
except Exception as e:
with excutils.save_and_reraise_exception():
LOG.warning("Task %(task_id)s failed with exception %(error)s",
{"error": encodeutils.exception_to_unicode(e),
{"error": e,
"task_id": task_id})
LOG.info("Task %(task_id)s: Could not import image file"
" %(image_data)s", {"image_data": uri,

View File

@@ -19,7 +19,6 @@ __all__ = [
from oslo_concurrency import lockutils
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
from glance.api.v2 import images as v2_api
@@ -64,8 +63,7 @@ def _execute(t_id, task_repo, image_repo, image_factory):
# TODO(nikhil): need to bring back save_and_reraise_exception when
# necessary
err_msg = ("Error: " + str(type(e)) + ': ' +
encodeutils.exception_to_unicode(e))
err_msg = ("Error: " + str(type(e)) + ': ' + str(e))
log_msg = _LE(err_msg + ("Task ID %s" % task.task_id)) # noqa
LOG.exception(log_msg)
@@ -153,7 +151,7 @@ def set_image_data(image, uri, task_id, backend=None, set_active=True,
with excutils.save_and_reraise_exception():
LOG.warning(_LW("Task %(task_id)s failed with exception "
"%(error)s"),
{"error": encodeutils.exception_to_unicode(e),
{"error": e,
"task_id": task_id})
LOG.info(_LI("Task %(task_id)s: Could not import image file"
" %(image_data)s"), {"image_data": uri,

View File

@@ -18,7 +18,6 @@ import urllib.parse as urlparse
import glance_store as store_api
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
import glance.db as db_api
from glance.i18n import _LE, _LW
@@ -72,7 +71,7 @@ def safe_delete_from_backend(context, image_id, location):
"this." % {'iid': image_id})
LOG.warning(msg)
except store_api.StoreDeleteNotSupported as e:
LOG.warning(encodeutils.exception_to_unicode(e))
LOG.warning(str(e))
except store_api.UnsupportedBackend:
exc_type = sys.exc_info()[0].__name__
msg = (_LE('Failed to delete image %(image_id)s from store: %(exc)s') %

View File

@@ -1173,12 +1173,10 @@ class Resource(object):
"decoded by Glance")
raise webob.exc.HTTPBadRequest(explanation=msg)
except exception.InvalidPropertyProtectionConfiguration as e:
LOG.exception(_LE("Caught error: %s"),
encodeutils.exception_to_unicode(e))
LOG.exception(_LE("Caught error: %s"), e)
raise webob.exc.HTTPBadRequest(explanation=e.msg)
except Exception as e:
LOG.exception(_LE("Caught error: %s"),
encodeutils.exception_to_unicode(e))
LOG.exception(_LE("Caught error: %s"), e)
response = webob.exc.HTTPInternalServerError()
return response

View File

@@ -25,7 +25,6 @@ import re
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import timeutils
import sqlalchemy
from sqlalchemy import and_
@@ -231,7 +230,7 @@ def _populate_metadata(meta, conn, metadata_path=None, merge=False,
if isfile(join(metadata_path, f))
and f.endswith('.json')]
except OSError as e:
LOG.error(encodeutils.exception_to_unicode(e))
LOG.error(str(e))
return
if not json_schema_files:
@@ -253,9 +252,9 @@ def _populate_metadata(meta, conn, metadata_path=None, merge=False,
metadata = json.load(json_file)
except Exception as e:
LOG.error(_LE("Failed to parse json file %(file_path)s while "
"populating metadata due to: %(error_msg)s"),
"populating metadata due to: %(exc)s"),
{"file_path": file,
"error_msg": encodeutils.exception_to_unicode(e)})
"exc": e})
continue
values = {
@@ -512,7 +511,7 @@ def _export_data_to_file(meta, conn, path):
with open(file_name, 'w') as json_file:
json_file.write(json.dumps(values))
except Exception as e:
LOG.exception(encodeutils.exception_to_unicode(e))
LOG.exception(str(e))
LOG.info(_LI("Namespace %(namespace)s saved in %(file)s"), {
'namespace': namespace_file_name, 'file': file_name})

View File

@@ -20,7 +20,6 @@ import hashlib
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
from oslo_utils import importutils
from oslo_utils import units
@@ -375,13 +374,13 @@ class ImageCache(object):
with excutils.save_and_reraise_exception():
# image_iter has given us bad, (size_checked_iter has found a
# bad length), or corrupt data (checksum is wrong).
LOG.exception(encodeutils.exception_to_unicode(e))
LOG.exception(str(e))
except Exception as e:
LOG.exception(_LE("Exception encountered while tee'ing "
"image '%(image_id)s' into cache: %(error)s. "
"Continuing with response."),
{'image_id': image_id,
'error': encodeutils.exception_to_unicode(e)})
'error': e})
# If no checksum provided continue responding even if
# caching failed.

View File

@@ -58,7 +58,6 @@ import time
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
from oslo_utils import fileutils
import xattr
@@ -279,13 +278,13 @@ class Driver(base.Driver):
self.get_image_filepath(image_id, 'queue'))
def rollback(e):
set_attr('error', encodeutils.exception_to_unicode(e))
set_attr('error', str(e))
invalid_path = self.get_image_filepath(image_id, 'invalid')
LOG.debug("Fetch of cache file failed (%(e)s), rolling back by "
"moving '%(incomplete_path)s' to "
"'%(invalid_path)s'",
{'e': encodeutils.exception_to_unicode(e),
{'e': e,
'incomplete_path': incomplete_path,
'invalid_path': invalid_path})
os.rename(incomplete_path, invalid_path)

View File

@@ -23,7 +23,6 @@ from cursive import signature_utils
import glance_store as store
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
from oslo_utils.imageutils import format_inspector
@@ -694,8 +693,7 @@ class ImageProxy(glance.domain.proxy.Image):
except Exception as e:
LOG.warning(_LW('Get image %(id)s data failed: '
'%(err)s.'),
{'id': self.image.image_id,
'err': encodeutils.exception_to_unicode(e)})
{'id': self.image.image_id, 'err': e})
err = e
# tried all locations
LOG.error(_LE('Glance tried all active locations to get data for '

View File

@@ -20,7 +20,6 @@ import glance_store
from oslo_config import cfg
from oslo_log import log as logging
import oslo_messaging
from oslo_utils import encodeutils
from oslo_utils import excutils
import webob
@@ -443,57 +442,54 @@ class ImageProxy(NotificationProxy, domain_proxy.Image):
self.repo.set_data(data, size, backend=backend,
set_active=set_active)
except glance_store.StorageFull as e:
msg = (_("Image storage media is full: %s") %
encodeutils.exception_to_unicode(e))
msg = _("Image storage media is full: %s") % e
_send_notification(notify_error, 'image.upload', msg)
raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg)
except glance_store.StorageWriteDenied as e:
msg = (_("Insufficient permissions on image storage media: %s")
% encodeutils.exception_to_unicode(e))
msg = _("Insufficient permissions on image storage media: %s") % e
_send_notification(notify_error, 'image.upload', msg)
raise webob.exc.HTTPServiceUnavailable(explanation=msg)
except ValueError as e:
msg = (_("Cannot save data for image %(image_id)s: %(error)s") %
{'image_id': self.repo.image_id,
'error': encodeutils.exception_to_unicode(e)})
'error': e})
_send_notification(notify_error, 'image.upload', msg)
raise webob.exc.HTTPBadRequest(
explanation=encodeutils.exception_to_unicode(e))
explanation=str(e))
except exception.Duplicate as e:
msg = (_("Unable to upload duplicate image data for image "
"%(image_id)s: %(error)s") %
{'image_id': self.repo.image_id,
'error': encodeutils.exception_to_unicode(e)})
'error': e})
_send_notification(notify_error, 'image.upload', msg)
raise webob.exc.HTTPConflict(explanation=msg)
except exception.Forbidden as e:
msg = (_("Not allowed to upload image data for image %(image_id)s:"
" %(error)s")
% {'image_id': self.repo.image_id,
'error': encodeutils.exception_to_unicode(e)})
'error': e})
_send_notification(notify_error, 'image.upload', msg)
raise webob.exc.HTTPForbidden(explanation=msg)
except exception.NotFound as e:
exc_str = encodeutils.exception_to_unicode(e)
msg = (_("Image %(image_id)s could not be found after upload."
" The image may have been deleted during the upload:"
" %(error)s") % {'image_id': self.repo.image_id,
'error': exc_str})
'error': e})
_send_notification(notify_error, 'image.upload', msg)
raise webob.exc.HTTPNotFound(explanation=exc_str)
raise webob.exc.HTTPNotFound(explanation=str(e))
except webob.exc.HTTPError as e:
with excutils.save_and_reraise_exception():
msg = (_("Failed to upload image data for image %(image_id)s"
" due to HTTP error: %(error)s") %
{'image_id': self.repo.image_id,
'error': encodeutils.exception_to_unicode(e)})
'error': e})
_send_notification(notify_error, 'image.upload', msg)
except Exception as e:
with excutils.save_and_reraise_exception():
msg = (_("Failed to upload image data for image %(image_id)s "
"due to internal error: %(error)s") %
{'image_id': self.repo.image_id,
'error': encodeutils.exception_to_unicode(e)})
'error': e})
_send_notification(notify_error, 'image.upload', msg)
else:
extra_payload = self._format_import_properties()

View File

@@ -17,7 +17,6 @@ import copy
import glance_store as store
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
import glance.api.common
@@ -112,7 +111,7 @@ class ImageRepoProxy(glance.domain.proxy.Repo):
if attempted > maximum:
kwargs = {'attempted': attempted, 'maximum': maximum}
exc = exception.ImagePropertyLimitExceeded(**kwargs)
LOG.debug(encodeutils.exception_to_unicode(exc))
LOG.debug(str(exc))
raise exc
def save(self, image, from_state=None):

View File

@@ -14,7 +14,6 @@
# under the License.
import jsonschema
from oslo_utils import encodeutils
from glance.common import exception
from glance.i18n import _
@@ -36,8 +35,7 @@ class Schema(object):
try:
jsonschema.validate(obj, self.raw())
except jsonschema.ValidationError as e:
reason = encodeutils.exception_to_unicode(e)
raise exception.InvalidObject(schema=self.name, reason=reason)
raise exception.InvalidObject(schema=self.name, reason=str(e))
def filter(self, obj):
filtered = {}

View File

@@ -20,7 +20,6 @@ import time
from glance_store import exceptions as store_exceptions
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import encodeutils
from glance.common import crypt
from glance.common import exception
@@ -331,8 +330,7 @@ class Scrubber(object):
except Exception as err:
# Note(dharinic): spawn_n, in Daemon mode will log the
# exception raised. Otherwise, exit 1 will occur.
msg = (_LC("Can not get scrub jobs from queue: %s") %
encodeutils.exception_to_unicode(err))
msg = _LC("Can not get scrub jobs from queue: %s") % err
LOG.critical(msg)
raise exception.FailedToGetScrubberJobs()
@@ -412,8 +410,7 @@ class Scrubber(object):
except Exception as e:
LOG.error(_LE("Unable to scrub image %(id)s from a location. "
"Reason: %(exc)s "),
{'id': image_id,
'exc': encodeutils.exception_to_unicode(e)})
{'id': image_id, 'exc': e})
raise
def revert_image_status(self, image_id):

View File

@@ -15,8 +15,6 @@
import http.client as http
from oslo_utils import encodeutils
from glance.common import exception
from glance.tests import utils as test_utils
@@ -28,26 +26,20 @@ class GlanceExceptionTestCase(test_utils.BaseTestCase):
message = "default message"
exc = FakeGlanceException()
self.assertEqual('default message',
encodeutils.exception_to_unicode(exc))
self.assertEqual('default message', str(exc))
def test_specified_error_msg(self):
msg = exception.GlanceException('test')
self.assertIn('test', encodeutils.exception_to_unicode(msg))
self.assertIn('test', str(msg))
def test_default_error_msg_with_kwargs(self):
class FakeGlanceException(exception.GlanceException):
message = "default message: %(code)s"
exc = FakeGlanceException(code=int(http.INTERNAL_SERVER_ERROR))
self.assertEqual("default message: 500",
encodeutils.exception_to_unicode(exc))
self.assertEqual("default message: 500", str(exc))
def test_specified_error_msg_with_kwargs(self):
msg = exception.GlanceException('test: %(code)s',
code=int(http.INTERNAL_SERVER_ERROR))
self.assertIn('test: 500', encodeutils.exception_to_unicode(msg))
def test_non_unicode_error_msg(self):
exc = exception.GlanceException('test')
self.assertIsInstance(encodeutils.exception_to_unicode(exc), str)
self.assertIn('test: 500', str(msg))

View File

@@ -20,7 +20,6 @@ import uuid
from oslo_config import cfg
from oslo_db import exception as db_exc
from oslo_utils import encodeutils
from oslo_utils.fixture import uuidsentinel as uuids
from oslo_utils import timeutils
from sqlalchemy import orm as sa_orm
@@ -380,7 +379,7 @@ class TestImageRepo(test_utils.BaseTestCase):
fake_uuid = str(uuid.uuid4())
exc = self.assertRaises(exception.ImageNotFound, self.image_repo.get,
fake_uuid)
self.assertIn(fake_uuid, encodeutils.exception_to_unicode(exc))
self.assertIn(fake_uuid, str(exc))
def test_get_forbidden(self):
self.assertRaises(exception.NotFound, self.image_repo.get, UUID4)
@@ -592,7 +591,7 @@ class TestImageRepo(test_utils.BaseTestCase):
image.image_id = fake_uuid
exc = self.assertRaises(exception.ImageNotFound, self.image_repo.save,
image)
self.assertIn(fake_uuid, encodeutils.exception_to_unicode(exc))
self.assertIn(fake_uuid, str(exc))
def test_save_excludes_atomic_props(self):
fake_uuid = str(uuid.uuid4())
@@ -645,7 +644,7 @@ class TestImageRepo(test_utils.BaseTestCase):
image.image_id = fake_uuid
exc = self.assertRaises(
exception.ImageNotFound, self.image_repo.remove, image)
self.assertIn(fake_uuid, encodeutils.exception_to_unicode(exc))
self.assertIn(fake_uuid, str(exc))
def test_restore_image_status(self):
image_id = uuid.uuid4()
@@ -920,7 +919,7 @@ class TestImageMemberRepo(test_utils.BaseTestCase):
exc = self.assertRaises(exception.NotFound,
self.image_member_repo.remove,
fake_member)
self.assertIn(fake_uuid, encodeutils.exception_to_unicode(exc))
self.assertIn(fake_uuid, str(exc))
class TestTaskRepo(test_utils.BaseTestCase):

View File

@@ -14,8 +14,6 @@
# License for the specific language governing permissions and limitations
# under the License.
from oslo_utils import encodeutils
from glance.common import exception
import glance.context
import glance.db
@@ -245,7 +243,7 @@ class TestMetadefRepo(test_utils.BaseTestCase):
exc = self.assertRaises(exception.NotFound,
self.namespace_repo.get,
fake_namespace)
self.assertIn(fake_namespace, encodeutils.exception_to_unicode(exc))
self.assertIn(fake_namespace, str(exc))
def test_get_namespace_forbidden(self):
self.assertRaises(exception.MetadefForbidden,
@@ -300,7 +298,7 @@ class TestMetadefRepo(test_utils.BaseTestCase):
namespace.namespace = fake_name
exc = self.assertRaises(exception.NotFound, self.namespace_repo.remove,
namespace)
self.assertIn(fake_name, encodeutils.exception_to_unicode(exc))
self.assertIn(fake_name, str(exc))
def test_get_property(self):
property = self.property_repo.get(NAMESPACE1, PROPERTY1)
@@ -312,7 +310,7 @@ class TestMetadefRepo(test_utils.BaseTestCase):
exc = self.assertRaises(exception.NotFound,
self.property_repo.get,
NAMESPACE2, PROPERTY1)
self.assertIn(PROPERTY1, encodeutils.exception_to_unicode(exc))
self.assertIn(PROPERTY1, str(exc))
def test_list_property(self):
properties = self.property_repo.list(filters={'namespace': NAMESPACE1})
@@ -329,7 +327,7 @@ class TestMetadefRepo(test_utils.BaseTestCase):
def test_list_property_namespace_not_found(self):
exc = self.assertRaises(exception.NotFound, self.property_repo.list,
filters={'namespace': 'not-a-namespace'})
self.assertIn('not-a-namespace', encodeutils.exception_to_unicode(exc))
self.assertIn('not-a-namespace', str(exc))
def test_add_property(self):
# NOTE(pawel-koniszewski): Change db_property_fixture to
@@ -393,7 +391,7 @@ class TestMetadefRepo(test_utils.BaseTestCase):
def test_get_object_not_found(self):
exc = self.assertRaises(exception.NotFound, self.object_repo.get,
NAMESPACE2, OBJECT1)
self.assertIn(OBJECT1, encodeutils.exception_to_unicode(exc))
self.assertIn(OBJECT1, str(exc))
def test_list_object(self):
objects = self.object_repo.list(filters={'namespace': NAMESPACE1})
@@ -408,7 +406,7 @@ class TestMetadefRepo(test_utils.BaseTestCase):
def test_list_object_namespace_not_found(self):
exc = self.assertRaises(exception.NotFound, self.object_repo.list,
filters={'namespace': 'not-a-namespace'})
self.assertIn('not-a-namespace', encodeutils.exception_to_unicode(exc))
self.assertIn('not-a-namespace', str(exc))
def test_add_object(self):
# NOTE(pawel-koniszewski): Change db_object_fixture to
@@ -476,7 +474,7 @@ class TestMetadefRepo(test_utils.BaseTestCase):
def test_get_tag_not_found(self):
exc = self.assertRaises(exception.NotFound, self.tag_repo.get,
NAMESPACE2, TAG1)
self.assertIn(TAG1, encodeutils.exception_to_unicode(exc))
self.assertIn(TAG1, str(exc))
def test_list_tag(self):
tags = self.tag_repo.list(filters={'namespace': NAMESPACE1})
@@ -491,7 +489,7 @@ class TestMetadefRepo(test_utils.BaseTestCase):
def test_list_tag_namespace_not_found(self):
exc = self.assertRaises(exception.NotFound, self.tag_repo.list,
filters={'namespace': 'not-a-namespace'})
self.assertIn('not-a-namespace', encodeutils.exception_to_unicode(exc))
self.assertIn('not-a-namespace', str(exc))
def test_add_tag(self):
# NOTE(pawel-koniszewski): Change db_tag_fixture to

View File

@@ -20,7 +20,6 @@ from unittest.mock import patch
import uuid
from oslo_limit import exception as ol_exc
from oslo_utils import encodeutils
from oslo_utils import units
from glance.common import exception
@@ -405,8 +404,7 @@ class TestImagePropertyQuotas(test_utils.BaseTestCase):
self.image.extra_properties = {'foo': 'bar', 'foo2': 'bar2'}
exc = self.assertRaises(exception.ImagePropertyLimitExceeded,
self.image_repo_proxy.save, self.image)
self.assertIn("Attempted: 2, Maximum: 1",
encodeutils.exception_to_unicode(exc))
self.assertIn("Attempted: 2, Maximum: 1", str(exc))
def test_save_image_unlimited_image_properties(self):
self.config(image_property_quota=-1)
@@ -431,8 +429,7 @@ class TestImagePropertyQuotas(test_utils.BaseTestCase):
self.image.extra_properties = {'foo': 'bar', 'foo2': 'bar2'}
exc = self.assertRaises(exception.ImagePropertyLimitExceeded,
self.image_repo_proxy.add, self.image)
self.assertIn("Attempted: 2, Maximum: 1",
encodeutils.exception_to_unicode(exc))
self.assertIn("Attempted: 2, Maximum: 1", str(exc))
def test_add_image_unlimited_image_properties(self):
self.config(image_property_quota=-1)
@@ -543,8 +540,7 @@ class TestImageTagQuotas(test_utils.BaseTestCase):
exc = self.assertRaises(exception.ImageTagLimitExceeded,
setattr, self.image, 'tags', ['foo', 'bar'])
self.assertIn('Attempted: 2, Maximum: 0',
encodeutils.exception_to_unicode(exc))
self.assertIn('Attempted: 2, Maximum: 0', str(exc))
self.assertEqual(0, len(self.image.tags))
def test_replace_unlimited_image_tags(self):
@@ -562,8 +558,7 @@ class TestImageTagQuotas(test_utils.BaseTestCase):
self.image.tags.add('foo')
exc = self.assertRaises(exception.ImageTagLimitExceeded,
self.image.tags.add, 'bar')
self.assertIn('Attempted: 2, Maximum: 1',
encodeutils.exception_to_unicode(exc))
self.assertIn('Attempted: 2, Maximum: 1', str(exc))
def test_add_unlimited_image_tags(self):
self.config(image_tag_quota=-1)
@@ -594,8 +589,7 @@ class TestQuotaImageTagsProxy(test_utils.BaseTestCase):
proxy = glance.quota.QuotaImageTagsProxy(set([]))
exc = self.assertRaises(exception.ImageTagLimitExceeded,
proxy.add, 'bar')
self.assertIn('Attempted: 1, Maximum: 0',
encodeutils.exception_to_unicode(exc))
self.assertIn('Attempted: 1, Maximum: 0', str(exc))
def test_equals(self):
proxy = glance.quota.QuotaImageTagsProxy(set([]))
@@ -721,8 +715,7 @@ class TestImageLocationQuotas(test_utils.BaseTestCase):
]
exc = self.assertRaises(exception.ImageLocationLimitExceeded,
setattr, self.image, 'locations', locations)
self.assertIn('Attempted: 3, Maximum: 1',
encodeutils.exception_to_unicode(exc))
self.assertIn('Attempted: 3, Maximum: 1', str(exc))
self.assertEqual(1, len(self.image.locations))
def test_replace_unlimited_image_locations(self):
@@ -745,8 +738,7 @@ class TestImageLocationQuotas(test_utils.BaseTestCase):
location2 = {"url": "file:///fake2.img.tar.gz", "metadata": {}}
exc = self.assertRaises(exception.ImageLocationLimitExceeded,
self.image.locations.append, location2)
self.assertIn('Attempted: 2, Maximum: 1',
encodeutils.exception_to_unicode(exc))
self.assertIn('Attempted: 2, Maximum: 1', str(exc))
def test_add_unlimited_image_locations(self):
self.config(image_location_quota=-1)