Merge "Run pyupgrade to clean up Python 2 syntaxes"

This commit is contained in:
Zuul 2024-11-01 04:47:53 +00:00 committed by Gerrit Code Review
commit 6e783c172c
14 changed files with 242 additions and 241 deletions

View File

@ -28,3 +28,8 @@ repos:
hooks: hooks:
- id: bandit - id: bandit
args: ['-x', 'tests', '--skip', 'B303'] args: ['-x', 'tests', '--skip', 'B303']
- repo: https://github.com/asottile/pyupgrade
rev: v3.18.0
hooks:
- id: pyupgrade
args: [--py3-only]

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2020 Red Hat, Inc. # Copyright (C) 2020 Red Hat, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");

View File

@ -34,7 +34,7 @@ from oslo_versionedobjects import fields as obj_fields
LOG = logging.getLogger('object') LOG = logging.getLogger('object')
class _NotSpecifiedSentinel(object): class _NotSpecifiedSentinel:
pass pass
@ -83,7 +83,7 @@ def _make_class_properties(cls):
return setattr(self, attrname, field_value) return setattr(self, attrname, field_value)
except Exception: except Exception:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
attr = "%s.%s" % (self.obj_name(), name) attr = "{}.{}".format(self.obj_name(), name)
LOG.exception('Error setting %(attr)s', LOG.exception('Error setting %(attr)s',
{'attr': attr}) {'attr': attr})
@ -96,7 +96,7 @@ def _make_class_properties(cls):
setattr(cls, name, property(getter, setter, deleter)) setattr(cls, name, property(getter, setter, deleter))
class VersionedObjectRegistry(object): class VersionedObjectRegistry:
_registry = None _registry = None
def __new__(cls, *args, **kwargs): def __new__(cls, *args, **kwargs):
@ -230,7 +230,7 @@ def remotable(fn):
return wrapper return wrapper
class VersionedObject(object): class VersionedObject:
"""Base class and object factory. """Base class and object factory.
This forms the base of all objects that can be remoted or instantiated This forms the base of all objects that can be remoted or instantiated
@ -307,9 +307,9 @@ class VersionedObject(object):
setattr(self, key, kwargs[key]) setattr(self, key, kwargs[key])
def __repr__(self): def __repr__(self):
repr_str = '%s(%s)' % ( repr_str = '{}({})'.format(
self.obj_name(), self.obj_name(),
','.join(['%s=%s' % (name, ','.join(['{}={}'.format(name,
(self.obj_attr_is_set(name) and (self.obj_attr_is_set(name) and
field.stringify(getattr(self, name)) or field.stringify(getattr(self, name)) or
'<?>')) '<?>'))
@ -343,7 +343,7 @@ class VersionedObject(object):
@classmethod @classmethod
def _obj_primitive_key(cls, field): def _obj_primitive_key(cls, field):
return '%s.%s' % (cls.OBJ_SERIAL_NAMESPACE, field) return '{}.{}'.format(cls.OBJ_SERIAL_NAMESPACE, field)
@classmethod @classmethod
def _obj_primitive_field(cls, primitive, field, def _obj_primitive_field(cls, primitive, field,
@ -395,7 +395,7 @@ class VersionedObject(object):
if name in objdata: if name in objdata:
setattr(self, name, field.from_primitive(self, name, setattr(self, name, field.from_primitive(self, name,
objdata[name])) objdata[name]))
self._changed_fields = set([x for x in changes if x in self.fields]) self._changed_fields = {x for x in changes if x in self.fields}
return self return self
@classmethod @classmethod
@ -408,7 +408,7 @@ class VersionedObject(object):
# NOTE(danms): We don't do anything with this now, but it's # NOTE(danms): We don't do anything with this now, but it's
# there for "the future" # there for "the future"
raise exception.UnsupportedObjectError( raise exception.UnsupportedObjectError(
objtype='%s.%s' % (objns, objname)) objtype='{}.{}'.format(objns, objname))
objclass = cls.obj_class_from_name(objname, objver) objclass = cls.obj_class_from_name(objname, objver)
return objclass._obj_from_primitive(context, objver, primitive) return objclass._obj_from_primitive(context, objver, primitive)
@ -610,8 +610,8 @@ class VersionedObject(object):
def obj_what_changed(self): def obj_what_changed(self):
"""Returns a set of fields that have been modified.""" """Returns a set of fields that have been modified."""
changes = set([field for field in self._changed_fields changes = {field for field in self._changed_fields
if field in self.fields]) if field in self.fields}
for field in self.fields: for field in self.fields:
if (self.obj_attr_is_set(field) and if (self.obj_attr_is_set(field) and
isinstance(getattr(self, field), VersionedObject) and isinstance(getattr(self, field), VersionedObject) and
@ -691,7 +691,7 @@ class VersionedObject(object):
return self._context return self._context
class ComparableVersionedObject(object): class ComparableVersionedObject:
"""Mix-in to provide comparison methods """Mix-in to provide comparison methods
When objects are to be compared with each other (in tests for example), When objects are to be compared with each other (in tests for example),
@ -705,7 +705,7 @@ class ComparableVersionedObject(object):
return NotImplemented return NotImplemented
def __hash__(self): def __hash__(self):
return super(ComparableVersionedObject, self).__hash__() return super().__hash__()
def __ne__(self, obj): def __ne__(self, obj):
if hasattr(obj, 'obj_to_primitive'): if hasattr(obj, 'obj_to_primitive'):
@ -713,7 +713,7 @@ class ComparableVersionedObject(object):
return NotImplemented return NotImplemented
class TimestampedObject(object): class TimestampedObject:
"""Mixin class for db backed objects with timestamp fields. """Mixin class for db backed objects with timestamp fields.
Sqlalchemy models that inherit from the oslo_db TimestampMixin will include Sqlalchemy models that inherit from the oslo_db TimestampMixin will include
@ -725,7 +725,7 @@ class TimestampedObject(object):
} }
class VersionedObjectDictCompat(object): class VersionedObjectDictCompat:
"""Mix-in to provide dictionary key access compatibility """Mix-in to provide dictionary key access compatibility
If an object needs to support attribute access using If an object needs to support attribute access using
@ -759,7 +759,7 @@ class VersionedObjectDictCompat(object):
def get(self, key, value=_NotSpecifiedSentinel): def get(self, key, value=_NotSpecifiedSentinel):
if key not in self.obj_fields: if key not in self.obj_fields:
raise AttributeError("'%s' object has no attribute '%s'" % ( raise AttributeError("'{}' object has no attribute '{}'".format(
self.__class__, key)) self.__class__, key))
if value != _NotSpecifiedSentinel and not self.obj_attr_is_set(key): if value != _NotSpecifiedSentinel and not self.obj_attr_is_set(key):
return value return value
@ -789,7 +789,7 @@ class ObjectListBase(collections_abc.Sequence):
child_versions = {} child_versions = {}
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(ObjectListBase, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
if 'objects' not in kwargs: if 'objects' not in kwargs:
self.objects = [] self.objects = []
self._changed_fields.discard('objects') self._changed_fields.discard('objects')
@ -959,7 +959,7 @@ class VersionedObjectSerializer(messaging.NoOpSerializer):
return entity return entity
class VersionedObjectIndirectionAPI(object, metaclass=abc.ABCMeta): class VersionedObjectIndirectionAPI(metaclass=abc.ABCMeta):
def object_action(self, context, objinst, objmethod, args, kwargs): def object_action(self, context, objinst, objmethod, args, kwargs):
"""Perform an action on a VersionedObject instance. """Perform an action on a VersionedObject instance.

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain # not use this file except in compliance with the License. You may obtain
# a copy of the License at # a copy of the License at

View File

@ -49,7 +49,7 @@ class ConvertedException(webob.exc.WSGIHTTPException):
self.code = code self.code = code
self.title = title self.title = title
self.explanation = explanation self.explanation = explanation
super(ConvertedException, self).__init__() super().__init__()
def _cleanse_dict(original): def _cleanse_dict(original):
@ -122,7 +122,7 @@ class VersionedObjectsException(Exception):
# log the issue and the kwargs # log the issue and the kwargs
LOG.exception('Exception in string format operation') LOG.exception('Exception in string format operation')
for name, value in kwargs.items(): for name, value in kwargs.items():
LOG.error("%s: %s" % (name, value)) # noqa LOG.error("{}: {}".format(name, value)) # noqa
if CONF.oslo_versionedobjects.fatal_exception_format_errors: if CONF.oslo_versionedobjects.fatal_exception_format_errors:
raise raise
@ -130,7 +130,7 @@ class VersionedObjectsException(Exception):
# at least get the core message out if something happened # at least get the core message out if something happened
message = self.msg_fmt message = self.msg_fmt
super(VersionedObjectsException, self).__init__(message) super().__init__(message)
def format_message(self): def format_message(self):
# NOTE(mrodden): use the first argument to the python Exception object # NOTE(mrodden): use the first argument to the python Exception object

View File

@ -33,7 +33,7 @@ from oslo_versionedobjects import exception
class KeyTypeError(TypeError): class KeyTypeError(TypeError):
def __init__(self, expected, value): def __init__(self, expected, value):
super(KeyTypeError, self).__init__( super().__init__(
_('Key %(key)s must be of type %(expected)s not %(actual)s' _('Key %(key)s must be of type %(expected)s not %(actual)s'
) % {'key': repr(value), ) % {'key': repr(value),
'expected': expected.__name__, 'expected': expected.__name__,
@ -43,7 +43,7 @@ class KeyTypeError(TypeError):
class ElementTypeError(TypeError): class ElementTypeError(TypeError):
def __init__(self, expected, key, value): def __init__(self, expected, key, value):
super(ElementTypeError, self).__init__( super().__init__(
_('Element %(key)s:%(val)s must be of type %(expected)s' _('Element %(key)s:%(val)s must be of type %(expected)s'
' not %(actual)s' ' not %(actual)s'
) % {'key': key, ) % {'key': key,
@ -53,7 +53,7 @@ class ElementTypeError(TypeError):
}) })
class AbstractFieldType(object, metaclass=abc.ABCMeta): class AbstractFieldType(metaclass=abc.ABCMeta):
@abc.abstractmethod @abc.abstractmethod
def coerce(self, obj, attr, value): def coerce(self, obj, attr, value):
"""This is called to coerce (if possible) a value on assignment. """This is called to coerce (if possible) a value on assignment.
@ -130,11 +130,11 @@ class FieldType(AbstractFieldType):
raise NotImplementedError() raise NotImplementedError()
class UnspecifiedDefault(object): class UnspecifiedDefault:
pass pass
class Field(object): class Field:
def __init__(self, field_type, nullable=False, def __init__(self, field_type, nullable=False,
default=UnspecifiedDefault, read_only=False): default=UnspecifiedDefault, read_only=False):
self._type = field_type self._type = field_type
@ -153,8 +153,8 @@ class Field(object):
) )
else: else:
default = str(self._default) default = str(self._default)
return '%s(default=%s,nullable=%s)' % (self._type.__class__.__name__, return '{}(default={},nullable={})'.format(
default, self._nullable) self._type.__class__.__name__, default, self._nullable)
@property @property
def nullable(self): def nullable(self):
@ -286,7 +286,7 @@ class SensitiveString(String):
Passwords in the string value are masked when stringified. Passwords in the string value are masked when stringified.
""" """
def stringify(self, value): def stringify(self, value):
return super(SensitiveString, self).stringify( return super().stringify(
strutils.mask_password(value)) strutils.mask_password(value))
@ -309,11 +309,11 @@ class Enum(String):
try: try:
# Test validity of the values # Test validity of the values
for value in valid_values: for value in valid_values:
super(Enum, self).coerce(None, 'init', value) super().coerce(None, 'init', value)
except (TypeError, ValueError): except (TypeError, ValueError):
raise exception.EnumValidValuesInvalidError() raise exception.EnumValidValuesInvalidError()
self._valid_values = valid_values self._valid_values = valid_values
super(Enum, self).__init__(**kwargs) super().__init__(**kwargs)
@property @property
def valid_values(self): def valid_values(self):
@ -323,16 +323,16 @@ class Enum(String):
if value not in self._valid_values: if value not in self._valid_values:
msg = _("Field value %s is invalid") % value msg = _("Field value %s is invalid") % value
raise ValueError(msg) raise ValueError(msg)
return super(Enum, self).coerce(obj, attr, value) return super().coerce(obj, attr, value)
def stringify(self, value): def stringify(self, value):
if value not in self._valid_values: if value not in self._valid_values:
msg = _("Field value %s is invalid") % value msg = _("Field value %s is invalid") % value
raise ValueError(msg) raise ValueError(msg)
return super(Enum, self).stringify(value) return super().stringify(value)
def get_schema(self): def get_schema(self):
schema = super(Enum, self).get_schema() schema = super().get_schema()
schema['enum'] = self._valid_values schema['enum'] = self._valid_values
return schema return schema
@ -465,7 +465,7 @@ class FlexibleBoolean(Boolean):
class DateTime(FieldType): class DateTime(FieldType):
def __init__(self, tzinfo_aware=True, *args, **kwargs): def __init__(self, tzinfo_aware=True, *args, **kwargs):
self.tzinfo_aware = tzinfo_aware self.tzinfo_aware = tzinfo_aware
super(DateTime, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
def coerce(self, obj, attr, value): def coerce(self, obj, attr, value):
if isinstance(value, str): if isinstance(value, str):
@ -586,7 +586,7 @@ class IPV4Network(IPNetwork):
class IPV6Network(IPNetwork): class IPV6Network(IPNetwork):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(IPV6Network, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.PATTERN = self._create_pattern() self.PATTERN = self._create_pattern()
@staticmethod @staticmethod
@ -684,19 +684,19 @@ class Dict(CompoundFieldType):
primitive = {} primitive = {}
for key, element in value.items(): for key, element in value.items():
primitive[key] = self._element_type.to_primitive( primitive[key] = self._element_type.to_primitive(
obj, '%s["%s"]' % (attr, key), element) obj, '{}["{}"]'.format(attr, key), element)
return primitive return primitive
def from_primitive(self, obj, attr, value): def from_primitive(self, obj, attr, value):
concrete = {} concrete = {}
for key, element in value.items(): for key, element in value.items():
concrete[key] = self._element_type.from_primitive( concrete[key] = self._element_type.from_primitive(
obj, '%s["%s"]' % (attr, key), element) obj, '{}["{}"]'.format(attr, key), element)
return concrete return concrete
def stringify(self, value): def stringify(self, value):
return '{%s}' % ( return '{%s}' % (
','.join(['%s=%s' % (key, self._element_type.stringify(val)) ','.join(['{}={}'.format(key, self._element_type.stringify(val))
for key, val in sorted(value.items())])) for key, val in sorted(value.items())]))
def get_schema(self): def get_schema(self):
@ -704,7 +704,7 @@ class Dict(CompoundFieldType):
'additionalProperties': self._element_type.get_schema()} 'additionalProperties': self._element_type.get_schema()}
class DictProxyField(object): class DictProxyField:
"""Descriptor allowing us to assign pinning data as a dict of key_types """Descriptor allowing us to assign pinning data as a dict of key_types
This allows us to have an object field that will be a dict of key_type This allows us to have an object field that will be a dict of key_type
@ -751,8 +751,8 @@ class Set(CompoundFieldType):
self._element_type.to_primitive(obj, attr, x) for x in value) self._element_type.to_primitive(obj, attr, x) for x in value)
def from_primitive(self, obj, attr, value): def from_primitive(self, obj, attr, value):
return set([self._element_type.from_primitive(obj, attr, x) return {self._element_type.from_primitive(obj, attr, x)
for x in value]) for x in value}
def stringify(self, value): def stringify(self, value):
return 'set([%s])' % ( return 'set([%s])' % (
@ -767,7 +767,7 @@ class Object(FieldType):
def __init__(self, obj_name, subclasses=False, **kwargs): def __init__(self, obj_name, subclasses=False, **kwargs):
self._obj_name = obj_name self._obj_name = obj_name
self._subclasses = subclasses self._subclasses = subclasses
super(Object, self).__init__(**kwargs) super().__init__(**kwargs)
@staticmethod @staticmethod
def _get_all_obj_names(obj): def _get_all_obj_names(obj):
@ -835,7 +835,7 @@ class Object(FieldType):
else: else:
ident = '' ident = ''
return '%s%s' % (value.obj_name(), ident) return '{}{}'.format(value.obj_name(), ident)
def get_schema(self): def get_schema(self):
from oslo_versionedobjects import base as obj_base from oslo_versionedobjects import base as obj_base
@ -890,7 +890,7 @@ class AutoTypedField(Field):
AUTO_TYPE = None AUTO_TYPE = None
def __init__(self, **kwargs): def __init__(self, **kwargs):
super(AutoTypedField, self).__init__(self.AUTO_TYPE, **kwargs) super().__init__(self.AUTO_TYPE, **kwargs)
class StringField(AutoTypedField): class StringField(AutoTypedField):
@ -924,7 +924,7 @@ class BaseEnumField(AutoTypedField):
typename=self.AUTO_TYPE.__class__.__name__, typename=self.AUTO_TYPE.__class__.__name__,
fieldname=self.__class__.__name__) fieldname=self.__class__.__name__)
super(BaseEnumField, self).__init__(**kwargs) super().__init__(**kwargs)
def __repr__(self): def __repr__(self):
valid_values = self._type.valid_values valid_values = self._type.valid_values
@ -933,8 +933,8 @@ class BaseEnumField(AutoTypedField):
'default': self._default, 'default': self._default,
} }
args.update({'valid_values': valid_values}) args.update({'valid_values': valid_values})
return '%s(%s)' % (self._type.__class__.__name__, return '{}({})'.format(self._type.__class__.__name__,
','.join(['%s=%s' % (k, v) ','.join(['{}={}'.format(k, v)
for k, v in sorted(args.items())])) for k, v in sorted(args.items())]))
@property @property
@ -955,7 +955,7 @@ class EnumField(BaseEnumField):
def __init__(self, valid_values, **kwargs): def __init__(self, valid_values, **kwargs):
self.AUTO_TYPE = Enum(valid_values=valid_values) self.AUTO_TYPE = Enum(valid_values=valid_values)
super(EnumField, self).__init__(**kwargs) super().__init__(**kwargs)
class StateMachine(EnumField): class StateMachine(EnumField):
@ -1009,7 +1009,7 @@ class StateMachine(EnumField):
return 'unknown' return 'unknown'
def coerce(self, obj, attr, value): def coerce(self, obj, attr, value):
super(StateMachine, self).coerce(obj, attr, value) super().coerce(obj, attr, value)
my_name = self._my_name(obj) my_name = self._my_name(obj)
msg = _("%(object)s.%(name)s is not allowed to transition out of " msg = _("%(object)s.%(name)s is not allowed to transition out of "
"%(value)s state") "%(value)s state")
@ -1113,7 +1113,7 @@ class FlexibleBooleanField(AutoTypedField):
class DateTimeField(AutoTypedField): class DateTimeField(AutoTypedField):
def __init__(self, tzinfo_aware=True, **kwargs): def __init__(self, tzinfo_aware=True, **kwargs):
self.AUTO_TYPE = DateTime(tzinfo_aware=tzinfo_aware) self.AUTO_TYPE = DateTime(tzinfo_aware=tzinfo_aware)
super(DateTimeField, self).__init__(**kwargs) super().__init__(**kwargs)
class DictOfStringsField(AutoTypedField): class DictOfStringsField(AutoTypedField):
@ -1139,7 +1139,7 @@ class DictOfListOfStringsField(AutoTypedField):
class ListOfEnumField(AutoTypedField): class ListOfEnumField(AutoTypedField):
def __init__(self, valid_values, **kwargs): def __init__(self, valid_values, **kwargs):
self.AUTO_TYPE = List(Enum(valid_values)) self.AUTO_TYPE = List(Enum(valid_values))
super(ListOfEnumField, self).__init__(**kwargs) super().__init__(**kwargs)
def __repr__(self): def __repr__(self):
valid_values = self._type._element_type._type.valid_values valid_values = self._type._element_type._type.valid_values
@ -1148,8 +1148,8 @@ class ListOfEnumField(AutoTypedField):
'default': self._default, 'default': self._default,
} }
args.update({'valid_values': valid_values}) args.update({'valid_values': valid_values})
return '%s(%s)' % (self._type.__class__.__name__, return '{}({})'.format(self._type.__class__.__name__,
','.join(['%s=%s' % (k, v) ','.join(['{}={}'.format(k, v)
for k, v in sorted(args.items())])) for k, v in sorted(args.items())]))
@ -1173,14 +1173,14 @@ class ObjectField(AutoTypedField):
def __init__(self, objtype, subclasses=False, **kwargs): def __init__(self, objtype, subclasses=False, **kwargs):
self.AUTO_TYPE = Object(objtype, subclasses) self.AUTO_TYPE = Object(objtype, subclasses)
self.objname = objtype self.objname = objtype
super(ObjectField, self).__init__(**kwargs) super().__init__(**kwargs)
class ListOfObjectsField(AutoTypedField): class ListOfObjectsField(AutoTypedField):
def __init__(self, objtype, subclasses=False, **kwargs): def __init__(self, objtype, subclasses=False, **kwargs):
self.AUTO_TYPE = List(Object(objtype, subclasses)) self.AUTO_TYPE = List(Object(objtype, subclasses))
self.objname = objtype self.objname = objtype
super(ListOfObjectsField, self).__init__(**kwargs) super().__init__(**kwargs)
class ListOfUUIDField(AutoTypedField): class ListOfUUIDField(AutoTypedField):
@ -1215,12 +1215,12 @@ class IPV6NetworkField(AutoTypedField):
AUTO_TYPE = IPV6Network() AUTO_TYPE = IPV6Network()
class CoercedCollectionMixin(object): class CoercedCollectionMixin:
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
self._element_type = None self._element_type = None
self._obj = None self._obj = None
self._field = None self._field = None
super(CoercedCollectionMixin, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
def enable_coercing(self, element_type, obj, field): def enable_coercing(self, element_type, obj, field):
self._element_type = element_type self._element_type = element_type
@ -1247,30 +1247,30 @@ class CoercedList(CoercedCollectionMixin, list):
step = i.step or 1 step = i.step or 1
coerced_items = [self._coerce_item(start + index * step, item) coerced_items = [self._coerce_item(start + index * step, item)
for index, item in enumerate(y)] for index, item in enumerate(y)]
super(CoercedList, self).__setitem__(i, coerced_items) super().__setitem__(i, coerced_items)
else: else:
super(CoercedList, self).__setitem__(i, self._coerce_item(i, y)) super().__setitem__(i, self._coerce_item(i, y))
def append(self, x): def append(self, x):
super(CoercedList, self).append(self._coerce_item(len(self) + 1, x)) super().append(self._coerce_item(len(self) + 1, x))
def extend(self, t): def extend(self, t):
coerced_items = [self._coerce_item(len(self) + index, item) coerced_items = [self._coerce_item(len(self) + index, item)
for index, item in enumerate(t)] for index, item in enumerate(t)]
super(CoercedList, self).extend(coerced_items) super().extend(coerced_items)
def insert(self, i, x): def insert(self, i, x):
super(CoercedList, self).insert(i, self._coerce_item(i, x)) super().insert(i, self._coerce_item(i, x))
def __iadd__(self, y): def __iadd__(self, y):
coerced_items = [self._coerce_item(len(self) + index, item) coerced_items = [self._coerce_item(len(self) + index, item)
for index, item in enumerate(y)] for index, item in enumerate(y)]
return super(CoercedList, self).__iadd__(coerced_items) return super().__iadd__(coerced_items)
def __setslice__(self, i, j, y): def __setslice__(self, i, j, y):
coerced_items = [self._coerce_item(i + index, item) coerced_items = [self._coerce_item(i + index, item)
for index, item in enumerate(y)] for index, item in enumerate(y)]
return super(CoercedList, self).__setslice__(i, j, coerced_items) return super().__setslice__(i, j, coerced_items)
class CoercedDict(CoercedCollectionMixin, dict): class CoercedDict(CoercedCollectionMixin, dict):
@ -1290,24 +1290,24 @@ class CoercedDict(CoercedCollectionMixin, dict):
if not isinstance(key, str): if not isinstance(key, str):
raise KeyTypeError(str, key) raise KeyTypeError(str, key)
if hasattr(self, "_element_type") and self._element_type is not None: if hasattr(self, "_element_type") and self._element_type is not None:
att_name = "%s[%s]" % (self._field, key) att_name = "{}[{}]".format(self._field, key)
return self._element_type.coerce(self._obj, att_name, item) return self._element_type.coerce(self._obj, att_name, item)
else: else:
return item return item
def __setitem__(self, key, value): def __setitem__(self, key, value):
super(CoercedDict, self).__setitem__(key, super().__setitem__(key,
self._coerce_item(key, value)) self._coerce_item(key, value))
def update(self, other=None, **kwargs): def update(self, other=None, **kwargs):
if other is not None: if other is not None:
super(CoercedDict, self).update(self._coerce_dict(other), super().update(self._coerce_dict(other),
**self._coerce_dict(kwargs)) **self._coerce_dict(kwargs))
else: else:
super(CoercedDict, self).update(**self._coerce_dict(kwargs)) super().update(**self._coerce_dict(kwargs))
def setdefault(self, key, default=None): def setdefault(self, key, default=None):
return super(CoercedDict, self).setdefault(key, return super().setdefault(key,
self._coerce_item(key, self._coerce_item(key,
default)) default))
@ -1321,7 +1321,8 @@ class CoercedSet(CoercedCollectionMixin, set):
def _coerce_element(self, element): def _coerce_element(self, element):
if hasattr(self, "_element_type") and self._element_type is not None: if hasattr(self, "_element_type") and self._element_type is not None:
return self._element_type.coerce(self._obj, return self._element_type.coerce(self._obj,
"%s[%s]" % (self._field, element), "{}[{}]".format(
self._field, element),
element) element)
else: else:
return element return element
@ -1333,17 +1334,17 @@ class CoercedSet(CoercedCollectionMixin, set):
return coerced return coerced
def add(self, value): def add(self, value):
return super(CoercedSet, self).add(self._coerce_element(value)) return super().add(self._coerce_element(value))
def update(self, values): def update(self, values):
return super(CoercedSet, self).update(self._coerce_iterable(values)) return super().update(self._coerce_iterable(values))
def symmetric_difference_update(self, values): def symmetric_difference_update(self, values):
return super(CoercedSet, self).symmetric_difference_update( return super().symmetric_difference_update(
self._coerce_iterable(values)) self._coerce_iterable(values))
def __ior__(self, y): def __ior__(self, y):
return super(CoercedSet, self).__ior__(self._coerce_iterable(y)) return super().__ior__(self._coerce_iterable(y))
def __ixor__(self, y): def __ixor__(self, y):
return super(CoercedSet, self).__ixor__(self._coerce_iterable(y)) return super().__ixor__(self._coerce_iterable(y))

View File

@ -113,14 +113,14 @@ class OsloOrderedDict(OrderedDict):
# Python >= 3.12 uses a dict instead of a list which changes the # Python >= 3.12 uses a dict instead of a list which changes the
# repr of the versioned object and its associated hash value # repr of the versioned object and its associated hash value
# Switch back to using list an use super class name. # Switch back to using list an use super class name.
return '%s(%r)' % ( return '{}({!r})'.format(
self.__class__.__bases__[0].__name__, list(self.items()) self.__class__.__bases__[0].__name__, list(self.items())
) )
class FakeIndirectionAPI(base.VersionedObjectIndirectionAPI): class FakeIndirectionAPI(base.VersionedObjectIndirectionAPI):
def __init__(self, serializer=None): def __init__(self, serializer=None):
super(FakeIndirectionAPI, self).__init__() super().__init__()
self._ser = serializer or base.VersionedObjectSerializer() self._ser = serializer or base.VersionedObjectSerializer()
def _get_changes(self, orig_obj, new_obj): def _get_changes(self, orig_obj, new_obj):
@ -139,10 +139,10 @@ class FakeIndirectionAPI(base.VersionedObjectIndirectionAPI):
[self._ser.deserialize_entity( [self._ser.deserialize_entity(
context, self._ser.serialize_entity(context, arg)) context, self._ser.serialize_entity(context, arg))
for arg in args]) for arg in args])
kwargs = dict( kwargs = {
[(argname, self._ser.deserialize_entity( argname: self._ser.deserialize_entity(
context, self._ser.serialize_entity(context, arg))) context, self._ser.serialize_entity(context, arg))
for argname, arg in kwargs.items()]) for argname, arg in kwargs.items()}
return args, kwargs return args, kwargs
def object_action(self, context, objinst, objmethod, args, kwargs): def object_action(self, context, objinst, objmethod, args, kwargs):
@ -199,7 +199,7 @@ class IndirectionFixture(fixtures.Fixture):
self.indirection_api = indirection_api or FakeIndirectionAPI() self.indirection_api = indirection_api or FakeIndirectionAPI()
def setUp(self): def setUp(self):
super(IndirectionFixture, self).setUp() super().setUp()
self.useFixture(fixtures.MonkeyPatch( self.useFixture(fixtures.MonkeyPatch(
'oslo_versionedobjects.base.VersionedObject.indirection_api', 'oslo_versionedobjects.base.VersionedObject.indirection_api',
self.indirection_api)) self.indirection_api))
@ -240,7 +240,7 @@ def get_method_spec(method):
fullspec.varkw, fullspec.defaults) fullspec.varkw, fullspec.defaults)
class ObjectVersionChecker(object): class ObjectVersionChecker:
def __init__(self, obj_classes=base.VersionedObjectRegistry.obj_classes()): def __init__(self, obj_classes=base.VersionedObjectRegistry.obj_classes()):
self.obj_classes = obj_classes self.obj_classes = obj_classes
@ -288,7 +288,7 @@ class ObjectVersionChecker(object):
if extra_data_func: if extra_data_func:
relevant_data += extra_data_func(obj_class) relevant_data += extra_data_func(obj_class)
fingerprint = '%s-%s' % (obj_class.VERSION, hashlib.md5( fingerprint = '{}-{}'.format(obj_class.VERSION, hashlib.md5(
bytes(repr(relevant_data).encode()), bytes(repr(relevant_data).encode()),
usedforsecurity=False).hexdigest()) usedforsecurity=False).hexdigest())
return fingerprint return fingerprint
@ -344,8 +344,8 @@ class ObjectVersionChecker(object):
def test_relationships(self, expected_tree): def test_relationships(self, expected_tree):
actual_tree = self.get_dependency_tree() actual_tree = self.get_dependency_tree()
stored = set([(x, str(y)) for x, y in expected_tree.items()]) stored = {(x, str(y)) for x, y in expected_tree.items()}
computed = set([(x, str(y)) for x, y in actual_tree.items()]) computed = {(x, str(y)) for x, y in actual_tree.items()}
changed = stored.symmetric_difference(computed) changed = stored.symmetric_difference(computed)
expected = {} expected = {}
actual = {} actual = {}
@ -445,7 +445,7 @@ class VersionedObjectRegistryFixture(fixtures.Fixture):
""" """
def setUp(self): def setUp(self):
super(VersionedObjectRegistryFixture, self).setUp() super().setUp()
self._base_test_obj_backup = copy.deepcopy( self._base_test_obj_backup = copy.deepcopy(
base.VersionedObjectRegistry._registry._obj_classes) base.VersionedObjectRegistry._registry._obj_classes)
self.addCleanup(self._restore_obj_registry) self.addCleanup(self._restore_obj_registry)
@ -475,7 +475,7 @@ class StableObjectJsonFixture(fixtures.Fixture):
self._original_otp = base.VersionedObject.obj_to_primitive self._original_otp = base.VersionedObject.obj_to_primitive
def setUp(self): def setUp(self):
super(StableObjectJsonFixture, self).setUp() super().setUp()
def _doit(obj, *args, **kwargs): def _doit(obj, *args, **kwargs):
result = self._original_otp(obj, *args, **kwargs) result = self._original_otp(obj, *args, **kwargs)

View File

@ -45,7 +45,7 @@ class TestingException(Exception):
pass pass
class skipIf(object): class skipIf:
def __init__(self, condition, reason): def __init__(self, condition, reason):
self.condition = condition self.condition = condition
self.reason = reason self.reason = reason
@ -109,7 +109,7 @@ class TestCase(testtools.TestCase):
def setUp(self): def setUp(self):
"""Run before each test method to initialize test environment.""" """Run before each test method to initialize test environment."""
super(TestCase, self).setUp() super().setUp()
self.useFixture(obj_fixtures.Timeout( self.useFixture(obj_fixtures.Timeout(
os.environ.get('OS_TEST_TIMEOUT', 0), os.environ.get('OS_TEST_TIMEOUT', 0),
self.TIMEOUT_SCALING_FACTOR)) self.TIMEOUT_SCALING_FACTOR))
@ -186,7 +186,7 @@ class TestCase(testtools.TestCase):
(name, baseclass)) (name, baseclass))
class APICoverage(object): class APICoverage:
cover_api = None cover_api = None

View File

@ -35,7 +35,7 @@ class TranslationFixture(fixtures.Fixture):
"""Use gettext NullTranslation objects in tests.""" """Use gettext NullTranslation objects in tests."""
def setUp(self): def setUp(self):
super(TranslationFixture, self).setUp() super().setUp()
nulltrans = gettext.NullTranslations() nulltrans = gettext.NullTranslations()
gettext_fixture = fixtures.MonkeyPatch('gettext.translation', gettext_fixture = fixtures.MonkeyPatch('gettext.translation',
lambda *x, **y: nulltrans) lambda *x, **y: nulltrans)
@ -87,7 +87,7 @@ class StandardLogging(fixtures.Fixture):
""" """
def setUp(self): def setUp(self):
super(StandardLogging, self).setUp() super().setUp()
# set root logger to debug # set root logger to debug
root = logging.getLogger() root = logging.getLogger()
@ -124,7 +124,7 @@ class OutputStreamCapture(fixtures.Fixture):
tests. tests.
""" """
def setUp(self): def setUp(self):
super(OutputStreamCapture, self).setUp() super().setUp()
if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES: if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
self.out = self.useFixture(fixtures.StringStream('stdout')) self.out = self.useFixture(fixtures.StringStream('stdout'))
self.useFixture( self.useFixture(
@ -155,7 +155,7 @@ class Timeout(fixtures.Fixture):
""" """
def __init__(self, timeout, scaling=1): def __init__(self, timeout, scaling=1):
super(Timeout, self).__init__() super().__init__()
try: try:
self.test_timeout = int(timeout) self.test_timeout = int(timeout)
except ValueError: except ValueError:
@ -167,7 +167,7 @@ class Timeout(fixtures.Fixture):
raise ValueError('scaling value must be >= 1') raise ValueError('scaling value must be >= 1')
def setUp(self): def setUp(self):
super(Timeout, self).setUp() super().setUp()
if self.test_timeout > 0: if self.test_timeout > 0:
self.useFixture(fixtures.Timeout(self.test_timeout, gentle=True)) self.useFixture(fixtures.Timeout(self.test_timeout, gentle=True))
@ -176,7 +176,7 @@ class WarningsFixture(fixtures.Fixture):
"""Filters out warnings during test runs.""" """Filters out warnings during test runs."""
def setUp(self): def setUp(self):
super(WarningsFixture, self).setUp() super().setUp()
# NOTE(sdague): Make deprecation warnings only happen once. Otherwise # NOTE(sdague): Make deprecation warnings only happen once. Otherwise
# this gets kind of crazy given the way that upstream python libs use # this gets kind of crazy given the way that upstream python libs use
# this. # this.

View File

@ -19,7 +19,7 @@ from oslo_versionedobjects import test
notifier = mock.Mock() notifier = mock.Mock()
class TestWrapper(object): class TestWrapper:
@exception.wrap_exception(notifier=notifier) @exception.wrap_exception(notifier=notifier)
def raise_exc(self, context, exc, admin_password): def raise_exc(self, context, exc, admin_password):
raise exc raise exc

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2013 Red Hat, Inc. # Copyright 2013 Red Hat, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may # Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -50,7 +49,7 @@ class FakeEnum(fields.Enum):
ALL = (FROG, PLATYPUS, ALLIGATOR) ALL = (FROG, PLATYPUS, ALLIGATOR)
def __init__(self, **kwargs): def __init__(self, **kwargs):
super(FakeEnum, self).__init__(valid_values=FakeEnum.ALL, super().__init__(valid_values=FakeEnum.ALL,
**kwargs) **kwargs)
@ -59,10 +58,10 @@ class FakeEnumAlt(fields.Enum):
PLATYPUS = "platypus" PLATYPUS = "platypus"
AARDVARK = "aardvark" AARDVARK = "aardvark"
ALL = set([FROG, PLATYPUS, AARDVARK]) ALL = {FROG, PLATYPUS, AARDVARK}
def __init__(self, **kwargs): def __init__(self, **kwargs):
super(FakeEnumAlt, self).__init__(valid_values=FakeEnumAlt.ALL, super().__init__(valid_values=FakeEnumAlt.ALL,
**kwargs) **kwargs)
@ -93,7 +92,7 @@ class FakeStateMachineField(fields.StateMachine):
_TYPES = (ACTIVE, PENDING, ERROR) _TYPES = (ACTIVE, PENDING, ERROR)
def __init__(self, **kwargs): def __init__(self, **kwargs):
super(FakeStateMachineField, self).__init__(self._TYPES, **kwargs) super().__init__(self._TYPES, **kwargs)
class FakeEnumAltField(fields.BaseEnumField): class FakeEnumAltField(fields.BaseEnumField):
@ -107,7 +106,7 @@ class TestFieldType(test.TestCase):
class TestField(test.TestCase): class TestField(test.TestCase):
def setUp(self): def setUp(self):
super(TestField, self).setUp() super().setUp()
self.field = fields.Field(FakeFieldType()) self.field = fields.Field(FakeFieldType())
self.coerce_good_values = [('foo', '*foo*')] self.coerce_good_values = [('foo', '*foo*')]
self.coerce_bad_values = [] self.coerce_bad_values = []
@ -129,7 +128,7 @@ class TestField(test.TestCase):
in_val)) in_val))
def test_from_primitive(self): def test_from_primitive(self):
class ObjectLikeThing(object): class ObjectLikeThing:
_context = 'context' _context = 'context'
for prim_val, out_val in self.from_primitive_values: for prim_val, out_val in self.from_primitive_values:
@ -142,7 +141,7 @@ class TestField(test.TestCase):
class TestSchema(test.TestCase): class TestSchema(test.TestCase):
def setUp(self): def setUp(self):
super(TestSchema, self).setUp() super().setUp()
self.field = fields.Field(FakeFieldType(), nullable=True, self.field = fields.Field(FakeFieldType(), nullable=True,
default='', read_only=False) default='', read_only=False)
@ -154,7 +153,7 @@ class TestSchema(test.TestCase):
class TestString(TestField): class TestString(TestField):
def setUp(self): def setUp(self):
super(TestString, self).setUp() super().setUp()
self.field = fields.StringField() self.field = fields.StringField()
self.coerce_good_values = [ self.coerce_good_values = [
('foo', 'foo'), (1, '1'), (1.0, '1.0'), (True, 'True')] ('foo', 'foo'), (1, '1'), (1.0, '1.0'), (True, 'True')]
@ -175,7 +174,7 @@ class TestString(TestField):
class TestSensitiveString(TestString): class TestSensitiveString(TestString):
def setUp(self): def setUp(self):
super(TestSensitiveString, self).setUp() super().setUp()
self.field = fields.SensitiveStringField() self.field = fields.SensitiveStringField()
def test_stringify(self): def test_stringify(self):
@ -186,7 +185,7 @@ class TestSensitiveString(TestString):
class TestVersionPredicate(TestString): class TestVersionPredicate(TestString):
def setUp(self): def setUp(self):
super(TestVersionPredicate, self).setUp() super().setUp()
self.field = fields.VersionPredicateField() self.field = fields.VersionPredicateField()
self.coerce_good_values = [('>=1.0', '>=1.0'), self.coerce_good_values = [('>=1.0', '>=1.0'),
('==1.1', '==1.1'), ('==1.1', '==1.1'),
@ -198,7 +197,7 @@ class TestVersionPredicate(TestString):
class TestMACAddress(TestField): class TestMACAddress(TestField):
def setUp(self): def setUp(self):
super(TestMACAddress, self).setUp() super().setUp()
self.field = fields.MACAddressField() self.field = fields.MACAddressField()
self.coerce_good_values = [ self.coerce_good_values = [
('c6:df:11:a5:c8:5d', 'c6:df:11:a5:c8:5d'), ('c6:df:11:a5:c8:5d', 'c6:df:11:a5:c8:5d'),
@ -231,7 +230,7 @@ class TestMACAddress(TestField):
class TestPCIAddress(TestField): class TestPCIAddress(TestField):
def setUp(self): def setUp(self):
super(TestPCIAddress, self).setUp() super().setUp()
self.field = fields.PCIAddressField() self.field = fields.PCIAddressField()
self.coerce_good_values = [ self.coerce_good_values = [
('0000:02:00.0', '0000:02:00.0'), ('0000:02:00.0', '0000:02:00.0'),
@ -264,7 +263,7 @@ class TestPCIAddress(TestField):
class TestUUID(TestField): class TestUUID(TestField):
def setUp(self): def setUp(self):
super(TestUUID, self).setUp() super().setUp()
self.field = fields.UUIDField() self.field = fields.UUIDField()
self.coerce_good_values = [ self.coerce_good_values = [
('da66a411-af0e-4829-9b67-475017ddd152', ('da66a411-af0e-4829-9b67-475017ddd152',
@ -322,7 +321,7 @@ class TestUUID(TestField):
class TestBaseEnum(TestField): class TestBaseEnum(TestField):
def setUp(self): def setUp(self):
super(TestBaseEnum, self).setUp() super().setUp()
self.field = FakeEnumField() self.field = FakeEnumField()
self.coerce_good_values = [('frog', 'frog'), self.coerce_good_values = [('frog', 'frog'),
('platypus', 'platypus'), ('platypus', 'platypus'),
@ -355,7 +354,7 @@ class TestBaseEnum(TestField):
class TestEnum(TestField): class TestEnum(TestField):
def setUp(self): def setUp(self):
super(TestEnum, self).setUp() super().setUp()
self.field = fields.EnumField( self.field = fields.EnumField(
valid_values=['foo', 'bar', 1, True]) valid_values=['foo', 'bar', 1, True])
self.coerce_good_values = [('foo', 'foo'), (1, '1'), (True, 'True')] self.coerce_good_values = [('foo', 'foo'), (1, '1'), (True, 'True')]
@ -490,7 +489,7 @@ class TestInteger(TestField):
class TestNonNegativeInteger(TestField): class TestNonNegativeInteger(TestField):
def setUp(self): def setUp(self):
super(TestNonNegativeInteger, self).setUp() super().setUp()
self.field = fields.NonNegativeIntegerField() self.field = fields.NonNegativeIntegerField()
self.coerce_good_values = [(1, 1), ('1', 1)] self.coerce_good_values = [(1, 1), ('1', 1)]
self.coerce_bad_values = ['-2', '4.2', 'foo', None] self.coerce_bad_values = ['-2', '4.2', 'foo', None]
@ -504,7 +503,7 @@ class TestNonNegativeInteger(TestField):
class TestFloat(TestField): class TestFloat(TestField):
def setUp(self): def setUp(self):
super(TestFloat, self).setUp() super().setUp()
self.field = fields.FloatField() self.field = fields.FloatField()
self.coerce_good_values = [(1.1, 1.1), ('1.1', 1.1)] self.coerce_good_values = [(1.1, 1.1), ('1.1', 1.1)]
self.coerce_bad_values = ['foo', None] self.coerce_bad_values = ['foo', None]
@ -521,7 +520,7 @@ class TestFloat(TestField):
class TestNonNegativeFloat(TestField): class TestNonNegativeFloat(TestField):
def setUp(self): def setUp(self):
super(TestNonNegativeFloat, self).setUp() super().setUp()
self.field = fields.NonNegativeFloatField() self.field = fields.NonNegativeFloatField()
self.coerce_good_values = [(1.1, 1.1), ('1.1', 1.1)] self.coerce_good_values = [(1.1, 1.1), ('1.1', 1.1)]
self.coerce_bad_values = ['-4.2', 'foo', None] self.coerce_bad_values = ['-4.2', 'foo', None]
@ -553,7 +552,7 @@ class TestBoolean(TestField):
class TestFlexibleBoolean(TestField): class TestFlexibleBoolean(TestField):
def setUp(self): def setUp(self):
super(TestFlexibleBoolean, self).setUp() super().setUp()
self.field = fields.FlexibleBooleanField() self.field = fields.FlexibleBooleanField()
self.coerce_good_values = [(True, True), (False, False), self.coerce_good_values = [(True, True), (False, False),
("true", True), ("false", False), ("true", True), ("false", False),
@ -570,7 +569,7 @@ class TestFlexibleBoolean(TestField):
class TestDateTime(TestField): class TestDateTime(TestField):
def setUp(self): def setUp(self):
super(TestDateTime, self).setUp() super().setUp()
self.dt = datetime.datetime(1955, 11, 5, tzinfo=iso8601.iso8601.UTC) self.dt = datetime.datetime(1955, 11, 5, tzinfo=iso8601.iso8601.UTC)
self.field = fields.DateTimeField() self.field = fields.DateTimeField()
self.coerce_good_values = [(self.dt, self.dt), self.coerce_good_values = [(self.dt, self.dt),
@ -594,7 +593,7 @@ class TestDateTime(TestField):
class TestDateTimeNoTzinfo(TestField): class TestDateTimeNoTzinfo(TestField):
def setUp(self): def setUp(self):
super(TestDateTimeNoTzinfo, self).setUp() super().setUp()
self.dt = datetime.datetime(1955, 11, 5) self.dt = datetime.datetime(1955, 11, 5)
self.field = fields.DateTimeField(tzinfo_aware=False) self.field = fields.DateTimeField(tzinfo_aware=False)
self.coerce_good_values = [(self.dt, self.dt), self.coerce_good_values = [(self.dt, self.dt),
@ -617,7 +616,7 @@ class TestDateTimeNoTzinfo(TestField):
class TestDict(TestField): class TestDict(TestField):
def setUp(self): def setUp(self):
super(TestDict, self).setUp() super().setUp()
self.field = fields.Field(fields.Dict(FakeFieldType())) self.field = fields.Field(fields.Dict(FakeFieldType()))
self.coerce_good_values = [({'foo': 'bar'}, {'foo': '*bar*'}), self.coerce_good_values = [({'foo': 'bar'}, {'foo': '*bar*'}),
({'foo': 1}, {'foo': '*1*'})] ({'foo': 1}, {'foo': '*1*'})]
@ -638,7 +637,7 @@ class TestDict(TestField):
class TestDictOfStrings(TestField): class TestDictOfStrings(TestField):
def setUp(self): def setUp(self):
super(TestDictOfStrings, self).setUp() super().setUp()
self.field = fields.DictOfStringsField() self.field = fields.DictOfStringsField()
self.coerce_good_values = [({'foo': 'bar'}, {'foo': 'bar'}), self.coerce_good_values = [({'foo': 'bar'}, {'foo': 'bar'}),
({'foo': 1}, {'foo': '1'})] ({'foo': 1}, {'foo': '1'})]
@ -652,7 +651,7 @@ class TestDictOfStrings(TestField):
class TestDictOfIntegers(TestField): class TestDictOfIntegers(TestField):
def setUp(self): def setUp(self):
super(TestDictOfIntegers, self).setUp() super().setUp()
self.field = fields.DictOfIntegersField() self.field = fields.DictOfIntegersField()
self.coerce_good_values = [({'foo': '42'}, {'foo': 42}), self.coerce_good_values = [({'foo': '42'}, {'foo': 42}),
({'foo': 4.2}, {'foo': 4})] ({'foo': 4.2}, {'foo': 4})]
@ -667,7 +666,7 @@ class TestDictOfIntegers(TestField):
class TestDictOfStringsNone(TestField): class TestDictOfStringsNone(TestField):
def setUp(self): def setUp(self):
super(TestDictOfStringsNone, self).setUp() super().setUp()
self.field = fields.DictOfNullableStringsField() self.field = fields.DictOfNullableStringsField()
self.coerce_good_values = [({'foo': 'bar'}, {'foo': 'bar'}), self.coerce_good_values = [({'foo': 'bar'}, {'foo': 'bar'}),
({'foo': 1}, {'foo': '1'}), ({'foo': 1}, {'foo': '1'}),
@ -684,7 +683,7 @@ class TestDictOfStringsNone(TestField):
class TestListOfDictOfNullableStringsField(TestField): class TestListOfDictOfNullableStringsField(TestField):
def setUp(self): def setUp(self):
super(TestListOfDictOfNullableStringsField, self).setUp() super().setUp()
self.field = fields.ListOfDictOfNullableStringsField() self.field = fields.ListOfDictOfNullableStringsField()
self.coerce_good_values = [([{'f': 'b', 'f1': 'b1'}, {'f2': 'b2'}], self.coerce_good_values = [([{'f': 'b', 'f1': 'b1'}, {'f2': 'b2'}],
[{'f': 'b', 'f1': 'b1'}, {'f2': 'b2'}]), [{'f': 'b', 'f1': 'b1'}, {'f2': 'b2'}]),
@ -707,7 +706,7 @@ class TestListOfDictOfNullableStringsField(TestField):
class TestList(TestField): class TestList(TestField):
def setUp(self): def setUp(self):
super(TestList, self).setUp() super().setUp()
self.field = fields.Field(fields.List(FakeFieldType())) self.field = fields.Field(fields.List(FakeFieldType()))
self.coerce_good_values = [(['foo', 'bar'], ['*foo*', '*bar*'])] self.coerce_good_values = [(['foo', 'bar'], ['*foo*', '*bar*'])]
self.coerce_bad_values = ['foo'] self.coerce_bad_values = ['foo']
@ -731,7 +730,7 @@ class TestList(TestField):
class TestListOfStrings(TestField): class TestListOfStrings(TestField):
def setUp(self): def setUp(self):
super(TestListOfStrings, self).setUp() super().setUp()
self.field = fields.ListOfStringsField() self.field = fields.ListOfStringsField()
self.coerce_good_values = [(['foo', 'bar'], ['foo', 'bar'])] self.coerce_good_values = [(['foo', 'bar'], ['foo', 'bar'])]
self.coerce_bad_values = ['foo'] self.coerce_bad_values = ['foo']
@ -744,7 +743,7 @@ class TestListOfStrings(TestField):
class TestDictOfListOfStrings(TestField): class TestDictOfListOfStrings(TestField):
def setUp(self): def setUp(self):
super(TestDictOfListOfStrings, self).setUp() super().setUp()
self.field = fields.DictOfListOfStringsField() self.field = fields.DictOfListOfStringsField()
self.coerce_good_values = [({'foo': ['1', '2']}, {'foo': ['1', '2']}), self.coerce_good_values = [({'foo': ['1', '2']}, {'foo': ['1', '2']}),
({'foo': [1]}, {'foo': ['1']})] ({'foo': [1]}, {'foo': ['1']})]
@ -760,7 +759,7 @@ class TestDictOfListOfStrings(TestField):
class TestListOfEnum(TestField): class TestListOfEnum(TestField):
def setUp(self): def setUp(self):
super(TestListOfEnum, self).setUp() super().setUp()
self.field = fields.ListOfEnumField(valid_values=['foo', 'bar']) self.field = fields.ListOfEnumField(valid_values=['foo', 'bar'])
self.coerce_good_values = [(['foo', 'bar'], ['foo', 'bar'])] self.coerce_good_values = [(['foo', 'bar'], ['foo', 'bar'])]
self.coerce_bad_values = ['foo', ['foo', 'bar1']] self.coerce_bad_values = ['foo', ['foo', 'bar1']]
@ -783,16 +782,16 @@ class TestListOfEnum(TestField):
class TestSet(TestField): class TestSet(TestField):
def setUp(self): def setUp(self):
super(TestSet, self).setUp() super().setUp()
self.field = fields.Field(fields.Set(FakeFieldType())) self.field = fields.Field(fields.Set(FakeFieldType()))
self.coerce_good_values = [(set(['foo', 'bar']), self.coerce_good_values = [({'foo', 'bar'},
set(['*foo*', '*bar*']))] {'*foo*', '*bar*'})]
self.coerce_bad_values = [['foo'], {'foo': 'bar'}] self.coerce_bad_values = [['foo'], {'foo': 'bar'}]
self.to_primitive_values = [(set(['foo']), tuple(['!foo!']))] self.to_primitive_values = [({'foo'}, tuple(['!foo!']))]
self.from_primitive_values = [(tuple(['!foo!']), set(['foo']))] self.from_primitive_values = [(tuple(['!foo!']), {'foo'})]
def test_stringify(self): def test_stringify(self):
self.assertEqual('set([123])', self.field.stringify(set([123]))) self.assertEqual('set([123])', self.field.stringify({123}))
def test_get_schema(self): def test_get_schema(self):
self.assertEqual({'type': ['array'], 'uniqueItems': True, self.assertEqual({'type': ['array'], 'uniqueItems': True,
@ -803,16 +802,16 @@ class TestSet(TestField):
class TestSetOfIntegers(TestField): class TestSetOfIntegers(TestField):
def setUp(self): def setUp(self):
super(TestSetOfIntegers, self).setUp() super().setUp()
self.field = fields.SetOfIntegersField() self.field = fields.SetOfIntegersField()
self.coerce_good_values = [(set(['1', 2]), self.coerce_good_values = [({'1', 2},
set([1, 2]))] {1, 2})]
self.coerce_bad_values = [set(['foo'])] self.coerce_bad_values = [{'foo'}]
self.to_primitive_values = [(set([1]), tuple([1]))] self.to_primitive_values = [({1}, tuple([1]))]
self.from_primitive_values = [(tuple([1]), set([1]))] self.from_primitive_values = [(tuple([1]), {1})]
def test_stringify(self): def test_stringify(self):
self.assertEqual('set([1,2])', self.field.stringify(set([1, 2]))) self.assertEqual('set([1,2])', self.field.stringify({1, 2}))
def test_repr(self): def test_repr(self):
self.assertEqual("Set(default=<class 'oslo_versionedobjects.fields." self.assertEqual("Set(default=<class 'oslo_versionedobjects.fields."
@ -826,21 +825,21 @@ class TestSetOfIntegers(TestField):
class TestListOfSetsOfIntegers(TestField): class TestListOfSetsOfIntegers(TestField):
def setUp(self): def setUp(self):
super(TestListOfSetsOfIntegers, self).setUp() super().setUp()
self.field = fields.ListOfSetsOfIntegersField() self.field = fields.ListOfSetsOfIntegersField()
self.coerce_good_values = [([set(['1', 2]), set([3, '4'])], self.coerce_good_values = [([{'1', 2}, {3, '4'}],
[set([1, 2]), set([3, 4])])] [{1, 2}, {3, 4}])]
self.coerce_bad_values = [[set(['foo'])]] self.coerce_bad_values = [[{'foo'}]]
self.to_primitive_values = [([set([1])], [tuple([1])])] self.to_primitive_values = [([{1}], [tuple([1])])]
self.from_primitive_values = [([tuple([1])], [set([1])])] self.from_primitive_values = [([tuple([1])], [{1}])]
def test_stringify(self): def test_stringify(self):
self.assertEqual('[set([1,2])]', self.field.stringify([set([1, 2])])) self.assertEqual('[set([1,2])]', self.field.stringify([{1, 2}]))
class TestListOfIntegers(TestField): class TestListOfIntegers(TestField):
def setUp(self): def setUp(self):
super(TestListOfIntegers, self).setUp() super().setUp()
self.field = fields.ListOfIntegersField() self.field = fields.ListOfIntegersField()
self.coerce_good_values = [(['1', 2], [1, 2]), self.coerce_good_values = [(['1', 2], [1, 2]),
([1, 2], [1, 2])] ([1, 2], [1, 2])]
@ -854,7 +853,7 @@ class TestListOfIntegers(TestField):
class TestListOfUUIDField(TestField): class TestListOfUUIDField(TestField):
def setUp(self): def setUp(self):
super(TestListOfUUIDField, self).setUp() super().setUp()
self.field = fields.ListOfUUIDField() self.field = fields.ListOfUUIDField()
self.uuid1 = '6b2097ea-d0e3-44dd-b131-95472b3ea8fd' self.uuid1 = '6b2097ea-d0e3-44dd-b131-95472b3ea8fd'
self.uuid2 = '478c193d-2533-4e71-ab2b-c7683f67d7f9' self.uuid2 = '478c193d-2533-4e71-ab2b-c7683f67d7f9'
@ -866,7 +865,7 @@ class TestListOfUUIDField(TestField):
self.from_primitive_values = [([self.uuid1], [self.uuid1])] self.from_primitive_values = [([self.uuid1], [self.uuid1])]
def test_stringify(self): def test_stringify(self):
self.assertEqual('[%s,%s]' % (self.uuid1, self.uuid2), self.assertEqual('[{},{}]'.format(self.uuid1, self.uuid2),
self.field.stringify([self.uuid1, self.uuid2])) self.field.stringify([self.uuid1, self.uuid2]))
@ -902,7 +901,7 @@ class TestLocalMethods(test.TestCase):
class TestObject(TestField): class TestObject(TestField):
def setUp(self): def setUp(self):
super(TestObject, self).setUp() super().setUp()
@obj_base.VersionedObjectRegistry.register @obj_base.VersionedObjectRegistry.register
class TestableObject(obj_base.VersionedObject): class TestableObject(obj_base.VersionedObject):
@ -978,7 +977,7 @@ class TestObject(TestField):
pass pass
# Non-versioned object mixin # Non-versioned object mixin
class TestScary(object): class TestScary:
pass pass
class TestCrocodile(TestReptile, TestPet, TestScary): class TestCrocodile(TestReptile, TestPet, TestScary):
@ -1092,7 +1091,7 @@ class TestObject(TestField):
class TestIPAddress(TestField): class TestIPAddress(TestField):
def setUp(self): def setUp(self):
super(TestIPAddress, self).setUp() super().setUp()
self.field = fields.IPAddressField() self.field = fields.IPAddressField()
self.coerce_good_values = [('1.2.3.4', netaddr.IPAddress('1.2.3.4')), self.coerce_good_values = [('1.2.3.4', netaddr.IPAddress('1.2.3.4')),
('::1', netaddr.IPAddress('::1')), ('::1', netaddr.IPAddress('::1')),
@ -1109,7 +1108,7 @@ class TestIPAddress(TestField):
class TestIPAddressV4(TestField): class TestIPAddressV4(TestField):
def setUp(self): def setUp(self):
super(TestIPAddressV4, self).setUp() super().setUp()
self.field = fields.IPV4AddressField() self.field = fields.IPV4AddressField()
self.coerce_good_values = [('1.2.3.4', netaddr.IPAddress('1.2.3.4')), self.coerce_good_values = [('1.2.3.4', netaddr.IPAddress('1.2.3.4')),
(netaddr.IPAddress('1.2.3.4'), (netaddr.IPAddress('1.2.3.4'),
@ -1127,7 +1126,7 @@ class TestIPAddressV4(TestField):
class TestIPAddressV6(TestField): class TestIPAddressV6(TestField):
def setUp(self): def setUp(self):
super(TestIPAddressV6, self).setUp() super().setUp()
self.field = fields.IPV6AddressField() self.field = fields.IPV6AddressField()
self.coerce_good_values = [('::1', netaddr.IPAddress('::1')), self.coerce_good_values = [('::1', netaddr.IPAddress('::1')),
(netaddr.IPAddress('::1'), (netaddr.IPAddress('::1'),
@ -1144,7 +1143,7 @@ class TestIPAddressV6(TestField):
class TestIPV4AndV6Address(TestField): class TestIPV4AndV6Address(TestField):
def setUp(self): def setUp(self):
super(TestIPV4AndV6Address, self).setUp() super().setUp()
self.field = fields.IPV4AndV6Address() self.field = fields.IPV4AndV6Address()
self.coerce_good_values = [('::1', netaddr.IPAddress('::1')), self.coerce_good_values = [('::1', netaddr.IPAddress('::1')),
(netaddr.IPAddress('::1'), (netaddr.IPAddress('::1'),
@ -1171,7 +1170,7 @@ class TestIPV4AndV6Address(TestField):
class TestIPNetwork(TestField): class TestIPNetwork(TestField):
def setUp(self): def setUp(self):
super(TestIPNetwork, self).setUp() super().setUp()
self.field = fields.IPNetworkField() self.field = fields.IPNetworkField()
self.coerce_good_values = [('::1/0', netaddr.IPNetwork('::1/0')), self.coerce_good_values = [('::1/0', netaddr.IPNetwork('::1/0')),
('1.2.3.4/24', ('1.2.3.4/24',
@ -1186,7 +1185,7 @@ class TestIPNetwork(TestField):
class TestIPV4Network(TestField): class TestIPV4Network(TestField):
def setUp(self): def setUp(self):
super(TestIPV4Network, self).setUp() super().setUp()
self.field = fields.IPV4NetworkField() self.field = fields.IPV4NetworkField()
self.coerce_good_values = [('1.2.3.4/24', self.coerce_good_values = [('1.2.3.4/24',
netaddr.IPNetwork('1.2.3.4/24'))] netaddr.IPNetwork('1.2.3.4/24'))]
@ -1210,7 +1209,7 @@ class TestIPV4Network(TestField):
class TestIPV6Network(TestField): class TestIPV6Network(TestField):
def setUp(self): def setUp(self):
super(TestIPV6Network, self).setUp() super().setUp()
self.field = fields.IPV6NetworkField() self.field = fields.IPV6NetworkField()
self.coerce_good_values = [('::1/0', netaddr.IPNetwork('::1/0')), self.coerce_good_values = [('::1/0', netaddr.IPNetwork('::1/0')),
(netaddr.IPNetwork('::1/32'), (netaddr.IPNetwork('::1/32'),
@ -1232,7 +1231,7 @@ class TestIPV6Network(TestField):
self.assertNotRegex(str(invalid_val), pattern) self.assertNotRegex(str(invalid_val), pattern)
class FakeCounter(object): class FakeCounter:
def __init__(self): def __init__(self):
self.n = 0 self.n = 0

View File

@ -211,7 +211,7 @@ class FakeResource(base.VersionedObject):
class TestObjectVersionChecker(test.TestCase): class TestObjectVersionChecker(test.TestCase):
def setUp(self): def setUp(self):
super(TestObjectVersionChecker, self).setUp() super().setUp()
objects = [MyObject, MyObject2, ] objects = [MyObject, MyObject2, ]
self.obj_classes = {obj.__name__: [obj] for obj in objects} self.obj_classes = {obj.__name__: [obj] for obj in objects}
self.ovc = fixture.ObjectVersionChecker(obj_classes=self.obj_classes) self.ovc = fixture.ObjectVersionChecker(obj_classes=self.obj_classes)
@ -544,7 +544,7 @@ class TestObjectVersionChecker(test.TestCase):
# bandit rule while py38 is in our supported runtimes. # bandit rule while py38 is in our supported runtimes.
expected_hash = hashlib.md5(bytes(repr( expected_hash = hashlib.md5(bytes(repr(
expected_relevant_data).encode())).hexdigest() # nosec expected_relevant_data).encode())).hexdigest() # nosec
expected_fp = '%s-%s' % (MyObject.VERSION, expected_hash) expected_fp = '{}-{}'.format(MyObject.VERSION, expected_hash)
self.assertEqual(expected_fp, fp, "_get_fingerprint() did not " self.assertEqual(expected_fp, fp, "_get_fingerprint() did not "
"generate a correct fingerprint.") "generate a correct fingerprint.")
@ -576,7 +576,7 @@ class TestObjectVersionChecker(test.TestCase):
# bandit rule while py38 is in our supported runtimes. # bandit rule while py38 is in our supported runtimes.
expected_hash = hashlib.md5(bytes(repr( expected_hash = hashlib.md5(bytes(repr(
exp_relevant_data).encode())).hexdigest() # nosec exp_relevant_data).encode())).hexdigest() # nosec
expected_fp = '%s-%s' % (MyObject.VERSION, expected_hash) expected_fp = '{}-{}'.format(MyObject.VERSION, expected_hash)
self.assertEqual(expected_fp, fp, "_get_fingerprint() did not " self.assertEqual(expected_fp, fp, "_get_fingerprint() did not "
"generate a correct fingerprint.") "generate a correct fingerprint.")
@ -611,7 +611,7 @@ class TestObjectVersionChecker(test.TestCase):
# bandit rule while py38 is in our supported runtimes. # bandit rule while py38 is in our supported runtimes.
expected_hash = hashlib.md5(bytes(repr( expected_hash = hashlib.md5(bytes(repr(
exp_relevant_data).encode())).hexdigest() # nosec exp_relevant_data).encode())).hexdigest() # nosec
expected_fp = '%s-%s' % (ExtraDataObj.VERSION, expected_hash) expected_fp = '{}-{}'.format(ExtraDataObj.VERSION, expected_hash)
self.assertEqual(expected_fp, fp, "_get_fingerprint() did not " self.assertEqual(expected_fp, fp, "_get_fingerprint() did not "
"generate a correct fingerprint.") "generate a correct fingerprint.")
@ -756,7 +756,7 @@ class TestStableObjectJsonFixture(test.TestCase):
class TestMethodSpec(test.TestCase): class TestMethodSpec(test.TestCase):
def setUp(self): def setUp(self):
super(TestMethodSpec, self).setUp() super().setUp()
def test_method1(a, b, kw1=123, **kwargs): def test_method1(a, b, kw1=123, **kwargs):
pass pass

View File

@ -112,7 +112,7 @@ class MyObj(base.VersionedObject, base.VersionedObjectDictCompat):
self.rel_object = MyOwnedObject(baz=42) self.rel_object = MyOwnedObject(baz=42)
def obj_make_compatible(self, primitive, target_version): def obj_make_compatible(self, primitive, target_version):
super(MyObj, self).obj_make_compatible(primitive, target_version) super().obj_make_compatible(primitive, target_version)
# NOTE(danms): Simulate an older version that had a different # NOTE(danms): Simulate an older version that had a different
# format for the 'bar' attribute # format for the 'bar' attribute
if target_version == '1.1' and 'bar' in primitive: if target_version == '1.1' and 'bar' in primitive:
@ -156,7 +156,7 @@ class MySensitiveObj(base.VersionedObject):
pass pass
class RandomMixInWithNoFields(object): class RandomMixInWithNoFields:
"""Used to test object inheritance using a mixin that has no fields.""" """Used to test object inheritance using a mixin that has no fields."""
pass pass
@ -189,7 +189,7 @@ class TestRegistry(test.TestCase):
def test_obj_tracking(self): def test_obj_tracking(self):
@base.VersionedObjectRegistry.register @base.VersionedObjectRegistry.register
class NewBaseClass(object): class NewBaseClass:
VERSION = '1.0' VERSION = '1.0'
fields = {} fields = {}
@ -330,7 +330,7 @@ class TestRegistry(test.TestCase):
mock_registry.return_value = mock_reg_obj mock_registry.return_value = mock_reg_obj
mock_reg_obj._register_class = mock.Mock() mock_reg_obj._register_class = mock.Mock()
class my_class(object): class my_class:
pass pass
base.VersionedObjectRegistry.register(my_class) base.VersionedObjectRegistry.register(my_class)
@ -338,7 +338,7 @@ class TestRegistry(test.TestCase):
@mock.patch.object(base.VersionedObjectRegistry, 'register') @mock.patch.object(base.VersionedObjectRegistry, 'register')
def test_register_if(self, mock_register): def test_register_if(self, mock_register):
class my_class(object): class my_class:
pass pass
base.VersionedObjectRegistry.register_if(True)(my_class) base.VersionedObjectRegistry.register_if(True)(my_class)
@ -346,7 +346,7 @@ class TestRegistry(test.TestCase):
@mock.patch.object(base, '_make_class_properties') @mock.patch.object(base, '_make_class_properties')
def test_register_if_false(self, mock_make_props): def test_register_if_false(self, mock_make_props):
class my_class(object): class my_class:
pass pass
base.VersionedObjectRegistry.register_if(False)(my_class) base.VersionedObjectRegistry.register_if(False)(my_class)
@ -357,7 +357,7 @@ class TestRegistry(test.TestCase):
mock_reg_callable = mock.Mock() mock_reg_callable = mock.Mock()
mock_register_if.return_value = mock_reg_callable mock_register_if.return_value = mock_reg_callable
class my_class(object): class my_class:
pass pass
base.VersionedObjectRegistry.objectify(my_class) base.VersionedObjectRegistry.objectify(my_class)
@ -389,7 +389,7 @@ class TestObjMakeList(test.TestCase):
class TestGetSubobjectVersion(test.TestCase): class TestGetSubobjectVersion(test.TestCase):
def setUp(self): def setUp(self):
super(TestGetSubobjectVersion, self).setUp() super().setUp()
self.backport_mock = mock.MagicMock() self.backport_mock = mock.MagicMock()
self.rels = [('1.1', '1.0'), ('1.3', '1.1')] self.rels = [('1.1', '1.0'), ('1.3', '1.1')]
@ -521,7 +521,7 @@ class TestDoSubobjectBackport(test.TestCase):
class _BaseTestCase(test.TestCase): class _BaseTestCase(test.TestCase):
def setUp(self): def setUp(self):
super(_BaseTestCase, self).setUp() super().setUp()
self.user_id = 'fake-user' self.user_id = 'fake-user'
self.project_id = 'fake-project' self.project_id = 'fake-project'
self.context = context.RequestContext(self.user_id, self.project_id) self.context = context.RequestContext(self.user_id, self.project_id)
@ -542,7 +542,7 @@ class _BaseTestCase(test.TestCase):
def assertNotIsInstance(self, obj, cls, msg=None): def assertNotIsInstance(self, obj, cls, msg=None):
"""Python < v2.7 compatibility. Assert 'not isinstance(obj, cls).""" """Python < v2.7 compatibility. Assert 'not isinstance(obj, cls)."""
try: try:
f = super(_BaseTestCase, self).assertNotIsInstance f = super().assertNotIsInstance
except AttributeError: except AttributeError:
self.assertThat(obj, self.assertThat(obj,
matchers.Not(matchers.IsInstance(cls)), matchers.Not(matchers.IsInstance(cls)),
@ -732,17 +732,17 @@ class TestFixture(_BaseTestCase):
class _LocalTest(_BaseTestCase): class _LocalTest(_BaseTestCase):
def setUp(self): def setUp(self):
super(_LocalTest, self).setUp() super().setUp()
self.assertIsNone(base.VersionedObject.indirection_api) self.assertIsNone(base.VersionedObject.indirection_api)
class _RemoteTest(_BaseTestCase): class _RemoteTest(_BaseTestCase):
def setUp(self): def setUp(self):
super(_RemoteTest, self).setUp() super().setUp()
self.useFixture(fixture.IndirectionFixture()) self.useFixture(fixture.IndirectionFixture())
class _TestObject(object): class _TestObject:
# def test_object_attrs_in_init(self): # def test_object_attrs_in_init(self):
# # Spot check a few # # Spot check a few
# objects.Instance # objects.Instance
@ -899,11 +899,11 @@ class _TestObject(object):
def test_changes_in_primitive(self): def test_changes_in_primitive(self):
obj = MyObj(foo=123) obj = MyObj(foo=123)
self.assertEqual(obj.obj_what_changed(), set(['foo'])) self.assertEqual(obj.obj_what_changed(), {'foo'})
primitive = obj.obj_to_primitive() primitive = obj.obj_to_primitive()
self.assertIn('versioned_object.changes', primitive) self.assertIn('versioned_object.changes', primitive)
obj2 = MyObj.obj_from_primitive(primitive) obj2 = MyObj.obj_from_primitive(primitive)
self.assertEqual(obj2.obj_what_changed(), set(['foo'])) self.assertEqual(obj2.obj_what_changed(), {'foo'})
obj2.obj_reset_changes() obj2.obj_reset_changes()
self.assertEqual(obj2.obj_what_changed(), set()) self.assertEqual(obj2.obj_what_changed(), set())
@ -938,34 +938,34 @@ class _TestObject(object):
def test_changed_1(self): def test_changed_1(self):
obj = MyObj.query(self.context) obj = MyObj.query(self.context)
obj.foo = 123 obj.foo = 123
self.assertEqual(obj.obj_what_changed(), set(['foo'])) self.assertEqual(obj.obj_what_changed(), {'foo'})
obj._update_test() obj._update_test()
self.assertEqual(obj.obj_what_changed(), set(['foo', 'bar'])) self.assertEqual(obj.obj_what_changed(), {'foo', 'bar'})
self.assertEqual(obj.foo, 123) self.assertEqual(obj.foo, 123)
def test_changed_2(self): def test_changed_2(self):
obj = MyObj.query(self.context) obj = MyObj.query(self.context)
obj.foo = 123 obj.foo = 123
self.assertEqual(obj.obj_what_changed(), set(['foo'])) self.assertEqual(obj.obj_what_changed(), {'foo'})
obj.save() obj.save()
self.assertEqual(obj.obj_what_changed(), set([])) self.assertEqual(obj.obj_what_changed(), set())
self.assertEqual(obj.foo, 123) self.assertEqual(obj.foo, 123)
def test_changed_3(self): def test_changed_3(self):
obj = MyObj.query(self.context) obj = MyObj.query(self.context)
obj.foo = 123 obj.foo = 123
self.assertEqual(obj.obj_what_changed(), set(['foo'])) self.assertEqual(obj.obj_what_changed(), {'foo'})
obj.refresh() obj.refresh()
self.assertEqual(obj.obj_what_changed(), set([])) self.assertEqual(obj.obj_what_changed(), set())
self.assertEqual(obj.foo, 321) self.assertEqual(obj.foo, 321)
self.assertEqual(obj.bar, 'refreshed') self.assertEqual(obj.bar, 'refreshed')
def test_changed_4(self): def test_changed_4(self):
obj = MyObj.query(self.context) obj = MyObj.query(self.context)
obj.bar = 'something' obj.bar = 'something'
self.assertEqual(obj.obj_what_changed(), set(['bar'])) self.assertEqual(obj.obj_what_changed(), {'bar'})
obj.modify_save_modify() obj.modify_save_modify()
self.assertEqual(obj.obj_what_changed(), set(['foo', 'rel_object'])) self.assertEqual(obj.obj_what_changed(), {'foo', 'rel_object'})
self.assertEqual(obj.foo, 42) self.assertEqual(obj.foo, 42)
self.assertEqual(obj.bar, 'meow') self.assertEqual(obj.bar, 'meow')
self.assertIsInstance(obj.rel_object, MyOwnedObject) self.assertIsInstance(obj.rel_object, MyOwnedObject)
@ -979,14 +979,14 @@ class _TestObject(object):
obj = ParentObject() obj = ParentObject()
self.assertEqual(set(), obj.obj_what_changed()) self.assertEqual(set(), obj.obj_what_changed())
obj.foo = 1 obj.foo = 1
self.assertEqual(set(['foo']), obj.obj_what_changed()) self.assertEqual({'foo'}, obj.obj_what_changed())
bar = MyObj() bar = MyObj()
obj.bar = bar obj.bar = bar
self.assertEqual(set(['foo', 'bar']), obj.obj_what_changed()) self.assertEqual({'foo', 'bar'}, obj.obj_what_changed())
obj.obj_reset_changes() obj.obj_reset_changes()
self.assertEqual(set(), obj.obj_what_changed()) self.assertEqual(set(), obj.obj_what_changed())
bar.foo = 1 bar.foo = 1
self.assertEqual(set(['bar']), obj.obj_what_changed()) self.assertEqual({'bar'}, obj.obj_what_changed())
def test_changed_with_bogus_field(self): def test_changed_with_bogus_field(self):
obj = MyObj() obj = MyObj()
@ -994,7 +994,7 @@ class _TestObject(object):
# Add a bogus field name to the changed list, as could be the # Add a bogus field name to the changed list, as could be the
# case if we're sent some broken primitive from another node. # case if we're sent some broken primitive from another node.
obj._changed_fields.add('does_not_exist') obj._changed_fields.add('does_not_exist')
self.assertEqual(set(['foo']), obj.obj_what_changed()) self.assertEqual({'foo'}, obj.obj_what_changed())
self.assertEqual({'foo': 123}, obj.obj_get_changes()) self.assertEqual({'foo': 123}, obj.obj_get_changes())
def test_static_result(self): def test_static_result(self):
@ -1025,19 +1025,19 @@ class _TestObject(object):
def test_obj_reset_changes_recursive(self): def test_obj_reset_changes_recursive(self):
obj = MyObj(rel_object=MyOwnedObject(baz=123), obj = MyObj(rel_object=MyOwnedObject(baz=123),
rel_objects=[MyOwnedObject(baz=456)]) rel_objects=[MyOwnedObject(baz=456)])
self.assertEqual(set(['rel_object', 'rel_objects']), self.assertEqual({'rel_object', 'rel_objects'},
obj.obj_what_changed()) obj.obj_what_changed())
obj.obj_reset_changes() obj.obj_reset_changes()
self.assertEqual(set(['rel_object']), obj.obj_what_changed()) self.assertEqual({'rel_object'}, obj.obj_what_changed())
self.assertEqual(set(['baz']), obj.rel_object.obj_what_changed()) self.assertEqual({'baz'}, obj.rel_object.obj_what_changed())
self.assertEqual(set(['baz']), obj.rel_objects[0].obj_what_changed()) self.assertEqual({'baz'}, obj.rel_objects[0].obj_what_changed())
obj.obj_reset_changes(recursive=True, fields=['foo']) obj.obj_reset_changes(recursive=True, fields=['foo'])
self.assertEqual(set(['rel_object']), obj.obj_what_changed()) self.assertEqual({'rel_object'}, obj.obj_what_changed())
self.assertEqual(set(['baz']), obj.rel_object.obj_what_changed()) self.assertEqual({'baz'}, obj.rel_object.obj_what_changed())
self.assertEqual(set(['baz']), obj.rel_objects[0].obj_what_changed()) self.assertEqual({'baz'}, obj.rel_objects[0].obj_what_changed())
obj.obj_reset_changes(recursive=True) obj.obj_reset_changes(recursive=True)
self.assertEqual(set([]), obj.rel_object.obj_what_changed()) self.assertEqual(set(), obj.rel_object.obj_what_changed())
self.assertEqual(set([]), obj.obj_what_changed()) self.assertEqual(set(), obj.obj_what_changed())
def test_get(self): def test_get(self):
obj = MyObj(foo=1) obj = MyObj(foo=1)
@ -1146,7 +1146,7 @@ class _TestObject(object):
obj = MyObj(context=self.context, foo=123, bar='abc') obj = MyObj(context=self.context, foo=123, bar='abc')
self.assertEqual(123, obj.foo) self.assertEqual(123, obj.foo)
self.assertEqual('abc', obj.bar) self.assertEqual('abc', obj.bar)
self.assertEqual(set(['foo', 'bar']), obj.obj_what_changed()) self.assertEqual({'foo', 'bar'}, obj.obj_what_changed())
def test_obj_read_only(self): def test_obj_read_only(self):
obj = MyObj(context=self.context, foo=123, bar='abc') obj = MyObj(context=self.context, foo=123, bar='abc')
@ -1388,7 +1388,7 @@ class _TestObject(object):
version_manifest=None) version_manifest=None)
def test_comparable_objects(self): def test_comparable_objects(self):
class NonVersionedObject(object): class NonVersionedObject:
pass pass
obj1 = MyComparableObj(foo=1) obj1 = MyComparableObj(foo=1)
@ -1404,7 +1404,7 @@ class _TestObject(object):
obj = MyCompoundObject() obj = MyCompoundObject()
obj.foo = [1, 2, 3] obj.foo = [1, 2, 3]
obj.bar = {"a": 1, "b": 2, "c": 3} obj.bar = {"a": 1, "b": 2, "c": 3}
obj.baz = set([1, 2, 3]) obj.baz = {1, 2, 3}
copy = obj.obj_clone() copy = obj.obj_clone()
self.assertEqual(obj.foo, copy.foo) self.assertEqual(obj.foo, copy.foo)
self.assertEqual(obj.bar, copy.bar) self.assertEqual(obj.bar, copy.bar)
@ -1415,7 +1415,7 @@ class _TestObject(object):
copy.baz.add("4") copy.baz.add("4")
self.assertEqual([1, 2, 3, 4], copy.foo) self.assertEqual([1, 2, 3, 4], copy.foo)
self.assertEqual({"a": 1, "b": 2, "c": 3, "d": 4}, copy.bar) self.assertEqual({"a": 1, "b": 2, "c": 3, "d": 4}, copy.bar)
self.assertEqual(set([1, 2, 3, 4]), copy.baz) self.assertEqual({1, 2, 3, 4}, copy.baz)
def test_obj_list_fields_modifications(self): def test_obj_list_fields_modifications(self):
@base.VersionedObjectRegistry.register @base.VersionedObjectRegistry.register
@ -1543,31 +1543,31 @@ class _TestObject(object):
'set_field': fields.Field(fields.Set(fields.Integer())) 'set_field': fields.Field(fields.Set(fields.Integer()))
} }
obj = ObjWithSet() obj = ObjWithSet()
obj.set_field = set([42]) obj.set_field = {42}
def add(value): def add(value):
obj.set_field.add(value) obj.set_field.add(value)
def update_w_set(value): def update_w_set(value):
obj.set_field.update(set([value])) obj.set_field.update({value})
def update_w_list(value): def update_w_list(value):
obj.set_field.update([value, value, value]) obj.set_field.update([value, value, value])
def sym_diff_upd(value): def sym_diff_upd(value):
obj.set_field.symmetric_difference_update(set([value])) obj.set_field.symmetric_difference_update({value})
def union(value): def union(value):
obj.set_field = obj.set_field | set([value]) obj.set_field = obj.set_field | {value}
def iunion(value): def iunion(value):
obj.set_field |= set([value]) obj.set_field |= {value}
def xor(value): def xor(value):
obj.set_field = obj.set_field ^ set([value]) obj.set_field = obj.set_field ^ {value}
def ixor(value): def ixor(value):
obj.set_field ^= set([value]) obj.set_field ^= {value}
# positive tests to ensure that coercing works properly # positive tests to ensure that coercing works properly
sym_diff_upd("42") sym_diff_upd("42")
add("1") add("1")
@ -1577,8 +1577,8 @@ class _TestObject(object):
iunion("5") iunion("5")
xor("6") xor("6")
ixor("7") ixor("7")
self.assertEqual(set([1, 2, 3, 4, 5, 6, 7]), obj.set_field) self.assertEqual({1, 2, 3, 4, 5, 6, 7}, obj.set_field)
obj.set_field = set([42]) obj.set_field = {42}
obj.obj_reset_changes() obj.obj_reset_changes()
# negative tests with non-coerceable values # negative tests with non-coerceable values
self.assertRaises(ValueError, add, "abc") self.assertRaises(ValueError, add, "abc")
@ -1590,7 +1590,7 @@ class _TestObject(object):
self.assertRaises(ValueError, xor, "abc") self.assertRaises(ValueError, xor, "abc")
self.assertRaises(ValueError, ixor, "abc") self.assertRaises(ValueError, ixor, "abc")
# ensure that nothing has been changed # ensure that nothing has been changed
self.assertEqual(set([42]), obj.set_field) self.assertEqual({42}, obj.set_field)
self.assertEqual({}, obj.obj_get_changes()) self.assertEqual({}, obj.obj_get_changes())
@ -1609,7 +1609,7 @@ class TestObject(_LocalTest, _TestObject):
def test_set_all_defaults(self): def test_set_all_defaults(self):
obj = MyObj() obj = MyObj()
obj.obj_set_defaults() obj.obj_set_defaults()
self.assertEqual(set(['mutable_default', 'foo']), self.assertEqual({'mutable_default', 'foo'},
obj.obj_what_changed()) obj.obj_what_changed())
self.assertEqual(1, obj.foo) self.assertEqual(1, obj.foo)
@ -1668,7 +1668,7 @@ class TestObjectListBase(test.TestCase):
fields = {'foo': fields.IntegerField()} fields = {'foo': fields.IntegerField()}
def __init__(self, foo): def __init__(self, foo):
super(MyElement, self).__init__() super().__init__()
self.foo = foo self.foo = foo
class Foo(base.ObjectListBase, base.VersionedObject): class Foo(base.ObjectListBase, base.VersionedObject):
@ -1802,12 +1802,12 @@ class TestObjectListBase(test.TestCase):
fields = {'foo': fields.StringField()} fields = {'foo': fields.StringField()}
obj = Foo(objects=[]) obj = Foo(objects=[])
self.assertEqual(set(['objects']), obj.obj_what_changed()) self.assertEqual({'objects'}, obj.obj_what_changed())
obj.objects.append(Bar(foo='test')) obj.objects.append(Bar(foo='test'))
self.assertEqual(set(['objects']), obj.obj_what_changed()) self.assertEqual({'objects'}, obj.obj_what_changed())
obj.obj_reset_changes() obj.obj_reset_changes()
# This should still look dirty because the child is dirty # This should still look dirty because the child is dirty
self.assertEqual(set(['objects']), obj.obj_what_changed()) self.assertEqual({'objects'}, obj.obj_what_changed())
obj.objects[0].obj_reset_changes() obj.objects[0].obj_reset_changes()
# This should now look clean because the child is clean # This should now look clean because the child is clean
self.assertEqual(set(), obj.obj_what_changed()) self.assertEqual(set(), obj.obj_what_changed())
@ -1849,7 +1849,7 @@ class TestObjectSerializer(_BaseTestCase):
def test_serialize_set_to_list(self): def test_serialize_set_to_list(self):
ser = base.VersionedObjectSerializer() ser = base.VersionedObjectSerializer()
self.assertEqual([1, 2], ser.serialize_entity(None, set([1, 2]))) self.assertEqual([1, 2], ser.serialize_entity(None, {1, 2}))
@mock.patch('oslo_versionedobjects.base.VersionedObject.indirection_api') @mock.patch('oslo_versionedobjects.base.VersionedObject.indirection_api')
def _test_deserialize_entity_newer(self, obj_version, backported_to, def _test_deserialize_entity_newer(self, obj_version, backported_to,
@ -2215,7 +2215,7 @@ class TestSchemaGeneration(test.TestCase):
class TestNamespaceCompatibility(test.TestCase): class TestNamespaceCompatibility(test.TestCase):
def setUp(self): def setUp(self):
super(TestNamespaceCompatibility, self).setUp() super().setUp()
@base.VersionedObjectRegistry.register_if(False) @base.VersionedObjectRegistry.register_if(False)
class TestObject(base.VersionedObject): class TestObject(base.VersionedObject):
@ -2454,7 +2454,7 @@ class TestTimestampedObject(test.TestCase):
""" """
def setUp(self): def setUp(self):
super(TestTimestampedObject, self).setUp() super().setUp()
@base.VersionedObjectRegistry.register_if(False) @base.VersionedObjectRegistry.register_if(False)
class MyTimestampedObject(base.VersionedObject, class MyTimestampedObject(base.VersionedObject,

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
# You may obtain a copy of the License at # You may obtain a copy of the License at