diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 521e1f42..45ab5821 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -28,3 +28,8 @@ repos: hooks: - id: bandit args: ['-x', 'tests', '--skip', 'B303'] + - repo: https://github.com/asottile/pyupgrade + rev: v3.18.0 + hooks: + - id: pyupgrade + args: [--py3-only] diff --git a/doc/source/conf.py b/doc/source/conf.py index abee76bf..9af474a0 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Copyright (C) 2020 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/oslo_versionedobjects/base.py b/oslo_versionedobjects/base.py index ac124acd..8e619b36 100644 --- a/oslo_versionedobjects/base.py +++ b/oslo_versionedobjects/base.py @@ -34,7 +34,7 @@ from oslo_versionedobjects import fields as obj_fields LOG = logging.getLogger('object') -class _NotSpecifiedSentinel(object): +class _NotSpecifiedSentinel: pass @@ -83,7 +83,7 @@ def _make_class_properties(cls): return setattr(self, attrname, field_value) except 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', {'attr': attr}) @@ -96,7 +96,7 @@ def _make_class_properties(cls): setattr(cls, name, property(getter, setter, deleter)) -class VersionedObjectRegistry(object): +class VersionedObjectRegistry: _registry = None def __new__(cls, *args, **kwargs): @@ -230,7 +230,7 @@ def remotable(fn): return wrapper -class VersionedObject(object): +class VersionedObject: """Base class and object factory. This forms the base of all objects that can be remoted or instantiated @@ -307,12 +307,12 @@ class VersionedObject(object): setattr(self, key, kwargs[key]) def __repr__(self): - repr_str = '%s(%s)' % ( + repr_str = '{}({})'.format( self.obj_name(), - ','.join(['%s=%s' % (name, - (self.obj_attr_is_set(name) and - field.stringify(getattr(self, name)) or - '')) + ','.join(['{}={}'.format(name, + (self.obj_attr_is_set(name) and + field.stringify(getattr(self, name)) or + '')) for name, field in sorted(self.fields.items())])) return repr_str @@ -343,7 +343,7 @@ class VersionedObject(object): @classmethod def _obj_primitive_key(cls, field): - return '%s.%s' % (cls.OBJ_SERIAL_NAMESPACE, field) + return '{}.{}'.format(cls.OBJ_SERIAL_NAMESPACE, field) @classmethod def _obj_primitive_field(cls, primitive, field, @@ -395,7 +395,7 @@ class VersionedObject(object): if name in objdata: setattr(self, name, field.from_primitive(self, 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 @classmethod @@ -408,7 +408,7 @@ class VersionedObject(object): # NOTE(danms): We don't do anything with this now, but it's # there for "the future" raise exception.UnsupportedObjectError( - objtype='%s.%s' % (objns, objname)) + objtype='{}.{}'.format(objns, objname)) objclass = cls.obj_class_from_name(objname, objver) return objclass._obj_from_primitive(context, objver, primitive) @@ -610,8 +610,8 @@ class VersionedObject(object): def obj_what_changed(self): """Returns a set of fields that have been modified.""" - changes = set([field for field in self._changed_fields - if field in self.fields]) + changes = {field for field in self._changed_fields + if field in self.fields} for field in self.fields: if (self.obj_attr_is_set(field) and isinstance(getattr(self, field), VersionedObject) and @@ -691,7 +691,7 @@ class VersionedObject(object): return self._context -class ComparableVersionedObject(object): +class ComparableVersionedObject: """Mix-in to provide comparison methods When objects are to be compared with each other (in tests for example), @@ -705,7 +705,7 @@ class ComparableVersionedObject(object): return NotImplemented def __hash__(self): - return super(ComparableVersionedObject, self).__hash__() + return super().__hash__() def __ne__(self, obj): if hasattr(obj, 'obj_to_primitive'): @@ -713,7 +713,7 @@ class ComparableVersionedObject(object): return NotImplemented -class TimestampedObject(object): +class TimestampedObject: """Mixin class for db backed objects with timestamp fields. 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 If an object needs to support attribute access using @@ -759,7 +759,7 @@ class VersionedObjectDictCompat(object): def get(self, key, value=_NotSpecifiedSentinel): 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)) if value != _NotSpecifiedSentinel and not self.obj_attr_is_set(key): return value @@ -789,7 +789,7 @@ class ObjectListBase(collections_abc.Sequence): child_versions = {} def __init__(self, *args, **kwargs): - super(ObjectListBase, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) if 'objects' not in kwargs: self.objects = [] self._changed_fields.discard('objects') @@ -959,7 +959,7 @@ class VersionedObjectSerializer(messaging.NoOpSerializer): return entity -class VersionedObjectIndirectionAPI(object, metaclass=abc.ABCMeta): +class VersionedObjectIndirectionAPI(metaclass=abc.ABCMeta): def object_action(self, context, objinst, objmethod, args, kwargs): """Perform an action on a VersionedObject instance. diff --git a/oslo_versionedobjects/examples/iot_bulb.py b/oslo_versionedobjects/examples/iot_bulb.py index 4ef0f62e..c68b50fe 100644 --- a/oslo_versionedobjects/examples/iot_bulb.py +++ b/oslo_versionedobjects/examples/iot_bulb.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at diff --git a/oslo_versionedobjects/exception.py b/oslo_versionedobjects/exception.py index 42222c38..6e299155 100644 --- a/oslo_versionedobjects/exception.py +++ b/oslo_versionedobjects/exception.py @@ -49,7 +49,7 @@ class ConvertedException(webob.exc.WSGIHTTPException): self.code = code self.title = title self.explanation = explanation - super(ConvertedException, self).__init__() + super().__init__() def _cleanse_dict(original): @@ -122,7 +122,7 @@ class VersionedObjectsException(Exception): # log the issue and the kwargs LOG.exception('Exception in string format operation') 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: raise @@ -130,7 +130,7 @@ class VersionedObjectsException(Exception): # at least get the core message out if something happened message = self.msg_fmt - super(VersionedObjectsException, self).__init__(message) + super().__init__(message) def format_message(self): # NOTE(mrodden): use the first argument to the python Exception object diff --git a/oslo_versionedobjects/fields.py b/oslo_versionedobjects/fields.py index 21d85039..2e272dd6 100644 --- a/oslo_versionedobjects/fields.py +++ b/oslo_versionedobjects/fields.py @@ -33,7 +33,7 @@ from oslo_versionedobjects import exception class KeyTypeError(TypeError): def __init__(self, expected, value): - super(KeyTypeError, self).__init__( + super().__init__( _('Key %(key)s must be of type %(expected)s not %(actual)s' ) % {'key': repr(value), 'expected': expected.__name__, @@ -43,7 +43,7 @@ class KeyTypeError(TypeError): class ElementTypeError(TypeError): def __init__(self, expected, key, value): - super(ElementTypeError, self).__init__( + super().__init__( _('Element %(key)s:%(val)s must be of type %(expected)s' ' not %(actual)s' ) % {'key': key, @@ -53,7 +53,7 @@ class ElementTypeError(TypeError): }) -class AbstractFieldType(object, metaclass=abc.ABCMeta): +class AbstractFieldType(metaclass=abc.ABCMeta): @abc.abstractmethod def coerce(self, obj, attr, value): """This is called to coerce (if possible) a value on assignment. @@ -130,11 +130,11 @@ class FieldType(AbstractFieldType): raise NotImplementedError() -class UnspecifiedDefault(object): +class UnspecifiedDefault: pass -class Field(object): +class Field: def __init__(self, field_type, nullable=False, default=UnspecifiedDefault, read_only=False): self._type = field_type @@ -153,8 +153,8 @@ class Field(object): ) else: default = str(self._default) - return '%s(default=%s,nullable=%s)' % (self._type.__class__.__name__, - default, self._nullable) + return '{}(default={},nullable={})'.format( + self._type.__class__.__name__, default, self._nullable) @property def nullable(self): @@ -286,7 +286,7 @@ class SensitiveString(String): Passwords in the string value are masked when stringified. """ def stringify(self, value): - return super(SensitiveString, self).stringify( + return super().stringify( strutils.mask_password(value)) @@ -309,11 +309,11 @@ class Enum(String): try: # Test validity of the values for value in valid_values: - super(Enum, self).coerce(None, 'init', value) + super().coerce(None, 'init', value) except (TypeError, ValueError): raise exception.EnumValidValuesInvalidError() self._valid_values = valid_values - super(Enum, self).__init__(**kwargs) + super().__init__(**kwargs) @property def valid_values(self): @@ -323,16 +323,16 @@ class Enum(String): if value not in self._valid_values: msg = _("Field value %s is invalid") % value raise ValueError(msg) - return super(Enum, self).coerce(obj, attr, value) + return super().coerce(obj, attr, value) def stringify(self, value): if value not in self._valid_values: msg = _("Field value %s is invalid") % value raise ValueError(msg) - return super(Enum, self).stringify(value) + return super().stringify(value) def get_schema(self): - schema = super(Enum, self).get_schema() + schema = super().get_schema() schema['enum'] = self._valid_values return schema @@ -465,7 +465,7 @@ class FlexibleBoolean(Boolean): class DateTime(FieldType): def __init__(self, tzinfo_aware=True, *args, **kwargs): self.tzinfo_aware = tzinfo_aware - super(DateTime, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def coerce(self, obj, attr, value): if isinstance(value, str): @@ -586,7 +586,7 @@ class IPV4Network(IPNetwork): class IPV6Network(IPNetwork): def __init__(self, *args, **kwargs): - super(IPV6Network, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.PATTERN = self._create_pattern() @staticmethod @@ -684,19 +684,19 @@ class Dict(CompoundFieldType): primitive = {} for key, element in value.items(): primitive[key] = self._element_type.to_primitive( - obj, '%s["%s"]' % (attr, key), element) + obj, '{}["{}"]'.format(attr, key), element) return primitive def from_primitive(self, obj, attr, value): concrete = {} for key, element in value.items(): concrete[key] = self._element_type.from_primitive( - obj, '%s["%s"]' % (attr, key), element) + obj, '{}["{}"]'.format(attr, key), element) return concrete def stringify(self, value): 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())])) def get_schema(self): @@ -704,7 +704,7 @@ class Dict(CompoundFieldType): 'additionalProperties': self._element_type.get_schema()} -class DictProxyField(object): +class DictProxyField: """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 @@ -751,8 +751,8 @@ class Set(CompoundFieldType): self._element_type.to_primitive(obj, attr, x) for x in value) def from_primitive(self, obj, attr, value): - return set([self._element_type.from_primitive(obj, attr, x) - for x in value]) + return {self._element_type.from_primitive(obj, attr, x) + for x in value} def stringify(self, value): return 'set([%s])' % ( @@ -767,7 +767,7 @@ class Object(FieldType): def __init__(self, obj_name, subclasses=False, **kwargs): self._obj_name = obj_name self._subclasses = subclasses - super(Object, self).__init__(**kwargs) + super().__init__(**kwargs) @staticmethod def _get_all_obj_names(obj): @@ -835,7 +835,7 @@ class Object(FieldType): else: ident = '' - return '%s%s' % (value.obj_name(), ident) + return '{}{}'.format(value.obj_name(), ident) def get_schema(self): from oslo_versionedobjects import base as obj_base @@ -890,7 +890,7 @@ class AutoTypedField(Field): AUTO_TYPE = None def __init__(self, **kwargs): - super(AutoTypedField, self).__init__(self.AUTO_TYPE, **kwargs) + super().__init__(self.AUTO_TYPE, **kwargs) class StringField(AutoTypedField): @@ -924,7 +924,7 @@ class BaseEnumField(AutoTypedField): typename=self.AUTO_TYPE.__class__.__name__, fieldname=self.__class__.__name__) - super(BaseEnumField, self).__init__(**kwargs) + super().__init__(**kwargs) def __repr__(self): valid_values = self._type.valid_values @@ -933,9 +933,9 @@ class BaseEnumField(AutoTypedField): 'default': self._default, } args.update({'valid_values': valid_values}) - return '%s(%s)' % (self._type.__class__.__name__, - ','.join(['%s=%s' % (k, v) - for k, v in sorted(args.items())])) + return '{}({})'.format(self._type.__class__.__name__, + ','.join(['{}={}'.format(k, v) + for k, v in sorted(args.items())])) @property def valid_values(self): @@ -955,7 +955,7 @@ class EnumField(BaseEnumField): def __init__(self, valid_values, **kwargs): self.AUTO_TYPE = Enum(valid_values=valid_values) - super(EnumField, self).__init__(**kwargs) + super().__init__(**kwargs) class StateMachine(EnumField): @@ -1009,7 +1009,7 @@ class StateMachine(EnumField): return 'unknown' def coerce(self, obj, attr, value): - super(StateMachine, self).coerce(obj, attr, value) + super().coerce(obj, attr, value) my_name = self._my_name(obj) msg = _("%(object)s.%(name)s is not allowed to transition out of " "%(value)s state") @@ -1113,7 +1113,7 @@ class FlexibleBooleanField(AutoTypedField): class DateTimeField(AutoTypedField): def __init__(self, tzinfo_aware=True, **kwargs): self.AUTO_TYPE = DateTime(tzinfo_aware=tzinfo_aware) - super(DateTimeField, self).__init__(**kwargs) + super().__init__(**kwargs) class DictOfStringsField(AutoTypedField): @@ -1139,7 +1139,7 @@ class DictOfListOfStringsField(AutoTypedField): class ListOfEnumField(AutoTypedField): def __init__(self, valid_values, **kwargs): self.AUTO_TYPE = List(Enum(valid_values)) - super(ListOfEnumField, self).__init__(**kwargs) + super().__init__(**kwargs) def __repr__(self): valid_values = self._type._element_type._type.valid_values @@ -1148,9 +1148,9 @@ class ListOfEnumField(AutoTypedField): 'default': self._default, } args.update({'valid_values': valid_values}) - return '%s(%s)' % (self._type.__class__.__name__, - ','.join(['%s=%s' % (k, v) - for k, v in sorted(args.items())])) + return '{}({})'.format(self._type.__class__.__name__, + ','.join(['{}={}'.format(k, v) + for k, v in sorted(args.items())])) class SetOfIntegersField(AutoTypedField): @@ -1173,14 +1173,14 @@ class ObjectField(AutoTypedField): def __init__(self, objtype, subclasses=False, **kwargs): self.AUTO_TYPE = Object(objtype, subclasses) self.objname = objtype - super(ObjectField, self).__init__(**kwargs) + super().__init__(**kwargs) class ListOfObjectsField(AutoTypedField): def __init__(self, objtype, subclasses=False, **kwargs): self.AUTO_TYPE = List(Object(objtype, subclasses)) self.objname = objtype - super(ListOfObjectsField, self).__init__(**kwargs) + super().__init__(**kwargs) class ListOfUUIDField(AutoTypedField): @@ -1215,12 +1215,12 @@ class IPV6NetworkField(AutoTypedField): AUTO_TYPE = IPV6Network() -class CoercedCollectionMixin(object): +class CoercedCollectionMixin: def __init__(self, *args, **kwargs): self._element_type = None self._obj = None self._field = None - super(CoercedCollectionMixin, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def enable_coercing(self, element_type, obj, field): self._element_type = element_type @@ -1247,30 +1247,30 @@ class CoercedList(CoercedCollectionMixin, list): step = i.step or 1 coerced_items = [self._coerce_item(start + index * step, item) for index, item in enumerate(y)] - super(CoercedList, self).__setitem__(i, coerced_items) + super().__setitem__(i, coerced_items) else: - super(CoercedList, self).__setitem__(i, self._coerce_item(i, y)) + super().__setitem__(i, self._coerce_item(i, y)) 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): coerced_items = [self._coerce_item(len(self) + index, item) for index, item in enumerate(t)] - super(CoercedList, self).extend(coerced_items) + super().extend(coerced_items) 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): coerced_items = [self._coerce_item(len(self) + index, item) for index, item in enumerate(y)] - return super(CoercedList, self).__iadd__(coerced_items) + return super().__iadd__(coerced_items) def __setslice__(self, i, j, y): coerced_items = [self._coerce_item(i + index, item) 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): @@ -1290,26 +1290,26 @@ class CoercedDict(CoercedCollectionMixin, dict): if not isinstance(key, str): raise KeyTypeError(str, key) 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) else: return item def __setitem__(self, key, value): - super(CoercedDict, self).__setitem__(key, - self._coerce_item(key, value)) + super().__setitem__(key, + self._coerce_item(key, value)) def update(self, other=None, **kwargs): if other is not None: - super(CoercedDict, self).update(self._coerce_dict(other), - **self._coerce_dict(kwargs)) + super().update(self._coerce_dict(other), + **self._coerce_dict(kwargs)) else: - super(CoercedDict, self).update(**self._coerce_dict(kwargs)) + super().update(**self._coerce_dict(kwargs)) def setdefault(self, key, default=None): - return super(CoercedDict, self).setdefault(key, - self._coerce_item(key, - default)) + return super().setdefault(key, + self._coerce_item(key, + default)) class CoercedSet(CoercedCollectionMixin, set): @@ -1321,7 +1321,8 @@ class CoercedSet(CoercedCollectionMixin, set): def _coerce_element(self, element): if hasattr(self, "_element_type") and self._element_type is not None: return self._element_type.coerce(self._obj, - "%s[%s]" % (self._field, element), + "{}[{}]".format( + self._field, element), element) else: return element @@ -1333,17 +1334,17 @@ class CoercedSet(CoercedCollectionMixin, set): return coerced def add(self, value): - return super(CoercedSet, self).add(self._coerce_element(value)) + return super().add(self._coerce_element(value)) 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): - return super(CoercedSet, self).symmetric_difference_update( + return super().symmetric_difference_update( self._coerce_iterable(values)) def __ior__(self, y): - return super(CoercedSet, self).__ior__(self._coerce_iterable(y)) + return super().__ior__(self._coerce_iterable(y)) def __ixor__(self, y): - return super(CoercedSet, self).__ixor__(self._coerce_iterable(y)) + return super().__ixor__(self._coerce_iterable(y)) diff --git a/oslo_versionedobjects/fixture.py b/oslo_versionedobjects/fixture.py index 8a1d2fc2..77a1a486 100644 --- a/oslo_versionedobjects/fixture.py +++ b/oslo_versionedobjects/fixture.py @@ -113,14 +113,14 @@ class OsloOrderedDict(OrderedDict): # Python >= 3.12 uses a dict instead of a list which changes the # repr of the versioned object and its associated hash value # Switch back to using list an use super class name. - return '%s(%r)' % ( + return '{}({!r})'.format( self.__class__.__bases__[0].__name__, list(self.items()) ) class FakeIndirectionAPI(base.VersionedObjectIndirectionAPI): def __init__(self, serializer=None): - super(FakeIndirectionAPI, self).__init__() + super().__init__() self._ser = serializer or base.VersionedObjectSerializer() def _get_changes(self, orig_obj, new_obj): @@ -139,10 +139,10 @@ class FakeIndirectionAPI(base.VersionedObjectIndirectionAPI): [self._ser.deserialize_entity( context, self._ser.serialize_entity(context, arg)) for arg in args]) - kwargs = dict( - [(argname, self._ser.deserialize_entity( - context, self._ser.serialize_entity(context, arg))) - for argname, arg in kwargs.items()]) + kwargs = { + argname: self._ser.deserialize_entity( + context, self._ser.serialize_entity(context, arg)) + for argname, arg in kwargs.items()} return 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() def setUp(self): - super(IndirectionFixture, self).setUp() + super().setUp() self.useFixture(fixtures.MonkeyPatch( 'oslo_versionedobjects.base.VersionedObject.indirection_api', self.indirection_api)) @@ -240,7 +240,7 @@ def get_method_spec(method): fullspec.varkw, fullspec.defaults) -class ObjectVersionChecker(object): +class ObjectVersionChecker: def __init__(self, obj_classes=base.VersionedObjectRegistry.obj_classes()): self.obj_classes = obj_classes @@ -288,7 +288,7 @@ class ObjectVersionChecker(object): if extra_data_func: 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()), usedforsecurity=False).hexdigest()) return fingerprint @@ -344,8 +344,8 @@ class ObjectVersionChecker(object): def test_relationships(self, expected_tree): actual_tree = self.get_dependency_tree() - stored = set([(x, str(y)) for x, y in expected_tree.items()]) - computed = set([(x, str(y)) for x, y in actual_tree.items()]) + stored = {(x, str(y)) for x, y in expected_tree.items()} + computed = {(x, str(y)) for x, y in actual_tree.items()} changed = stored.symmetric_difference(computed) expected = {} actual = {} @@ -445,7 +445,7 @@ class VersionedObjectRegistryFixture(fixtures.Fixture): """ def setUp(self): - super(VersionedObjectRegistryFixture, self).setUp() + super().setUp() self._base_test_obj_backup = copy.deepcopy( base.VersionedObjectRegistry._registry._obj_classes) self.addCleanup(self._restore_obj_registry) @@ -475,7 +475,7 @@ class StableObjectJsonFixture(fixtures.Fixture): self._original_otp = base.VersionedObject.obj_to_primitive def setUp(self): - super(StableObjectJsonFixture, self).setUp() + super().setUp() def _doit(obj, *args, **kwargs): result = self._original_otp(obj, *args, **kwargs) diff --git a/oslo_versionedobjects/test.py b/oslo_versionedobjects/test.py index 4589e018..da893d8a 100644 --- a/oslo_versionedobjects/test.py +++ b/oslo_versionedobjects/test.py @@ -45,7 +45,7 @@ class TestingException(Exception): pass -class skipIf(object): +class skipIf: def __init__(self, condition, reason): self.condition = condition self.reason = reason @@ -109,7 +109,7 @@ class TestCase(testtools.TestCase): def setUp(self): """Run before each test method to initialize test environment.""" - super(TestCase, self).setUp() + super().setUp() self.useFixture(obj_fixtures.Timeout( os.environ.get('OS_TEST_TIMEOUT', 0), self.TIMEOUT_SCALING_FACTOR)) @@ -186,7 +186,7 @@ class TestCase(testtools.TestCase): (name, baseclass)) -class APICoverage(object): +class APICoverage: cover_api = None diff --git a/oslo_versionedobjects/tests/obj_fixtures.py b/oslo_versionedobjects/tests/obj_fixtures.py index 9cb73650..cee7c241 100644 --- a/oslo_versionedobjects/tests/obj_fixtures.py +++ b/oslo_versionedobjects/tests/obj_fixtures.py @@ -35,7 +35,7 @@ class TranslationFixture(fixtures.Fixture): """Use gettext NullTranslation objects in tests.""" def setUp(self): - super(TranslationFixture, self).setUp() + super().setUp() nulltrans = gettext.NullTranslations() gettext_fixture = fixtures.MonkeyPatch('gettext.translation', lambda *x, **y: nulltrans) @@ -87,7 +87,7 @@ class StandardLogging(fixtures.Fixture): """ def setUp(self): - super(StandardLogging, self).setUp() + super().setUp() # set root logger to debug root = logging.getLogger() @@ -124,7 +124,7 @@ class OutputStreamCapture(fixtures.Fixture): tests. """ def setUp(self): - super(OutputStreamCapture, self).setUp() + super().setUp() if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES: self.out = self.useFixture(fixtures.StringStream('stdout')) self.useFixture( @@ -155,7 +155,7 @@ class Timeout(fixtures.Fixture): """ def __init__(self, timeout, scaling=1): - super(Timeout, self).__init__() + super().__init__() try: self.test_timeout = int(timeout) except ValueError: @@ -167,7 +167,7 @@ class Timeout(fixtures.Fixture): raise ValueError('scaling value must be >= 1') def setUp(self): - super(Timeout, self).setUp() + super().setUp() if self.test_timeout > 0: self.useFixture(fixtures.Timeout(self.test_timeout, gentle=True)) @@ -176,7 +176,7 @@ class WarningsFixture(fixtures.Fixture): """Filters out warnings during test runs.""" def setUp(self): - super(WarningsFixture, self).setUp() + super().setUp() # NOTE(sdague): Make deprecation warnings only happen once. Otherwise # this gets kind of crazy given the way that upstream python libs use # this. diff --git a/oslo_versionedobjects/tests/test_exception.py b/oslo_versionedobjects/tests/test_exception.py index 2aac16b9..42ed8c46 100644 --- a/oslo_versionedobjects/tests/test_exception.py +++ b/oslo_versionedobjects/tests/test_exception.py @@ -19,7 +19,7 @@ from oslo_versionedobjects import test notifier = mock.Mock() -class TestWrapper(object): +class TestWrapper: @exception.wrap_exception(notifier=notifier) def raise_exc(self, context, exc, admin_password): raise exc diff --git a/oslo_versionedobjects/tests/test_fields.py b/oslo_versionedobjects/tests/test_fields.py index 65c8b546..f68181dc 100644 --- a/oslo_versionedobjects/tests/test_fields.py +++ b/oslo_versionedobjects/tests/test_fields.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -50,8 +49,8 @@ class FakeEnum(fields.Enum): ALL = (FROG, PLATYPUS, ALLIGATOR) def __init__(self, **kwargs): - super(FakeEnum, self).__init__(valid_values=FakeEnum.ALL, - **kwargs) + super().__init__(valid_values=FakeEnum.ALL, + **kwargs) class FakeEnumAlt(fields.Enum): @@ -59,11 +58,11 @@ class FakeEnumAlt(fields.Enum): PLATYPUS = "platypus" AARDVARK = "aardvark" - ALL = set([FROG, PLATYPUS, AARDVARK]) + ALL = {FROG, PLATYPUS, AARDVARK} def __init__(self, **kwargs): - super(FakeEnumAlt, self).__init__(valid_values=FakeEnumAlt.ALL, - **kwargs) + super().__init__(valid_values=FakeEnumAlt.ALL, + **kwargs) class FakeEnumField(fields.BaseEnumField): @@ -93,7 +92,7 @@ class FakeStateMachineField(fields.StateMachine): _TYPES = (ACTIVE, PENDING, ERROR) def __init__(self, **kwargs): - super(FakeStateMachineField, self).__init__(self._TYPES, **kwargs) + super().__init__(self._TYPES, **kwargs) class FakeEnumAltField(fields.BaseEnumField): @@ -107,7 +106,7 @@ class TestFieldType(test.TestCase): class TestField(test.TestCase): def setUp(self): - super(TestField, self).setUp() + super().setUp() self.field = fields.Field(FakeFieldType()) self.coerce_good_values = [('foo', '*foo*')] self.coerce_bad_values = [] @@ -129,7 +128,7 @@ class TestField(test.TestCase): in_val)) def test_from_primitive(self): - class ObjectLikeThing(object): + class ObjectLikeThing: _context = 'context' for prim_val, out_val in self.from_primitive_values: @@ -142,7 +141,7 @@ class TestField(test.TestCase): class TestSchema(test.TestCase): def setUp(self): - super(TestSchema, self).setUp() + super().setUp() self.field = fields.Field(FakeFieldType(), nullable=True, default='', read_only=False) @@ -154,7 +153,7 @@ class TestSchema(test.TestCase): class TestString(TestField): def setUp(self): - super(TestString, self).setUp() + super().setUp() self.field = fields.StringField() self.coerce_good_values = [ ('foo', 'foo'), (1, '1'), (1.0, '1.0'), (True, 'True')] @@ -175,7 +174,7 @@ class TestString(TestField): class TestSensitiveString(TestString): def setUp(self): - super(TestSensitiveString, self).setUp() + super().setUp() self.field = fields.SensitiveStringField() def test_stringify(self): @@ -186,7 +185,7 @@ class TestSensitiveString(TestString): class TestVersionPredicate(TestString): def setUp(self): - super(TestVersionPredicate, self).setUp() + super().setUp() self.field = fields.VersionPredicateField() self.coerce_good_values = [('>=1.0', '>=1.0'), ('==1.1', '==1.1'), @@ -198,7 +197,7 @@ class TestVersionPredicate(TestString): class TestMACAddress(TestField): def setUp(self): - super(TestMACAddress, self).setUp() + super().setUp() self.field = fields.MACAddressField() self.coerce_good_values = [ ('c6:df:11:a5:c8:5d', 'c6:df:11:a5:c8:5d'), @@ -231,7 +230,7 @@ class TestMACAddress(TestField): class TestPCIAddress(TestField): def setUp(self): - super(TestPCIAddress, self).setUp() + super().setUp() self.field = fields.PCIAddressField() self.coerce_good_values = [ ('0000:02:00.0', '0000:02:00.0'), @@ -264,7 +263,7 @@ class TestPCIAddress(TestField): class TestUUID(TestField): def setUp(self): - super(TestUUID, self).setUp() + super().setUp() self.field = fields.UUIDField() self.coerce_good_values = [ ('da66a411-af0e-4829-9b67-475017ddd152', @@ -322,7 +321,7 @@ class TestUUID(TestField): class TestBaseEnum(TestField): def setUp(self): - super(TestBaseEnum, self).setUp() + super().setUp() self.field = FakeEnumField() self.coerce_good_values = [('frog', 'frog'), ('platypus', 'platypus'), @@ -355,7 +354,7 @@ class TestBaseEnum(TestField): class TestEnum(TestField): def setUp(self): - super(TestEnum, self).setUp() + super().setUp() self.field = fields.EnumField( valid_values=['foo', 'bar', 1, True]) self.coerce_good_values = [('foo', 'foo'), (1, '1'), (True, 'True')] @@ -490,7 +489,7 @@ class TestInteger(TestField): class TestNonNegativeInteger(TestField): def setUp(self): - super(TestNonNegativeInteger, self).setUp() + super().setUp() self.field = fields.NonNegativeIntegerField() self.coerce_good_values = [(1, 1), ('1', 1)] self.coerce_bad_values = ['-2', '4.2', 'foo', None] @@ -504,7 +503,7 @@ class TestNonNegativeInteger(TestField): class TestFloat(TestField): def setUp(self): - super(TestFloat, self).setUp() + super().setUp() self.field = fields.FloatField() self.coerce_good_values = [(1.1, 1.1), ('1.1', 1.1)] self.coerce_bad_values = ['foo', None] @@ -521,7 +520,7 @@ class TestFloat(TestField): class TestNonNegativeFloat(TestField): def setUp(self): - super(TestNonNegativeFloat, self).setUp() + super().setUp() self.field = fields.NonNegativeFloatField() self.coerce_good_values = [(1.1, 1.1), ('1.1', 1.1)] self.coerce_bad_values = ['-4.2', 'foo', None] @@ -553,7 +552,7 @@ class TestBoolean(TestField): class TestFlexibleBoolean(TestField): def setUp(self): - super(TestFlexibleBoolean, self).setUp() + super().setUp() self.field = fields.FlexibleBooleanField() self.coerce_good_values = [(True, True), (False, False), ("true", True), ("false", False), @@ -570,7 +569,7 @@ class TestFlexibleBoolean(TestField): class TestDateTime(TestField): def setUp(self): - super(TestDateTime, self).setUp() + super().setUp() self.dt = datetime.datetime(1955, 11, 5, tzinfo=iso8601.iso8601.UTC) self.field = fields.DateTimeField() self.coerce_good_values = [(self.dt, self.dt), @@ -594,7 +593,7 @@ class TestDateTime(TestField): class TestDateTimeNoTzinfo(TestField): def setUp(self): - super(TestDateTimeNoTzinfo, self).setUp() + super().setUp() self.dt = datetime.datetime(1955, 11, 5) self.field = fields.DateTimeField(tzinfo_aware=False) self.coerce_good_values = [(self.dt, self.dt), @@ -617,7 +616,7 @@ class TestDateTimeNoTzinfo(TestField): class TestDict(TestField): def setUp(self): - super(TestDict, self).setUp() + super().setUp() self.field = fields.Field(fields.Dict(FakeFieldType())) self.coerce_good_values = [({'foo': 'bar'}, {'foo': '*bar*'}), ({'foo': 1}, {'foo': '*1*'})] @@ -638,7 +637,7 @@ class TestDict(TestField): class TestDictOfStrings(TestField): def setUp(self): - super(TestDictOfStrings, self).setUp() + super().setUp() self.field = fields.DictOfStringsField() self.coerce_good_values = [({'foo': 'bar'}, {'foo': 'bar'}), ({'foo': 1}, {'foo': '1'})] @@ -652,7 +651,7 @@ class TestDictOfStrings(TestField): class TestDictOfIntegers(TestField): def setUp(self): - super(TestDictOfIntegers, self).setUp() + super().setUp() self.field = fields.DictOfIntegersField() self.coerce_good_values = [({'foo': '42'}, {'foo': 42}), ({'foo': 4.2}, {'foo': 4})] @@ -667,7 +666,7 @@ class TestDictOfIntegers(TestField): class TestDictOfStringsNone(TestField): def setUp(self): - super(TestDictOfStringsNone, self).setUp() + super().setUp() self.field = fields.DictOfNullableStringsField() self.coerce_good_values = [({'foo': 'bar'}, {'foo': 'bar'}), ({'foo': 1}, {'foo': '1'}), @@ -684,7 +683,7 @@ class TestDictOfStringsNone(TestField): class TestListOfDictOfNullableStringsField(TestField): def setUp(self): - super(TestListOfDictOfNullableStringsField, self).setUp() + super().setUp() self.field = fields.ListOfDictOfNullableStringsField() self.coerce_good_values = [([{'f': 'b', 'f1': 'b1'}, {'f2': 'b2'}], [{'f': 'b', 'f1': 'b1'}, {'f2': 'b2'}]), @@ -707,7 +706,7 @@ class TestListOfDictOfNullableStringsField(TestField): class TestList(TestField): def setUp(self): - super(TestList, self).setUp() + super().setUp() self.field = fields.Field(fields.List(FakeFieldType())) self.coerce_good_values = [(['foo', 'bar'], ['*foo*', '*bar*'])] self.coerce_bad_values = ['foo'] @@ -731,7 +730,7 @@ class TestList(TestField): class TestListOfStrings(TestField): def setUp(self): - super(TestListOfStrings, self).setUp() + super().setUp() self.field = fields.ListOfStringsField() self.coerce_good_values = [(['foo', 'bar'], ['foo', 'bar'])] self.coerce_bad_values = ['foo'] @@ -744,7 +743,7 @@ class TestListOfStrings(TestField): class TestDictOfListOfStrings(TestField): def setUp(self): - super(TestDictOfListOfStrings, self).setUp() + super().setUp() self.field = fields.DictOfListOfStringsField() self.coerce_good_values = [({'foo': ['1', '2']}, {'foo': ['1', '2']}), ({'foo': [1]}, {'foo': ['1']})] @@ -760,7 +759,7 @@ class TestDictOfListOfStrings(TestField): class TestListOfEnum(TestField): def setUp(self): - super(TestListOfEnum, self).setUp() + super().setUp() self.field = fields.ListOfEnumField(valid_values=['foo', 'bar']) self.coerce_good_values = [(['foo', 'bar'], ['foo', 'bar'])] self.coerce_bad_values = ['foo', ['foo', 'bar1']] @@ -783,16 +782,16 @@ class TestListOfEnum(TestField): class TestSet(TestField): def setUp(self): - super(TestSet, self).setUp() + super().setUp() self.field = fields.Field(fields.Set(FakeFieldType())) - self.coerce_good_values = [(set(['foo', 'bar']), - set(['*foo*', '*bar*']))] + self.coerce_good_values = [({'foo', 'bar'}, + {'*foo*', '*bar*'})] self.coerce_bad_values = [['foo'], {'foo': 'bar'}] - self.to_primitive_values = [(set(['foo']), tuple(['!foo!']))] - self.from_primitive_values = [(tuple(['!foo!']), set(['foo']))] + self.to_primitive_values = [({'foo'}, tuple(['!foo!']))] + self.from_primitive_values = [(tuple(['!foo!']), {'foo'})] 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): self.assertEqual({'type': ['array'], 'uniqueItems': True, @@ -803,16 +802,16 @@ class TestSet(TestField): class TestSetOfIntegers(TestField): def setUp(self): - super(TestSetOfIntegers, self).setUp() + super().setUp() self.field = fields.SetOfIntegersField() - self.coerce_good_values = [(set(['1', 2]), - set([1, 2]))] - self.coerce_bad_values = [set(['foo'])] - self.to_primitive_values = [(set([1]), tuple([1]))] - self.from_primitive_values = [(tuple([1]), set([1]))] + self.coerce_good_values = [({'1', 2}, + {1, 2})] + self.coerce_bad_values = [{'foo'}] + self.to_primitive_values = [({1}, tuple([1]))] + self.from_primitive_values = [(tuple([1]), {1})] 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): self.assertEqual("Set(default=