Clean up pep8 E128 violations

Fixed E128 errors
All ignores are to be removed in the next sequence of patches

Change-Id: I3ccff7df8c382f83ae6aa9aa6a7f16324c3aec75
This commit is contained in:
Zhongyue Luo 2012-09-20 14:06:57 +08:00
parent 46d38734ec
commit cb64f58b99
45 changed files with 630 additions and 435 deletions

View File

@ -22,13 +22,13 @@ LOG = logging.getLogger(__name__)
def size_checked_iter(response, image_meta, expected_size, image_iter, def size_checked_iter(response, image_meta, expected_size, image_iter,
notifier): notifier):
image_id = image_meta['id'] image_id = image_meta['id']
bytes_written = 0 bytes_written = 0
def notify_image_sent_hook(env): def notify_image_sent_hook(env):
image_send_notification(bytes_written, expected_size, image_send_notification(bytes_written, expected_size,
image_meta, response.request, notifier) image_meta, response.request, notifier)
# Add hook to process after response is fully sent # Add hook to process after response is fully sent
if 'eventlet.posthooks' in response.request.environ: if 'eventlet.posthooks' in response.request.environ:
@ -55,7 +55,7 @@ def size_checked_iter(response, image_meta, expected_size, image_iter,
def image_send_notification(bytes_written, expected_size, image_meta, request, def image_send_notification(bytes_written, expected_size, image_meta, request,
notifier): notifier):
"""Send an image.send message to the notifier.""" """Send an image.send message to the notifier."""
try: try:
context = request.context context = request.context

View File

@ -34,39 +34,39 @@ class CacheManageFilter(wsgi.Middleware):
resource = cached_images.create_resource() resource = cached_images.create_resource()
mapper.connect("/v1/cached_images", mapper.connect("/v1/cached_images",
controller=resource, controller=resource,
action="get_cached_images", action="get_cached_images",
conditions=dict(method=["GET"])) conditions=dict(method=["GET"]))
mapper.connect("/v1/cached_images/{image_id}", mapper.connect("/v1/cached_images/{image_id}",
controller=resource, controller=resource,
action="delete_cached_image", action="delete_cached_image",
conditions=dict(method=["DELETE"])) conditions=dict(method=["DELETE"]))
mapper.connect("/v1/cached_images", mapper.connect("/v1/cached_images",
controller=resource, controller=resource,
action="delete_cached_images", action="delete_cached_images",
conditions=dict(method=["DELETE"])) conditions=dict(method=["DELETE"]))
mapper.connect("/v1/queued_images/{image_id}", mapper.connect("/v1/queued_images/{image_id}",
controller=resource, controller=resource,
action="queue_image", action="queue_image",
conditions=dict(method=["PUT"])) conditions=dict(method=["PUT"]))
mapper.connect("/v1/queued_images", mapper.connect("/v1/queued_images",
controller=resource, controller=resource,
action="get_queued_images", action="get_queued_images",
conditions=dict(method=["GET"])) conditions=dict(method=["GET"]))
mapper.connect("/v1/queued_images/{image_id}", mapper.connect("/v1/queued_images/{image_id}",
controller=resource, controller=resource,
action="delete_queued_image", action="delete_queued_image",
conditions=dict(method=["DELETE"])) conditions=dict(method=["DELETE"]))
mapper.connect("/v1/queued_images", mapper.connect("/v1/queued_images",
controller=resource, controller=resource,
action="delete_queued_images", action="delete_queued_images",
conditions=dict(method=["DELETE"])) conditions=dict(method=["DELETE"]))
self._mapper = mapper self._mapper = mapper
self._resource = resource self._resource = resource

View File

@ -47,8 +47,9 @@ class BaseController(object):
except exception.Forbidden: except exception.Forbidden:
msg = _("Forbidden image access") msg = _("Forbidden image access")
LOG.debug(msg) LOG.debug(msg)
raise webob.exc.HTTPForbidden(msg, request=request, raise webob.exc.HTTPForbidden(msg,
content_type='text/plain') request=request,
content_type='text/plain')
def get_active_image_meta_or_404(self, request, image_id): def get_active_image_meta_or_404(self, request, image_id):
""" """

View File

@ -58,7 +58,7 @@ SUPPORTED_PARAMS = glance.api.v1.SUPPORTED_PARAMS
SUPPORTED_FILTERS = glance.api.v1.SUPPORTED_FILTERS SUPPORTED_FILTERS = glance.api.v1.SUPPORTED_FILTERS
CONTAINER_FORMATS = ['ami', 'ari', 'aki', 'bare', 'ovf'] CONTAINER_FORMATS = ['ami', 'ari', 'aki', 'bare', 'ovf']
DISK_FORMATS = ['ami', 'ari', 'aki', 'vhd', 'vmdk', 'raw', 'qcow2', 'vdi', DISK_FORMATS = ['ami', 'ari', 'aki', 'vhd', 'vmdk', 'raw', 'qcow2', 'vdi',
'iso'] 'iso']
# Defined at module level due to _is_opt_registered # Defined at module level due to _is_opt_registered
@ -361,8 +361,8 @@ class Controller(controller.BaseController):
image_meta = registry.add_image_metadata(req.context, image_meta) image_meta = registry.add_image_metadata(req.context, image_meta)
return image_meta return image_meta
except exception.Duplicate: except exception.Duplicate:
msg = (_("An image with identifier %s already exists") msg = (_("An image with identifier %s already exists") %
% image_meta['id']) image_meta['id'])
LOG.error(msg) LOG.error(msg)
raise HTTPConflict(explanation=msg, raise HTTPConflict(explanation=msg,
request=req, request=req,
@ -440,9 +440,9 @@ class Controller(controller.BaseController):
supplied_checksum = image_meta.get('checksum') supplied_checksum = image_meta.get('checksum')
if supplied_checksum and supplied_checksum != checksum: if supplied_checksum and supplied_checksum != checksum:
msg = _("Supplied checksum (%(supplied_checksum)s) and " msg = _("Supplied checksum (%(supplied_checksum)s) and "
"checksum generated from uploaded image " "checksum generated from uploaded image "
"(%(checksum)s) did not match. Setting image " "(%(checksum)s) did not match. Setting image "
"status to 'killed'.") % locals() "status to 'killed'.") % locals()
LOG.error(msg) LOG.error(msg)
self._safe_kill(req, image_id) self._safe_kill(req, image_id)
raise HTTPBadRequest(explanation=msg, raise HTTPBadRequest(explanation=msg,
@ -515,7 +515,7 @@ class Controller(controller.BaseController):
msg = _("Error uploading image: (%(class_name)s): " msg = _("Error uploading image: (%(class_name)s): "
"%(exc)s") % ({'class_name': e.__class__.__name__, "%(exc)s") % ({'class_name': e.__class__.__name__,
'exc': str(e)}) 'exc': str(e)})
raise HTTPBadRequest(explanation=msg, request=req) raise HTTPBadRequest(explanation=msg, request=req)
@ -534,8 +534,8 @@ class Controller(controller.BaseController):
try: try:
image_meta_data = registry.update_image_metadata(req.context, image_meta_data = registry.update_image_metadata(req.context,
image_id, image_id,
image_meta) image_meta)
self.notifier.info("image.update", image_meta_data) self.notifier.info("image.update", image_meta_data)
return image_meta_data return image_meta_data
except exception.Invalid, e: except exception.Invalid, e:
@ -572,7 +572,7 @@ class Controller(controller.BaseController):
except Exception, e: except Exception, e:
LOG.error(_("Unable to kill image %(id)s: " LOG.error(_("Unable to kill image %(id)s: "
"%(exc)s") % ({'id': image_id, "%(exc)s") % ({'id': image_id,
'exc': repr(e)})) 'exc': repr(e)}))
def _upload_and_activate(self, req, image_meta): def _upload_and_activate(self, req, image_meta):
""" """
@ -600,8 +600,9 @@ class Controller(controller.BaseController):
def _handle_source(self, req, image_id, image_meta, image_data): def _handle_source(self, req, image_id, image_meta, image_data):
if image_data: if image_data:
image_meta = self._validate_image_for_activation(req, image_id, image_meta = self._validate_image_for_activation(req,
image_meta) image_id,
image_meta)
image_meta = self._upload_and_activate(req, image_meta) image_meta = self._upload_and_activate(req, image_meta)
elif self._copy_from(req): elif self._copy_from(req):
msg = _('Triggering asynchronous copy from external source') msg = _('Triggering asynchronous copy from external source')

View File

@ -73,13 +73,13 @@ class ImageDataController(object):
msg = _("Image storage media is full: %s") % e msg = _("Image storage media is full: %s") % e
LOG.error(msg) LOG.error(msg)
raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg, raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg,
request=req) request=req)
except exception.StorageWriteDenied, e: except exception.StorageWriteDenied, e:
msg = _("Insufficient permissions on image storage media: %s") % e msg = _("Insufficient permissions on image storage media: %s") % e
LOG.error(msg) LOG.error(msg)
raise webob.exc.HTTPServiceUnavailable(explanation=msg, raise webob.exc.HTTPServiceUnavailable(explanation=msg,
request=req) request=req)
except webob.exc.HTTPError, e: except webob.exc.HTTPError, e:
LOG.error("Failed to upload image data due to HTTP error") LOG.error("Failed to upload image data due to HTTP error")

View File

@ -42,7 +42,7 @@ CONF = cfg.CONF
class ImagesController(object): class ImagesController(object):
def __init__(self, db_api=None, policy_enforcer=None, notifier=None, def __init__(self, db_api=None, policy_enforcer=None, notifier=None,
store_api=None): store_api=None):
self.db_api = db_api or glance.db.get_api() self.db_api = db_api or glance.db.get_api()
self.db_api.configure_db() self.db_api.configure_db()
self.policy = policy_enforcer or policy.Enforcer() self.policy = policy_enforcer or policy.Enforcer()
@ -289,12 +289,13 @@ class ImagesController(object):
class RequestDeserializer(wsgi.JSONRequestDeserializer): class RequestDeserializer(wsgi.JSONRequestDeserializer):
_readonly_properties = ['created_at', 'updated_at', 'status', 'checksum', _readonly_properties = ['created_at', 'updated_at', 'status', 'checksum',
'size', 'direct_url', 'self', 'file', 'schema'] 'size', 'direct_url', 'self', 'file', 'schema']
_reserved_properties = ['owner', 'is_public', 'location', _reserved_properties = ['owner', 'is_public', 'location', 'deleted',
'deleted', 'deleted_at'] 'deleted_at']
_base_properties = ['checksum', 'created_at', 'container_format', _base_properties = ['checksum', 'created_at', 'container_format',
'disk_format', 'id', 'min_disk', 'min_ram', 'name', 'size', 'disk_format', 'id', 'min_disk', 'min_ram', 'name',
'status', 'tags', 'updated_at', 'visibility', 'protected'] 'size', 'status', 'tags', 'updated_at', 'visibility',
'protected']
def __init__(self, schema=None): def __init__(self, schema=None):
super(RequestDeserializer, self).__init__() super(RequestDeserializer, self).__init__()

View File

@ -189,12 +189,12 @@ class BadRegistryConnectionConfiguration(GlanceException):
class BadStoreConfiguration(GlanceException): class BadStoreConfiguration(GlanceException):
message = _("Store %(store_name)s could not be configured correctly. " message = _("Store %(store_name)s could not be configured correctly. "
"Reason: %(reason)s") "Reason: %(reason)s")
class BadDriverConfiguration(GlanceException): class BadDriverConfiguration(GlanceException):
message = _("Driver %(driver_name)s could not be configured correctly. " message = _("Driver %(driver_name)s could not be configured correctly. "
"Reason: %(reason)s") "Reason: %(reason)s")
class StoreDeleteNotSupported(GlanceException): class StoreDeleteNotSupported(GlanceException):
@ -203,7 +203,7 @@ class StoreDeleteNotSupported(GlanceException):
class StoreAddDisabled(GlanceException): class StoreAddDisabled(GlanceException):
message = _("Configuration for store failed. Adding images to this " message = _("Configuration for store failed. Adding images to this "
"store is disabled.") "store is disabled.")
class InvalidNotifierStrategy(GlanceException): class InvalidNotifierStrategy(GlanceException):

View File

@ -340,17 +340,17 @@ def get_terminal_size():
try: try:
height_width = struct.unpack('hh', fcntl.ioctl(sys.stderr.fileno(), height_width = struct.unpack('hh', fcntl.ioctl(sys.stderr.fileno(),
termios.TIOCGWINSZ, termios.TIOCGWINSZ,
struct.pack('HH', 0, 0))) struct.pack('HH', 0, 0)))
except: except:
pass pass
if not height_width: if not height_width:
try: try:
p = subprocess.Popen(['stty', 'size'], p = subprocess.Popen(['stty', 'size'],
shell=False, shell=False,
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=open(os.devnull, 'w')) stderr=open(os.devnull, 'w'))
result = p.communicate() result = p.communicate()
if p.returncode == 0: if p.returncode == 0:
return tuple(int(x) for x in result[0].split()) return tuple(int(x) for x in result[0].split())
@ -371,7 +371,7 @@ def get_terminal_size():
import struct import struct
unpack_tmp = struct.unpack("hhhhHhhhhhh", csbi.raw) unpack_tmp = struct.unpack("hhhhHhhhhhh", csbi.raw)
(bufx, bufy, curx, cury, wattr, (bufx, bufy, curx, cury, wattr,
left, top, right, bottom, maxx, maxy) = unpack_tmp left, top, right, bottom, maxx, maxy) = unpack_tmp
height = bottom - top + 1 height = bottom - top + 1
width = right - left + 1 width = right - left + 1
return (height, width) return (height, width)

View File

@ -98,9 +98,13 @@ def get_socket(default_port):
# TODO(jaypipes): eventlet's greened socket module does not actually # TODO(jaypipes): eventlet's greened socket module does not actually
# support IPv6 in getaddrinfo(). We need to get around this in the # support IPv6 in getaddrinfo(). We need to get around this in the
# future or monitor upstream for a fix # future or monitor upstream for a fix
address_family = [addr[0] for addr in socket.getaddrinfo(bind_addr[0], address_family = [
bind_addr[1], socket.AF_UNSPEC, socket.SOCK_STREAM) addr[0] for addr in socket.getaddrinfo(bind_addr[0],
if addr[0] in (socket.AF_INET, socket.AF_INET6)][0] bind_addr[1],
socket.AF_UNSPEC,
socket.SOCK_STREAM)
if addr[0] in (socket.AF_INET, socket.AF_INET6)
][0]
cert_file = CONF.cert_file cert_file = CONF.cert_file
key_file = CONF.key_file key_file = CONF.key_file
@ -272,8 +276,10 @@ class Server(object):
raise exception.WorkerCreationFailure(reason=msg) raise exception.WorkerCreationFailure(reason=msg)
self.pool = self.create_pool() self.pool = self.create_pool()
try: try:
eventlet.wsgi.server(self.sock, self.app_func(), eventlet.wsgi.server(self.sock,
log=WritableLogger(self.logger), custom_pool=self.pool) self.app_func(),
log=WritableLogger(self.logger),
custom_pool=self.pool)
except socket.error, err: except socket.error, err:
if err[0] != errno.EINVAL: if err[0] != errno.EINVAL:
raise raise

View File

@ -239,8 +239,9 @@ def image_get_all(context, filters=None, marker=None, limit=None,
@log_call @log_call
def image_property_create(context, values): def image_property_create(context, values):
image = image_get(context, values['image_id']) image = image_get(context, values['image_id'])
prop = _image_property_format(values['image_id'], values['name'], prop = _image_property_format(values['image_id'],
values['value']) values['name'],
values['value'])
image['properties'].append(prop) image['properties'].append(prop)
return prop return prop

View File

@ -22,22 +22,29 @@ from glance.db.sqlalchemy.migrate_repo.schema import (
def define_images_table(meta): def define_images_table(meta):
images = Table('images', meta, images = Table('images',
Column('id', Integer(), primary_key=True, nullable=False), meta,
Column('name', String(255)), Column('id', Integer(), primary_key=True, nullable=False),
Column('type', String(30)), Column('name', String(255)),
Column('size', Integer()), Column('type', String(30)),
Column('status', String(30), nullable=False), Column('size', Integer()),
Column('is_public', Boolean(), nullable=False, default=False, Column('status', String(30), nullable=False),
index=True), Column('is_public',
Column('location', Text()), Boolean(),
Column('created_at', DateTime(), nullable=False), nullable=False,
Column('updated_at', DateTime()), default=False,
Column('deleted_at', DateTime()), index=True),
Column('deleted', Boolean(), nullable=False, default=False, Column('location', Text()),
index=True), Column('created_at', DateTime(), nullable=False),
mysql_engine='InnoDB', Column('updated_at', DateTime()),
extend_existing=True) Column('deleted_at', DateTime()),
Column('deleted',
Boolean(),
nullable=False,
default=False,
index=True),
mysql_engine='InnoDB',
extend_existing=True)
return images return images

View File

@ -29,22 +29,33 @@ def define_image_properties_table(meta):
images = define_images_table(meta) images = define_images_table(meta)
image_properties = Table('image_properties', meta, image_properties = Table('image_properties',
Column('id', Integer(), primary_key=True, nullable=False), meta,
Column('image_id', Integer(), ForeignKey('images.id'), nullable=False, Column('id',
index=True), Integer(),
Column('key', String(255), nullable=False), primary_key=True,
Column('value', Text()), nullable=False),
Column('created_at', DateTime(), nullable=False), Column('image_id',
Column('updated_at', DateTime()), Integer(),
Column('deleted_at', DateTime()), ForeignKey('images.id'),
Column('deleted', Boolean(), nullable=False, default=False, nullable=False,
index=True), index=True),
UniqueConstraint('image_id', 'key'), Column('key', String(255), nullable=False),
mysql_engine='InnoDB', Column('value', Text()),
extend_existing=True) Column('created_at', DateTime(), nullable=False),
Column('updated_at', DateTime()),
Column('deleted_at', DateTime()),
Column('deleted',
Boolean(),
nullable=False,
default=False,
index=True),
UniqueConstraint('image_id', 'key'),
mysql_engine='InnoDB',
extend_existing=True)
Index('ix_image_properties_image_id_key', image_properties.c.image_id, Index('ix_image_properties_image_id_key',
image_properties.c.image_id,
image_properties.c.key) image_properties.c.key)
return image_properties return image_properties

View File

@ -27,23 +27,30 @@ def get_images_table(meta):
Returns the Table object for the images table that Returns the Table object for the images table that
corresponds to the images table definition of this version. corresponds to the images table definition of this version.
""" """
images = Table('images', meta, images = Table('images',
Column('id', Integer(), primary_key=True, nullable=False), meta,
Column('name', String(255)), Column('id', Integer(), primary_key=True, nullable=False),
Column('disk_format', String(20)), Column('name', String(255)),
Column('container_format', String(20)), Column('disk_format', String(20)),
Column('size', Integer()), Column('container_format', String(20)),
Column('status', String(30), nullable=False), Column('size', Integer()),
Column('is_public', Boolean(), nullable=False, default=False, Column('status', String(30), nullable=False),
index=True), Column('is_public',
Column('location', Text()), Boolean(),
Column('created_at', DateTime(), nullable=False), nullable=False,
Column('updated_at', DateTime()), default=False,
Column('deleted_at', DateTime()), index=True),
Column('deleted', Boolean(), nullable=False, default=False, Column('location', Text()),
index=True), Column('created_at', DateTime(), nullable=False),
mysql_engine='InnoDB', Column('updated_at', DateTime()),
useexisting=True) Column('deleted_at', DateTime()),
Column('deleted',
Boolean(),
nullable=False,
default=False,
index=True),
mysql_engine='InnoDB',
useexisting=True)
return images return images

View File

@ -27,24 +27,31 @@ def get_images_table(meta):
Returns the Table object for the images table that Returns the Table object for the images table that
corresponds to the images table definition of this version. corresponds to the images table definition of this version.
""" """
images = Table('images', meta, images = Table('images',
Column('id', Integer(), primary_key=True, nullable=False), meta,
Column('name', String(255)), Column('id', Integer(), primary_key=True, nullable=False),
Column('disk_format', String(20)), Column('name', String(255)),
Column('container_format', String(20)), Column('disk_format', String(20)),
Column('size', Integer()), Column('container_format', String(20)),
Column('status', String(30), nullable=False), Column('size', Integer()),
Column('is_public', Boolean(), nullable=False, default=False, Column('status', String(30), nullable=False),
index=True), Column('is_public',
Column('location', Text()), Boolean(),
Column('created_at', DateTime(), nullable=False), nullable=False,
Column('updated_at', DateTime()), default=False,
Column('deleted_at', DateTime()), index=True),
Column('deleted', Boolean(), nullable=False, default=False, Column('location', Text()),
index=True), Column('created_at', DateTime(), nullable=False),
Column('checksum', String(32)), Column('updated_at', DateTime()),
mysql_engine='InnoDB', Column('deleted_at', DateTime()),
extend_existing=True) Column('deleted',
Boolean(),
nullable=False,
default=False,
index=True),
Column('checksum', String(32)),
mysql_engine='InnoDB',
extend_existing=True)
return images return images

View File

@ -28,23 +28,30 @@ def get_images_table(meta):
Returns the Table object for the images table that Returns the Table object for the images table that
corresponds to the images table definition of this version. corresponds to the images table definition of this version.
""" """
images = Table('images', meta, images = Table('images',
Column('id', Integer(), primary_key=True, nullable=False), meta,
Column('name', String(255)), Column('id', Integer(), primary_key=True, nullable=False),
Column('disk_format', String(20)), Column('name', String(255)),
Column('container_format', String(20)), Column('disk_format', String(20)),
Column('size', BigInteger()), Column('container_format', String(20)),
Column('status', String(30), nullable=False), Column('size', BigInteger()),
Column('is_public', Boolean(), nullable=False, default=False, Column('status', String(30), nullable=False),
index=True), Column('is_public',
Column('location', Text()), Boolean(),
Column('created_at', DateTime(), nullable=False), nullable=False,
Column('updated_at', DateTime()), default=False,
Column('deleted_at', DateTime()), index=True),
Column('deleted', Boolean(), nullable=False, default=False, Column('location', Text()),
index=True), Column('created_at', DateTime(), nullable=False),
mysql_engine='InnoDB', Column('updated_at', DateTime()),
useexisting=True) Column('deleted_at', DateTime()),
Column('deleted',
Boolean(),
nullable=False,
default=False,
index=True),
mysql_engine='InnoDB',
useexisting=True)
return images return images

View File

@ -43,20 +43,30 @@ def get_image_properties_table(meta):
images = get_images_table(meta) images = get_images_table(meta)
image_properties = Table('image_properties', meta, image_properties = Table('image_properties',
Column('id', Integer(), primary_key=True, nullable=False), meta,
Column('image_id', Integer(), ForeignKey('images.id'), nullable=False, Column('id',
index=True), Integer(),
Column('name', String(255), nullable=False), primary_key=True,
Column('value', Text()), nullable=False),
Column('created_at', DateTime(), nullable=False), Column('image_id',
Column('updated_at', DateTime()), Integer(),
Column('deleted_at', DateTime()), ForeignKey('images.id'),
Column('deleted', Boolean(), nullable=False, default=False, nullable=False,
index=True), index=True),
UniqueConstraint('image_id', 'name'), Column('name', String(255), nullable=False),
mysql_engine='InnoDB', Column('value', Text()),
useexisting=True) Column('created_at', DateTime(), nullable=False),
Column('updated_at', DateTime()),
Column('deleted_at', DateTime()),
Column('deleted',
Boolean(),
nullable=False,
default=False,
index=True),
UniqueConstraint('image_id', 'name'),
mysql_engine='InnoDB',
useexisting=True)
return image_properties return image_properties
@ -71,7 +81,7 @@ def upgrade(migrate_engine):
index = Index('ix_image_properties_image_id_key', index = Index('ix_image_properties_image_id_key',
image_properties.c.image_id, image_properties.c.image_id,
image_properties.c.key) image_properties.c.key)
index.rename('ix_image_properties_image_id_name') index.rename('ix_image_properties_image_id_name')
image_properties = get_image_properties_table(meta) image_properties = get_image_properties_table(meta)
@ -86,7 +96,7 @@ def downgrade(migrate_engine):
index = Index('ix_image_properties_image_id_name', index = Index('ix_image_properties_image_id_name',
image_properties.c.image_id, image_properties.c.image_id,
image_properties.c.name) image_properties.c.name)
index.rename('ix_image_properties_image_id_key') index.rename('ix_image_properties_image_id_key')
image_properties.columns['name'].alter(name="key") image_properties.columns['name'].alter(name="key")

View File

@ -28,25 +28,32 @@ def get_images_table(meta):
Returns the Table object for the images table that corresponds to Returns the Table object for the images table that corresponds to
the images table definition of this version. the images table definition of this version.
""" """
images = Table('images', meta, images = Table('images',
Column('id', Integer(), primary_key=True, nullable=False), meta,
Column('name', String(255)), Column('id', Integer(), primary_key=True, nullable=False),
Column('disk_format', String(20)), Column('name', String(255)),
Column('container_format', String(20)), Column('disk_format', String(20)),
Column('size', BigInteger()), Column('container_format', String(20)),
Column('status', String(30), nullable=False), Column('size', BigInteger()),
Column('is_public', Boolean(), nullable=False, default=False, Column('status', String(30), nullable=False),
index=True), Column('is_public',
Column('location', Text()), Boolean(),
Column('created_at', DateTime(), nullable=False), nullable=False,
Column('updated_at', DateTime()), default=False,
Column('deleted_at', DateTime()), index=True),
Column('deleted', Boolean(), nullable=False, default=False, Column('location', Text()),
index=True), Column('created_at', DateTime(), nullable=False),
Column('checksum', String(32)), Column('updated_at', DateTime()),
Column('owner', String(255)), Column('deleted_at', DateTime()),
mysql_engine='InnoDB', Column('deleted',
extend_existing=True) Boolean(),
nullable=False,
default=False,
index=True),
Column('checksum', String(32)),
Column('owner', String(255)),
mysql_engine='InnoDB',
extend_existing=True)
return images return images

View File

@ -48,20 +48,33 @@ def get_image_properties_table(meta):
def get_image_members_table(meta): def get_image_members_table(meta):
images = get_images_table(meta) images = get_images_table(meta)
image_members = Table('image_members', meta, image_members = Table('image_members',
Column('id', Integer(), primary_key=True, nullable=False), meta,
Column('image_id', Integer(), ForeignKey('images.id'), nullable=False, Column('id',
index=True), Integer(),
Column('member', String(255), nullable=False), primary_key=True,
Column('can_share', Boolean(), nullable=False, default=False), nullable=False),
Column('created_at', DateTime(), nullable=False), Column('image_id',
Column('updated_at', DateTime()), Integer(),
Column('deleted_at', DateTime()), ForeignKey('images.id'),
Column('deleted', Boolean(), nullable=False, default=False, nullable=False,
index=True), index=True),
UniqueConstraint('image_id', 'member'), Column('member', String(255), nullable=False),
mysql_engine='InnoDB', Column('can_share',
extend_existing=True) Boolean(),
nullable=False,
default=False),
Column('created_at', DateTime(), nullable=False),
Column('updated_at', DateTime()),
Column('deleted_at', DateTime()),
Column('deleted',
Boolean(),
nullable=False,
default=False,
index=True),
UniqueConstraint('image_id', 'member'),
mysql_engine='InnoDB',
extend_existing=True)
Index('ix_image_members_image_id_member', image_members.c.image_id, Index('ix_image_members_image_id_member', image_members.c.image_id,
image_members.c.member) image_members.c.member)

View File

@ -27,26 +27,33 @@ def get_images_table(meta):
Returns the Table object for the images table that Returns the Table object for the images table that
corresponds to the images table definition of this version. corresponds to the images table definition of this version.
""" """
images = Table('images', meta, images = Table('images',
Column('id', Integer(), primary_key=True, nullable=False), meta,
Column('name', String(255)), Column('id', Integer(), primary_key=True, nullable=False),
Column('disk_format', String(20)), Column('name', String(255)),
Column('container_format', String(20)), Column('disk_format', String(20)),
Column('size', Integer()), Column('container_format', String(20)),
Column('status', String(30), nullable=False), Column('size', Integer()),
Column('is_public', Boolean(), nullable=False, default=False, Column('status', String(30), nullable=False),
index=True), Column('is_public',
Column('location', Text()), Boolean(),
Column('created_at', DateTime(), nullable=False), nullable=False,
Column('updated_at', DateTime()), default=False,
Column('deleted_at', DateTime()), index=True),
Column('deleted', Boolean(), nullable=False, default=False, Column('location', Text()),
index=True), Column('created_at', DateTime(), nullable=False),
Column('checksum', String(32)), Column('updated_at', DateTime()),
Column('min_disk', Integer(), default=0), Column('deleted_at', DateTime()),
Column('min_ram', Integer(), default=0), Column('deleted',
mysql_engine='InnoDB', Boolean(),
extend_existing=True) nullable=False,
default=False,
index=True),
Column('checksum', String(32)),
Column('min_disk', Integer(), default=0),
Column('min_ram', Integer(), default=0),
mysql_engine='InnoDB',
extend_existing=True)
return images return images

View File

@ -22,18 +22,31 @@ def define_image_tags_table(meta):
# Load the images table so the foreign key can be set up properly # Load the images table so the foreign key can be set up properly
schema.Table('images', meta, autoload=True) schema.Table('images', meta, autoload=True)
image_tags = schema.Table('image_tags', meta, image_tags = schema.Table('image_tags',
schema.Column('id', glance_schema.Integer(), meta,
primary_key=True, nullable=False), schema.Column('id',
schema.Column('image_id', glance_schema.String(36), glance_schema.Integer(),
schema.ForeignKey('images.id'), nullable=False), primary_key=True,
schema.Column('value', glance_schema.String(255), nullable=False), nullable=False),
schema.Column('created_at', glance_schema.DateTime(), nullable=False), schema.Column('image_id',
schema.Column('updated_at', glance_schema.DateTime()), glance_schema.String(36),
schema.Column('deleted_at', glance_schema.DateTime()), schema.ForeignKey('images.id'),
schema.Column('deleted', glance_schema.Boolean(), nullable=False, nullable=False),
default=False), schema.Column('value',
mysql_engine='InnoDB') glance_schema.String(255),
nullable=False),
schema.Column('created_at',
glance_schema.DateTime(),
nullable=False),
schema.Column('updated_at',
glance_schema.DateTime()),
schema.Column('deleted_at',
glance_schema.DateTime()),
schema.Column('deleted',
glance_schema.Boolean(),
nullable=False,
default=False),
mysql_engine='InnoDB')
schema.Index('ix_image_tags_image_id', schema.Index('ix_image_tags_image_id',
image_tags.c.image_id) image_tags.c.image_id)

View File

@ -289,7 +289,7 @@ class ImageCache(object):
CHUNKSIZE = 64 * 1024 * 1024 CHUNKSIZE = 64 * 1024 * 1024
return self.cache_image_iter(image_id, return self.cache_image_iter(image_id,
utils.chunkiter(image_file, CHUNKSIZE)) utils.chunkiter(image_file, CHUNKSIZE))
def open_for_read(self, image_id): def open_for_read(self, image_id):
""" """

View File

@ -399,8 +399,8 @@ class Controller(object):
msg = _("Image %(id)s not found") msg = _("Image %(id)s not found")
LOG.info(msg % {'id': id}) LOG.info(msg % {'id': id})
raise exc.HTTPNotFound(body='Image not found', raise exc.HTTPNotFound(body='Image not found',
request=req, request=req,
content_type='text/plain') content_type='text/plain')
except exception.ForbiddenPublicImage: except exception.ForbiddenPublicImage:
msg = _("Update denied for public image %(id)s") msg = _("Update denied for public image %(id)s")
LOG.info(msg % {'id': id}) LOG.info(msg % {'id': id})
@ -411,8 +411,8 @@ class Controller(object):
msg = _("Access denied to image %(id)s but returning 'not found'") msg = _("Access denied to image %(id)s but returning 'not found'")
LOG.info(msg % {'id': id}) LOG.info(msg % {'id': id})
raise exc.HTTPNotFound(body='Image not found', raise exc.HTTPNotFound(body='Image not found',
request=req, request=req,
content_type='text/plain') content_type='text/plain')
def make_image_dict(image): def make_image_dict(image):

View File

@ -86,7 +86,8 @@ class RegistryClient(BaseClient):
def do_request(self, method, action, **kwargs): def do_request(self, method, action, **kwargs):
try: try:
res = super(RegistryClient, self).do_request(method, res = super(RegistryClient, self).do_request(method,
action, **kwargs) action,
**kwargs)
status = res.status status = res.status
request_id = res.getheader('x-openstack-request-id') request_id = res.getheader('x-openstack-request-id')
msg = _("Registry request %(method)s %(action)s HTTP %(status)s" msg = _("Registry request %(method)s %(action)s HTTP %(status)s"
@ -94,8 +95,8 @@ class RegistryClient(BaseClient):
LOG.debug(msg % locals()) LOG.debug(msg % locals())
except: except:
LOG.exception(_("Registry request %(method)s %(action)s Exception") LOG.exception(_("Registry request %(method)s %(action)s "
% locals()) "Exception") % locals())
raise raise
return res return res

View File

@ -208,7 +208,7 @@ class Store(glance.store.base.Store):
try: try:
with open(filepath, 'wb') as f: with open(filepath, 'wb') as f:
for buf in utils.chunkreadable(image_file, for buf in utils.chunkreadable(image_file,
ChunkedFile.CHUNKSIZE): ChunkedFile.CHUNKSIZE):
bytes_written += len(buf) bytes_written += len(buf)
checksum.update(buf) checksum.update(buf)
f.write(buf) f.write(buf)

View File

@ -296,8 +296,9 @@ class Store(glance.store.base.Store):
msg = _("Retrieved image object from S3 using (s3_host=%(s3_host)s, " msg = _("Retrieved image object from S3 using (s3_host=%(s3_host)s, "
"access_key=%(accesskey)s, bucket=%(bucket)s, " "access_key=%(accesskey)s, bucket=%(bucket)s, "
"key=%(obj_name)s)") % ({'s3_host': loc.s3serviceurl, "key=%(obj_name)s)") % ({'s3_host': loc.s3serviceurl,
'accesskey': loc.accesskey, 'bucket': loc.bucket, 'accesskey': loc.accesskey,
'obj_name': loc.key}) 'bucket': loc.bucket,
'obj_name': loc.key})
LOG.debug(msg) LOG.debug(msg)
return key return key
@ -358,8 +359,9 @@ class Store(glance.store.base.Store):
msg = _("Adding image object to S3 using (s3_host=%(s3_host)s, " msg = _("Adding image object to S3 using (s3_host=%(s3_host)s, "
"access_key=%(access_key)s, bucket=%(bucket)s, " "access_key=%(access_key)s, bucket=%(bucket)s, "
"key=%(obj_name)s)") % ({'s3_host': self.s3_host, "key=%(obj_name)s)") % ({'s3_host': self.s3_host,
'access_key': self.access_key, 'bucket': self.bucket, 'access_key': self.access_key,
'obj_name': obj_name}) 'bucket': self.bucket,
'obj_name': obj_name})
LOG.debug(msg) LOG.debug(msg)
key = bucket_obj.new_key(obj_name) key = bucket_obj.new_key(obj_name)
@ -426,8 +428,9 @@ class Store(glance.store.base.Store):
msg = _("Deleting image object from S3 using (s3_host=%(s3_host)s, " msg = _("Deleting image object from S3 using (s3_host=%(s3_host)s, "
"access_key=%(accesskey)s, bucket=%(bucket)s, " "access_key=%(accesskey)s, bucket=%(bucket)s, "
"key=%(obj_name)s)") % ({'s3_host': loc.s3serviceurl, "key=%(obj_name)s)") % ({'s3_host': loc.s3serviceurl,
'accesskey': loc.accesskey, 'bucket': loc.bucket, 'accesskey': loc.accesskey,
'obj_name': loc.key}) 'bucket': loc.bucket,
'obj_name': loc.key})
LOG.debug(msg) LOG.debug(msg)
return key.delete() return key.delete()

View File

@ -294,7 +294,7 @@ class Store(glance.store.base.Store):
if e.http_status == httplib.NOT_FOUND: if e.http_status == httplib.NOT_FOUND:
uri = location.get_store_uri() uri = location.get_store_uri()
raise exception.NotFound(_("Swift could not find image at " raise exception.NotFound(_("Swift could not find image at "
"uri %(uri)s") % locals()) "uri %(uri)s") % locals())
else: else:
raise raise
@ -543,7 +543,8 @@ class Store(glance.store.base.Store):
except swiftclient.ClientException, e: except swiftclient.ClientException, e:
if e.http_status == httplib.CONFLICT: if e.http_status == httplib.CONFLICT:
raise exception.Duplicate(_("Swift already has an image at " raise exception.Duplicate(_("Swift already has an image at "
"location %s") % location.get_uri()) "location %s") %
location.get_uri())
msg = (_("Failed to add object to Swift.\n" msg = (_("Failed to add object to Swift.\n"
"Got error from Swift: %(e)s") % locals()) "Got error from Swift: %(e)s") % locals())
LOG.error(msg) LOG.error(msg)
@ -597,7 +598,7 @@ class Store(glance.store.base.Store):
if e.http_status == httplib.NOT_FOUND: if e.http_status == httplib.NOT_FOUND:
uri = location.get_store_uri() uri = location.get_store_uri()
raise exception.NotFound(_("Swift could not find image at " raise exception.NotFound(_("Swift could not find image at "
"uri %(uri)s") % locals()) "uri %(uri)s") % locals())
else: else:
raise raise
@ -638,7 +639,7 @@ class Store(glance.store.base.Store):
if e.http_status == httplib.NOT_FOUND: if e.http_status == httplib.NOT_FOUND:
uri = location.get_store_uri() uri = location.get_store_uri()
raise exception.NotFound(_("Swift could not find image at " raise exception.NotFound(_("Swift could not find image at "
"uri %(uri)s") % locals()) "uri %(uri)s") % locals())
else: else:
raise raise
@ -677,14 +678,14 @@ def create_container_if_missing(container, swift_conn):
swift_conn.put_container(container) swift_conn.put_container(container)
except swiftclient.ClientException, e: except swiftclient.ClientException, e:
msg = _("Failed to add container to Swift.\n" msg = _("Failed to add container to Swift.\n"
"Got error from Swift: %(e)s") % locals() "Got error from Swift: %(e)s") % locals()
raise glance.store.BackendException(msg) raise glance.store.BackendException(msg)
else: else:
msg = (_("The container %(container)s does not exist in " msg = (_("The container %(container)s does not exist in "
"Swift. Please set the " "Swift. Please set the "
"swift_store_create_container_on_put option" "swift_store_create_container_on_put option"
"to add container to Swift automatically.") "to add container to Swift automatically.") %
% locals()) locals())
raise glance.store.BackendException(msg) raise glance.store.BackendException(msg)
else: else:
raise raise

View File

@ -240,13 +240,15 @@ class BaseTestCase(object):
def test_image_get_all_with_filter(self): def test_image_get_all_with_filter(self):
images = self.db_api.image_get_all(self.context, images = self.db_api.image_get_all(self.context,
filters={'id': self.fixtures[0]['id']}) filters={
'id': self.fixtures[0]['id'],
})
self.assertEquals(len(images), 1) self.assertEquals(len(images), 1)
self.assertEquals(images[0]['id'], self.fixtures[0]['id']) self.assertEquals(images[0]['id'], self.fixtures[0]['id'])
def test_image_get_all_with_filter_user_defined_property(self): def test_image_get_all_with_filter_user_defined_property(self):
images = self.db_api.image_get_all(self.context, images = self.db_api.image_get_all(self.context,
filters={'foo': 'bar'}) filters={'foo': 'bar'})
self.assertEquals(len(images), 1) self.assertEquals(len(images), 1)
self.assertEquals(images[0]['id'], self.fixtures[0]['id']) self.assertEquals(images[0]['id'], self.fixtures[0]['id'])
@ -255,16 +257,20 @@ class BaseTestCase(object):
prop = self.db_api.image_property_create(self.context, prop = self.db_api.image_property_create(self.context,
fixture) fixture)
images = self.db_api.image_get_all(self.context, images = self.db_api.image_get_all(self.context,
filters={'properties': {'poo': 'bear'}}) filters={
'properties': {'poo': 'bear'},
})
self.assertEquals(len(images), 1) self.assertEquals(len(images), 1)
self.db_api.image_property_delete(self.context, prop) self.db_api.image_property_delete(self.context, prop)
images = self.db_api.image_get_all(self.context, images = self.db_api.image_get_all(self.context,
filters={'properties': {'poo': 'bear'}}) filters={
'properties': {'poo': 'bear'},
})
self.assertEquals(len(images), 0) self.assertEquals(len(images), 0)
def test_image_get_all_with_filter_undefined_property(self): def test_image_get_all_with_filter_undefined_property(self):
images = self.db_api.image_get_all(self.context, images = self.db_api.image_get_all(self.context,
filters={'poo': 'bear'}) filters={'poo': 'bear'})
self.assertEquals(len(images), 0) self.assertEquals(len(images), 0)
def test_image_get_all_size_min_max(self): def test_image_get_all_size_min_max(self):
@ -278,20 +284,20 @@ class BaseTestCase(object):
def test_image_get_all_size_min(self): def test_image_get_all_size_min(self):
images = self.db_api.image_get_all(self.context, images = self.db_api.image_get_all(self.context,
filters={'size_min': 15}) filters={'size_min': 15})
self.assertEquals(len(images), 2) self.assertEquals(len(images), 2)
self.assertEquals(images[0]['id'], self.fixtures[2]['id']) self.assertEquals(images[0]['id'], self.fixtures[2]['id'])
self.assertEquals(images[1]['id'], self.fixtures[1]['id']) self.assertEquals(images[1]['id'], self.fixtures[1]['id'])
def test_image_get_all_size_range(self): def test_image_get_all_size_range(self):
images = self.db_api.image_get_all(self.context, images = self.db_api.image_get_all(self.context,
filters={'size_max': 15, filters={'size_max': 15,
'size_min': 20}) 'size_min': 20})
self.assertEquals(len(images), 0) self.assertEquals(len(images), 0)
def test_image_get_all_size_max(self): def test_image_get_all_size_max(self):
images = self.db_api.image_get_all(self.context, images = self.db_api.image_get_all(self.context,
filters={'size_max': 15}) filters={'size_max': 15})
self.assertEquals(len(images), 1) self.assertEquals(len(images), 1)
self.assertEquals(images[0]['id'], self.fixtures[0]['id']) self.assertEquals(images[0]['id'], self.fixtures[0]['id'])
@ -352,14 +358,16 @@ class BaseTestCase(object):
TENANT1 = utils.generate_uuid() TENANT1 = utils.generate_uuid()
ctxt1 = context.RequestContext(is_admin=False, tenant=TENANT1) ctxt1 = context.RequestContext(is_admin=False, tenant=TENANT1)
UUIDX = utils.generate_uuid() UUIDX = utils.generate_uuid()
self.db_api.image_create(ctxt1, self.db_api.image_create(ctxt1, {'id': UUIDX,
{'id': UUIDX, 'status': 'queued', 'owner': TENANT1}) 'status': 'queued',
'owner': TENANT1})
TENANT2 = utils.generate_uuid() TENANT2 = utils.generate_uuid()
ctxt2 = context.RequestContext(is_admin=False, tenant=TENANT2) ctxt2 = context.RequestContext(is_admin=False, tenant=TENANT2)
UUIDY = utils.generate_uuid() UUIDY = utils.generate_uuid()
self.db_api.image_create(ctxt2, self.db_api.image_create(ctxt2, {'id': UUIDY,
{'id': UUIDY, 'status': 'queued', 'owner': TENANT2}) 'status': 'queued',
'owner': TENANT2})
# NOTE(bcwaldon): the is_public=True flag indicates that you want # NOTE(bcwaldon): the is_public=True flag indicates that you want
# to get all images that are public AND those that are owned by the # to get all images that are public AND those that are owned by the
@ -457,7 +465,8 @@ class BaseTestCase(object):
def test_image_member_update(self): def test_image_member_update(self):
TENANT1 = utils.generate_uuid() TENANT1 = utils.generate_uuid()
member = self.db_api.image_member_create(self.context, member = self.db_api.image_member_create(self.context,
{'member': TENANT1, 'image_id': UUID1}) {'member': TENANT1,
'image_id': UUID1})
member_id = member.pop('id') member_id = member.pop('id')
expected = {'member': TENANT1, 'image_id': UUID1, 'can_share': False} expected = {'member': TENANT1, 'image_id': UUID1, 'can_share': False}

View File

@ -127,7 +127,7 @@ def swift_head_object(swift_conn, container_name, obj_name):
def keystone_authenticate(auth_url, auth_version, tenant_name, def keystone_authenticate(auth_url, auth_version, tenant_name,
username, password): username, password):
assert int(auth_version) == 2, 'Only auth version 2 is supported' assert int(auth_version) == 2, 'Only auth version 2 is supported'
import keystoneclient.v2_0.client import keystoneclient.v2_0.client
@ -314,8 +314,10 @@ class TestSwiftStore(store_tests.BaseTestCase, unittest.TestCase):
read_tenant = utils.generate_uuid() read_tenant = utils.generate_uuid()
write_tenant = utils.generate_uuid() write_tenant = utils.generate_uuid()
store.set_acls(location, public=False, store.set_acls(location,
read_tenants=[read_tenant], write_tenants=[write_tenant]) public=False,
read_tenants=[read_tenant],
write_tenants=[write_tenant])
container_name = location.store_location.container container_name = location.store_location.container
container, _ = swift_get_container(self.swift_client, container_name) container, _ = swift_get_container(self.swift_client, container_name)

View File

@ -200,7 +200,7 @@ def get_swift_uri(test, image_id):
uri = ('swift+https://%(swift_store_user)s:%(swift_store_key)s' % uri = ('swift+https://%(swift_store_user)s:%(swift_store_key)s' %
test.__dict__) test.__dict__)
uri += ('@%(swift_store_auth_address)s/%(swift_store_container)s/' % uri += ('@%(swift_store_auth_address)s/%(swift_store_container)s/' %
test.__dict__) test.__dict__)
uri += image_id uri += image_id
return uri.replace('@http://', '@') return uri.replace('@http://', '@')

View File

@ -25,10 +25,12 @@ from glance.tests.utils import execute
TEST_IMAGE_DATA = '*' * 5 * 1024 TEST_IMAGE_DATA = '*' * 5 * 1024
TEST_IMAGE_META = {'name': 'test_image', TEST_IMAGE_META = {
'is_public': False, 'name': 'test_image',
'disk_format': 'raw', 'is_public': False,
'container_format': 'ovf'} 'disk_format': 'raw',
'container_format': 'ovf',
}
class TestScrubber(functional.FunctionalTest): class TestScrubber(functional.FunctionalTest):

View File

@ -133,16 +133,17 @@ class TestApi(functional.FunctionalTest):
for expected_key, expected_value in expected_image_headers.items(): for expected_key, expected_value in expected_image_headers.items():
self.assertEqual(response[expected_key], expected_value, self.assertEqual(response[expected_key], expected_value,
"For key '%s' expected header value '%s'. Got '%s'" "For key '%s' expected header value '%s'. "
% (expected_key, expected_value, "Got '%s'" % (expected_key,
response[expected_key])) expected_value,
response[expected_key]))
for expected_key, expected_value in expected_std_headers.items(): for expected_key, expected_value in expected_std_headers.items():
self.assertEqual(response[expected_key], expected_value, self.assertEqual(response[expected_key], expected_value,
"For key '%s' expected header value '%s'. Got '%s'" "For key '%s' expected header value '%s'. "
% (expected_key, "Got '%s'" % (expected_key,
expected_value, expected_value,
response[expected_key])) response[expected_key]))
self.assertEqual(content, "*" * FIVE_KB) self.assertEqual(content, "*" * FIVE_KB)
self.assertEqual(hashlib.md5(content).hexdigest(), self.assertEqual(hashlib.md5(content).hexdigest(),
@ -187,10 +188,10 @@ class TestApi(functional.FunctionalTest):
for expected_key, expected_value in expected_image.items(): for expected_key, expected_value in expected_image.items():
self.assertEqual(expected_value, image['images'][0][expected_key], self.assertEqual(expected_value, image['images'][0][expected_key],
"For key '%s' expected header value '%s'. Got '%s'" "For key '%s' expected header value '%s'. "
% (expected_key, "Got '%s'" % (expected_key,
expected_value, expected_value,
image['images'][0][expected_key])) image['images'][0][expected_key]))
# 7. PUT image with custom properties of "distro" and "arch" # 7. PUT image with custom properties of "distro" and "arch"
# Verify 200 returned # Verify 200 returned
@ -228,10 +229,10 @@ class TestApi(functional.FunctionalTest):
for expected_key, expected_value in expected_image.items(): for expected_key, expected_value in expected_image.items():
self.assertEqual(expected_value, image['images'][0][expected_key], self.assertEqual(expected_value, image['images'][0][expected_key],
"For key '%s' expected header value '%s'. Got '%s'" "For key '%s' expected header value '%s'. "
% (expected_key, "Got '%s'" % (expected_key,
expected_value, expected_value,
image['images'][0][expected_key])) image['images'][0][expected_key]))
# 9. PUT image and remove a previously existing property. # 9. PUT image and remove a previously existing property.
headers = {'X-Image-Meta-Property-Arch': 'x86_64'} headers = {'X-Image-Meta-Property-Arch': 'x86_64'}
@ -358,8 +359,9 @@ class TestApi(functional.FunctionalTest):
# 4. PUT image with image data, verify 200 returned # 4. PUT image with image data, verify 200 returned
image_data = "*" * FIVE_KB image_data = "*" * FIVE_KB
headers = {'Content-Type': 'application/octet-stream'} headers = {'Content-Type': 'application/octet-stream'}
path = "http://%s:%d/v1/images/%s" % ("127.0.0.1", self.api_port, path = "http://%s:%d/v1/images/%s" % ("127.0.0.1",
image_id) self.api_port,
image_id)
http = httplib2.Http() http = httplib2.Http()
response, content = http.request(path, 'PUT', headers=headers, response, content = http.request(path, 'PUT', headers=headers,
body=image_data) body=image_data)
@ -532,9 +534,10 @@ class TestApi(functional.FunctionalTest):
http = httplib2.Http() http = httplib2.Http()
headers = minimal_headers('Image1') headers = minimal_headers('Image1')
headers['Content-Type'] = 'not octet-stream' headers['Content-Type'] = 'not octet-stream'
response, content = http.request(path, 'POST', response, content = http.request(path,
body=test_data_file.name, 'POST',
headers=headers) body=test_data_file.name,
headers=headers)
self.assertEqual(response.status, 400) self.assertEqual(response.status, 400)
expected = "Content-Type must be application/octet-stream" expected = "Content-Type must be application/octet-stream"
self.assertTrue(expected in content, self.assertTrue(expected in content,
@ -811,8 +814,9 @@ class TestApi(functional.FunctionalTest):
yesterday = timeutils.isotime(timeutils.utcnow() - yesterday = timeutils.isotime(timeutils.utcnow() -
datetime.timedelta(1)) datetime.timedelta(1))
params = "changes-since=%s" % yesterday params = "changes-since=%s" % yesterday
path = "http://%s:%d/v1/images?%s" % ("127.0.0.1", self.api_port, path = "http://%s:%d/v1/images?%s" % ("127.0.0.1",
params) self.api_port,
params)
response, content = http.request(path, 'GET') response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200) self.assertEqual(response.status, 200)
data = json.loads(content) data = json.loads(content)
@ -826,8 +830,9 @@ class TestApi(functional.FunctionalTest):
now = timeutils.utcnow() now = timeutils.utcnow()
hour_ago = now.strftime('%Y-%m-%dT%H:%M:%S%%2B01:00') hour_ago = now.strftime('%Y-%m-%dT%H:%M:%S%%2B01:00')
params = "changes-since=%s" % hour_ago params = "changes-since=%s" % hour_ago
path = "http://%s:%d/v1/images?%s" % ("127.0.0.1", self.api_port, path = "http://%s:%d/v1/images?%s" % ("127.0.0.1",
params) self.api_port,
params)
response, content = http.request(path, 'GET') response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200) self.assertEqual(response.status, 200)
data = json.loads(content) data = json.loads(content)
@ -837,8 +842,9 @@ class TestApi(functional.FunctionalTest):
tomorrow = timeutils.isotime(timeutils.utcnow() + tomorrow = timeutils.isotime(timeutils.utcnow() +
datetime.timedelta(1)) datetime.timedelta(1))
params = "changes-since=%s" % tomorrow params = "changes-since=%s" % tomorrow
path = "http://%s:%d/v1/images?%s" % ("127.0.0.1", self.api_port, path = "http://%s:%d/v1/images?%s" % ("127.0.0.1",
params) self.api_port,
params)
response, content = http.request(path, 'GET') response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200) self.assertEqual(response.status, 200)
data = json.loads(content) data = json.loads(content)
@ -848,8 +854,9 @@ class TestApi(functional.FunctionalTest):
now = timeutils.utcnow() now = timeutils.utcnow()
hour_hence = now.strftime('%Y-%m-%dT%H:%M:%S-01:00') hour_hence = now.strftime('%Y-%m-%dT%H:%M:%S-01:00')
params = "changes-since=%s" % hour_hence params = "changes-since=%s" % hour_hence
path = "http://%s:%d/v1/images?%s" % ("127.0.0.1", self.api_port, path = "http://%s:%d/v1/images?%s" % ("127.0.0.1",
params) self.api_port,
params)
response, content = http.request(path, 'GET') response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200) self.assertEqual(response.status, 200)
data = json.loads(content) data = json.loads(content)
@ -1076,8 +1083,9 @@ class TestApi(functional.FunctionalTest):
# 3. GET /images sorted by name asc # 3. GET /images sorted by name asc
params = 'sort_key=name&sort_dir=asc' params = 'sort_key=name&sort_dir=asc'
path = "http://%s:%d/v1/images?%s" % ("127.0.0.1", self.api_port, path = "http://%s:%d/v1/images?%s" % ("127.0.0.1",
params) self.api_port,
params)
http = httplib2.Http() http = httplib2.Http()
response, content = http.request(path, 'GET') response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200) self.assertEqual(response.status, 200)
@ -1089,8 +1097,9 @@ class TestApi(functional.FunctionalTest):
# 4. GET /images sorted by size desc # 4. GET /images sorted by size desc
params = 'sort_key=size&sort_dir=desc' params = 'sort_key=size&sort_dir=desc'
path = "http://%s:%d/v1/images?%s" % ("127.0.0.1", self.api_port, path = "http://%s:%d/v1/images?%s" % ("127.0.0.1",
params) self.api_port,
params)
http = httplib2.Http() http = httplib2.Http()
response, content = http.request(path, 'GET') response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200) self.assertEqual(response.status, 200)
@ -1102,8 +1111,9 @@ class TestApi(functional.FunctionalTest):
# 5. GET /images sorted by size desc with a marker # 5. GET /images sorted by size desc with a marker
params = 'sort_key=size&sort_dir=desc&marker=%s' % image_ids[0] params = 'sort_key=size&sort_dir=desc&marker=%s' % image_ids[0]
path = "http://%s:%d/v1/images?%s" % ("127.0.0.1", self.api_port, path = "http://%s:%d/v1/images?%s" % ("127.0.0.1",
params) self.api_port,
params)
http = httplib2.Http() http = httplib2.Http()
response, content = http.request(path, 'GET') response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200) self.assertEqual(response.status, 200)
@ -1114,8 +1124,9 @@ class TestApi(functional.FunctionalTest):
# 6. GET /images sorted by name asc with a marker # 6. GET /images sorted by name asc with a marker
params = 'sort_key=name&sort_dir=asc&marker=%s' % image_ids[2] params = 'sort_key=name&sort_dir=asc&marker=%s' % image_ids[2]
path = "http://%s:%d/v1/images?%s" % ("127.0.0.1", self.api_port, path = "http://%s:%d/v1/images?%s" % ("127.0.0.1",
params) self.api_port,
params)
http = httplib2.Http() http = httplib2.Http()
response, content = http.request(path, 'GET') response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200) self.assertEqual(response.status, 200)
@ -1258,9 +1269,10 @@ class TestApi(functional.FunctionalTest):
test_data_file.write("XXX") test_data_file.write("XXX")
test_data_file.flush() test_data_file.flush()
http = httplib2.Http() http = httplib2.Http()
response, content = http.request(path, 'POST', response, content = http.request(path,
headers=headers, 'POST',
body=test_data_file.name) headers=headers,
body=test_data_file.name)
self.assertEqual(response.status, 400) self.assertEqual(response.status, 400)
type = format.replace('_format', '') type = format.replace('_format', '')
expected = "Invalid %s format 'bad_value' for image" % type expected = "Invalid %s format 'bad_value' for image" % type
@ -1319,9 +1331,10 @@ class TestApi(functional.FunctionalTest):
test_data_file.write("XXX") test_data_file.write("XXX")
test_data_file.flush() test_data_file.flush()
http = httplib2.Http() http = httplib2.Http()
response, content = http.request(path, 'PUT', response, content = http.request(path,
headers=headers, 'PUT',
body=test_data_file.name) headers=headers,
body=test_data_file.name)
self.assertEqual(response.status, 400) self.assertEqual(response.status, 400)
type = format.replace('_format', '') type = format.replace('_format', '')
expected = "Invalid %s format 'None' for image" % type expected = "Invalid %s format 'None' for image" % type

View File

@ -147,8 +147,10 @@ class TestSSL(functional.FunctionalTest):
headers = minimal_headers('Image1') headers = minimal_headers('Image1')
path = "https://%s:%d/v1/images" % ("127.0.0.1", self.api_port) path = "https://%s:%d/v1/images" % ("127.0.0.1", self.api_port)
https = httplib2.Http(disable_ssl_certificate_validation=True) https = httplib2.Http(disable_ssl_certificate_validation=True)
response, content = https.request(path, 'POST', headers=headers, response, content = https.request(path,
body=image_data) 'POST',
headers=headers,
body=image_data)
self.assertEqual(response.status, 201) self.assertEqual(response.status, 201)
data = json.loads(content) data = json.loads(content)
self.assertEqual(data['image']['checksum'], self.assertEqual(data['image']['checksum'],
@ -191,16 +193,17 @@ class TestSSL(functional.FunctionalTest):
for expected_key, expected_value in expected_image_headers.items(): for expected_key, expected_value in expected_image_headers.items():
self.assertEqual(response[expected_key], expected_value, self.assertEqual(response[expected_key], expected_value,
"For key '%s' expected header value '%s'. Got '%s'" "For key '%s' expected header value '%s'. "
% (expected_key, expected_value, "Got '%s'" % (expected_key,
response[expected_key])) expected_value,
response[expected_key]))
for expected_key, expected_value in expected_std_headers.items(): for expected_key, expected_value in expected_std_headers.items():
self.assertEqual(response[expected_key], expected_value, self.assertEqual(response[expected_key], expected_value,
"For key '%s' expected header value '%s'. Got '%s'" "For key '%s' expected header value '%s'. "
% (expected_key, "Got '%s'" % (expected_key,
expected_value, expected_value,
response[expected_key])) response[expected_key]))
self.assertEqual(content, "*" * FIVE_KB) self.assertEqual(content, "*" * FIVE_KB)
self.assertEqual(hashlib.md5(content).hexdigest(), self.assertEqual(hashlib.md5(content).hexdigest(),
@ -244,11 +247,12 @@ class TestSSL(functional.FunctionalTest):
image = json.loads(content) image = json.loads(content)
for expected_key, expected_value in expected_image.items(): for expected_key, expected_value in expected_image.items():
self.assertEqual(expected_value, image['images'][0][expected_key], self.assertEqual(expected_value,
"For key '%s' expected header value '%s'. Got '%s'" image['images'][0][expected_key],
% (expected_key, "For key '%s' expected header value '%s'. "
expected_value, "Got '%s'" % (expected_key,
image['images'][0][expected_key])) expected_value,
image['images'][0][expected_key]))
# 7. PUT image with custom properties of "distro" and "arch" # 7. PUT image with custom properties of "distro" and "arch"
# Verify 200 returned # Verify 200 returned
@ -285,11 +289,12 @@ class TestSSL(functional.FunctionalTest):
image = json.loads(content) image = json.loads(content)
for expected_key, expected_value in expected_image.items(): for expected_key, expected_value in expected_image.items():
self.assertEqual(expected_value, image['images'][0][expected_key], self.assertEqual(expected_value,
"For key '%s' expected header value '%s'. Got '%s'" image['images'][0][expected_key],
% (expected_key, "For key '%s' expected header value '%s'. "
expected_value, "Got '%s'" % (expected_key,
image['images'][0][expected_key])) expected_value,
image['images'][0][expected_key]))
# 9. PUT image and remove a previously existing property. # 9. PUT image and remove a previously existing property.
headers = {'X-Image-Meta-Property-Arch': 'x86_64'} headers = {'X-Image-Meta-Property-Arch': 'x86_64'}
@ -411,8 +416,10 @@ class TestSSL(functional.FunctionalTest):
path = "https://%s:%d/v1/images/%s" % ("127.0.0.1", self.api_port, path = "https://%s:%d/v1/images/%s" % ("127.0.0.1", self.api_port,
image_id) image_id)
https = httplib2.Http(disable_ssl_certificate_validation=True) https = httplib2.Http(disable_ssl_certificate_validation=True)
response, content = https.request(path, 'PUT', headers=headers, response, content = https.request(path,
body=image_data) 'PUT',
headers=headers,
body=image_data)
self.assertEqual(response.status, 200) self.assertEqual(response.status, 200)
data = json.loads(content) data = json.loads(content)
self.assertEqual(data['image']['checksum'], self.assertEqual(data['image']['checksum'],
@ -669,8 +676,9 @@ class TestSSL(functional.FunctionalTest):
test_data_file.flush() test_data_file.flush()
path = "https://%s:%d/v1/images" % ("127.0.0.1", self.api_port) path = "https://%s:%d/v1/images" % ("127.0.0.1", self.api_port)
https = httplib2.Http(disable_ssl_certificate_validation=True) https = httplib2.Http(disable_ssl_certificate_validation=True)
response, content = https.request(path, 'POST', response, content = https.request(path,
body=test_data_file.name) 'POST',
body=test_data_file.name)
self.assertEqual(response.status, 400) self.assertEqual(response.status, 400)
expected = "Content-Type must be application/octet-stream" expected = "Content-Type must be application/octet-stream"
self.assertTrue(expected in content, self.assertTrue(expected in content,

View File

@ -76,8 +76,7 @@ class TestCacheMiddlewareRequestStashCacheInfo(unittest.TestCase):
class ChecksumTestCacheFilter(glance.api.middleware.cache.CacheFilter): class ChecksumTestCacheFilter(glance.api.middleware.cache.CacheFilter):
def __init__(self): def __init__(self):
class DummyCache(object): class DummyCache(object):
def get_caching_iter(self, image_id, image_checksum, def get_caching_iter(self, image_id, image_checksum, app_iter):
app_iter):
self.image_checksum = image_checksum self.image_checksum = image_checksum
self.cache = DummyCache() self.cache = DummyCache()

View File

@ -1030,7 +1030,8 @@ class TestRegistryClient(base.IsolatedUnitTest):
"""Tests replacing image members""" """Tests replacing image members"""
self.assertTrue(self.client.add_member(UUID2, 'pattieblack')) self.assertTrue(self.client.add_member(UUID2, 'pattieblack'))
self.assertTrue(self.client.replace_members(UUID2, self.assertTrue(self.client.replace_members(UUID2,
dict(member_id='pattieblack2'))) dict(member_id='pattie'
'black2')))
def test_add_delete_member(self): def test_add_delete_member(self):
"""Tests deleting image members""" """Tests deleting image members"""

View File

@ -84,7 +84,7 @@ class TestPasteApp(test_utils.BaseTestCase):
def test_load_paste_app_paste_config_not_found(self): def test_load_paste_app_paste_config_not_found(self):
expected_middleware = context.UnauthenticatedContextMiddleware expected_middleware = context.UnauthenticatedContextMiddleware
self.assertRaises(RuntimeError, self._do_test_load_paste_app, self.assertRaises(RuntimeError, self._do_test_load_paste_app,
expected_middleware, make_paste_file=False) expected_middleware, make_paste_file=False)
def test_load_paste_app_with_paste_flavor(self): def test_load_paste_app_with_paste_flavor(self):
pipeline = ('[pipeline:glance-registry-incomplete]\n' pipeline = ('[pipeline:glance-registry-incomplete]\n'

View File

@ -8,7 +8,7 @@ from glance.tests.unit import base
class TestContextMiddleware(base.IsolatedUnitTest): class TestContextMiddleware(base.IsolatedUnitTest):
def _build_request(self, roles=None, identity_status='Confirmed', def _build_request(self, roles=None, identity_status='Confirmed',
service_catalog=None): service_catalog=None):
req = webob.Request.blank('/') req = webob.Request.blank('/')
req.headers['x-auth-token'] = 'token1' req.headers['x-auth-token'] = 'token1'
req.headers['x-identity-status'] = identity_status req.headers['x-identity-status'] = identity_status

View File

@ -113,10 +113,10 @@ class TestHttpStore(base.StoreClearingUnitTest):
# both redirects. # both redirects.
redirect_headers_1 = {"location": "http://example.com/teapot.img"} redirect_headers_1 = {"location": "http://example.com/teapot.img"}
redirect_resp_1 = utils.FakeHTTPResponse(status=302, redirect_resp_1 = utils.FakeHTTPResponse(status=302,
headers=redirect_headers_1) headers=redirect_headers_1)
redirect_headers_2 = {"location": "http://example.com/teapot_real.img"} redirect_headers_2 = {"location": "http://example.com/teapot_real.img"}
redirect_resp_2 = utils.FakeHTTPResponse(status=301, redirect_resp_2 = utils.FakeHTTPResponse(status=301,
headers=redirect_headers_2) headers=redirect_headers_2)
FAKE_RESPONSE_STACK.append(redirect_resp_1) FAKE_RESPONSE_STACK.append(redirect_resp_1)
FAKE_RESPONSE_STACK.append(redirect_resp_2) FAKE_RESPONSE_STACK.append(redirect_resp_2)
@ -134,7 +134,7 @@ class TestHttpStore(base.StoreClearingUnitTest):
# Add more than MAX_REDIRECTS redirects to the response stack # Add more than MAX_REDIRECTS redirects to the response stack
redirect_headers = {"location": "http://example.com/teapot.img"} redirect_headers = {"location": "http://example.com/teapot.img"}
redirect_resp = utils.FakeHTTPResponse(status=302, redirect_resp = utils.FakeHTTPResponse(status=302,
headers=redirect_headers) headers=redirect_headers)
for i in xrange(MAX_REDIRECTS + 2): for i in xrange(MAX_REDIRECTS + 2):
FAKE_RESPONSE_STACK.append(redirect_resp) FAKE_RESPONSE_STACK.append(redirect_resp)
@ -145,7 +145,7 @@ class TestHttpStore(base.StoreClearingUnitTest):
def test_http_get_redirect_invalid(self): def test_http_get_redirect_invalid(self):
redirect_headers = {"location": "http://example.com/teapot.img"} redirect_headers = {"location": "http://example.com/teapot.img"}
redirect_resp = utils.FakeHTTPResponse(status=307, redirect_resp = utils.FakeHTTPResponse(status=307,
headers=redirect_headers) headers=redirect_headers)
FAKE_RESPONSE_STACK.append(redirect_resp) FAKE_RESPONSE_STACK.append(redirect_resp)
uri = "http://netloc/path/to/file.tar.gz" uri = "http://netloc/path/to/file.tar.gz"
@ -154,7 +154,7 @@ class TestHttpStore(base.StoreClearingUnitTest):
def test_http_get_not_found(self): def test_http_get_not_found(self):
not_found_resp = utils.FakeHTTPResponse(status=404, not_found_resp = utils.FakeHTTPResponse(status=404,
data="404 Not Found") data="404 Not Found")
FAKE_RESPONSE_STACK.append(not_found_resp) FAKE_RESPONSE_STACK.append(not_found_resp)
uri = "http://netloc/path/to/file.tar.gz" uri = "http://netloc/path/to/file.tar.gz"

View File

@ -165,18 +165,22 @@ class TestMigrations(utils.BaseTestCase):
# Create the initial version of the images table # Create the initial version of the images table
meta = MetaData() meta = MetaData()
meta.bind = engine meta.bind = engine
images_001 = Table('images', meta, images_001 = Table('images',
Column('id', models.Integer, primary_key=True), meta,
Column('name', String(255)), Column('id', models.Integer, primary_key=True),
Column('type', String(30)), Column('name', String(255)),
Column('size', Integer), Column('type', String(30)),
Column('status', String(30)), Column('size', Integer),
Column('is_public', Boolean, default=False), Column('status', String(30)),
Column('location', Text), Column('is_public', Boolean, default=False),
Column('created_at', DateTime(), nullable=False), Column('location', Text),
Column('updated_at', DateTime()), Column('created_at', DateTime(), nullable=False),
Column('deleted_at', DateTime()), Column('updated_at', DateTime()),
Column('deleted', Boolean(), nullable=False, default=False)) Column('deleted_at', DateTime()),
Column('deleted',
Boolean(),
nullable=False,
default=False))
images_001.create() images_001.create()
def _walk_versions(self, initial_version=0): def _walk_versions(self, initial_version=0):

View File

@ -330,9 +330,10 @@ class TestQpidNotifier(utils.BaseTestCase):
self.mock_connection.open() self.mock_connection.open()
self.mock_connection.session().AndReturn(self.mock_session) self.mock_connection.session().AndReturn(self.mock_session)
for p in ["info", "warn", "error"]: for p in ["info", "warn", "error"]:
expected_address = ('glance/glance_notifications.%s ; {"node": ' expected_address = ('glance/glance_notifications.%s ; '
'{"x-declare": {"auto-delete": true, "durable": false}, ' '{"node": {"x-declare": {"auto-delete": true, '
'"type": "topic"}, "create": "always"}' % p) '"durable": false}, "type": "topic"}, '
'"create": "always"}' % p)
self.mock_session.sender(expected_address).AndReturn( self.mock_session.sender(expected_address).AndReturn(
self.mock_sender) self.mock_sender)
self.mock_sender.send(mox.IgnoreArg()) self.mock_sender.send(mox.IgnoreArg())

View File

@ -59,9 +59,12 @@ SWIFT_CONF = {'verbose': True,
def stub_out_swiftclient(stubs, swift_store_auth_version): def stub_out_swiftclient(stubs, swift_store_auth_version):
fixture_containers = ['glance'] fixture_containers = ['glance']
fixture_container_headers = {} fixture_container_headers = {}
fixture_headers = {'glance/%s' % FAKE_UUID: fixture_headers = {
{'content-length': FIVE_KB, 'glance/%s' % FAKE_UUID: {
'etag': 'c2e5db72bd7fd153f53ede5da5a06de3'}} 'content-length': FIVE_KB,
'etag': 'c2e5db72bd7fd153f53ede5da5a06de3'
}
}
fixture_objects = {'glance/%s' % FAKE_UUID: fixture_objects = {'glance/%s' % FAKE_UUID:
StringIO.StringIO("*" * FIVE_KB)} StringIO.StringIO("*" * FIVE_KB)}
@ -69,7 +72,7 @@ def stub_out_swiftclient(stubs, swift_store_auth_version):
if container not in fixture_containers: if container not in fixture_containers:
msg = "No container %s found" % container msg = "No container %s found" % container
raise swiftclient.ClientException(msg, raise swiftclient.ClientException(msg,
http_status=httplib.NOT_FOUND) http_status=httplib.NOT_FOUND)
return fixture_container_headers return fixture_container_headers
def fake_put_container(url, token, container, **kwargs): def fake_put_container(url, token, container, **kwargs):
@ -118,7 +121,7 @@ def stub_out_swiftclient(stubs, swift_store_auth_version):
msg = ("Object PUT failed - Object with key %s already exists" msg = ("Object PUT failed - Object with key %s already exists"
% fixture_key) % fixture_key)
raise swiftclient.ClientException(msg, raise swiftclient.ClientException(msg,
http_status=httplib.CONFLICT) http_status=httplib.CONFLICT)
def fake_get_object(url, token, container, name, **kwargs): def fake_get_object(url, token, container, name, **kwargs):
# GET returns the tuple (list of headers, file object) # GET returns the tuple (list of headers, file object)
@ -126,7 +129,7 @@ def stub_out_swiftclient(stubs, swift_store_auth_version):
if not fixture_key in fixture_headers: if not fixture_key in fixture_headers:
msg = "Object GET failed" msg = "Object GET failed"
raise swiftclient.ClientException(msg, raise swiftclient.ClientException(msg,
http_status=httplib.NOT_FOUND) http_status=httplib.NOT_FOUND)
fixture = fixture_headers[fixture_key] fixture = fixture_headers[fixture_key]
if 'manifest' in fixture: if 'manifest' in fixture:
@ -151,7 +154,7 @@ def stub_out_swiftclient(stubs, swift_store_auth_version):
except KeyError: except KeyError:
msg = "Object HEAD failed - Object does not exist" msg = "Object HEAD failed - Object does not exist"
raise swiftclient.ClientException(msg, raise swiftclient.ClientException(msg,
http_status=httplib.NOT_FOUND) http_status=httplib.NOT_FOUND)
def fake_delete_object(url, token, container, name, **kwargs): def fake_delete_object(url, token, container, name, **kwargs):
# DELETE returns nothing # DELETE returns nothing
@ -159,7 +162,7 @@ def stub_out_swiftclient(stubs, swift_store_auth_version):
if fixture_key not in fixture_headers.keys(): if fixture_key not in fixture_headers.keys():
msg = "Object DELETE failed - Object does not exist" msg = "Object DELETE failed - Object does not exist"
raise swiftclient.ClientException(msg, raise swiftclient.ClientException(msg,
http_status=httplib.NOT_FOUND) http_status=httplib.NOT_FOUND)
else: else:
del fixture_headers[fixture_key] del fixture_headers[fixture_key]
del fixture_objects[fixture_key] del fixture_objects[fixture_key]

View File

@ -180,7 +180,7 @@ class JSONRequestDeserializerTest(test_utils.BaseTestCase):
def test_from_json_malformed(self): def test_from_json_malformed(self):
fixture = 'kjasdklfjsklajf' fixture = 'kjasdklfjsklajf'
self.assertRaises(webob.exc.HTTPBadRequest, self.assertRaises(webob.exc.HTTPBadRequest,
wsgi.JSONRequestDeserializer().from_json, fixture) wsgi.JSONRequestDeserializer().from_json, fixture)
def test_default_no_body(self): def test_default_no_body(self):
request = wsgi.Request.blank('/') request = wsgi.Request.blank('/')

View File

@ -1701,7 +1701,7 @@ class TestRegistryAPI(base.IsolatedUnitTest):
res_dict = json.loads(res.body) res_dict = json.loads(res.body)
self.assertNotEquals(res_dict['image']['created_at'], self.assertNotEquals(res_dict['image']['created_at'],
res_dict['image']['updated_at']) res_dict['image']['updated_at'])
for k, v in fixture.iteritems(): for k, v in fixture.iteritems():
self.assertEquals(v, res_dict['image'][k]) self.assertEquals(v, res_dict['image'][k])
@ -1954,11 +1954,13 @@ class TestGlanceAPI(base.IsolatedUnitTest):
self._do_test_defaulted_format(key, value) self._do_test_defaulted_format(key, value)
def test_bad_disk_format(self): def test_bad_disk_format(self):
fixture_headers = {'x-image-meta-store': 'bad', fixture_headers = {
'x-image-meta-name': 'bogus', 'x-image-meta-store': 'bad',
'x-image-meta-location': 'http://localhost:0/image.tar.gz', 'x-image-meta-name': 'bogus',
'x-image-meta-disk-format': 'invalid', 'x-image-meta-location': 'http://localhost:0/image.tar.gz',
'x-image-meta-container-format': 'ami'} 'x-image-meta-disk-format': 'invalid',
'x-image-meta-container-format': 'ami',
}
req = webob.Request.blank("/images") req = webob.Request.blank("/images")
req.method = 'POST' req.method = 'POST'
@ -1970,10 +1972,12 @@ class TestGlanceAPI(base.IsolatedUnitTest):
self.assertTrue('Invalid disk format' in res.body, res.body) self.assertTrue('Invalid disk format' in res.body, res.body)
def test_create_with_location_no_container_format(self): def test_create_with_location_no_container_format(self):
fixture_headers = {'x-image-meta-store': 'bad', fixture_headers = {
'x-image-meta-name': 'bogus', 'x-image-meta-store': 'bad',
'x-image-meta-location': 'http://localhost:0/image.tar.gz', 'x-image-meta-name': 'bogus',
'x-image-meta-disk-format': 'vhd'} 'x-image-meta-location': 'http://localhost:0/image.tar.gz',
'x-image-meta-disk-format': 'vhd',
}
req = webob.Request.blank("/images") req = webob.Request.blank("/images")
req.method = 'POST' req.method = 'POST'
@ -1985,11 +1989,13 @@ class TestGlanceAPI(base.IsolatedUnitTest):
self.assertTrue('Invalid container format' in res.body) self.assertTrue('Invalid container format' in res.body)
def test_bad_container_format(self): def test_bad_container_format(self):
fixture_headers = {'x-image-meta-store': 'bad', fixture_headers = {
'x-image-meta-name': 'bogus', 'x-image-meta-store': 'bad',
'x-image-meta-location': 'http://localhost:0/image.tar.gz', 'x-image-meta-name': 'bogus',
'x-image-meta-disk-format': 'vhd', 'x-image-meta-location': 'http://localhost:0/image.tar.gz',
'x-image-meta-container-format': 'invalid'} 'x-image-meta-disk-format': 'vhd',
'x-image-meta-container-format': 'invalid',
}
req = webob.Request.blank("/images") req = webob.Request.blank("/images")
req.method = 'POST' req.method = 'POST'
@ -2001,12 +2007,14 @@ class TestGlanceAPI(base.IsolatedUnitTest):
self.assertTrue('Invalid container format' in res.body) self.assertTrue('Invalid container format' in res.body)
def test_bad_image_size(self): def test_bad_image_size(self):
fixture_headers = {'x-image-meta-store': 'bad', fixture_headers = {
'x-image-meta-name': 'bogus', 'x-image-meta-store': 'bad',
'x-image-meta-location': 'http://example.com/image.tar.gz', 'x-image-meta-name': 'bogus',
'x-image-meta-disk-format': 'vhd', 'x-image-meta-location': 'http://example.com/image.tar.gz',
'x-image-meta-size': 'invalid', 'x-image-meta-disk-format': 'vhd',
'x-image-meta-container-format': 'bare'} 'x-image-meta-size': 'invalid',
'x-image-meta-container-format': 'bare',
}
req = webob.Request.blank("/images") req = webob.Request.blank("/images")
req.method = 'POST' req.method = 'POST'
@ -2018,11 +2026,13 @@ class TestGlanceAPI(base.IsolatedUnitTest):
self.assertTrue('Incoming image size' in res.body) self.assertTrue('Incoming image size' in res.body)
def test_bad_image_name(self): def test_bad_image_name(self):
fixture_headers = {'x-image-meta-store': 'bad', fixture_headers = {
'x-image-meta-name': 'X' * 256, 'x-image-meta-store': 'bad',
'x-image-meta-location': 'http://example.com/image.tar.gz', 'x-image-meta-name': 'X' * 256,
'x-image-meta-disk-format': 'vhd', 'x-image-meta-location': 'http://example.com/image.tar.gz',
'x-image-meta-container-format': 'bare'} 'x-image-meta-disk-format': 'vhd',
'x-image-meta-container-format': 'bare',
}
req = webob.Request.blank("/images") req = webob.Request.blank("/images")
req.method = 'POST' req.method = 'POST'

View File

@ -81,8 +81,8 @@ class TestImagesController(base.StoreClearingUnitTest):
def test_upload_storage_full(self): def test_upload_storage_full(self):
request = unit_test_utils.get_fake_request() request = unit_test_utils.get_fake_request()
self.assertRaises(webob.exc.HTTPRequestEntityTooLarge, self.assertRaises(webob.exc.HTTPRequestEntityTooLarge,
self.controller.upload, self.controller.upload,
request, unit_test_utils.UUID2, 'YYYYYYY', 7) request, unit_test_utils.UUID2, 'YYYYYYY', 7)
def test_upload_storage_forbidden(self): def test_upload_storage_forbidden(self):
request = unit_test_utils.get_fake_request(user=unit_test_utils.USER2) request = unit_test_utils.get_fake_request(user=unit_test_utils.USER2)
@ -92,8 +92,8 @@ class TestImagesController(base.StoreClearingUnitTest):
def test_upload_storage_write_denied(self): def test_upload_storage_write_denied(self):
request = unit_test_utils.get_fake_request(user=unit_test_utils.USER3) request = unit_test_utils.get_fake_request(user=unit_test_utils.USER3)
self.assertRaises(webob.exc.HTTPServiceUnavailable, self.assertRaises(webob.exc.HTTPServiceUnavailable,
self.controller.upload, self.controller.upload,
request, unit_test_utils.UUID2, 'YY', 2) request, unit_test_utils.UUID2, 'YY', 2)
def test_upload_download_no_size(self): def test_upload_download_no_size(self):
request = unit_test_utils.get_fake_request() request = unit_test_utils.get_fake_request()
@ -183,7 +183,7 @@ class TestImageDataDeserializer(test_utils.BaseTestCase):
request.headers['Content-Type'] = 'application/json' request.headers['Content-Type'] = 'application/json'
request.body = 'YYYYY' request.body = 'YYYYY'
self.assertRaises(webob.exc.HTTPUnsupportedMediaType, self.assertRaises(webob.exc.HTTPUnsupportedMediaType,
self.deserializer.upload, request) self.deserializer.upload, request)
class TestImageDataSerializer(test_utils.BaseTestCase): class TestImageDataSerializer(test_utils.BaseTestCase):

View File

@ -208,7 +208,10 @@ class TestImagesController(test_utils.BaseTestCase):
url = '/images?status=queued&name=2' url = '/images?status=queued&name=2'
request = unit_test_utils.get_fake_request(url) request = unit_test_utils.get_fake_request(url)
output = self.controller.index(request, output = self.controller.index(request,
filters={'status': 'queued', 'name': '2'}) filters={
'status': 'queued',
'name': '2',
})
self.assertEqual(1, len(output['images'])) self.assertEqual(1, len(output['images']))
actual = set([image['id'] for image in output['images']]) actual = set([image['id'] for image in output['images']])
expected = set([UUID2]) expected = set([UUID2])
@ -1101,7 +1104,7 @@ class TestImagesDeserializerWithExtendedSchema(test_utils.BaseTestCase):
request = unit_test_utils.get_fake_request() request = unit_test_utils.get_fake_request()
request.body = json.dumps({'name': 'image-1', 'pants': 'borked'}) request.body = json.dumps({'name': 'image-1', 'pants': 'borked'})
self.assertRaises(webob.exc.HTTPBadRequest, self.assertRaises(webob.exc.HTTPBadRequest,
self.deserializer.create, request) self.deserializer.create, request)
def test_update(self): def test_update(self):
request = unit_test_utils.get_fake_request() request = unit_test_utils.get_fake_request()
@ -1118,7 +1121,8 @@ class TestImagesDeserializerWithExtendedSchema(test_utils.BaseTestCase):
request.content_type = 'application/openstack-images-v2.0-json-patch' request.content_type = 'application/openstack-images-v2.0-json-patch'
request.body = json.dumps([{'add': '/pants', 'value': 'cutoffs'}]) request.body = json.dumps([{'add': '/pants', 'value': 'cutoffs'}])
self.assertRaises(webob.exc.HTTPBadRequest, self.assertRaises(webob.exc.HTTPBadRequest,
self.deserializer.update, request) self.deserializer.update,
request)
class TestImagesDeserializerWithAdditionalProperties(test_utils.BaseTestCase): class TestImagesDeserializerWithAdditionalProperties(test_utils.BaseTestCase):
@ -1199,11 +1203,19 @@ class TestImagesSerializer(test_utils.BaseTestCase):
self.serializer = glance.api.v2.images.ResponseSerializer() self.serializer = glance.api.v2.images.ResponseSerializer()
self.fixtures = [ self.fixtures = [
#NOTE(bcwaldon): This first fixture has every property defined #NOTE(bcwaldon): This first fixture has every property defined
_fixture(UUID1, name='image-1', size=1024, tags=['one', 'two'], _fixture(UUID1,
created_at=DATETIME, updated_at=DATETIME, owner=TENANT1, name='image-1',
is_public=True, container_format='ami', disk_format='ami', size=1024,
checksum='ca425b88f047ce8ec45ee90e813ada91', tags=['one', 'two'],
min_ram=128, min_disk=10), created_at=DATETIME,
updated_at=DATETIME,
owner=TENANT1,
is_public=True,
container_format='ami',
disk_format='ami',
checksum='ca425b88f047ce8ec45ee90e813ada91',
min_ram=128,
min_disk=10),
#NOTE(bcwaldon): This second fixture depends on default behavior #NOTE(bcwaldon): This second fixture depends on default behavior
# and sets most values to None # and sets most values to None
@ -1377,14 +1389,23 @@ class TestImagesSerializerWithUnicode(test_utils.BaseTestCase):
self.serializer = glance.api.v2.images.ResponseSerializer() self.serializer = glance.api.v2.images.ResponseSerializer()
self.fixtures = [ self.fixtures = [
#NOTE(bcwaldon): This first fixture has every property defined #NOTE(bcwaldon): This first fixture has every property defined
_fixture(UUID1, name=u'OpenStack\u2122-1', _fixture(UUID1,
size=1024, tags=[u'\u2160', u'\u2161'], name=u'OpenStack\u2122-1',
created_at=DATETIME, updated_at=DATETIME, owner=TENANT1, size=1024,
is_public=True, container_format='ami', disk_format='ami', tags=[u'\u2160', u'\u2161'],
checksum=u'ca425b88f047ce8ec45ee90e813ada91', created_at=DATETIME,
min_ram=128, min_disk=10, updated_at=DATETIME,
properties={'lang': u'Fran\u00E7ais', owner=TENANT1,
u'dispos\u00E9': u'f\u00E2ch\u00E9'}), is_public=True,
container_format='ami',
disk_format='ami',
checksum=u'ca425b88f047ce8ec45ee90e813ada91',
min_ram=128,
min_disk=10,
properties={
'lang': u'Fran\u00E7ais',
u'dispos\u00E9': u'f\u00E2ch\u00E9',
}),
] ]
def test_index(self): def test_index(self):
@ -1521,10 +1542,17 @@ class TestImagesSerializerWithExtendedSchema(test_utils.BaseTestCase):
schema = glance.api.v2.images.get_schema(custom_image_properties) schema = glance.api.v2.images.get_schema(custom_image_properties)
self.serializer = glance.api.v2.images.ResponseSerializer(schema) self.serializer = glance.api.v2.images.ResponseSerializer(schema)
self.fixture = _fixture(UUID2, name='image-2', owner=TENANT2, self.fixture = _fixture(UUID2,
checksum='ca425b88f047ce8ec45ee90e813ada91', name='image-2',
created_at=DATETIME, updated_at=DATETIME, owner=TENANT2,
size=1024, properties={'color': 'green', 'mood': 'grouchy'}) checksum='ca425b88f047ce8ec45ee90e813ada91',
created_at=DATETIME,
updated_at=DATETIME,
size=1024,
properties={
'color': 'green',
'mood': 'grouchy',
})
def test_show(self): def test_show(self):
expected = { expected = {
@ -1575,10 +1603,14 @@ class TestImagesSerializerWithAdditionalProperties(test_utils.BaseTestCase):
def setUp(self): def setUp(self):
super(TestImagesSerializerWithAdditionalProperties, self).setUp() super(TestImagesSerializerWithAdditionalProperties, self).setUp()
self.config(allow_additional_image_properties=True) self.config(allow_additional_image_properties=True)
self.fixture = _fixture(UUID2, name='image-2', owner=TENANT2, self.fixture = _fixture(UUID2,
checksum='ca425b88f047ce8ec45ee90e813ada91', name='image-2',
created_at=DATETIME, updated_at=DATETIME, owner=TENANT2,
properties={'marx': 'groucho'}, size=1024) checksum='ca425b88f047ce8ec45ee90e813ada91',
created_at=DATETIME,
updated_at=DATETIME,
properties={'marx': 'groucho'},
size=1024)
def test_show(self): def test_show(self):
serializer = glance.api.v2.images.ResponseSerializer() serializer = glance.api.v2.images.ResponseSerializer()
@ -1656,20 +1688,27 @@ class TestImagesSerializerDirectUrl(test_utils.BaseTestCase):
super(TestImagesSerializerDirectUrl, self).setUp() super(TestImagesSerializerDirectUrl, self).setUp()
self.serializer = glance.api.v2.images.ResponseSerializer() self.serializer = glance.api.v2.images.ResponseSerializer()
self.active_image = _fixture(UUID1, name='image-1', is_public=True, self.active_image = _fixture(UUID1,
status='active', size=1024, name='image-1',
created_at=DATETIME, updated_at=DATETIME, is_public=True,
location='http://some/fake/location') status='active', size=1024,
created_at=DATETIME, updated_at=DATETIME,
location='http://some/fake/location')
self.queued_image = _fixture(UUID2, name='image-2', status='active', self.queued_image = _fixture(UUID2,
created_at=DATETIME, updated_at=DATETIME, name='image-2',
checksum='ca425b88f047ce8ec45ee90e813ada91') status='active',
created_at=DATETIME,
updated_at=DATETIME,
checksum='ca425b88f047ce8e'
'c45ee90e813ada91')
def _do_index(self): def _do_index(self):
request = webob.Request.blank('/v2/images') request = webob.Request.blank('/v2/images')
response = webob.Response(request=request) response = webob.Response(request=request)
self.serializer.index(response, self.serializer.index(response,
{'images': [self.active_image, self.queued_image]}) {'images': [self.active_image,
self.queued_image]})
return json.loads(response.body)['images'] return json.loads(response.body)['images']
def _do_show(self, image): def _do_show(self, image):

View File

@ -18,7 +18,7 @@ downloadcache = ~/cache/pip
[testenv:pep8] [testenv:pep8]
deps = pep8==1.3.3 deps = pep8==1.3.3
commands = pep8 --ignore=E125,E126,E128,E711 --repeat --show-source --exclude=.venv,.tox,dist,doc,openstack . commands = pep8 --ignore=E125,E126,E711 --repeat --show-source --exclude=.venv,.tox,dist,doc,openstack .
[testenv:cover] [testenv:cover]
setenv = NOSE_WITH_COVERAGE=1 setenv = NOSE_WITH_COVERAGE=1