From feed7bedb65b8e618f31db2efc51b83db2850891 Mon Sep 17 00:00:00 2001 From: Michael Howitz Date: Mon, 5 Aug 2024 09:16:47 +0200 Subject: [PATCH] Update Python version support. --- setup.py | 4 +- src/zope/schema/_bootstrapfields.py | 56 ++--- src/zope/schema/_bootstrapinterfaces.py | 14 +- src/zope/schema/_field.py | 109 ++++----- src/zope/schema/_messageid.py | 2 +- src/zope/schema/fieldproperty.py | 6 +- src/zope/schema/interfaces.py | 4 +- src/zope/schema/tests/states.py | 122 +++++------ .../schema/tests/test__bootstrapfields.py | 206 +++++++++--------- src/zope/schema/tests/test__field.py | 180 +++++++-------- src/zope/schema/tests/test_accessors.py | 30 +-- src/zope/schema/tests/test_equality.py | 2 +- src/zope/schema/tests/test_fieldproperty.py | 140 ++++++------ src/zope/schema/tests/test_interfaces.py | 4 +- src/zope/schema/tests/test_schema.py | 24 +- src/zope/schema/tests/test_states.py | 16 +- src/zope/schema/tests/test_vocabulary.py | 10 +- src/zope/schema/vocabulary.py | 49 ++--- 18 files changed, 479 insertions(+), 499 deletions(-) diff --git a/setup.py b/setup.py index 673679a..61660e9 100644 --- a/setup.py +++ b/setup.py @@ -64,17 +64,17 @@ def read(*rnames): "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Framework :: Zope :: 3", "Topic :: Software Development :: Libraries :: Python Modules", ], - python_requires='>=3.7', + python_requires='>=3.8', include_package_data=True, zip_safe=False, extras_require={ diff --git a/src/zope/schema/_bootstrapfields.py b/src/zope/schema/_bootstrapfields.py index 94e4dad..65145e3 100644 --- a/src/zope/schema/_bootstrapfields.py +++ b/src/zope/schema/_bootstrapfields.py @@ -55,7 +55,7 @@ from zope.schema._bootstrapinterfaces import WrongType -class _NotGiven(object): +class _NotGiven: def __repr__(self): # pragma: no cover return "" @@ -64,7 +64,7 @@ def __repr__(self): # pragma: no cover _NotGiven = _NotGiven() -class ValidatedProperty(object): +class ValidatedProperty: def __init__(self, name, check=None, allow_none=False): self._name = name @@ -123,7 +123,7 @@ def getFields(schema): return fields -class _DocStringHelpers(object): +class _DocStringHelpers: # Namespace object to hold methods related to ReST formatting # docstrings @@ -164,11 +164,11 @@ def make_class_directive(kind): if mod in ('zope.schema._bootstrapfields', 'zope.schema._field'): mod = 'zope.schema' mod += '.' if mod else '' - return ':class:`%s%s`' % (mod, kind.__name__) + return ':class:`{}{}`'.format(mod, kind.__name__) @classmethod def make_field(cls, name, value): - return ":%s: %s" % (name, value) + return ":{}: {}".format(name, value) @classmethod def make_class_field(cls, name, kind): @@ -176,7 +176,7 @@ def make_class_field(cls, name, kind): return cls.make_field(name, cls.make_class_directive(kind)) if not isinstance(kind, tuple): # pragma: no cover raise TypeError( - "make_class_field() can't handle kind %r" % (kind,)) + "make_class_field() can't handle kind {!r}".format(kind)) return cls.make_field( name, ', '.join([cls.make_class_directive(t) for t in kind])) @@ -213,7 +213,7 @@ class Field(Attribute): interface = None _Element__tagged_values = None - def __init__(self, title=u'', description=u'', __name__='', + def __init__(self, title='', description='', __name__='', required=True, readonly=False, constraint=None, default=None, defaultFactory=None, missing_value=__missing_value_marker): """Pass in field values as keyword parameters. @@ -247,18 +247,18 @@ def __init__(self, title=u'', description=u'', __name__='', # strings, but don't overwrite the original, we need to # preserve it (it could be a MessageID). doc_description = '\n'.join( - _DocStringHelpers.docstring_to_lines(description or u'')[:-1] + _DocStringHelpers.docstring_to_lines(description or '')[:-1] ) if title: if doc_description: - __doc__ = "%s\n\n%s" % (title, doc_description) + __doc__ = "{}\n\n{}".format(title, doc_description) else: __doc__ = title elif description: __doc__ = doc_description - super(Field, self).__init__(__name__, __doc__) + super().__init__(__name__, __doc__) self.title = title self.description = description self.required = required @@ -420,7 +420,7 @@ def getExtraDocLines(self): return lines def getDoc(self): - doc = super(Field, self).getDoc() + doc = super().getDoc() lines = _DocStringHelpers.docstring_to_lines(doc) lines += self.getExtraDocLines() lines.append('') @@ -431,7 +431,7 @@ def getDoc(self): class Container(Field): def _validate(self, value): - super(Container, self)._validate(value) + super()._validate(value) if not hasattr(value, '__contains__'): try: @@ -446,7 +446,7 @@ def _validate(self, value): class Iterable(Container): def _validate(self, value): - super(Iterable, self)._validate(value) + super()._validate(value) # See if we can get an iterator for it try: @@ -455,7 +455,7 @@ def _validate(self, value): raise NotAnIterator(value).with_field_and_value(self, value) -class Orderable(object): +class Orderable: """Values of ordered fields can be sorted. They can be restricted to a range of values. @@ -473,7 +473,7 @@ def __init__(self, min=None, max=None, default=None, **kw): self.min = None self.max = None - super(Orderable, self).__init__(**kw) + super().__init__(**kw) # Now really set min and max self.min = min @@ -484,7 +484,7 @@ def __init__(self, min=None, max=None, default=None, **kw): self.default = default def _validate(self, value): - super(Orderable, self)._validate(value) + super()._validate(value) if self.min is not None and value < self.min: raise TooSmall(value, self.min).with_field_and_value(self, value) @@ -493,7 +493,7 @@ def _validate(self, value): raise TooBig(value, self.max).with_field_and_value(self, value) -class MinMaxLen(object): +class MinMaxLen: """Expresses constraints on the length of a field. MinMaxLen is a mixin used in combination with Field. @@ -504,10 +504,10 @@ class MinMaxLen(object): def __init__(self, min_length=0, max_length=None, **kw): self.min_length = min_length self.max_length = max_length - super(MinMaxLen, self).__init__(**kw) + super().__init__(**kw) def _validate(self, value): - super(MinMaxLen, self)._validate(value) + super()._validate(value) if self.min_length is not None and len(value) < self.min_length: raise TooShort(value, self.min_length).with_field_and_value( @@ -527,7 +527,7 @@ class Text(MinMaxLen, Field): def __init__(self, *args, **kw): self.unicode_normalization = kw.pop( 'unicode_normalization', self.unicode_normalization) - super(Text, self).__init__(*args, **kw) + super().__init__(*args, **kw) def fromUnicode(self, value): """ @@ -581,7 +581,7 @@ def set(self, context, value): """ if value is self.UNCHANGED_PASSWORD: return - super(Password, self).set(context, value) + super().set(context, value) def validate(self, value): try: @@ -591,7 +591,7 @@ def validate(self, value): if value is self.UNCHANGED_PASSWORD and existing: # Allow the UNCHANGED_PASSWORD value, if a password is set already return - return super(Password, self).validate(value) + return super().validate(value) @implementer(IFromUnicode, IFromBytes) @@ -994,7 +994,7 @@ class Decimal(Number): class _ObjectsBeingValidated(threading.local): def __init__(self): - super(_ObjectsBeingValidated, self).__init__() + super().__init__() self.ids_being_validated = set() @@ -1123,16 +1123,16 @@ def __init__(self, schema=_NotGiven, **kw): self.schema = schema self.validate_invariants = kw.pop('validate_invariants', True) - super(Object, self).__init__(**kw) + super().__init__(**kw) def getExtraDocLines(self): - lines = super(Object, self).getExtraDocLines() + lines = super().getExtraDocLines() lines.append(_DocStringHelpers.make_class_field( "Must Provide", self.schema)) return lines def _validate(self, value): - super(Object, self)._validate(value) + super()._validate(value) # schema has to be provided by value if not self.schema.providedBy(value): @@ -1173,11 +1173,11 @@ def set(self, object, value): # The event subscribers are allowed to replace the object, thus we need # to replace our previous value. value = event.object - super(Object, self).set(object, value) + super().set(object, value) @implementer(IBeforeObjectAssignedEvent) -class BeforeObjectAssignedEvent(object): +class BeforeObjectAssignedEvent: """An object is going to be assigned to an attribute on another object.""" def __init__(self, object, name, context): diff --git a/src/zope/schema/_bootstrapinterfaces.py b/src/zope/schema/_bootstrapinterfaces.py index 7bf45d5..ecf3b15 100644 --- a/src/zope/schema/_bootstrapinterfaces.py +++ b/src/zope/schema/_bootstrapinterfaces.py @@ -69,7 +69,7 @@ def __eq__(self, other): __hash__ = zope.interface.Invalid.__hash__ # python3 def __repr__(self): # pragma: no cover - return '%s(%s)' % ( + return '{}({})'.format( self.__class__.__name__, ', '.join(repr(arg) for arg in self.args)) @@ -129,7 +129,7 @@ def __init__(self, value=None, bound=None, *args): """ OutOfBounds(value, bound) """ - super(OutOfBounds, self).__init__(value, bound, *args) + super().__init__(value, bound, *args) self.value = value self.bound = bound @@ -206,7 +206,7 @@ def __init__(self, errors=None, name=None, *args): .. versionchanged:: 4.7.0 Added named arguments to the constructor, and the `errors` property. """ - super(WrongContainedType, self).__init__(errors, name, *args) + super().__init__(errors, name, *args) self.errors = errors @@ -230,7 +230,7 @@ def __init__(self, errors=None, name=None, schema_errors=None, .. versionchanged:: 4.7.0 Added named arguments to the constructor. """ - super(SchemaNotCorrectlyImplemented, self).__init__( + super().__init__( errors, name, *args) self.schema_errors = schema_errors self.invariant_errors = invariant_errors @@ -254,7 +254,7 @@ def __init__(self, schema=None, value=None, *args): .. versionchanged:: 4.7.0 Added named arguments to the constructor and the `schema` property. """ - super(SchemaNotProvided, self).__init__(schema, value, *args) + super().__init__(schema, value, *args) self.schema = schema self.value = value @@ -276,7 +276,7 @@ class NotAnInterface(WrongType, SchemaNotProvided): expected_type = IInterface def __init__(self, value, name): - super(NotAnInterface, self).__init__(value, IInterface, name) + super().__init__(value, IInterface, name) class IFromUnicode(zope.interface.Interface): @@ -348,7 +348,7 @@ def validate(value): """ -class NO_VALUE(object): +class NO_VALUE: def __repr__(self): # pragma: no cover return '' diff --git a/src/zope/schema/_field.py b/src/zope/schema/_field.py index 8414220..9c6ec63 100644 --- a/src/zope/schema/_field.py +++ b/src/zope/schema/_field.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- ############################################################################## # Copyright (c) 2002 Zope Foundation and Contributors. # All Rights Reserved. @@ -141,7 +140,7 @@ classImplementsFirst(Object, IObject) -class implementer_if_needed(object): +class implementer_if_needed: # Helper to make sure we don't redundantly implement # interfaces already inherited. Doing so tends to produce # problems with the C3 order. This is used when we cannot @@ -154,8 +153,7 @@ def __call__(self, cls): ifaces_needed = [] implemented = implementedBy(cls) ifaces_needed = [ - iface - for iface in self._ifaces + iface for iface in self._ifaces if not implemented.isOrExtends(iface) ] return implementer(*ifaces_needed)(cls) @@ -208,7 +206,7 @@ class ASCII(NativeString): __doc__ = IASCII.__doc__ def _validate(self, value): - super(ASCII, self)._validate(value) + super()._validate(value) if not value: return if not max(map(ord, value)) < 128: @@ -319,7 +317,7 @@ class Float(Real): """ _type = float - _unicode_converters = (float,) + _unicode_converters = (float, ) _validation_error = InvalidFloatLiteral @@ -329,7 +327,7 @@ class Datetime(Orderable, Field): _type = datetime def __init__(self, *args, **kw): - super(Datetime, self).__init__(*args, **kw) + super().__init__(*args, **kw) @implementer(IDate) @@ -338,11 +336,10 @@ class Date(Orderable, Field): _type = date def _validate(self, value): - super(Date, self)._validate(value) + super()._validate(value) if isinstance(value, datetime): - raise WrongType( - value, self._type, self.__name__ - ).with_field_and_value(self, value) + raise WrongType(value, self._type, + self.__name__).with_field_and_value(self, value) @implementer(ITimedelta) @@ -357,22 +354,18 @@ class Time(Orderable, Field): _type = time -class MissingVocabularyError(ValidationError, - ValueError, - LookupError): +class MissingVocabularyError(ValidationError, ValueError, LookupError): """Raised when a named vocabulary cannot be found.""" # Subclasses ValueError and LookupError for backwards compatibility -class InvalidVocabularyError(ValidationError, - ValueError, - TypeError): +class InvalidVocabularyError(ValidationError, ValueError, TypeError): """Raised when the vocabulary is not an ISource.""" + # Subclasses TypeError and ValueError for backwards compatibility def __init__(self, vocabulary): - super(InvalidVocabularyError, self).__init__( - "Invalid vocabulary %r" % (vocabulary,)) + super().__init__("Invalid vocabulary {!r}".format(vocabulary)) @implementer(IChoice, IFromUnicode) @@ -395,13 +388,9 @@ def __init__(self, values=None, vocabulary=None, source=None, **kw): vocabulary = source if (values is None and vocabulary is None): - raise ValueError( - "You must specify either values or vocabulary." - ) + raise ValueError("You must specify either values or vocabulary.") if values is not None and vocabulary is not None: - raise ValueError( - "You cannot specify both values and vocabulary." - ) + raise ValueError("You cannot specify both values and vocabulary.") self.vocabulary = None self.vocabularyName = None @@ -421,7 +410,7 @@ def __init__(self, values=None, vocabulary=None, source=None, **kw): # registered vocabulary. self._init_field = (bool(self.vocabularyName) or IContextSourceBinder.providedBy(self.vocabulary)) - super(Choice, self).__init__(**kw) + super().__init__(**kw) self._init_field = False source = property(lambda self: self.vocabulary) @@ -440,9 +429,9 @@ def _resolve_vocabulary(self, value): vocabulary = vr.get(self.context, self.vocabularyName) except LookupError: raise MissingVocabularyError( - "Can't validate value without vocabulary named %r" % ( - self.vocabularyName,) - ).with_field_and_value(self, value) + "Can't validate value without vocabulary named" + f" {self.vocabularyName!r}").with_field_and_value( + self, value) if not ISource.providedBy(vocabulary): raise InvalidVocabularyError(vocabulary).with_field_and_value( @@ -452,7 +441,7 @@ def _resolve_vocabulary(self, value): def bind(self, context): """See zope.schema._bootstrapinterfaces.IField.""" - clone = super(Choice, self).bind(context) + clone = super().bind(context) # Eagerly get registered vocabulary if needed; # once that's done, just return it vocabulary = clone.vocabulary = clone._resolve_vocabulary(None) @@ -469,12 +458,12 @@ def _validate(self, value): # Pass all validations during initialization if self._init_field: return - super(Choice, self)._validate(value) + super()._validate(value) vocabulary = self._resolve_vocabulary(value) if value not in vocabulary: - raise ConstraintNotSatisfied( - value, self.__name__ - ).with_field_and_value(self, value) + raise ConstraintNotSatisfied(value, + self.__name__).with_field_and_value( + self, value) # Both of these are inherited from the parent; re-declaring them @@ -528,7 +517,7 @@ class URI(_StrippedNativeStringLine): """ def _validate(self, value): - super(URI, self)._validate(value) + super()._validate(value) if _isuri(value): return @@ -574,7 +563,7 @@ class PythonIdentifier(_StrippedNativeStringLine): """ def _validate(self, value): - super(PythonIdentifier, self)._validate(value) + super()._validate(value) if value and not _is_identifier(value): raise InvalidValue(value).with_field_and_value(self, value) @@ -614,24 +603,24 @@ def __init__(self, *args, **kw): self.max_dots = int(self.max_dots) if self.max_dots < self.min_dots: raise ValueError("max_dots cannot be less than min_dots") - super(DottedName, self).__init__(*args, **kw) + super().__init__(*args, **kw) def _validate(self, value): """ """ - super(DottedName, self)._validate(value) + super()._validate(value) if not _isdotted(value): raise InvalidDottedName(value).with_field_and_value(self, value) dots = value.count(".") if dots < self.min_dots: raise InvalidDottedName( - "too few dots; %d required" % self.min_dots, value - ).with_field_and_value(self, value) + "too few dots; %d required" % self.min_dots, + value).with_field_and_value(self, value) if self.max_dots is not None and dots > self.max_dots: raise InvalidDottedName( - "too many dots; no more than %d allowed" % self.max_dots, value - ).with_field_and_value(self, value) + "too many dots; no more than %d allowed" % self.max_dots, + value).with_field_and_value(self, value) @implementer(IId) @@ -647,7 +636,7 @@ class Id(_StrippedNativeStringLine): _invalid_exc_type = InvalidId def _validate(self, value): - super(Id, self)._validate(value) + super()._validate(value) if _isuri(value): return if _isdotted(value) and "." in value: @@ -661,12 +650,10 @@ class InterfaceField(Field): __doc__ = IInterfaceField.__doc__ def _validate(self, value): - super(InterfaceField, self)._validate(value) + super()._validate(value) if not IInterface.providedBy(value): - raise NotAnInterface( - value, - self.__name__ - ).with_field_and_value(self, value) + raise NotAnInterface(value, self.__name__).with_field_and_value( + self, value) def _validate_sequence(value_type, value, errors=None): @@ -744,7 +731,7 @@ class (or tuple of classes) that the collection itself will unique = False def __init__(self, value_type=_NotGiven, unique=_NotGiven, **kw): - super(Collection, self).__init__(**kw) + super().__init__(**kw) # whine if value_type is not a field if value_type is not _NotGiven: self.value_type = value_type @@ -757,7 +744,7 @@ def __init__(self, value_type=_NotGiven, unique=_NotGiven, **kw): def bind(self, context): """See zope.schema._bootstrapinterfaces.IField.""" - clone = super(Collection, self).bind(context) + clone = super().bind(context) # binding value_type is necessary for choices with named vocabularies, # and possibly also for other fields. if clone.value_type is not None: @@ -765,13 +752,13 @@ def bind(self, context): return clone def _validate(self, value): - super(Collection, self)._validate(value) + super()._validate(value) errors = _validate_sequence(self.value_type, value) if errors: try: - raise WrongContainedType( - errors, self.__name__ - ).with_field_and_value(self, value) + raise WrongContainedType(errors, + self.__name__).with_field_and_value( + self, value) finally: # Break cycles del errors @@ -822,7 +809,7 @@ class _AbstractSet(Collection): unique = True def __init__(self, *args, **kwargs): - super(_AbstractSet, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) if not self.unique: # set members are always unique raise TypeError( "__init__() got an unexpected keyword argument 'unique'") @@ -851,7 +838,7 @@ class Mapping(MinMaxLen, Iterable): value_type = None def __init__(self, key_type=None, value_type=None, **kw): - super(Mapping, self).__init__(**kw) + super().__init__(**kw) # whine if key_type or value_type is not a field if key_type is not None and not IField.providedBy(key_type): raise ValueError("'key_type' must be field instance.") @@ -861,7 +848,7 @@ def __init__(self, key_type=None, value_type=None, **kw): self.value_type = value_type def _validate(self, value): - super(Mapping, self)._validate(value) + super()._validate(value) errors = [] if self.value_type: errors = _validate_sequence(self.value_type, value.values(), @@ -870,16 +857,16 @@ def _validate(self, value): if errors: try: - raise WrongContainedType( - errors, self.__name__ - ).with_field_and_value(self, value) + raise WrongContainedType(errors, + self.__name__).with_field_and_value( + self, value) finally: # Break cycles del errors def bind(self, object): """See zope.schema._bootstrapinterfaces.IField.""" - clone = super(Mapping, self).bind(object) + clone = super().bind(object) # binding value_type is necessary for choices with named vocabularies, # and possibly also for other fields. if clone.key_type is not None: diff --git a/src/zope/schema/_messageid.py b/src/zope/schema/_messageid.py index 2ba1363..77c70d9 100644 --- a/src/zope/schema/_messageid.py +++ b/src/zope/schema/_messageid.py @@ -14,7 +14,7 @@ try: from zope.i18nmessageid import MessageFactory -except ImportError: +except ImportError: # Cannot be ModuleNotFoundError. _ = str else: _ = MessageFactory("zope") diff --git a/src/zope/schema/fieldproperty.py b/src/zope/schema/fieldproperty.py index 1a9c928..ae9de39 100644 --- a/src/zope/schema/fieldproperty.py +++ b/src/zope/schema/fieldproperty.py @@ -28,7 +28,7 @@ @interface.implementer(interfaces.IFieldUpdatedEvent) -class FieldUpdatedEvent(object): +class FieldUpdatedEvent: def __init__(self, obj, field, old_value, new_value): self.object = obj @@ -44,7 +44,7 @@ def __init__(self, obj, field, old_value, new_value): lambda self, new_value: setattr(self, 'object', new_value)) -class FieldProperty(object): +class FieldProperty: """Computed attributes based on schema fields Field properties provide default values, data validation and error messages @@ -112,7 +112,7 @@ class A(object): frame.f_locals[name] = FieldProperty(schema[name]) -class FieldPropertyStoredThroughField(object): +class FieldPropertyStoredThroughField: def __init__(self, field, name=None): if name is None: diff --git a/src/zope/schema/interfaces.py b/src/zope/schema/interfaces.py index 36275d7..58542db 100644 --- a/src/zope/schema/interfaces.py +++ b/src/zope/schema/interfaces.py @@ -226,14 +226,14 @@ def bind(object): title = TextLine( title=_("Title"), description=_("A short summary or label"), - default=u"", + default="", required=False, ) description = Text( title=_("Description"), description=_("A description of the field"), - default=u"", + default="", required=False, ) diff --git a/src/zope/schema/tests/states.py b/src/zope/schema/tests/states.py index c7815d5..defc432 100644 --- a/src/zope/schema/tests/states.py +++ b/src/zope/schema/tests/states.py @@ -22,70 +22,70 @@ # This table is based on information from the United States Postal Service: # http://www.usps.com/ncsc/lookups/abbreviations.html#states _states = { - 'AL': u'Alabama', - 'AK': u'Alaska', - 'AS': u'American Samoa', - 'AZ': u'Arizona', - 'AR': u'Arkansas', - 'CA': u'California', - 'CO': u'Colorado', - 'CT': u'Connecticut', - 'DE': u'Delaware', - 'DC': u'District of Columbia', - 'FM': u'Federated States of Micronesia', - 'FL': u'Florida', - 'GA': u'Georgia', - 'GU': u'Guam', - 'HI': u'Hawaii', - 'ID': u'Idaho', - 'IL': u'Illinois', - 'IN': u'Indiana', - 'IA': u'Iowa', - 'KS': u'Kansas', - 'KY': u'Kentucky', - 'LA': u'Louisiana', - 'ME': u'Maine', - 'MH': u'Marshall Islands', - 'MD': u'Maryland', - 'MA': u'Massachusetts', - 'MI': u'Michigan', - 'MN': u'Minnesota', - 'MS': u'Mississippi', - 'MO': u'Missouri', - 'MT': u'Montana', - 'NE': u'Nebraska', - 'NV': u'Nevada', - 'NH': u'New Hampshire', - 'NJ': u'New Jersey', - 'NM': u'New Mexico', - 'NY': u'New York', - 'NC': u'North Carolina', - 'ND': u'North Dakota', - 'MP': u'Northern Mariana Islands', - 'OH': u'Ohio', - 'OK': u'Oklahoma', - 'OR': u'Oregon', - 'PW': u'Palau', - 'PA': u'Pennsylvania', - 'PR': u'Puerto Rico', - 'RI': u'Rhode Island', - 'SC': u'South Carolina', - 'SD': u'South Dakota', - 'TN': u'Tennessee', - 'TX': u'Texas', - 'UT': u'Utah', - 'VT': u'Vermont', - 'VI': u'Virgin Islands', - 'VA': u'Virginia', - 'WA': u'Washington', - 'WV': u'West Virginia', - 'WI': u'Wisconsin', - 'WY': u'Wyoming', + 'AL': 'Alabama', + 'AK': 'Alaska', + 'AS': 'American Samoa', + 'AZ': 'Arizona', + 'AR': 'Arkansas', + 'CA': 'California', + 'CO': 'Colorado', + 'CT': 'Connecticut', + 'DE': 'Delaware', + 'DC': 'District of Columbia', + 'FM': 'Federated States of Micronesia', + 'FL': 'Florida', + 'GA': 'Georgia', + 'GU': 'Guam', + 'HI': 'Hawaii', + 'ID': 'Idaho', + 'IL': 'Illinois', + 'IN': 'Indiana', + 'IA': 'Iowa', + 'KS': 'Kansas', + 'KY': 'Kentucky', + 'LA': 'Louisiana', + 'ME': 'Maine', + 'MH': 'Marshall Islands', + 'MD': 'Maryland', + 'MA': 'Massachusetts', + 'MI': 'Michigan', + 'MN': 'Minnesota', + 'MS': 'Mississippi', + 'MO': 'Missouri', + 'MT': 'Montana', + 'NE': 'Nebraska', + 'NV': 'Nevada', + 'NH': 'New Hampshire', + 'NJ': 'New Jersey', + 'NM': 'New Mexico', + 'NY': 'New York', + 'NC': 'North Carolina', + 'ND': 'North Dakota', + 'MP': 'Northern Mariana Islands', + 'OH': 'Ohio', + 'OK': 'Oklahoma', + 'OR': 'Oregon', + 'PW': 'Palau', + 'PA': 'Pennsylvania', + 'PR': 'Puerto Rico', + 'RI': 'Rhode Island', + 'SC': 'South Carolina', + 'SD': 'South Dakota', + 'TN': 'Tennessee', + 'TX': 'Texas', + 'UT': 'Utah', + 'VT': 'Vermont', + 'VI': 'Virgin Islands', + 'VA': 'Virginia', + 'WA': 'Washington', + 'WV': 'West Virginia', + 'WI': 'Wisconsin', + 'WY': 'Wyoming', } @implementer(interfaces.ITerm) -class State(object): +class State: __slots__ = 'value', 'title' def __init__(self, value, title): @@ -102,7 +102,7 @@ class IStateVocabulary(interfaces.IVocabulary): @implementer(IStateVocabulary) -class StateVocabulary(object): +class StateVocabulary: __slots__ = () def __init__(self, object=None): diff --git a/src/zope/schema/tests/test__bootstrapfields.py b/src/zope/schema/tests/test__bootstrapfields.py index 1cb7630..04811ca 100644 --- a/src/zope/schema/tests/test__bootstrapfields.py +++ b/src/zope/schema/tests/test__bootstrapfields.py @@ -21,7 +21,7 @@ # pylint:disable=attribute-defined-outside-init -class InterfaceConformanceTestsMixin(object): +class InterfaceConformanceTestsMixin: def _getTargetClass(self): raise NotImplementedError @@ -112,8 +112,8 @@ def test_hash_across_unequal_instances(self): # Hash equality does not imply equal objects. # Our implementation only considers property names, # not values. That's OK, a dict still does the right thing. - field1 = self._makeOne(title=u'foo') - field2 = self._makeOne(title=u'bar') + field1 = self._makeOne(title='foo') + field2 = self._makeOne(title='bar') self.assertIsNot(field1, field2) self.assertNotEqual(field1, field2) self.assertEqual(hash(field1), hash(field2)) @@ -149,7 +149,7 @@ def test___eq___same_type_same_attrs(self): self.assertFalse(left != right) -class OrderableMissingValueMixin(object): +class OrderableMissingValueMixin: mvm_missing_value = -1 mvm_default = 0 @@ -169,7 +169,7 @@ def test_missing_value_no_min_or_max(self): self.assertEqual(self.mvm_missing_value, field.missing_value) -class OrderableTestsMixin(object): +class OrderableTestsMixin: def assertRaisesTooBig(self, field, value): from zope.schema.interfaces import TooBig @@ -221,7 +221,7 @@ def test_validate_min_and_max(self): self.assertRaisesTooBig(field, value) -class LenTestsMixin(object): +class LenTestsMixin: def assertRaisesTooLong(self, field, value): from zope.schema.interfaces import TooLong @@ -244,7 +244,7 @@ def assertRaisesTooShort(self, field, value): self.assertEqual(TooShort.TOO_SMALL, ex.violation_direction) -class WrongTypeTestsMixin(object): +class WrongTypeTestsMixin: def assertRaisesWrongType(self, field_or_meth, expected_type, *args, **kwargs): @@ -442,7 +442,7 @@ def test_getDoc(self): # value_type and key_type are automatically picked up field.value_type = self._makeOne() # Make sure the formatting works also with fields that have a title - field.key_type = self._makeOne(title=u'Key Type') + field.key_type = self._makeOne(title='Key Type') doc = field.getDoc() self.assertIn('.. rubric:: Key Type', doc) self.assertIn('.. rubric:: Value Type', doc) @@ -477,8 +477,8 @@ def test_getDoc(self): ) field = self._makeOne( - title=u'A title', - description=u"""Multiline description. + title='A title', + description="""Multiline description. Some lines have leading whitespace. @@ -513,14 +513,14 @@ def test_ctor_description_preserved(self): msg_factory = MessageFactory('zope') - description = msg_factory(u"""Multiline description. + description = msg_factory("""Multiline description. Some lines have leading whitespace. It gets stripped. """) - title = msg_factory(u'A title') + title = msg_factory('A title') field = self._makeOne(title=title, description=description) @@ -551,7 +551,7 @@ def test_ctor_description_none(self): description = None - title = u'A title' + title = 'A title' field = self._makeOne(title=title, description=description) @@ -573,10 +573,10 @@ def test_ctor_description_none(self): def test_ctor_defaults(self): field = self._makeOne() - self.assertEqual(field.__name__, u'') - self.assertEqual(field.__doc__, u'') - self.assertEqual(field.title, u'') - self.assertEqual(field.description, u'') + self.assertEqual(field.__name__, '') + self.assertEqual(field.__doc__, '') + self.assertEqual(field.title, '') + self.assertEqual(field.description, '') self.assertEqual(field.required, True) self.assertEqual(field.readonly, False) self.assertEqual(field.constraint(object()), True) @@ -587,27 +587,27 @@ def test_ctor_defaults(self): def test_ctor_w_title_wo_description(self): - field = self._makeOne(u'TITLE') - self.assertEqual(field.__name__, u'') - self.assertEqual(field.__doc__, u'TITLE') - self.assertEqual(field.title, u'TITLE') - self.assertEqual(field.description, u'') + field = self._makeOne('TITLE') + self.assertEqual(field.__name__, '') + self.assertEqual(field.__doc__, 'TITLE') + self.assertEqual(field.title, 'TITLE') + self.assertEqual(field.description, '') def test_ctor_wo_title_w_description(self): - field = self._makeOne(description=u'DESC') - self.assertEqual(field.__name__, u'') - self.assertEqual(field.__doc__, u'DESC') - self.assertEqual(field.title, u'') - self.assertEqual(field.description, u'DESC') + field = self._makeOne(description='DESC') + self.assertEqual(field.__name__, '') + self.assertEqual(field.__doc__, 'DESC') + self.assertEqual(field.title, '') + self.assertEqual(field.description, 'DESC') def test_ctor_w_both_title_and_description(self): - field = self._makeOne(u'TITLE', u'DESC', u'NAME') - self.assertEqual(field.__name__, u'NAME') - self.assertEqual(field.__doc__, u'TITLE\n\nDESC') - self.assertEqual(field.title, u'TITLE') - self.assertEqual(field.description, u'DESC') + field = self._makeOne('TITLE', 'DESC', 'NAME') + self.assertEqual(field.__name__, 'NAME') + self.assertEqual(field.__doc__, 'TITLE\n\nDESC') + self.assertEqual(field.title, 'TITLE') + self.assertEqual(field.description, 'DESC') def test_ctor_order_madness(self): klass = self._getTargetClass() @@ -822,7 +822,7 @@ def test__validate_not_collection_not_iterable(self): def test__validate_collection_but_not_iterable(self): cont = self._makeOne() - class Dummy(object): + class Dummy: def __contains__(self, item): raise AssertionError("Not called") cont._validate(Dummy()) # doesn't raise @@ -830,7 +830,7 @@ def __contains__(self, item): def test__validate_not_collection_but_iterable(self): cont = self._makeOne() - class Dummy(object): + class Dummy: def __iter__(self): return iter(()) cont._validate(Dummy()) # doesn't raise @@ -857,7 +857,7 @@ def test__validate_collection_but_not_iterable(self): from zope.schema._bootstrapinterfaces import NotAnIterator itr = self._makeOne() - class Dummy(object): + class Dummy: def __contains__(self, item): raise AssertionError("Not called") dummy = Dummy() @@ -968,18 +968,18 @@ def test_validate_w_invalid_default(self): def test_validate_not_required(self): field = self._makeOne(required=False) - field.validate(u'') - field.validate(u'abc') - field.validate(u'abc\ndef') + field.validate('') + field.validate('abc') + field.validate('abc\ndef') field.validate(None) def test_validate_required(self): from zope.schema.interfaces import RequiredMissing field = self._makeOne() - field.validate(u'') - field.validate(u'abc') - field.validate(u'abc\ndef') + field.validate('') + field.validate('abc') + field.validate('abc\ndef') self.assertRaises(RequiredMissing, field.validate, None) def test_fromUnicode_miss(self): @@ -988,7 +988,7 @@ def test_fromUnicode_miss(self): self.assertRaisesWrongType(txt.fromUnicode, txt._type, deadbeef) def test_fromUnicode_hit(self): - deadbeef = u'DEADBEEF' + deadbeef = 'DEADBEEF' txt = self._makeOne() self.assertEqual(txt.fromUnicode(deadbeef), deadbeef) @@ -1068,24 +1068,24 @@ def test_validate_wrong_types(self): def test_validate_not_required(self): field = self._makeOne(required=False) - field.validate(u'') - field.validate(u'abc') + field.validate('') + field.validate('abc') field.validate(None) def test_validate_required(self): from zope.schema.interfaces import RequiredMissing field = self._makeOne() - field.validate(u'') - field.validate(u'abc') + field.validate('') + field.validate('abc') self.assertRaises(RequiredMissing, field.validate, None) def test_constraint(self): field = self._makeOne() - self.assertEqual(field.constraint(u''), True) - self.assertEqual(field.constraint(u'abc'), True) - self.assertEqual(field.constraint(u'abc\ndef'), False) + self.assertEqual(field.constraint(''), True) + self.assertEqual(field.constraint('abc'), True) + self.assertEqual(field.constraint('abc\ndef'), False) class PasswordTests(EqualityTestsMixin, @@ -1118,16 +1118,16 @@ def test_set_normal(self): def test_validate_not_required(self): field = self._makeOne(required=False) - field.validate(u'') - field.validate(u'abc') + field.validate('') + field.validate('abc') field.validate(None) def test_validate_required(self): from zope.schema.interfaces import RequiredMissing field = self._makeOne() - field.validate(u'') - field.validate(u'abc') + field.validate('') + field.validate('abc') self.assertRaises(RequiredMissing, field.validate, None) def test_validate_unchanged_not_already_set(self): @@ -1146,9 +1146,9 @@ def test_validate_unchanged_already_set(self): def test_constraint(self): field = self._makeOne() - self.assertEqual(field.constraint(u''), True) - self.assertEqual(field.constraint(u'abc'), True) - self.assertEqual(field.constraint(u'abc\ndef'), False) + self.assertEqual(field.constraint(''), True) + self.assertEqual(field.constraint('abc'), True) + self.assertEqual(field.constraint('abc\ndef'), False) class BoolTests(EqualityTestsMixin, @@ -1200,17 +1200,17 @@ def test_set_w_bool(self): def test_fromUnicode_miss(self): txt = self._makeOne() - self.assertEqual(txt.fromUnicode(u''), False) - self.assertEqual(txt.fromUnicode(u'0'), False) - self.assertEqual(txt.fromUnicode(u'1'), False) - self.assertEqual(txt.fromUnicode(u'False'), False) - self.assertEqual(txt.fromUnicode(u'false'), False) + self.assertEqual(txt.fromUnicode(''), False) + self.assertEqual(txt.fromUnicode('0'), False) + self.assertEqual(txt.fromUnicode('1'), False) + self.assertEqual(txt.fromUnicode('False'), False) + self.assertEqual(txt.fromUnicode('false'), False) def test_fromUnicode_hit(self): txt = self._makeOne() - self.assertEqual(txt.fromUnicode(u'True'), True) - self.assertEqual(txt.fromUnicode(u'true'), True) + self.assertEqual(txt.fromUnicode('True'), True) + self.assertEqual(txt.fromUnicode('true'), True) class NumberTests(EqualityTestsMixin, @@ -1231,7 +1231,7 @@ def test_class_conforms_to_iface(self): from zope.schema._bootstrapinterfaces import IFromBytes from zope.schema._bootstrapinterfaces import IFromUnicode - super(NumberTests, self).test_class_conforms_to_iface() + super().test_class_conforms_to_iface() verifyClass(IFromUnicode, self._getTargetClass()) verifyClass(IFromBytes, self._getTargetClass()) @@ -1240,7 +1240,7 @@ def test_instance_conforms_to_iface(self): from zope.schema._bootstrapinterfaces import IFromBytes from zope.schema._bootstrapinterfaces import IFromUnicode - super(NumberTests, self).test_instance_conforms_to_iface() + super().test_instance_conforms_to_iface() verifyObject(IFromUnicode, self._makeOne()) verifyObject(IFromBytes, self._makeOne()) @@ -1321,16 +1321,16 @@ def test_validate_required(self): def test_fromUnicode_miss(self): txt = self._makeOne() - self.assertRaises(ValueError, txt.fromUnicode, u'') - self.assertRaises(ValueError, txt.fromUnicode, u'False') - self.assertRaises(ValueError, txt.fromUnicode, u'True') + self.assertRaises(ValueError, txt.fromUnicode, '') + self.assertRaises(ValueError, txt.fromUnicode, 'False') + self.assertRaises(ValueError, txt.fromUnicode, 'True') def test_fromUnicode_hit(self): txt = self._makeOne() - self.assertEqual(txt.fromUnicode(u'0'), 0) - self.assertEqual(txt.fromUnicode(u'1'), 1) - self.assertEqual(txt.fromUnicode(u'-1'), -1) + self.assertEqual(txt.fromUnicode('0'), 0) + self.assertEqual(txt.fromUnicode('1'), 1) + self.assertEqual(txt.fromUnicode('-1'), -1) class IntTests(IntegralTests): @@ -1385,23 +1385,23 @@ def test_validate_required(self): def test_fromUnicode_miss(self): from zope.schema.interfaces import ValidationError flt = self._makeOne() - self.assertRaises(ValueError, flt.fromUnicode, u'') - self.assertRaises(ValueError, flt.fromUnicode, u'abc') + self.assertRaises(ValueError, flt.fromUnicode, '') + self.assertRaises(ValueError, flt.fromUnicode, 'abc') with self.assertRaises(ValueError) as exc: - flt.fromUnicode(u'1.4G') + flt.fromUnicode('1.4G') value_error = exc.exception self.assertIs(value_error.field, flt) - self.assertEqual(value_error.value, u'1.4G') + self.assertEqual(value_error.value, '1.4G') self.assertIsInstance(value_error, ValidationError) def test_fromUnicode_hit(self): from decimal import Decimal flt = self._makeOne() - self.assertEqual(flt.fromUnicode(u'0'), Decimal('0.0')) - self.assertEqual(flt.fromUnicode(u'1.23'), Decimal('1.23')) - self.assertEqual(flt.fromUnicode(u'12345.6'), Decimal('12345.6')) + self.assertEqual(flt.fromUnicode('0'), Decimal('0.0')) + self.assertEqual(flt.fromUnicode('1.23'), Decimal('1.23')) + self.assertEqual(flt.fromUnicode('12345.6'), Decimal('12345.6')) class ObjectTests(EqualityTestsMixin, @@ -1427,7 +1427,7 @@ def _getTargetInterface(self): def _makeOneFromClass(self, cls, schema=None, *args, **kw): if schema is None: schema = self._makeSchema() - return super(ObjectTests, self)._makeOneFromClass( + return super()._makeOneFromClass( cls, schema, *args, **kw) def _makeSchema(self, **kw): @@ -1477,13 +1477,13 @@ class IPerson(Interface): IUnit['members'].value_type.schema = IPerson @implementer(IUnit) - class Unit(object): + class Unit: def __init__(self, person, person_list): self.boss = person self.members = person_list @implementer(IPerson) - class Person(object): + class Person: def __init__(self, unit): self.unit = unit @@ -1543,7 +1543,7 @@ def test__validate_w_value_providing_schema_but_missing_fields(self): schema = self._makeSchema(foo=Text(), bar=Text()) @implementer(schema) - class Broken(object): + class Broken: pass objf = self._makeOne(schema) @@ -1592,7 +1592,7 @@ def test__validate_w_value_providing_schema_but_invalid_fields(self): schema = self._makeSchema(foo=Text(), bar=Text()) @implementer(schema) - class Broken(object): + class Broken: foo = None bar = 1 @@ -1636,9 +1636,9 @@ def test__validate_w_value_providing_schema(self): ) @implementer(schema) - class OK(object): - foo = u'Foo' - bar = u'Bar' + class OK: + foo = 'Foo' + bar = 'Bar' baz = 2 objf = self._makeOne(schema) objf.validate(OK()) # doesn't raise @@ -1712,9 +1712,9 @@ def test_set_emits_IBOAE(self): ) @implementer(schema) - class OK(object): - foo = u'Foo' - bar = u'Bar' + class OK: + foo = 'Foo' + bar = 'Bar' baz = 2 log = [] subscribers.append(log.append) @@ -1743,13 +1743,13 @@ def test_set_allows_IBOAE_subscr_to_replace_value(self): ) @implementer(schema) - class OK(object): - def __init__(self, foo=u'Foo', bar=u'Bar', baz=2): + class OK: + def __init__(self, foo='Foo', bar='Bar', baz=2): self.foo = foo self.bar = bar self.baz = baz ok1 = OK() - ok2 = OK(u'Foo2', u'Bar2', 3) + ok2 = OK('Foo2', 'Bar2', 3) log = [] subscribers.append(log.append) @@ -1782,7 +1782,7 @@ class ISchema(Interface): @invariant def check_foo(self): - if self.foo == u'bar': + if self.foo == 'bar': raise Invalid("Foo is not valid") @invariant @@ -1791,8 +1791,8 @@ def check_bar(self): raise Invalid("Bar is not valid") @implementer(ISchema) - class Obj(object): - foo = u'' + class Obj: + foo = '' bar = b'' field = self._makeOne(ISchema) @@ -1801,7 +1801,7 @@ class Obj(object): # Fine at first field.validate(inst) - inst.foo = u'bar' + inst.foo = 'bar' errors = self._getErrors(field.validate, inst) self.assertEqual(len(errors), 1) self.assertEqual(errors[0].args[0], "Foo is not valid") @@ -1813,7 +1813,7 @@ class Obj(object): self.assertEqual(errors[0].args[0], "Bar is not valid") # Both invalid - inst.foo = u'bar' + inst.foo = 'bar' errors = self._getErrors(field.validate, inst) self.assertEqual(len(errors), 2) errors.sort(key=lambda i: i.args) @@ -1845,7 +1845,7 @@ class Field(self._getTargetClass()): # Actual implementation works @interface.implementer(IValueType) - class ValueType(object): + class ValueType: "The value type" field.validate(ValueType()) @@ -1867,7 +1867,7 @@ def test_bound_field_of_collection_with_choice(self): from zope.schema.vocabulary import SimpleVocabulary @implementer(IContextSourceBinder) - class EnumContext(object): + class EnumContext: def __call__(self, context): return SimpleVocabulary.fromValues(list(context)) @@ -1879,7 +1879,7 @@ class IMultipleChoice(Interface): non_field = Attribute("An attribute") @implementer(IMultipleChoice) - class Choices(object): + class Choices: def __init__(self, choices): self.choices = choices @@ -1891,10 +1891,10 @@ def __iter__(self): return iter(range(5)) class IFavorites(Interface): - fav = Object(title=u"Favorites number", schema=IMultipleChoice) + fav = Object(title="Favorites number", schema=IMultipleChoice) @implementer(IFavorites) - class Favorites(object): + class Favorites: fav = FieldProperty(IFavorites['fav']) # must not raise @@ -1949,7 +1949,7 @@ def test_getDoc(self): self.assertIn(":Must Provide: :class:", doc) -class DummyInst(object): +class DummyInst: missing_value = object() def __init__(self, exc=None): diff --git a/src/zope/schema/tests/test__field.py b/src/zope/schema/tests/test__field.py index f6509a0..664cb17 100644 --- a/src/zope/schema/tests/test__field.py +++ b/src/zope/schema/tests/test__field.py @@ -52,7 +52,7 @@ def test_validate_wrong_types(self): self.assertAllRaiseWrongType( field, field._type, - u'', + '', 1, 1.0, (), @@ -65,7 +65,7 @@ def test_validate_wrong_types(self): def test_validate_w_invalid_default(self): from zope.schema.interfaces import ValidationError - self.assertRaises(ValidationError, self._makeOne, default=u'') + self.assertRaises(ValidationError, self._makeOne, default='') def test_validate_not_required(self): @@ -86,12 +86,12 @@ def test_validate_required(self): def test_fromUnicode_miss(self): byt = self._makeOne() - self.assertRaises(UnicodeEncodeError, byt.fromUnicode, u'\x81') + self.assertRaises(UnicodeEncodeError, byt.fromUnicode, '\x81') def test_fromUnicode_hit(self): byt = self._makeOne() - self.assertEqual(byt.fromUnicode(u''), b'') - self.assertEqual(byt.fromUnicode(u'DEADBEEF'), b'DEADBEEF') + self.assertEqual(byt.fromUnicode(''), b'') + self.assertEqual(byt.fromUnicode('DEADBEEF'), b'DEADBEEF') def test_fromBytes(self): field = self._makeOne() @@ -168,7 +168,7 @@ def test_validate_wrong_types(self): self.assertAllRaiseWrongType( field, field._type, - u'', + '', 1, 1.0, (), @@ -299,16 +299,16 @@ def test_validate_required(self): def test_fromUnicode_miss(self): flt = self._makeOne() - self.assertRaises(ValueError, flt.fromUnicode, u'') - self.assertRaises(ValueError, flt.fromUnicode, u'abc') - self.assertRaises(ValueError, flt.fromUnicode, u'14.G') + self.assertRaises(ValueError, flt.fromUnicode, '') + self.assertRaises(ValueError, flt.fromUnicode, 'abc') + self.assertRaises(ValueError, flt.fromUnicode, '14.G') def test_fromUnicode_hit(self): flt = self._makeOne() - self.assertEqual(flt.fromUnicode(u'0'), 0.0) - self.assertEqual(flt.fromUnicode(u'1.23'), 1.23) - self.assertEqual(flt.fromUnicode(u'1.23e6'), 1230000.0) + self.assertEqual(flt.fromUnicode('0'), 0.0) + self.assertEqual(flt.fromUnicode('1.23'), 1.23) + self.assertEqual(flt.fromUnicode('1.23e6'), 1230000.0) class DatetimeTests(OrderableMissingValueMixin, @@ -334,7 +334,7 @@ def test_validate_wrong_types(self): self.assertAllRaiseWrongType( field, field._type, - u'', + '', 1, 1.0, (), @@ -357,9 +357,9 @@ def test_validate_required(self): MIN = datetime.datetime(2000, 10, 1) MAX = datetime.datetime(2000, 10, 4) - TOO_BIG = tuple((datetime.datetime(2000, 10, x) for x in (5, 6))) - TOO_SMALL = tuple((datetime.datetime(2000, 9, x) for x in (5, 6))) - VALID = tuple((datetime.datetime(2000, 10, x) for x in (1, 2, 3, 4))) + TOO_BIG = tuple(datetime.datetime(2000, 10, x) for x in (5, 6)) + TOO_SMALL = tuple(datetime.datetime(2000, 9, x) for x in (5, 6)) + VALID = tuple(datetime.datetime(2000, 10, x) for x in (1, 2, 3, 4)) class DateTests(OrderableMissingValueMixin, @@ -384,7 +384,7 @@ def test_validate_wrong_types(self): self.assertAllRaiseWrongType( field, field._type, - u'', + '', 1, 1.0, (), @@ -409,9 +409,9 @@ def test_validate_required(self): MIN = datetime.date(2000, 10, 1) MAX = datetime.date(2000, 10, 4) - TOO_BIG = tuple((datetime.date(2000, 10, x) for x in (5, 6))) - TOO_SMALL = tuple((datetime.date(2000, 9, x) for x in (5, 6))) - VALID = tuple((datetime.date(2000, 10, x) for x in (1, 2, 3, 4))) + TOO_BIG = tuple(datetime.date(2000, 10, x) for x in (5, 6)) + TOO_SMALL = tuple(datetime.date(2000, 9, x) for x in (5, 6)) + VALID = tuple(datetime.date(2000, 10, x) for x in (1, 2, 3, 4)) class TimedeltaTests(OrderableMissingValueMixin, @@ -484,9 +484,9 @@ def test_validate_required(self): MIN = datetime.time(12, 10, 1) MAX = datetime.time(12, 10, 4) - TOO_BIG = tuple((datetime.time(12, 10, x) for x in (5, 6))) - TOO_SMALL = tuple((datetime.time(12, 9, x) for x in (5, 6))) - VALID = tuple((datetime.time(12, 10, x) for x in (1, 2, 3, 4))) + TOO_BIG = tuple(datetime.time(12, 10, x) for x in (5, 6)) + TOO_SMALL = tuple(datetime.time(12, 9, x) for x in (5, 6)) + VALID = tuple(datetime.time(12, 10, x) for x in (1, 2, 3, 4)) class ChoiceTests(EqualityTestsMixin, @@ -511,7 +511,7 @@ def _makeOneFromClass(self, cls, *args, **kwargs): and 'source' not in kwargs): from zope.schema.vocabulary import SimpleVocabulary kwargs['vocabulary'] = SimpleVocabulary.fromValues([1, 2, 3]) - return super(ChoiceTests, self)._makeOneFromClass(cls, *args, **kwargs) + return super()._makeOneFromClass(cls, *args, **kwargs) def _getTargetInterface(self): from zope.schema.interfaces import IChoice @@ -545,7 +545,7 @@ def test_ctor_w_values(self): self.assertEqual(sorted(choose.source.by_value.keys()), [1, 2]) def test_ctor_w_unicode_non_ascii_values(self): - values = [u'K\xf6ln', u'D\xfcsseldorf', 'Bonn'] + values = ['K\xf6ln', 'D\xfcsseldorf', 'Bonn'] choose = self._makeOne(values=values) self.assertEqual(sorted(choose.vocabulary.by_value.keys()), sorted(values)) @@ -591,7 +591,7 @@ def test_bind_w_voc_not_ICSB(self): @implementer(IBaseVocabulary) @implementer(ISource) - class Vocab(object): + class Vocab: def __init__(self): pass @@ -608,7 +608,7 @@ def test_bind_w_voc_is_ICSB(self): @implementer(IContextSourceBinder) @implementer(ISource) - class Vocab(object): + class Vocab: def __init__(self, context): self.context = context @@ -629,7 +629,7 @@ def test_bind_w_voc_is_ICSB_but_not_ISource(self): from zope.schema.interfaces import IContextSourceBinder @implementer(IContextSourceBinder) - class Vocab(object): + class Vocab: def __init__(self, context): self.context = context @@ -646,22 +646,22 @@ def __call__(self, context): def test_fromUnicode_miss(self): from zope.schema.interfaces import ConstraintNotSatisfied - flt = self._makeOne(values=(u'foo', u'bar', u'baz')) - self.assertRaises(ConstraintNotSatisfied, flt.fromUnicode, u'') - self.assertRaises(ConstraintNotSatisfied, flt.fromUnicode, u'abc') + flt = self._makeOne(values=('foo', 'bar', 'baz')) + self.assertRaises(ConstraintNotSatisfied, flt.fromUnicode, '') + self.assertRaises(ConstraintNotSatisfied, flt.fromUnicode, 'abc') with self.assertRaises(ConstraintNotSatisfied) as exc: - flt.fromUnicode(u'1.4G') + flt.fromUnicode('1.4G') cns = exc.exception self.assertIs(cns.field, flt) - self.assertEqual(cns.value, u'1.4G') + self.assertEqual(cns.value, '1.4G') def test_fromUnicode_hit(self): - flt = self._makeOne(values=(u'foo', u'bar', u'baz')) - self.assertEqual(flt.fromUnicode(u'foo'), u'foo') - self.assertEqual(flt.fromUnicode(u'bar'), u'bar') - self.assertEqual(flt.fromUnicode(u'baz'), u'baz') + flt = self._makeOne(values=('foo', 'bar', 'baz')) + self.assertEqual(flt.fromUnicode('foo'), 'foo') + self.assertEqual(flt.fromUnicode('bar'), 'bar') + self.assertEqual(flt.fromUnicode('baz'), 'baz') def test__validate_int(self): from zope.schema.interfaces import ConstraintNotSatisfied @@ -676,7 +676,7 @@ def test__validate_string(self): choice = self._makeOne(values=['a', 'c']) choice._validate('a') # doesn't raise choice._validate('c') # doesn't raise - choice._validate(u'c') # doesn't raise + choice._validate('c') # doesn't raise self.assertRaises(ConstraintNotSatisfied, choice._validate, 'd') def test__validate_tuple(self): @@ -714,7 +714,7 @@ def test__validate_w_named_vocabulary_raises_LookupError(self): # we do the same thing from zope.schema.vocabulary import setVocabularyRegistry - class Reg(object): + class Reg: def get(self, *args): raise LookupError @@ -726,7 +726,7 @@ def test__validate_w_named_vocabulary_passes_context(self): context = object() choice = self._makeOne(vocabulary='vocab') - class Reg(object): + class Reg: called_with = () def get(self, *args): @@ -757,7 +757,7 @@ def test__validate_source_is_ICSB_unbound(self): from zope.schema.interfaces import IContextSourceBinder @implementer(IContextSourceBinder) - class SampleContextSourceBinder(object): + class SampleContextSourceBinder: def __call__(self, context): raise AssertionError("This is not called") @@ -772,7 +772,7 @@ def test__validate_source_is_ICSB_bound(self): from zope.schema.tests.test_vocabulary import _makeSampleVocabulary @implementer(IContextSourceBinder) - class SampleContextSourceBinder(object): + class SampleContextSourceBinder: def __call__(self, context): return _makeSampleVocabulary() @@ -849,7 +849,7 @@ def test_validate_not_a_uri(self): def test_fromUnicode_ok(self): field = self._makeOne() - self.assertEqual(field.fromUnicode(u'http://example.com/'), + self.assertEqual(field.fromUnicode('http://example.com/'), 'http://example.com/') def test_fromUnicode_invalid(self): @@ -857,10 +857,10 @@ def test_fromUnicode_invalid(self): from zope.schema.interfaces import InvalidURI field = self._makeOne() - self.assertRaises(InvalidURI, field.fromUnicode, u'') - self.assertRaises(InvalidURI, field.fromUnicode, u'abc') + self.assertRaises(InvalidURI, field.fromUnicode, '') + self.assertRaises(InvalidURI, field.fromUnicode, 'abc') self.assertRaises(ConstraintNotSatisfied, - field.fromUnicode, u'http://example.com/\nDAV:') + field.fromUnicode, 'http://example.com/\nDAV:') class PythonIdentifierTests(EqualityTestsMixin, @@ -882,16 +882,16 @@ def _getTargetInterface(self): def test_fromUnicode_empty(self): pi = self._makeOne() - self.assertEqual(pi.fromUnicode(u''), '') + self.assertEqual(pi.fromUnicode(''), '') def test_fromUnicode_normal(self): pi = self._makeOne() - self.assertEqual(pi.fromUnicode(u'normal'), 'normal') + self.assertEqual(pi.fromUnicode('normal'), 'normal') def test_fromUnicode_strips_ws(self): pi = self._makeOne() - self.assertEqual(pi.fromUnicode(u' '), '') - self.assertEqual(pi.fromUnicode(u' normal '), 'normal') + self.assertEqual(pi.fromUnicode(' '), '') + self.assertEqual(pi.fromUnicode(' normal '), 'normal') def test__validate_miss(self): from zope.schema.interfaces import InvalidValue @@ -1007,29 +1007,29 @@ def test_validate_not_a_dotted_name(self): def test_fromUnicode_dotted_name_ok(self): field = self._makeOne() - self.assertEqual(field.fromUnicode(u'dotted.name'), 'dotted.name') + self.assertEqual(field.fromUnicode('dotted.name'), 'dotted.name') # Underscores are allowed in any component - self.assertEqual(field.fromUnicode(u'dotted._name'), 'dotted._name') - self.assertEqual(field.fromUnicode(u'_leading_underscore'), + self.assertEqual(field.fromUnicode('dotted._name'), 'dotted._name') + self.assertEqual(field.fromUnicode('_leading_underscore'), '_leading_underscore') - self.assertEqual(field.fromUnicode(u'_dotted.name'), '_dotted.name') - self.assertEqual(field.fromUnicode(u'_dotted._name'), '_dotted._name') + self.assertEqual(field.fromUnicode('_dotted.name'), '_dotted.name') + self.assertEqual(field.fromUnicode('_dotted._name'), '_dotted._name') def test_fromUnicode_invalid(self): from zope.schema.interfaces import ConstraintNotSatisfied from zope.schema.interfaces import InvalidDottedName field = self._makeOne() - self.assertRaises(InvalidDottedName, field.fromUnicode, u'') + self.assertRaises(InvalidDottedName, field.fromUnicode, '') with self.assertRaises(InvalidDottedName) as exc: - field.fromUnicode(u'\u2603') + field.fromUnicode('\u2603') invalid = exc.exception self.assertIs(invalid.field, field) - self.assertEqual(invalid.value, u'\u2603') + self.assertEqual(invalid.value, '\u2603') self.assertRaises(ConstraintNotSatisfied, - field.fromUnicode, u'http://example.com/\nDAV:') + field.fromUnicode, 'http://example.com/\nDAV:') class IdTests(EqualityTestsMixin, @@ -1096,24 +1096,24 @@ def test_validate_not_a_uri(self): def test_fromUnicode_url_ok(self): field = self._makeOne() - self.assertEqual(field.fromUnicode(u'http://example.com/'), + self.assertEqual(field.fromUnicode('http://example.com/'), 'http://example.com/') def test_fromUnicode_dotted_name_ok(self): field = self._makeOne() - self.assertEqual(field.fromUnicode(u'dotted.name'), 'dotted.name') + self.assertEqual(field.fromUnicode('dotted.name'), 'dotted.name') def test_fromUnicode_invalid(self): from zope.schema.interfaces import ConstraintNotSatisfied from zope.schema.interfaces import InvalidId field = self._makeOne() - self.assertRaises(InvalidId, field.fromUnicode, u'') - self.assertRaises(InvalidId, field.fromUnicode, u'abc') - self.assertRaises(InvalidId, field.fromUnicode, u'\u2603') + self.assertRaises(InvalidId, field.fromUnicode, '') + self.assertRaises(InvalidId, field.fromUnicode, 'abc') + self.assertRaises(InvalidId, field.fromUnicode, '\u2603') self.assertRaises(ConstraintNotSatisfied, - field.fromUnicode, u'http://example.com/\nDAV:') + field.fromUnicode, 'http://example.com/\nDAV:') class InterfaceFieldTests(EqualityTestsMixin, @@ -1137,7 +1137,7 @@ def test_validate_wrong_types(self): self.assertAllRaiseWrongType( field, IInterface, - u'', + '', b'', 1, 1.0, @@ -1220,7 +1220,7 @@ class Field(self._getTargetClass()): # Actual implementation works @interface.implementer(IValueType) - class ValueType(object): + class ValueType: "The value type" field.validate(self._makeCollection([ValueType()])) @@ -1238,7 +1238,7 @@ def test_ctor_explicit(self): self.assertEqual(absc.unique, True) def test_ctor_w_non_field_value_type(self): - class NotAField(object): + class NotAField: pass self.assertRaises(ValueError, self._makeOne, NotAField) @@ -1286,12 +1286,12 @@ def test__validate_miss_uniqueness(self): text = Text() absc = self._makeOne(text, True) with self.assertRaises((NotUnique, WrongType)) as exc: - absc.validate([u'a', u'a']) + absc.validate(['a', 'a']) not_uniq = exc.exception self.assertIs(not_uniq.field, absc) self.assertEqual(not_uniq.value, - [u'a', u'a']) + ['a', 'a']) def test_validate_min_length(self): field = self._makeOne(min_length=2) @@ -1412,22 +1412,22 @@ def _getTargetInterface(self): def test_mutable_sequence(self): from zope.schema.interfaces import WrongType with self.assertRaises(WrongType): - super(TupleTests, self).test_mutable_sequence() + super().test_mutable_sequence() def test_sequence(self): from zope.schema.interfaces import WrongType with self.assertRaises(WrongType): - super(TupleTests, self).test_sequence() + super().test_sequence() def test_validate_wrong_types(self): field = self._makeOne() self.assertAllRaiseWrongType( field, field._type, - u'', + '', b'', []) - super(TupleTests, self).test_validate_wrong_types() + super().test_validate_wrong_types() class MutableSequenceTests(SequenceTests): @@ -1445,15 +1445,15 @@ def test_validate_wrong_types(self): self.assertAllRaiseWrongType( field, field._type, - u'', + '', b'', ()) - super(MutableSequenceTests, self).test_validate_wrong_types() + super().test_validate_wrong_types() def test_sequence(self): from zope.schema.interfaces import WrongType with self.assertRaises(WrongType): - super(MutableSequenceTests, self).test_sequence() + super().test_sequence() class ListTests(MutableSequenceTests): @@ -1469,7 +1469,7 @@ def _getTargetInterface(self): def test_mutable_sequence(self): from zope.schema.interfaces import WrongType with self.assertRaises(WrongType): - super(ListTests, self).test_mutable_sequence() + super().test_mutable_sequence() class SetTests(WrongTypeTestsMixin, @@ -1497,7 +1497,7 @@ def test_validate_wrong_types(self): self.assertAllRaiseWrongType( field, field._type, - u'', + '', b'', 1, 1.0, @@ -1546,7 +1546,7 @@ def test_validate_wrong_types(self): self.assertAllRaiseWrongType( field, field._type, - u'', + '', b'', 1, 1.0, @@ -1699,7 +1699,7 @@ def _getTargetInterface(self): def test_mapping(self): from zope.schema.interfaces import WrongType with self.assertRaises(WrongType): - super(MutableMappingTests, self).test_mapping() + super().test_mapping() class DictTests(MutableMappingTests): @@ -1715,7 +1715,7 @@ def _getTargetInterface(self): def test_mutable_mapping(self): from zope.schema.interfaces import WrongType with self.assertRaises(WrongType): - super(DictTests, self).test_mutable_mapping() + super().test_mutable_mapping() class NativeStringTests(EqualityTestsMixin, @@ -1742,9 +1742,9 @@ def test_fromBytes(self): def test_fromUnicode(self): field = self._makeOne() - self.assertIsInstance(field.fromUnicode(u''), str) - self.assertEqual(field.fromUnicode(u''), '') - self.assertEqual(field.fromUnicode(u'DEADBEEF'), 'DEADBEEF') + self.assertIsInstance(field.fromUnicode(''), str) + self.assertEqual(field.fromUnicode(''), '') + self.assertEqual(field.fromUnicode('DEADBEEF'), 'DEADBEEF') class NativeStringLineTests(EqualityTestsMixin, @@ -1771,9 +1771,9 @@ def test_fromBytes(self): def test_fromUnicode(self): field = self._makeOne() - self.assertIsInstance(field.fromUnicode(u''), str) - self.assertEqual(field.fromUnicode(u''), '') - self.assertEqual(field.fromUnicode(u'DEADBEEF'), 'DEADBEEF') + self.assertIsInstance(field.fromUnicode(''), str) + self.assertEqual(field.fromUnicode(''), '') + self.assertEqual(field.fromUnicode('DEADBEEF'), 'DEADBEEF') class StrippedNativeStringLineTests(NativeStringLineTests): @@ -1785,7 +1785,7 @@ def _getTargetClass(self): def test_strips(self): field = self._makeOne() self.assertEqual(field.fromBytes(b' '), '') - self.assertEqual(field.fromUnicode(u' '), '') + self.assertEqual(field.fromUnicode(' '), '') def test_iface_is_first_in_sro(self): self.skipTest("Not applicable; we inherit implementation but have no " @@ -1798,7 +1798,7 @@ def _makeSampleVocabulary(): from zope.schema.interfaces import IVocabulary @implementer(IVocabulary) - class SampleVocabulary(object): + class SampleVocabulary: def __iter__(self): raise AssertionError("Not implemented") diff --git a/src/zope/schema/tests/test_accessors.py b/src/zope/schema/tests/test_accessors.py index 531fe47..f141765 100644 --- a/src/zope/schema/tests/test_accessors.py +++ b/src/zope/schema/tests/test_accessors.py @@ -34,7 +34,7 @@ def _makeOne(self, field=None): def test_ctor_not_created_inside_interface(self): from zope.schema import Text - field = Text(title=u'Hmm') + field = Text(title='Hmm') wrapped = self._makeOne(field) self.assertTrue(wrapped.field is field) self.assertEqual(wrapped.__name__, '') # __name__ set when in iface @@ -45,7 +45,7 @@ def test_ctor_created_inside_interface(self): from zope.schema import Text - field = Text(title=u'Hmm') + field = Text(title='Hmm') class IFoo(Interface): getter = self._makeOne(field) @@ -120,7 +120,7 @@ class IFoo(Interface): getter = self._makeOne() getter = IFoo['getter'] - class Foo(object): + class Foo: pass self.assertRaises(AttributeError, getter.get, Foo()) @@ -131,7 +131,7 @@ class IFoo(Interface): getter = self._makeOne() getter = IFoo['getter'] - class Foo(object): + class Foo: def getter(self): return '123' self.assertEqual(getter.get(Foo()), '123') @@ -143,7 +143,7 @@ class IFoo(Interface): getter = self._makeOne() getter = IFoo['getter'] - class Foo(object): + class Foo: pass self.assertEqual(getter.query(Foo()), None) @@ -154,7 +154,7 @@ class IFoo(Interface): getter = self._makeOne() getter = IFoo['getter'] - class Foo(object): + class Foo: pass self.assertEqual(getter.query(Foo(), 234), 234) @@ -165,7 +165,7 @@ class IFoo(Interface): getter = self._makeOne() getter = IFoo['getter'] - class Foo(object): + class Foo: def getter(self): return '123' @@ -181,7 +181,7 @@ class IFoo(Interface): getter = self._makeOne(field) getter = IFoo['getter'] - class Foo(object): + class Foo: def getter(self): raise AssertionError("Not called") self.assertRaises(TypeError, getter.set, Foo(), '456') @@ -193,7 +193,7 @@ class IFoo(Interface): getter = self._makeOne() getter = IFoo['getter'] - class Foo(object): + class Foo: def getter(self): raise AssertionError("Not called") @@ -208,7 +208,7 @@ class IFoo(Interface): getter = IFoo['getter'] _called_with = [] - class Writer(object): + class Writer: pass writer = Writer() @@ -217,7 +217,7 @@ class Writer(object): # pylint:enable=attribute-defined-outside-init getter.writer = writer - class Foo(object): + class Foo: def setMe(self, value): _called_with.append(value) @@ -253,7 +253,7 @@ def _makeOne(self, field=None): def test_ctor_not_created_inside_interface(self): from zope.schema import Text - field = Text(title=u'Hmm') + field = Text(title='Hmm') wrapped = self._makeOne(field) self.assertTrue(wrapped.field is field) self.assertEqual(wrapped.__name__, '') # __name__ set when in iface @@ -264,7 +264,7 @@ def test_ctor_created_inside_interface(self): from zope.schema import Text - field = Text(title=u'Hmm') + field = Text(title='Hmm') class IFoo(Interface): setter = self._makeOne(field) @@ -298,7 +298,7 @@ def test_w_only_read_accessor(self): from zope.schema import Text - field = Text(title=u'Hmm', readonly=True) + field = Text(title='Hmm', readonly=True) class IFoo(Interface): getter, = self._callFUT(field) @@ -319,7 +319,7 @@ def test_w_read_and_write_accessors(self): from zope.schema import Text - field = Text(title=u'Hmm') + field = Text(title='Hmm') class IFoo(Interface): getter, setter = self._callFUT(field) diff --git a/src/zope/schema/tests/test_equality.py b/src/zope/schema/tests/test_equality.py index f8f0dd5..0983861 100644 --- a/src/zope/schema/tests/test_equality.py +++ b/src/zope/schema/tests/test_equality.py @@ -24,7 +24,7 @@ def test_equality(self): from zope.schema import Text def _makeOne(cls): - return cls(title=u"Foo", description=u"Bar") + return cls(title="Foo", description="Bar") for cls in (Int, Text): self.assertEqual(_makeOne(cls), _makeOne(cls)) diff --git a/src/zope/schema/tests/test_fieldproperty.py b/src/zope/schema/tests/test_fieldproperty.py index 492d258..e410fdb 100644 --- a/src/zope/schema/tests/test_fieldproperty.py +++ b/src/zope/schema/tests/test_fieldproperty.py @@ -28,12 +28,12 @@ def _makeOne(self, field=None, name=None): return self._getTargetClass()(field, name) -class _Integration(object): +class _Integration: def _makeImplementer(self): schema = _getSchema() - class _Implementer(object): + class _Implementer: title = self._makeOne(schema['title']) weight = self._makeOne(schema['weight']) code = self._makeOne(schema['code']) @@ -45,7 +45,7 @@ def test_basic(self): from zope.schema.interfaces import ValidationError c = self._makeImplementer() - self.assertEqual(c.title, u'say something') + self.assertEqual(c.title, 'say something') self.assertEqual(c.weight, None) self.assertEqual(c.code, b'xxxxxx') self.assertRaises(ValidationError, setattr, c, 'title', b'foo') @@ -54,13 +54,13 @@ def test_basic(self): self.assertRaises(ValidationError, setattr, c, 'weight', 2) self.assertRaises(ValidationError, setattr, c, 'code', -1) self.assertRaises(ValidationError, setattr, c, 'code', b'xxxx') - self.assertRaises(ValidationError, setattr, c, 'code', u'xxxxxx') + self.assertRaises(ValidationError, setattr, c, 'code', 'xxxxxx') - c.title = u'c is good' + c.title = 'c is good' c.weight = 10.0 c.code = b'abcdef' - self.assertEqual(c.title, u'c is good') + self.assertEqual(c.title, 'c is good') self.assertEqual(c.weight, 10) self.assertEqual(c.code, b'abcdef') @@ -96,8 +96,8 @@ def test_ctor_explicit(self): field = Text( __name__='testing', - description=u'DESCRIPTION', - default=u'DEFAULT', + description='DESCRIPTION', + default='DEFAULT', readonly=True, required=True, ) @@ -115,34 +115,34 @@ def test_query_value_with_default(self): field = Text( __name__='testing', - description=u'DESCRIPTION', - default=u'DEFAULT', + description='DESCRIPTION', + default='DEFAULT', readonly=True, required=True, ) prop = self._makeOne(field=field) - class Foo(object): + class Foo: testing = prop foo = Foo() - self.assertEqual(prop.queryValue(foo, 'test'), u'DEFAULT') - foo.testing = u'NO' - self.assertEqual(prop.queryValue(foo, 'test'), u'NO') + self.assertEqual(prop.queryValue(foo, 'test'), 'DEFAULT') + foo.testing = 'NO' + self.assertEqual(prop.queryValue(foo, 'test'), 'NO') def test_query_value_without_default(self): from zope.schema import Text field = Text( __name__='testing', - description=u'DESCRIPTION', + description='DESCRIPTION', readonly=True, required=True, ) prop = self._makeOne(field=field) - class Foo(object): + class Foo: testing = prop foo = Foo() # field initialize its default to None if it hasn't any default @@ -152,18 +152,18 @@ class Foo(object): def test___get___from_class(self): prop = self._makeOne() - class Foo(object): + class Foo: testing = prop self.assertTrue(Foo.testing is prop) def test___get___from_instance_pseudo_field_wo_default(self): - class _Faux(object): + class _Faux: def bind(self, other): return self prop = self._makeOne(_Faux(), 'nonesuch') - class Foo(object): + class Foo: testing = prop foo = Foo() @@ -172,7 +172,7 @@ class Foo(object): def test___get___from_instance_miss_uses_field_default(self): prop = self._makeOne() - class Foo(object): + class Foo: testing = prop foo = Foo() @@ -181,7 +181,7 @@ class Foo(object): def test___get___from_instance_hit(self): prop = self._makeOne(name='other') - class Foo(object): + class Foo: testing = prop foo = Foo() @@ -189,7 +189,7 @@ class Foo(object): self.assertEqual(foo.testing, '123') def test___get___from_instance_hit_after_bind(self): - class _Faux(object): + class _Faux: default = '456' def bind(self, other): @@ -197,14 +197,14 @@ def bind(self, other): prop = self._makeOne(_Faux(), 'testing') - class Foo(object): + class Foo: testing = prop foo = Foo() self.assertEqual(foo.testing, '456') def test___set___not_readonly(self): - class _Faux(object): + class _Faux: readonly = False default = '456' @@ -216,7 +216,7 @@ def bind(self, other): faux.validate = _validated.append prop = self._makeOne(faux, 'testing') - class Foo(object): + class Foo: testing = prop foo = Foo() @@ -224,7 +224,7 @@ class Foo(object): self.assertEqual(foo.__dict__['testing'], '123') def test___set___w_readonly_not_already_set(self): - class _Faux(object): + class _Faux: readonly = True default = '456' @@ -236,7 +236,7 @@ def bind(self, other): faux.validate = _validated.append prop = self._makeOne(faux, 'testing') - class Foo(object): + class Foo: testing = prop foo = Foo() @@ -245,7 +245,7 @@ class Foo(object): self.assertEqual(_validated, ['123']) def test___set___w_readonly_and_already_set(self): - class _Faux(object): + class _Faux: readonly = True default = '456' @@ -257,7 +257,7 @@ def bind(self, other): faux.validate = _validated.append prop = self._makeOne(faux, 'testing') - class Foo(object): + class Foo: testing = prop foo = Foo() @@ -277,8 +277,8 @@ def test_field_event(self): self.assertEqual(log, []) field = Text( __name__='testing', - description=u'DESCRIPTION', - default=u'DEFAULT', + description='DESCRIPTION', + default='DEFAULT', readonly=True, required=True, ) @@ -309,28 +309,28 @@ def test_field_event_update(self): from zope.schema.interfaces import IFieldUpdatedEvent field = Text( __name__='testing', - description=u'DESCRIPTION', - default=u'DEFAULT', + description='DESCRIPTION', + default='DEFAULT', required=True, ) prop = self._makeOne(field=field) - class Foo(object): + class Foo: testing = prop foo = Foo() log = [] subscribers.append(log.append) - foo.testing = u'Bar' - foo.testing = u'Foo' + foo.testing = 'Bar' + foo.testing = 'Foo' self.assertEqual(len(log), 2) event = log[1] self.assertTrue(isinstance(event, FieldUpdatedEvent)) self.assertTrue(verifyObject(IFieldUpdatedEvent, event)) self.assertEqual(event.object, foo) self.assertEqual(event.field, field) - self.assertEqual(event.old_value, u'Bar') - self.assertEqual(event.new_value, u'Foo') + self.assertEqual(event.old_value, 'Bar') + self.assertEqual(event.new_value, 'Foo') # BBB, but test this works. self.assertEqual(event.inst, foo) marker = object() @@ -377,8 +377,8 @@ def test_ctor_explicit(self): field = Text( __name__='testing', - description=u'DESCRIPTION', - default=u'DEFAULT', + description='DESCRIPTION', + default='DEFAULT', readonly=True, required=True, ) @@ -397,7 +397,7 @@ def test_ctor_explicit(self): def test_setValue(self): from zope.schema import Text - class Foo(object): + class Foo: pass foo = Foo() @@ -410,7 +410,7 @@ def test_getValue_miss(self): from zope.schema import Text from zope.schema.fieldproperty import _marker - class Foo(object): + class Foo: pass foo = Foo() @@ -422,7 +422,7 @@ class Foo(object): def test_getValue_hit(self): from zope.schema import Text - class Foo(object): + class Foo: pass foo = Foo() @@ -435,7 +435,7 @@ class Foo(object): def test_queryValue_miss(self): from zope.schema import Text - class Foo(object): + class Foo: pass foo = Foo() @@ -448,7 +448,7 @@ class Foo(object): def test_queryValue_hit(self): from zope.schema import Text - class Foo(object): + class Foo: pass foo = Foo() @@ -462,13 +462,13 @@ class Foo(object): def test___get___from_class(self): prop = self._makeOne() - class Foo(object): + class Foo: testing = prop self.assertTrue(Foo.testing is prop) def test___get___from_instance_pseudo_field_wo_default(self): - class _Faux(object): + class _Faux: __name__ = 'Faux' def bind(self, other): @@ -479,7 +479,7 @@ def query(self, inst, default): prop = self._makeOne(_Faux(), 'nonesuch') - class Foo(object): + class Foo: testing = prop foo = Foo() @@ -488,7 +488,7 @@ class Foo(object): def test___get___from_instance_miss_uses_field_default(self): prop = self._makeOne() - class Foo(object): + class Foo: testing = prop foo = Foo() @@ -499,7 +499,7 @@ def test___get___from_instance_hit(self): field = Text(__name__='testing') prop = self._makeOne(field, name='other') - class Foo(object): + class Foo: testing = prop foo = Foo() @@ -508,7 +508,7 @@ class Foo(object): self.assertEqual(foo.testing, '456') def test___set___not_readonly(self): - class _Faux(object): + class _Faux: __name__ = 'Faux' readonly = False default = '456' @@ -527,7 +527,7 @@ def set(self, inst, value): faux.validate = _validated.append prop = self._makeOne(faux, 'testing') - class Foo(object): + class Foo: testing = prop foo = Foo() @@ -536,7 +536,7 @@ class Foo(object): self.assertEqual(_validated, ['123']) def test___set___w_readonly_not_already_set(self): - class _Faux(object): + class _Faux: __name__ = 'Faux' readonly = True default = '456' @@ -557,7 +557,7 @@ def set(self, inst, value): faux.validate = _validated.append prop = self._makeOne(faux, 'testing') - class Foo(object): + class Foo: testing = prop foo = Foo() @@ -566,7 +566,7 @@ class Foo(object): self.assertEqual(_validated, ['123']) def test___set___w_readonly_and_already_set(self): - class _Faux(object): + class _Faux: __name__ = 'Faux' readonly = True default = '456' @@ -582,7 +582,7 @@ def query(self, inst, default): faux.validate = _validated.append prop = self._makeOne(faux, 'testing') - class Foo(object): + class Foo: testing = prop foo = Foo() @@ -596,27 +596,27 @@ def test_field_event_update(self): from zope.schema.fieldproperty import FieldUpdatedEvent field = Text( __name__='testing', - description=u'DESCRIPTION', - default=u'DEFAULT', + description='DESCRIPTION', + default='DEFAULT', required=True, ) prop = self._makeOne(field=field) - class Foo(object): + class Foo: testing = prop foo = Foo() log = [] subscribers.append(log.append) - foo.testing = u'Bar' - foo.testing = u'Foo' + foo.testing = 'Bar' + foo.testing = 'Foo' self.assertEqual(len(log), 2) event = log[1] self.assertTrue(isinstance(event, FieldUpdatedEvent)) self.assertEqual(event.object, foo) self.assertEqual(event.field, field) - self.assertEqual(event.old_value, u'Bar') - self.assertEqual(event.new_value, u'Foo') + self.assertEqual(event.old_value, 'Bar') + self.assertEqual(event.new_value, 'Foo') def test_field_event(self): # fieldproperties are everywhere including in field themselfs @@ -630,8 +630,8 @@ def test_field_event(self): self.assertEqual(log, []) field = Text( __name__='testing', - description=u'DESCRIPTION', - default=u'DEFAULT', + description='DESCRIPTION', + default='DEFAULT', readonly=True, required=True, ) @@ -656,11 +656,11 @@ def _getSchema(): from zope.schema import Text class Schema(Interface): - title = Text(description=u"Short summary", - default=u'say something') + title = Text(description="Short summary", + default='say something') weight = Float(min=0.0) code = Bytes(min_length=6, max_length=6, default=b'xxxxxx') - date = Float(title=u'Date', readonly=True) + date = Float(title='Date', readonly=True) return Schema @@ -673,7 +673,7 @@ def test_creates_fieldproperties_on_class(self): from zope.schema.fieldproperty import createFieldProperties schema = _getSchema() - class Dummy(object): + class Dummy: createFieldProperties(schema) self.assertTrue(isinstance(Dummy.title, FieldProperty)) @@ -683,7 +683,7 @@ class Dummy(object): def test_fields_in_omit_are_not_created_on_class(self): from zope.schema.fieldproperty import createFieldProperties - class Dummy(object): + class Dummy: createFieldProperties(_getSchema(), omit=['date', 'code']) self.assertFalse(hasattr(Dummy, 'date')) diff --git a/src/zope/schema/tests/test_interfaces.py b/src/zope/schema/tests/test_interfaces.py index 249776f..184e401 100644 --- a/src/zope/schema/tests/test_interfaces.py +++ b/src/zope/schema/tests/test_interfaces.py @@ -13,7 +13,7 @@ def test_non_fields(self): self.assertEqual(self._callFUT(0.0), False) self.assertEqual(self._callFUT(True), False) self.assertEqual(self._callFUT(b''), False) - self.assertEqual(self._callFUT(u''), False) + self.assertEqual(self._callFUT(''), False) self.assertEqual(self._callFUT(()), False) self.assertEqual(self._callFUT([]), False) self.assertEqual(self._callFUT({}), False) @@ -38,7 +38,7 @@ def test_w_explicitly_provided(self): from zope.schema.interfaces import IField - class Foo(object): + class Foo: pass foo = Foo() diff --git a/src/zope/schema/tests/test_schema.py b/src/zope/schema/tests/test_schema.py index 6172abe..04c5acd 100644 --- a/src/zope/schema/tests/test_schema.py +++ b/src/zope/schema/tests/test_schema.py @@ -24,18 +24,18 @@ def _makeSchema(): class ISchemaTest(Interface): title = Bytes( - title=u"Title", - description=u"Title", + title="Title", + description="Title", default=b"", required=True) description = Bytes( - title=u"Description", - description=u"Description", + title="Description", + description="Description", default=b"", required=True) spam = Bytes( - title=u"Spam", - description=u"Spam", + title="Spam", + description="Spam", default=b"", required=True) return ISchemaTest @@ -49,8 +49,8 @@ def _makeDerivedSchema(): class ISchemaTestSubclass(base): foo = Bytes( - title=u'Foo', - description=u'Fooness', + title='Foo', + description='Fooness', default=b"", required=False) return ISchemaTestSubclass @@ -231,9 +231,9 @@ class IWithFields(Interface): foo = Text() bar = Text() - class Obj(object): - foo = u'Foo' - bar = u'Bar' + class Obj: + foo = 'Foo' + bar = 'Bar' errors = self._callFUT(IWithFields, Obj()) self.assertEqual(len(errors), 0) @@ -264,7 +264,7 @@ def test_schema_with_invalid_field(self): class IWithMinium(Interface): value = Int(required=True, min=0) - class Obj(object): + class Obj: value = -1 errors = self._callFUT(IWithMinium, Obj()) diff --git a/src/zope/schema/tests/test_states.py b/src/zope/schema/tests/test_states.py index bc1d7a5..29f5e01 100644 --- a/src/zope/schema/tests/test_states.py +++ b/src/zope/schema/tests/test_states.py @@ -39,25 +39,25 @@ def _makeSchema(self): class IBirthInfo(Interface): state1 = Choice( - title=u'State of Birth', - description=u'The state in which you were born.', + title='State of Birth', + description='The state in which you were born.', vocabulary="states", default="AL", ) state2 = Choice( - title=u'State of Birth', - description=u'The state in which you were born.', + title='State of Birth', + description='The state in which you were born.', vocabulary="states", default="AL", ) state3 = Choice( - title=u'Favorite State', - description=u'The state you like the most.', + title='Favorite State', + description='The state you like the most.', vocabulary=StateVocabulary(), ) state4 = Choice( - title=u"Name", - description=u"The name of your new state", + title="Name", + description="The name of your new state", vocabulary="states", ) return IBirthInfo diff --git a/src/zope/schema/tests/test_vocabulary.py b/src/zope/schema/tests/test_vocabulary.py index 24383df..a5d953a 100644 --- a/src/zope/schema/tests/test_vocabulary.py +++ b/src/zope/schema/tests/test_vocabulary.py @@ -69,8 +69,8 @@ def test_bytes_non_ascii_value(self): def test_unicode_non_ascii_value(self): from zope.schema.interfaces import ITitledTokenizedTerm - term = self._makeOne(u'Snowman \u2603') - self.assertEqual(term.value, u'Snowman \u2603') + term = self._makeOne('Snowman \u2603') + self.assertEqual(term.value, 'Snowman \u2603') self.assertEqual(term.token, 'Snowman \\u2603') self.assertFalse(ITitledTokenizedTerm.providedBy(term)) @@ -259,7 +259,7 @@ def test_nonunique_token_messages(self): self.assertEqual(str(e), "term values must be unique: 'one'") def test_overriding_createTerm(self): - class MyTerm(object): + class MyTerm: def __init__(self, value): self.value = value self.token = repr(value) @@ -718,11 +718,11 @@ def _makeSampleVocabulary(): from zope.schema.interfaces import IVocabulary - class SampleTerm(object): + class SampleTerm: pass @implementer(IVocabulary) - class SampleVocabulary(object): + class SampleVocabulary: def __iter__(self): raise AssertionError("Not called") diff --git a/src/zope/schema/vocabulary.py b/src/zope/schema/vocabulary.py index 7c27411..eb26612 100644 --- a/src/zope/schema/vocabulary.py +++ b/src/zope/schema/vocabulary.py @@ -31,7 +31,7 @@ @implementer(ITokenizedTerm) -class SimpleTerm(object): +class SimpleTerm: """ Simple tokenized term used by SimpleVocabulary. @@ -74,11 +74,8 @@ def __eq__(self, other): if not isinstance(other, SimpleTerm): return False - return ( - self.value == other.value - and self.token == other.token - and self.title == other.title - ) + return (self.value == other.value and self.token == other.token + and self.title == other.title) def __ne__(self, other): return not self.__eq__(other) @@ -88,7 +85,7 @@ def __hash__(self): @implementer(IVocabularyTokenized) -class SimpleVocabulary(object): +class SimpleVocabulary: """ Vocabulary that works from a sequence of terms. @@ -118,11 +115,11 @@ def __init__(self, terms, *interfaces, **kwargs): for term in self._terms: if not swallow_dupes: if term.value in self.by_value: - raise ValueError( - 'term values must be unique: %s' % repr(term.value)) + raise ValueError('term values must be unique: %s' % + repr(term.value)) if term.token in self.by_token: - raise ValueError( - 'term tokens must be unique: %s' % repr(term.token)) + raise ValueError('term tokens must be unique: %s' % + repr(term.token)) self.by_value[term.value] = term self.by_token[term.token] = term if interfaces: @@ -145,8 +142,7 @@ def fromItems(cls, items, *interfaces): .. versionchanged:: 4.6.0 Allow passing in triples to set item titles. """ - terms = [cls.createTerm(item[1], item[0], *item[2:]) - for item in items] + terms = [cls.createTerm(item[1], item[0], *item[2:]) for item in items] return cls(terms, *interfaces) @classmethod @@ -211,10 +207,8 @@ def __eq__(self, other): if not isinstance(other, SimpleVocabulary): return False - return ( - self._terms == other._terms - and providedBy(self) == providedBy(other) - ) + return (self._terms == other._terms + and providedBy(self) == providedBy(other)) def __ne__(self, other): return not self.__eq__(other) @@ -237,7 +231,7 @@ def _createTermTree(ttree, dict_): @implementer(ITreeVocabulary) -class TreeVocabulary(object): +class TreeVocabulary: """ Vocabulary that relies on a tree (i.e nested) structure. """ # The default implementation uses a dict to create the tree structure. This @@ -366,19 +360,17 @@ def _populateIndexes(self, tree): token = getattr(term, 'token') if value in self.term_by_value: - raise ValueError( - "Term values must be unique: '%s'" % value) + raise ValueError("Term values must be unique: '%s'" % value) if token in self.term_by_token: - raise ValueError( - "Term tokens must be unique: '%s'" % token) + raise ValueError("Term tokens must be unique: '%s'" % token) self.term_by_value[value] = term self.term_by_token[token] = term if value not in self.path_by_value: # pragma: no branch - self.path_by_value[value] = self._getPathToTreeNode(self, - value) + self.path_by_value[value] = self._getPathToTreeNode( + self, value) self._populateIndexes(tree[term]) def getTerm(self, value): @@ -428,16 +420,17 @@ class VocabularyRegistryError(LookupError): .. seealso:: `VocabularyRegistry` """ + def __init__(self, name): self.name = name - super(VocabularyRegistryError, self).__init__(str(self)) + super().__init__(str(self)) def __str__(self): return "unknown vocabulary: %r" % self.name @implementer(IVocabularyRegistry) -class VocabularyRegistry(object): +class VocabularyRegistry: """ Default implementation of :class:`zope.schema.interfaces.IVocabularyRegistry`. @@ -454,7 +447,7 @@ class VocabularyRegistry(object): `zope.vocabularyregistry `_. """ - __slots__ = ('_map',) + __slots__ = ('_map', ) def __init__(self): self._map = {} @@ -500,7 +493,7 @@ def _clear(): try: from zope.testing.cleanup import addCleanUp -except ImportError: # pragma: no cover +except ModuleNotFoundError: # pragma: no cover # don't have that part of Zope pass else: # pragma: no cover