zope.schema-6.2.0/0000755000100100000240000000000014133212652013575 5ustar macstaff00000000000000zope.schema-6.2.0/CHANGES.rst0000644000100100000240000005103414133212652015402 0ustar macstaff00000000000000========= Changes ========= 6.2.0 (2021-10-18) ================== - Add support for Python 3.10. 6.1.1 (2021-10-13) ================== - Fix incompatibility introduced in 6.1.0: The `Bool` field constructor implicitly set required to False if not given. While this is the desired behavior in most common cases, it broke special cases. See `issue 104 `_ (scroll down, it is around the *reopen*). 6.1.0 (2021-02-09) ================== - Fix ``IField.required`` to not be required by default. See `issue 104 `_. 6.0.1 (2021-01-25) ================== - Bring branch coverage to 100%. - Add support for Python 3.9. - Fix FieldUpdateEvent implementation by having an ``object`` attribute as the ``IFieldUpdatedEvent`` interfaces claims there should be. 6.0.0 (2020-03-21) ================== - Require zope.interface 5.0. - Ensure the resolution orders of all fields are consistent and make sense. In particular, ``Bool`` fields now correctly implement ``IBool`` before ``IFromUnicode``. See `issue 80 `_. - Add support for Python 3.8. - Drop support for Python 3.4. 5.0.1 (2020-03-06) ================== - Fix: add ``Text.unicode_normalization = 'NFC'`` as default, because some are persisting schema fields. Setting that attribute only in ``__init__`` breaks loading old objects. 5.0 (2020-03-06) ================ - Set ``IDecimal`` attributes ``min``, ``max`` and ``default`` as ``Decimal`` type instead of ``Number``. See `issue 88 `_. - Enable unicode normalization for ``Text`` fields. The default is NFC normalization. Valid forms are 'NFC', 'NFKC', 'NFD', and 'NFKD'. To disable normalization, set ``unicode_normalization`` to ``False`` or ``None`` when calling ``__init__`` of the ``Text`` field. See `issue 86 `_. 4.9.3 (2018-10-12) ================== - Fix a ReST error in getDoc() results when having "subfields" with titles. 4.9.2 (2018-10-11) ================== - Make sure that the title for ``IObject.validate_invariants`` is a unicode string. 4.9.1 (2018-10-05) ================== - Fix ``SimpleTerm`` token for non-ASCII bytes values. 4.9.0 (2018-09-24) ================== - Make ``NativeString`` and ``NativeStringLine`` distinct types that implement the newly-distinct interfaces ``INativeString`` and ``INativeStringLine``. Previously these were just aliases for either ``Text`` (on Python 3) or ``Bytes`` (on Python 2). - Fix ``Field.getDoc()`` when ``value_type`` or ``key_type`` is present. Previously it could produce ReST that generated Sphinx warnings. See `issue 76 `_. - Make ``DottedName`` accept leading underscores for each segment. - Add ``PythonIdentifier``, which accepts one segment of a dotted name, e.g., a python variable or class. 4.8.0 (2018-09-19) ================== - Add the interface ``IFromBytes``, which is implemented by the numeric and bytes fields, as well as ``URI``, ``DottedName``, and ``Id``. - Fix passing ``None`` as the description to a field constructor. See `issue 69 `_. 4.7.0 (2018-09-11) ================== - Make ``WrongType`` have an ``expected_type`` field. - Add ``NotAnInterface``, an exception derived from ``WrongType`` and ``SchemaNotProvided`` and raised by the constructor of ``Object`` and when validation fails for ``InterfaceField``. - Give ``SchemaNotProvided`` a ``schema`` field. - Give ``WrongContainedType`` an ``errors`` list. - Give ``TooShort``, ``TooLong``, ``TooBig`` and ``TooSmall`` a ``bound`` field and the common superclasses ``LenOutOfBounds``, ``OrderableOutOfBounds``, respectively, both of which inherit from ``OutOfBounds``. 4.6.2 (2018-09-10) ================== - Fix checking a field's constraint to set the ``field`` and ``value`` properties if the constraint raises a ``ValidationError``. See `issue 66 `_. 4.6.1 (2018-09-10) ================== - Fix the ``Field`` constructor to again allow ``MessageID`` values for the ``description``. This was a regression introduced with the fix for `issue 60 `_. See `issue 63 `_. 4.6.0 (2018-09-07) ================== - Add support for Python 3.7. - ``Object`` instances call their schema's ``validateInvariants`` method by default to collect errors from functions decorated with ``@invariant`` when validating. This can be disabled by passing ``validate_invariants=False`` to the ``Object`` constructor. See `issue 10 `_. - ``ValidationError`` can be sorted on Python 3. - ``DottedName`` and ``Id`` consistently handle non-ASCII unicode values on Python 2 and 3 by raising ``InvalidDottedName`` and ``InvalidId`` in ``fromUnicode`` respectively. Previously, a ``UnicodeEncodeError`` would be raised on Python 2 while Python 3 would raise the descriptive exception. - ``Field`` instances are hashable on Python 3, and use a defined hashing algorithm that matches what equality does on all versions of Python. Previously, on Python 2, fields were hashed based on their identity. This violated the rule that equal objects should have equal hashes, and now they do. Since having equal hashes does not imply that the objects are equal, this is not expected to be a compatibility problem. See `issue 36 `_. - ``Field`` instances are only equal when their ``.interface`` is equal. In practice, this means that two otherwise identical fields of separate schemas are not equal, do not hash the same, and can both be members of the same ``dict`` or ``set``. Prior to this release, when hashing was identity based but only worked on Python 2, that was the typical behaviour. (Field objects that are *not* members of a schema continue to compare and hash equal if they have the same attributes and interfaces.) See `issue 40 `_. - Orderable fields, including ``Int``, ``Float``, ``Decimal``, ``Timedelta``, ``Date`` and ``Time``, can now have a ``missing_value`` without needing to specify concrete ``min`` and ``max`` values (they must still specify a ``default`` value). See `issue 9 `_. - ``Choice``, ``SimpleVocabulary`` and ``SimpleTerm`` all gracefully handle using Unicode token values with non-ASCII characters by encoding them with the ``backslashreplace`` error handler. See `issue 15 `_ and `PR 6 `_. - All instances of ``ValidationError`` have a ``field`` and ``value`` attribute that is set to the field that raised the exception and the value that failed validation. - ``Float``, ``Int`` and ``Decimal`` fields raise ``ValidationError`` subclasses for literals that cannot be parsed. These subclasses also subclass ``ValueError`` for backwards compatibility. - Add a new exception ``SchemaNotCorrectlyImplemented``, a subclass of ``WrongContainedType`` that is raised by the ``Object`` field. It has a dictionary (``schema_errors``) mapping invalid schema attributes to their corresponding exception, and a list (``invariant_errors``) containing the exceptions raised by validating invariants. See `issue 16 `_. - Add new fields ``Mapping`` and ``MutableMapping``, corresponding to the collections ABCs of the same name; ``Dict`` now extends and specializes ``MutableMapping`` to only accept instances of ``dict``. - Add new fields ``Sequence`` and ``MutableSequence``, corresponding to the collections ABCs of the same name; ``Tuple`` now extends ``Sequence`` and ``List`` now extends ``MutableSequence``. - Add new field ``Collection``, implementing ``ICollection``. This is the base class of ``Sequence``. Previously this was known as ``AbstractCollection`` and was not public. It can be subclassed to add ``value_type``, ``_type`` and ``unique`` attributes at the class level, enabling a simpler constructor call. See `issue 23 `_. - Make ``Object`` respect a ``schema`` attribute defined by a subclass, enabling a simpler constructor call. See `issue 23 `_. - Add fields and interfaces representing Python's numeric tower. In descending order of generality these are ``Number``, ``Complex``, ``Real``, ``Rational`` and ``Integral``. The ``Int`` class extends ``Integral``, the ``Float`` class extends ``Real``, and the ``Decimal`` class extends ``Number``. See `issue 49 `_. - Make ``Iterable`` and ``Container`` properly implement ``IIterable`` and ``IContainer``, respectively. - Make ``SimpleVocabulary.fromItems`` accept triples to allow specifying the title of terms. See `issue 18 `_. - Make ``TreeVocabulary.fromDict`` only create ``ITitledTokenizedTerms`` when a title is actually provided. - Make ``Choice`` fields reliably raise a ``ValidationError`` when a named vocabulary cannot be found; for backwards compatibility this is also a ``ValueError``. Previously this only worked when the default ``VocabularyRegistry`` was in use, not when it was replaced with `zope.vocabularyregistry `_. See `issue 55 `_. - Make ``SimpleVocabulary`` and ``SimpleTerm`` have value-based equality and hashing methods. - All fields of the schema of an ``Object`` field are bound to the top-level value being validated before attempting validation of their particular attribute. Previously only ``IChoice`` fields were bound. See `issue 17 `_. - Share the internal logic of ``Object`` field validation and ``zope.schema.getValidationErrors``. See `issue 57 `_. - Make ``Field.getDoc()`` return more information about the properties of the field, such as its required and readonly status. Subclasses can add more information using the new method ``Field.getExtraDocLines()``. This is used to generate Sphinx documentation when using `repoze.sphinx.autointerface `_. See `issue 60 `_. 4.5.0 (2017-07-10) ================== - Drop support for Python 2.6, 3.2, and 3.3. - Add support for Python 3.5 and 3.6. - Drop support for 'setup.py test'. Use zope.testrunner instead. 4.4.2 (2014-09-04) ================== - Fix description of min max field: max value is included, not excluded. 4.4.1 (2014-03-19) ================== - Add support for Python 3.4. 4.4.0 (2014-01-22) ================== - Add an event on field properties to notify that a field has been updated. This event enables definition of subscribers based on an event, a context and a field. The event contains also the old value and the new value. (also see package ``zope.schemaevent`` that define a field event handler) 4.3.3 (2014-01-06) ================== - PEP 8 cleanup. - Don't raise RequiredMissing if a field's defaultFactory returns the field's missing_value. - Update ``boostrap.py`` to version 2.2. - Add the ability to swallow ValueErrors when rendering a SimpleVocabulary, allowing for cases where vocabulary items may be duplicated (e.g., due to user input). - Include the field name in ``ConstraintNotSatisfied``. 4.3.2 (2013-02-24) ================== - Fix Python 2.6 support. (Forgot to run tox with all environments before last release.) 4.3.1 (2013-02-24) ================== - Make sure that we do not fail during bytes decoding of term token when generated from a bytes value by ignoring all errors. (Another option would have been to hexlify the value, but that would break way too many tests.) 4.3.0 (2013-02-24) ================== - Fix a bug where bytes values were turned into tokens inproperly in Python 3. - Add ``zope.schema.fieldproperty.createFieldProperties()`` function which maps schema fields into ``FieldProperty`` instances. 4.2.2 (2012-11-21) ================== - Add support for Python 3.3. 4.2.1 (2012-11-09) ================== - Fix the default property of fields that have no defaultFactory attribute. 4.2.0 (2012-05-12) ================== - Automate build of Sphinx HTML docs and running doctest snippets via tox. - Drop explicit support for Python 3.1. - Introduce NativeString and NativeStringLine which are equal to Bytes and BytesLine on Python 2 and Text and TextLine on Python 3. - Change IURI from a Bytes string to a "native" string. This is a backwards incompatibility which only affects Python 3. - Bring unit test coverage to 100%. - Move doctests from the package and wired up as normal Sphinx documentation. - Add explicit support for PyPy. - Add support for continuous integration using ``tox`` and ``jenkins``. - Drop the external ``six`` dependency in favor of a much-trimmed ``zope.schema._compat`` module. - Ensure tests pass when run under ``nose``. - Add ``setup.py dev`` alias (runs ``setup.py develop`` plus installs ``nose`` and ``coverage``). - Add ``setup.py docs`` alias (installs ``Sphinx`` and dependencies). 4.1.1 (2012-03-23) ================== - Remove trailing slash in MANIFEST.in, it causes Winbot to crash. 4.1.0 (2012-03-23) ================== - Add TreeVocabulary for nested tree-like vocabularies. - Fix broken Object field validation where the schema contains a Choice with ICountextSourceBinder source. In this case the vocabulary was not iterable because the field was not bound and the source binder didn't return the real vocabulary. Added simple test for IContextSourceBinder validation. But a test with an Object field with a schema using a Choice with IContextSourceBinder is still missing. 4.0.1 (2011-11-14) ================== - Fix bug in ``fromUnicode`` method of ``DottedName`` which would fail validation on being given unicode. Introduced in 4.0.0. 4.0.0 (2011-11-09) ================== - Fix deprecated unittest methods. - Port to Python 3. This adds a dependency on six and removes support for Python 2.5. 3.8.1 (2011-09-23) ================== - Fix broken Object field validation. Previous version was using a volatile property on object field values which ends in a ForbiddenAttribute error on security proxied objects. 3.8.0 (2011-03-18) ================== - Implement a ``defaultFactory`` attribute for all fields. It is a callable that can be used to compute default values. The simplest case is:: Date(defaultFactory=datetime.date.today) If the factory needs a context to compute a sensible default value, then it must provide ``IContextAwareDefaultFactory``, which can be used as follows:: @provider(IContextAwareDefaultFactory) def today(context): return context.today() Date(defaultFactory=today) 3.7.1 (2010-12-25) ================== - Rename the validation token, used in the validation of schema with Object Field to avoid infinite recursion: ``__schema_being_validated`` became ``_v_schema_being_validated``, a volatile attribute, to avoid persistency and therefore, read/write conflicts. - Don't allow "[\]^`" in DottedName. https://bugs.launchpad.net/zope.schema/+bug/191236 3.7.0 (2010-09-12) ================== - Improve error messages when term tokens or values are duplicates. - Fix the buildout so the tests run. 3.6.4 (2010-06-08) ================== - fix validation of schema with Object Field that specify Interface schema. 3.6.3 (2010-04-30) ================== - Prefer the standard libraries doctest module to the one from zope.testing. 3.6.2 (2010-04-30) ================== - Avoid maximum recursion when validating Object field that points to cycles - Make the dependency on ``zope.i18nmessageid`` optional. 3.6.1 (2010-01-05) ================== - Allow "setup.py test" to run at least a subset of the tests runnable via ``bin/test`` (227 for ``setup.py test`` vs. 258. for ``bin/test``) - Make ``zope.schema._bootstrapfields.ValidatedProperty`` descriptor work under Jython. - Make "setup.py test" tests pass on Jython. 3.6.0 (2009-12-22) ================== - Prefer zope.testing.doctest over doctestunit. - Extend validation error to hold the field name. - Add FieldProperty class that uses Field.get and Field.set methods instead of storing directly on the instance __dict__. 3.5.4 (2009-03-25) ================== - Don't fail trying to validate default value for Choice fields with IContextSourceBinder object given as a source. See https://bugs.launchpad.net/zope3/+bug/340416. - Add an interface for ``DottedName`` field. - Add ``vocabularyName`` attribute to the ``IChoice`` interface, change "vocabulary" attribute description to be more sensible, making it ``zope.schema.Field`` instead of plain ``zope.interface.Attribute``. - Make IBool interface of Bool more important than IFromUnicode so adapters registered for IBool take precendence over adapters registered for IFromUnicode. 3.5.3 (2009-03-10) ================== - Make Choice and Bool fields implement IFromUnicode interface, because they do provide the ``fromUnicode`` method. - Change package's mailing list address to zope-dev at zope.org, as zope3-dev at zope.org is now retired. - Fix package's documentation formatting. Change package's description. - Add buildout part that builds Sphinx-generated documentation. - Remove zpkg-related file. 3.5.2 (2009-02-04) ================== - Made validation tests compatible with Python 2.5 again (hopefully not breaking Python 2.4) - Add an __all__ package attribute to expose documentation. 3.5.1 (2009-01-31) ================== - Stop using the old old set type. - Make tests compatible and silent with Python 2.4. - Fix __cmp__ method in ValidationError. Show some side effects based on the existing __cmp__ implementation. See validation.txt - Make 'repr' of the ValidationError and its subclasses more sensible. This may require you to adapt your doctests for the new style, but now it makes much more sense for debugging for developers. 3.5.0a2 (2008-12-11) ==================== - Move zope.testing to "test" extras_require, as it is not needed for zope.schema itself. - Change the order of classes in SET_TYPES tuple, introduced in previous release to one that was in 3.4 (SetType, set), because third-party code could be dependent on that order. The one example is z3c.form's converter. 3.5.0a1 (2008-10-10) ==================== - Add the doctests to the long description. - Remove use of deprecated 'sets' module when running under Python 2.6. - Remove spurious doctest failure when running under Python 2.6. - Add support to bootstrap on Jython. - Add helper methods for schema validation: ``getValidationErrors`` and ``getSchemaValidationErrors``. - zope.schema now works on Python2.5 3.4.0 (2007-09-28) ================== Add BeforeObjectAssignedEvent that is triggered before the object field sets a value. 3.3.0 (2007-03-15) ================== Corresponds to the version of the zope.schema package shipped as part of the Zope 3.3.0 release. 3.2.1 (2006-03-26) ================== Corresponds to the version of the zope.schema package shipped as part of the Zope 3.2.1 release. Fix missing import of 'VocabularyRegistryError'. See http://www.zope.org/Collectors/Zope3-dev/544 . 3.2.0 (2006-01-05) ================== Corresponds to the version of the zope.schema package shipped as part of the Zope 3.2.0 release. Add "iterable" sources to replace vocabularies, which are now deprecated and scheduled for removal in Zope 3.3. 3.1.0 (2005-10-03) ================== Corresponds to the version of the zope.schema package shipped as part of the Zope 3.1.0 release. Allow 'Choice' fields to take either a 'vocabulary' or a 'source' argument (sources are a simpler implementation). Add 'TimeDelta' and 'ASCIILine' field types. 3.0.0 (2004-11-07) ================== Corresponds to the version of the zope.schema package shipped as part of the Zope X3.0.0 release. zope.schema-6.2.0/COPYRIGHT.txt0000644000100100000240000000004014133212652015700 0ustar macstaff00000000000000Zope Foundation and Contributorszope.schema-6.2.0/LICENSE.txt0000644000100100000240000000402614133212652015422 0ustar macstaff00000000000000Zope Public License (ZPL) Version 2.1 A copyright notice accompanies this license document that identifies the copyright holders. This license has been certified as open source. It has also been designated as GPL compatible by the Free Software Foundation (FSF). Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions in source code must retain the accompanying copyright notice, this list of conditions, and the following disclaimer. 2. Redistributions in binary form must reproduce the accompanying copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Names of the copyright holders must not be used to endorse or promote products derived from this software without prior written permission from the copyright holders. 4. The right to distribute this software or to use it for any purpose does not give you the right to use Servicemarks (sm) or Trademarks (tm) of the copyright holders. Use of them is covered by separate agreement with the copyright holders. 5. If any files are modified, you must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. zope.schema-6.2.0/MANIFEST.in0000644000100100000240000000051314133212652015332 0ustar macstaff00000000000000# Generated from: # https://github.com/zopefoundation/meta/tree/master/config/pure-python include *.rst include *.txt include buildout.cfg include tox.ini recursive-include docs *.py recursive-include docs *.rst recursive-include docs *.txt recursive-include docs Makefile recursive-include src *.py recursive-include docs *.bat zope.schema-6.2.0/PKG-INFO0000644000100100000240000007115114133212652014677 0ustar macstaff00000000000000Metadata-Version: 2.1 Name: zope.schema Version: 6.2.0 Summary: zope.interface extension for defining data schemas Home-page: https://github.com/zopefoundation/zope.schema Author: Zope Foundation and Contributors Author-email: zope-dev@zope.org License: ZPL 2.1 Description: ============= zope.schema ============= .. image:: https://img.shields.io/pypi/v/zope.schema.svg :target: https://pypi.org/project/zope.schema/ :alt: Latest Version .. image:: https://img.shields.io/pypi/pyversions/zope.schema.svg :target: https://pypi.org/project/zope.schema/ :alt: Supported Python versions .. image:: https://github.com/zopefoundation/zope.schema/workflows/tests/badge.svg :target: https://github.com/zopefoundation/zope.schema/actions?query=workflow%3Atests :alt: Tests Status .. image:: https://readthedocs.org/projects/zopeschema/badge/?version=latest :target: https://zopeschema.readthedocs.org/en/latest/ :alt: Documentation Status .. image:: https://coveralls.io/repos/github/zopefoundation/zope.schema/badge.svg :target: https://coveralls.io/github/zopefoundation/zope.schema :alt: Code Coverage Schemas extend the notion of interfaces to detailed descriptions of Attributes (but not methods). Every schema is an interface and specifies the public fields of an object. A *field* roughly corresponds to an attribute of a Python object. But a Field provides space for at least a title and a description. It can also constrain its value and provide a validation method. Besides you can optionally specify characteristics such as its value being read-only or not required. See https://zopeschema.readthedocs.io/ for more information. ========= Changes ========= 6.2.0 (2021-10-18) ================== - Add support for Python 3.10. 6.1.1 (2021-10-13) ================== - Fix incompatibility introduced in 6.1.0: The `Bool` field constructor implicitly set required to False if not given. While this is the desired behavior in most common cases, it broke special cases. See `issue 104 `_ (scroll down, it is around the *reopen*). 6.1.0 (2021-02-09) ================== - Fix ``IField.required`` to not be required by default. See `issue 104 `_. 6.0.1 (2021-01-25) ================== - Bring branch coverage to 100%. - Add support for Python 3.9. - Fix FieldUpdateEvent implementation by having an ``object`` attribute as the ``IFieldUpdatedEvent`` interfaces claims there should be. 6.0.0 (2020-03-21) ================== - Require zope.interface 5.0. - Ensure the resolution orders of all fields are consistent and make sense. In particular, ``Bool`` fields now correctly implement ``IBool`` before ``IFromUnicode``. See `issue 80 `_. - Add support for Python 3.8. - Drop support for Python 3.4. 5.0.1 (2020-03-06) ================== - Fix: add ``Text.unicode_normalization = 'NFC'`` as default, because some are persisting schema fields. Setting that attribute only in ``__init__`` breaks loading old objects. 5.0 (2020-03-06) ================ - Set ``IDecimal`` attributes ``min``, ``max`` and ``default`` as ``Decimal`` type instead of ``Number``. See `issue 88 `_. - Enable unicode normalization for ``Text`` fields. The default is NFC normalization. Valid forms are 'NFC', 'NFKC', 'NFD', and 'NFKD'. To disable normalization, set ``unicode_normalization`` to ``False`` or ``None`` when calling ``__init__`` of the ``Text`` field. See `issue 86 `_. 4.9.3 (2018-10-12) ================== - Fix a ReST error in getDoc() results when having "subfields" with titles. 4.9.2 (2018-10-11) ================== - Make sure that the title for ``IObject.validate_invariants`` is a unicode string. 4.9.1 (2018-10-05) ================== - Fix ``SimpleTerm`` token for non-ASCII bytes values. 4.9.0 (2018-09-24) ================== - Make ``NativeString`` and ``NativeStringLine`` distinct types that implement the newly-distinct interfaces ``INativeString`` and ``INativeStringLine``. Previously these were just aliases for either ``Text`` (on Python 3) or ``Bytes`` (on Python 2). - Fix ``Field.getDoc()`` when ``value_type`` or ``key_type`` is present. Previously it could produce ReST that generated Sphinx warnings. See `issue 76 `_. - Make ``DottedName`` accept leading underscores for each segment. - Add ``PythonIdentifier``, which accepts one segment of a dotted name, e.g., a python variable or class. 4.8.0 (2018-09-19) ================== - Add the interface ``IFromBytes``, which is implemented by the numeric and bytes fields, as well as ``URI``, ``DottedName``, and ``Id``. - Fix passing ``None`` as the description to a field constructor. See `issue 69 `_. 4.7.0 (2018-09-11) ================== - Make ``WrongType`` have an ``expected_type`` field. - Add ``NotAnInterface``, an exception derived from ``WrongType`` and ``SchemaNotProvided`` and raised by the constructor of ``Object`` and when validation fails for ``InterfaceField``. - Give ``SchemaNotProvided`` a ``schema`` field. - Give ``WrongContainedType`` an ``errors`` list. - Give ``TooShort``, ``TooLong``, ``TooBig`` and ``TooSmall`` a ``bound`` field and the common superclasses ``LenOutOfBounds``, ``OrderableOutOfBounds``, respectively, both of which inherit from ``OutOfBounds``. 4.6.2 (2018-09-10) ================== - Fix checking a field's constraint to set the ``field`` and ``value`` properties if the constraint raises a ``ValidationError``. See `issue 66 `_. 4.6.1 (2018-09-10) ================== - Fix the ``Field`` constructor to again allow ``MessageID`` values for the ``description``. This was a regression introduced with the fix for `issue 60 `_. See `issue 63 `_. 4.6.0 (2018-09-07) ================== - Add support for Python 3.7. - ``Object`` instances call their schema's ``validateInvariants`` method by default to collect errors from functions decorated with ``@invariant`` when validating. This can be disabled by passing ``validate_invariants=False`` to the ``Object`` constructor. See `issue 10 `_. - ``ValidationError`` can be sorted on Python 3. - ``DottedName`` and ``Id`` consistently handle non-ASCII unicode values on Python 2 and 3 by raising ``InvalidDottedName`` and ``InvalidId`` in ``fromUnicode`` respectively. Previously, a ``UnicodeEncodeError`` would be raised on Python 2 while Python 3 would raise the descriptive exception. - ``Field`` instances are hashable on Python 3, and use a defined hashing algorithm that matches what equality does on all versions of Python. Previously, on Python 2, fields were hashed based on their identity. This violated the rule that equal objects should have equal hashes, and now they do. Since having equal hashes does not imply that the objects are equal, this is not expected to be a compatibility problem. See `issue 36 `_. - ``Field`` instances are only equal when their ``.interface`` is equal. In practice, this means that two otherwise identical fields of separate schemas are not equal, do not hash the same, and can both be members of the same ``dict`` or ``set``. Prior to this release, when hashing was identity based but only worked on Python 2, that was the typical behaviour. (Field objects that are *not* members of a schema continue to compare and hash equal if they have the same attributes and interfaces.) See `issue 40 `_. - Orderable fields, including ``Int``, ``Float``, ``Decimal``, ``Timedelta``, ``Date`` and ``Time``, can now have a ``missing_value`` without needing to specify concrete ``min`` and ``max`` values (they must still specify a ``default`` value). See `issue 9 `_. - ``Choice``, ``SimpleVocabulary`` and ``SimpleTerm`` all gracefully handle using Unicode token values with non-ASCII characters by encoding them with the ``backslashreplace`` error handler. See `issue 15 `_ and `PR 6 `_. - All instances of ``ValidationError`` have a ``field`` and ``value`` attribute that is set to the field that raised the exception and the value that failed validation. - ``Float``, ``Int`` and ``Decimal`` fields raise ``ValidationError`` subclasses for literals that cannot be parsed. These subclasses also subclass ``ValueError`` for backwards compatibility. - Add a new exception ``SchemaNotCorrectlyImplemented``, a subclass of ``WrongContainedType`` that is raised by the ``Object`` field. It has a dictionary (``schema_errors``) mapping invalid schema attributes to their corresponding exception, and a list (``invariant_errors``) containing the exceptions raised by validating invariants. See `issue 16 `_. - Add new fields ``Mapping`` and ``MutableMapping``, corresponding to the collections ABCs of the same name; ``Dict`` now extends and specializes ``MutableMapping`` to only accept instances of ``dict``. - Add new fields ``Sequence`` and ``MutableSequence``, corresponding to the collections ABCs of the same name; ``Tuple`` now extends ``Sequence`` and ``List`` now extends ``MutableSequence``. - Add new field ``Collection``, implementing ``ICollection``. This is the base class of ``Sequence``. Previously this was known as ``AbstractCollection`` and was not public. It can be subclassed to add ``value_type``, ``_type`` and ``unique`` attributes at the class level, enabling a simpler constructor call. See `issue 23 `_. - Make ``Object`` respect a ``schema`` attribute defined by a subclass, enabling a simpler constructor call. See `issue 23 `_. - Add fields and interfaces representing Python's numeric tower. In descending order of generality these are ``Number``, ``Complex``, ``Real``, ``Rational`` and ``Integral``. The ``Int`` class extends ``Integral``, the ``Float`` class extends ``Real``, and the ``Decimal`` class extends ``Number``. See `issue 49 `_. - Make ``Iterable`` and ``Container`` properly implement ``IIterable`` and ``IContainer``, respectively. - Make ``SimpleVocabulary.fromItems`` accept triples to allow specifying the title of terms. See `issue 18 `_. - Make ``TreeVocabulary.fromDict`` only create ``ITitledTokenizedTerms`` when a title is actually provided. - Make ``Choice`` fields reliably raise a ``ValidationError`` when a named vocabulary cannot be found; for backwards compatibility this is also a ``ValueError``. Previously this only worked when the default ``VocabularyRegistry`` was in use, not when it was replaced with `zope.vocabularyregistry `_. See `issue 55 `_. - Make ``SimpleVocabulary`` and ``SimpleTerm`` have value-based equality and hashing methods. - All fields of the schema of an ``Object`` field are bound to the top-level value being validated before attempting validation of their particular attribute. Previously only ``IChoice`` fields were bound. See `issue 17 `_. - Share the internal logic of ``Object`` field validation and ``zope.schema.getValidationErrors``. See `issue 57 `_. - Make ``Field.getDoc()`` return more information about the properties of the field, such as its required and readonly status. Subclasses can add more information using the new method ``Field.getExtraDocLines()``. This is used to generate Sphinx documentation when using `repoze.sphinx.autointerface `_. See `issue 60 `_. 4.5.0 (2017-07-10) ================== - Drop support for Python 2.6, 3.2, and 3.3. - Add support for Python 3.5 and 3.6. - Drop support for 'setup.py test'. Use zope.testrunner instead. 4.4.2 (2014-09-04) ================== - Fix description of min max field: max value is included, not excluded. 4.4.1 (2014-03-19) ================== - Add support for Python 3.4. 4.4.0 (2014-01-22) ================== - Add an event on field properties to notify that a field has been updated. This event enables definition of subscribers based on an event, a context and a field. The event contains also the old value and the new value. (also see package ``zope.schemaevent`` that define a field event handler) 4.3.3 (2014-01-06) ================== - PEP 8 cleanup. - Don't raise RequiredMissing if a field's defaultFactory returns the field's missing_value. - Update ``boostrap.py`` to version 2.2. - Add the ability to swallow ValueErrors when rendering a SimpleVocabulary, allowing for cases where vocabulary items may be duplicated (e.g., due to user input). - Include the field name in ``ConstraintNotSatisfied``. 4.3.2 (2013-02-24) ================== - Fix Python 2.6 support. (Forgot to run tox with all environments before last release.) 4.3.1 (2013-02-24) ================== - Make sure that we do not fail during bytes decoding of term token when generated from a bytes value by ignoring all errors. (Another option would have been to hexlify the value, but that would break way too many tests.) 4.3.0 (2013-02-24) ================== - Fix a bug where bytes values were turned into tokens inproperly in Python 3. - Add ``zope.schema.fieldproperty.createFieldProperties()`` function which maps schema fields into ``FieldProperty`` instances. 4.2.2 (2012-11-21) ================== - Add support for Python 3.3. 4.2.1 (2012-11-09) ================== - Fix the default property of fields that have no defaultFactory attribute. 4.2.0 (2012-05-12) ================== - Automate build of Sphinx HTML docs and running doctest snippets via tox. - Drop explicit support for Python 3.1. - Introduce NativeString and NativeStringLine which are equal to Bytes and BytesLine on Python 2 and Text and TextLine on Python 3. - Change IURI from a Bytes string to a "native" string. This is a backwards incompatibility which only affects Python 3. - Bring unit test coverage to 100%. - Move doctests from the package and wired up as normal Sphinx documentation. - Add explicit support for PyPy. - Add support for continuous integration using ``tox`` and ``jenkins``. - Drop the external ``six`` dependency in favor of a much-trimmed ``zope.schema._compat`` module. - Ensure tests pass when run under ``nose``. - Add ``setup.py dev`` alias (runs ``setup.py develop`` plus installs ``nose`` and ``coverage``). - Add ``setup.py docs`` alias (installs ``Sphinx`` and dependencies). 4.1.1 (2012-03-23) ================== - Remove trailing slash in MANIFEST.in, it causes Winbot to crash. 4.1.0 (2012-03-23) ================== - Add TreeVocabulary for nested tree-like vocabularies. - Fix broken Object field validation where the schema contains a Choice with ICountextSourceBinder source. In this case the vocabulary was not iterable because the field was not bound and the source binder didn't return the real vocabulary. Added simple test for IContextSourceBinder validation. But a test with an Object field with a schema using a Choice with IContextSourceBinder is still missing. 4.0.1 (2011-11-14) ================== - Fix bug in ``fromUnicode`` method of ``DottedName`` which would fail validation on being given unicode. Introduced in 4.0.0. 4.0.0 (2011-11-09) ================== - Fix deprecated unittest methods. - Port to Python 3. This adds a dependency on six and removes support for Python 2.5. 3.8.1 (2011-09-23) ================== - Fix broken Object field validation. Previous version was using a volatile property on object field values which ends in a ForbiddenAttribute error on security proxied objects. 3.8.0 (2011-03-18) ================== - Implement a ``defaultFactory`` attribute for all fields. It is a callable that can be used to compute default values. The simplest case is:: Date(defaultFactory=datetime.date.today) If the factory needs a context to compute a sensible default value, then it must provide ``IContextAwareDefaultFactory``, which can be used as follows:: @provider(IContextAwareDefaultFactory) def today(context): return context.today() Date(defaultFactory=today) 3.7.1 (2010-12-25) ================== - Rename the validation token, used in the validation of schema with Object Field to avoid infinite recursion: ``__schema_being_validated`` became ``_v_schema_being_validated``, a volatile attribute, to avoid persistency and therefore, read/write conflicts. - Don't allow "[\]^`" in DottedName. https://bugs.launchpad.net/zope.schema/+bug/191236 3.7.0 (2010-09-12) ================== - Improve error messages when term tokens or values are duplicates. - Fix the buildout so the tests run. 3.6.4 (2010-06-08) ================== - fix validation of schema with Object Field that specify Interface schema. 3.6.3 (2010-04-30) ================== - Prefer the standard libraries doctest module to the one from zope.testing. 3.6.2 (2010-04-30) ================== - Avoid maximum recursion when validating Object field that points to cycles - Make the dependency on ``zope.i18nmessageid`` optional. 3.6.1 (2010-01-05) ================== - Allow "setup.py test" to run at least a subset of the tests runnable via ``bin/test`` (227 for ``setup.py test`` vs. 258. for ``bin/test``) - Make ``zope.schema._bootstrapfields.ValidatedProperty`` descriptor work under Jython. - Make "setup.py test" tests pass on Jython. 3.6.0 (2009-12-22) ================== - Prefer zope.testing.doctest over doctestunit. - Extend validation error to hold the field name. - Add FieldProperty class that uses Field.get and Field.set methods instead of storing directly on the instance __dict__. 3.5.4 (2009-03-25) ================== - Don't fail trying to validate default value for Choice fields with IContextSourceBinder object given as a source. See https://bugs.launchpad.net/zope3/+bug/340416. - Add an interface for ``DottedName`` field. - Add ``vocabularyName`` attribute to the ``IChoice`` interface, change "vocabulary" attribute description to be more sensible, making it ``zope.schema.Field`` instead of plain ``zope.interface.Attribute``. - Make IBool interface of Bool more important than IFromUnicode so adapters registered for IBool take precendence over adapters registered for IFromUnicode. 3.5.3 (2009-03-10) ================== - Make Choice and Bool fields implement IFromUnicode interface, because they do provide the ``fromUnicode`` method. - Change package's mailing list address to zope-dev at zope.org, as zope3-dev at zope.org is now retired. - Fix package's documentation formatting. Change package's description. - Add buildout part that builds Sphinx-generated documentation. - Remove zpkg-related file. 3.5.2 (2009-02-04) ================== - Made validation tests compatible with Python 2.5 again (hopefully not breaking Python 2.4) - Add an __all__ package attribute to expose documentation. 3.5.1 (2009-01-31) ================== - Stop using the old old set type. - Make tests compatible and silent with Python 2.4. - Fix __cmp__ method in ValidationError. Show some side effects based on the existing __cmp__ implementation. See validation.txt - Make 'repr' of the ValidationError and its subclasses more sensible. This may require you to adapt your doctests for the new style, but now it makes much more sense for debugging for developers. 3.5.0a2 (2008-12-11) ==================== - Move zope.testing to "test" extras_require, as it is not needed for zope.schema itself. - Change the order of classes in SET_TYPES tuple, introduced in previous release to one that was in 3.4 (SetType, set), because third-party code could be dependent on that order. The one example is z3c.form's converter. 3.5.0a1 (2008-10-10) ==================== - Add the doctests to the long description. - Remove use of deprecated 'sets' module when running under Python 2.6. - Remove spurious doctest failure when running under Python 2.6. - Add support to bootstrap on Jython. - Add helper methods for schema validation: ``getValidationErrors`` and ``getSchemaValidationErrors``. - zope.schema now works on Python2.5 3.4.0 (2007-09-28) ================== Add BeforeObjectAssignedEvent that is triggered before the object field sets a value. 3.3.0 (2007-03-15) ================== Corresponds to the version of the zope.schema package shipped as part of the Zope 3.3.0 release. 3.2.1 (2006-03-26) ================== Corresponds to the version of the zope.schema package shipped as part of the Zope 3.2.1 release. Fix missing import of 'VocabularyRegistryError'. See http://www.zope.org/Collectors/Zope3-dev/544 . 3.2.0 (2006-01-05) ================== Corresponds to the version of the zope.schema package shipped as part of the Zope 3.2.0 release. Add "iterable" sources to replace vocabularies, which are now deprecated and scheduled for removal in Zope 3.3. 3.1.0 (2005-10-03) ================== Corresponds to the version of the zope.schema package shipped as part of the Zope 3.1.0 release. Allow 'Choice' fields to take either a 'vocabulary' or a 'source' argument (sources are a simpler implementation). Add 'TimeDelta' and 'ASCIILine' field types. 3.0.0 (2004-11-07) ================== Corresponds to the version of the zope.schema package shipped as part of the Zope X3.0.0 release. Keywords: zope3 schema field interface typing Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Zope Public License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Framework :: Zope :: 3 Classifier: Topic :: Software Development :: Libraries :: Python Modules Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.* Provides-Extra: docs Provides-Extra: test zope.schema-6.2.0/README.rst0000644000100100000240000000257014133212652015270 0ustar macstaff00000000000000============= zope.schema ============= .. image:: https://img.shields.io/pypi/v/zope.schema.svg :target: https://pypi.org/project/zope.schema/ :alt: Latest Version .. image:: https://img.shields.io/pypi/pyversions/zope.schema.svg :target: https://pypi.org/project/zope.schema/ :alt: Supported Python versions .. image:: https://github.com/zopefoundation/zope.schema/workflows/tests/badge.svg :target: https://github.com/zopefoundation/zope.schema/actions?query=workflow%3Atests :alt: Tests Status .. image:: https://readthedocs.org/projects/zopeschema/badge/?version=latest :target: https://zopeschema.readthedocs.org/en/latest/ :alt: Documentation Status .. image:: https://coveralls.io/repos/github/zopefoundation/zope.schema/badge.svg :target: https://coveralls.io/github/zopefoundation/zope.schema :alt: Code Coverage Schemas extend the notion of interfaces to detailed descriptions of Attributes (but not methods). Every schema is an interface and specifies the public fields of an object. A *field* roughly corresponds to an attribute of a Python object. But a Field provides space for at least a title and a description. It can also constrain its value and provide a validation method. Besides you can optionally specify characteristics such as its value being read-only or not required. See https://zopeschema.readthedocs.io/ for more information. zope.schema-6.2.0/buildout.cfg0000644000100100000240000000023114133212652016101 0ustar macstaff00000000000000[buildout] develop = . parts = tox test [test] recipe = zc.recipe.testrunner eggs = zope.schema [test] [tox] recipe = zc.recipe.egg eggs = tox zope.schema-6.2.0/docs/0000755000100100000240000000000014133212652014525 5ustar macstaff00000000000000zope.schema-6.2.0/docs/Makefile0000644000100100000240000001271414133212652016172 0ustar macstaff00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/zopeschema.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/zopeschema.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/zopeschema" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/zopeschema" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." zope.schema-6.2.0/docs/api.rst0000644000100100000240000002052414133212652016033 0ustar macstaff00000000000000===== API ===== This document describes the low-level API of the interfaces and classes provided by this package. The narrative documentation is a better guide to the intended usage. Interfaces ========== .. autointerface:: zope.schema.interfaces.IField .. autointerface:: zope.schema.interfaces.IChoice .. autointerface:: zope.schema.interfaces.IContextAwareDefaultFactory .. autointerface:: zope.schema.interfaces.IOrderable .. autointerface:: zope.schema.interfaces.ILen .. autointerface:: zope.schema.interfaces.IMinMax .. autointerface:: zope.schema.interfaces.IMinMaxLen .. autointerface:: zope.schema.interfaces.IInterfaceField .. autointerface:: zope.schema.interfaces.IBool .. autointerface:: zope.schema.interfaces.IObject Conversions ----------- .. autointerface:: zope.schema.interfaces.IFromBytes .. autointerface:: zope.schema.interfaces.IFromUnicode Strings ------- .. autointerface:: zope.schema.interfaces.IBytes .. autointerface:: zope.schema.interfaces.IBytesLine .. autointerface:: zope.schema.interfaces.IText .. autointerface:: zope.schema.interfaces.ITextLine .. autointerface:: zope.schema.interfaces.IASCII .. autointerface:: zope.schema.interfaces.IASCIILine .. autointerface:: zope.schema.interfaces.INativeString .. autointerface:: zope.schema.interfaces.INativeStringLine .. autointerface:: zope.schema.interfaces.IPassword .. autointerface:: zope.schema.interfaces.IURI .. autointerface:: zope.schema.interfaces.IId .. autointerface:: zope.schema.interfaces.IPythonIdentifier .. autointerface:: zope.schema.interfaces.IDottedName Numbers ------- .. autointerface:: zope.schema.interfaces.INumber .. autointerface:: zope.schema.interfaces.IComplex .. autointerface:: zope.schema.interfaces.IReal .. autointerface:: zope.schema.interfaces.IRational .. autointerface:: zope.schema.interfaces.IIntegral .. autointerface:: zope.schema.interfaces.IInt .. autointerface:: zope.schema.interfaces.IFloat .. autointerface:: zope.schema.interfaces.IDecimal Date/Time --------- .. autointerface:: zope.schema.interfaces.IDatetime .. autointerface:: zope.schema.interfaces.IDate .. autointerface:: zope.schema.interfaces.ITimedelta .. autointerface:: zope.schema.interfaces.ITime Collections ----------- .. autointerface:: zope.schema.interfaces.IIterable .. autointerface:: zope.schema.interfaces.IContainer .. autointerface:: zope.schema.interfaces.ICollection .. autointerface:: zope.schema.interfaces.ISequence .. autointerface:: zope.schema.interfaces.IMutableSequence .. autointerface:: zope.schema.interfaces.IUnorderedCollection .. autointerface:: zope.schema.interfaces.IAbstractSet .. autointerface:: zope.schema.interfaces.IAbstractBag .. autointerface:: zope.schema.interfaces.ITuple .. autointerface:: zope.schema.interfaces.IList .. autointerface:: zope.schema.interfaces.ISet .. autointerface:: zope.schema.interfaces.IFrozenSet Mappings ~~~~~~~~ .. autointerface:: zope.schema.interfaces.IMapping .. autointerface:: zope.schema.interfaces.IMutableMapping .. autointerface:: zope.schema.interfaces.IDict Events ------ .. autointerface:: zope.schema.interfaces.IBeforeObjectAssignedEvent .. autointerface:: zope.schema.interfaces.IFieldEvent .. autointerface:: zope.schema.interfaces.IFieldUpdatedEvent Vocabularies ------------ .. autointerface:: zope.schema.interfaces.ITerm .. autointerface:: zope.schema.interfaces.ITokenizedTerm .. autointerface:: zope.schema.interfaces.ITitledTokenizedTerm .. autointerface:: zope.schema.interfaces.ISource .. autointerface:: zope.schema.interfaces.ISourceQueriables .. autointerface:: zope.schema.interfaces.IContextSourceBinder .. autointerface:: zope.schema.interfaces.IBaseVocabulary .. autointerface:: zope.schema.interfaces.IIterableVocabulary .. autointerface:: zope.schema.interfaces.IIterableSource .. autointerface:: zope.schema.interfaces.IVocabulary .. autointerface:: zope.schema.interfaces.IVocabularyTokenized .. autointerface:: zope.schema.interfaces.ITreeVocabulary .. autointerface:: zope.schema.interfaces.IVocabularyRegistry .. autointerface:: zope.schema.interfaces.IVocabularyFactory Exceptions ---------- .. autoexception:: zope.schema._bootstrapinterfaces.ValidationError .. exception:: zope.schema.ValidationError The preferred alias for :class:`zope.schema._bootstrapinterfaces.ValidationError`. .. autoexception:: zope.schema.interfaces.StopValidation .. autoexception:: zope.schema.interfaces.RequiredMissing .. autoexception:: zope.schema.interfaces.WrongType .. autoexception:: zope.schema.interfaces.ConstraintNotSatisfied .. autoexception:: zope.schema.interfaces.NotAContainer .. autoexception:: zope.schema.interfaces.NotAnIterator .. autoexception:: zope.schema.interfaces.NotAnInterface Bounds ~~~~~~ .. autoexception:: zope.schema.interfaces.OutOfBounds .. autoexception:: zope.schema.interfaces.OrderableOutOfBounds .. autoexception:: zope.schema.interfaces.LenOutOfBounds .. autoexception:: zope.schema.interfaces.TooSmall .. autoexception:: zope.schema.interfaces.TooBig .. autoexception:: zope.schema.interfaces.TooLong .. autoexception:: zope.schema.interfaces.TooShort .. autoexception:: zope.schema.interfaces.InvalidValue .. autoexception:: zope.schema.interfaces.WrongContainedType .. autoexception:: zope.schema.interfaces.NotUnique .. autoexception:: zope.schema.interfaces.SchemaNotFullyImplemented .. autoexception:: zope.schema.interfaces.SchemaNotProvided .. autoexception:: zope.schema.interfaces.InvalidURI .. autoexception:: zope.schema.interfaces.InvalidId .. autoexception:: zope.schema.interfaces.InvalidDottedName .. autoexception:: zope.schema.interfaces.Unbound Schema APIs =========== .. autofunction:: zope.schema.getFields .. autofunction:: zope.schema.getFieldsInOrder .. autofunction:: zope.schema.getFieldNames .. autofunction:: zope.schema.getFieldNamesInOrder .. autofunction:: zope.schema.getValidationErrors :noindex: .. autofunction:: zope.schema.getSchemaValidationErrors :noindex: Field Implementations ===================== .. autoclass:: zope.schema.Field .. autoclass:: zope.schema.Collection .. autoclass:: zope.schema._field.AbstractCollection .. autoclass:: zope.schema.Bool :no-show-inheritance: .. autoclass:: zope.schema.Choice :no-show-inheritance: .. autoclass:: zope.schema.Container :no-show-inheritance: .. autoclass:: zope.schema.Date :no-show-inheritance: .. autoclass:: zope.schema.Datetime :no-show-inheritance: .. autoclass:: zope.schema.Dict .. autoclass:: zope.schema.FrozenSet :no-show-inheritance: .. autoclass:: zope.schema.Id :no-show-inheritance: .. autoclass:: zope.schema.InterfaceField :no-show-inheritance: .. autoclass:: zope.schema.Iterable :no-show-inheritance: .. autoclass:: zope.schema.List .. autoclass:: zope.schema.Mapping :no-show-inheritance: .. autoclass:: zope.schema.MutableMapping .. autoclass:: zope.schema.MutableSequence .. autoclass:: zope.schema.MinMaxLen .. autoclass:: zope.schema.Object :no-show-inheritance: .. autoclass:: zope.schema.Orderable .. autoclass:: zope.schema.Set .. autoclass:: zope.schema.Sequence .. autoclass:: zope.schema.Time :no-show-inheritance: .. autoclass:: zope.schema.Timedelta :no-show-inheritance: .. autoclass:: zope.schema.Tuple .. autoclass:: zope.schema.URI :no-show-inheritance: Strings ------- .. autoclass:: zope.schema.ASCII :no-show-inheritance: .. autoclass:: zope.schema.ASCIILine :no-show-inheritance: .. autoclass:: zope.schema.Bytes :no-show-inheritance: .. autoclass:: zope.schema.BytesLine :no-show-inheritance: .. autoclass:: zope.schema.SourceText :no-show-inheritance: .. autoclass:: zope.schema.Text :no-show-inheritance: .. autoclass:: zope.schema.TextLine :no-show-inheritance: .. autoclass:: zope.schema.NativeString :no-show-inheritance: .. autoclass:: zope.schema.NativeStringLine :no-show-inheritance: .. autoclass:: zope.schema.Password :no-show-inheritance: .. autoclass:: zope.schema.DottedName :no-show-inheritance: .. autoclass:: zope.schema.PythonIdentifier :no-show-inheritance: Numbers ------- .. autoclass:: zope.schema.Number .. autoclass:: zope.schema.Complex .. autoclass:: zope.schema.Real .. autoclass:: zope.schema.Rational .. autoclass:: zope.schema.Integral .. autoclass:: zope.schema.Float .. autoclass:: zope.schema.Int .. autoclass:: zope.schema.Decimal Vocabularies ============ .. automodule:: zope.schema.vocabulary Accessors ========= .. automodule:: zope.schema.accessors .. autofunction:: zope.schema.accessors.accessors zope.schema-6.2.0/docs/changelog.rst0000644000100100000240000000003414133212652017203 0ustar macstaff00000000000000.. include:: ../CHANGES.rst zope.schema-6.2.0/docs/conf.py0000644000100100000240000002050614133212652016027 0ustar macstaff00000000000000# -*- coding: utf-8 -*- # # zope.schema documentation build configuration file, created by # sphinx-quickstart on Fri Apr 20 15:00:47 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'repoze.sphinx.autointerface', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'zope.schema' copyright = u'2012, Zope Foundation Contributors' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The full version, including alpha/beta/rc tags. with open('../version.txt') as f: release = f.read().strip() # The short X.Y version. version = '.'.join(release.split('.')[:2]) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. default_role = 'obj' # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'zopeschemadoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'zopeschema.tex', u'zope.schema Documentation', u'Zope Foundation Contributors', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'zopeschema', u'zope.schema Documentation', [u'Zope Foundation Contributors'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'zopeschema', u'zope.schema Documentation', u'Zope Foundation Contributors', 'zopeschema', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' intersphinx_mapping = { 'https://docs.python.org/': None, 'https://zopecomponent.readthedocs.io/en/latest': None, } extlinks = {'issue': ('https://github.com/zopefoundation/zope.schema/issues/%s', 'issue #'), 'pr': ('https://github.com/zopefoundation/zope.schema/pull/%s', 'pull request #')} autodoc_default_flags = ['members', 'show-inheritance'] autoclass_content = 'both' autodoc_member_order = 'bysource' zope.schema-6.2.0/docs/fields.rst0000644000100100000240000004716514133212652016542 0ustar macstaff00000000000000======== Fields ======== This document highlights unusual and subtle aspects of various fields and field classes, and is not intended to be a general introduction to schema fields. Please see README.txt for a more general introduction. While many field types, such as Int, TextLine, Text, and Bool are relatively straightforward, a few have some subtlety. We will explore the general class of collections and discuss how to create a custom creation field; discuss Choice fields, vocabularies, and their use with collections; and close with a look at the standard zope.app approach to using these fields to find views ("widgets"). Scalars ======= Scalar fields represent simple. immutable Python types. Bytes ----- :class:`zope.schema.Bytes` fields contain binary data, represented as a sequence of bytes (``str`` in Python2, ``bytes`` in Python3). Conversion from Unicode: .. doctest:: >>> from zope.schema import Bytes >>> obj = Bytes(constraint=lambda v: b'x' in v) >>> result = obj.fromUnicode(u" foo x.y.z bat") >>> isinstance(result, bytes) True >>> str(result.decode("ascii")) ' foo x.y.z bat' >>> obj.fromUnicode(u" foo y.z bat") Traceback (most recent call last): ... ConstraintNotSatisfied: foo y.z bat ASCII ----- :class:`zope.schema.ASCII` fields are a restricted form of :class:`zope.schema.Bytes`: they can contain only 7-bit bytes. Validation accepts empty strings: .. doctest:: >>> from zope.schema import ASCII >>> ascii = ASCII() >>> empty = '' >>> ascii._validate(empty) and all kinds of alphanumeric strings: .. doctest:: >>> alphanumeric = "Bob\'s my 23rd uncle" >>> ascii._validate(alphanumeric) but fails with 8-bit (encoded) strings: .. doctest:: >>> umlauts = "Köhlerstraße" >>> ascii._validate(umlauts) Traceback (most recent call last): ... InvalidValue BytesLine --------- :class:`zope.schema.BytesLine` fields are a restricted form of :class:`zope.schema.Bytes`: they cannot contain newlines. ASCIILine --------- :class:`zope.schema.BytesLine` fields are a restricted form of :class:`zope.schema.ASCII`: they cannot contain newlines. Float ----- :class:`zope.schema.Float` fields contain binary data, represented as a a Python ``float``. Conversion from Unicode: .. doctest:: >>> from zope.schema import Float >>> f = Float() >>> f.fromUnicode("1.25") 1.25 >>> f.fromUnicode("1.25.6") #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidFloatLiteral: invalid literal for float(): 1.25.6 Int --- :class:`zope.schema.Int` fields contain binary data, represented as a a Python ``int``. Conversion from Unicode: .. doctest:: >>> from zope.schema import Int >>> f = Int() >>> f.fromUnicode("1") 1 >>> f.fromUnicode("1.25.6") #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidIntLiteral: invalid literal for int() with base 10: 1.25.6 Decimal ------- :class:`zope.schema.Decimal` fields contain binary data, represented as a a Python :class:`decimal.Decimal`. Conversion from Unicode: .. doctest:: >>> from zope.schema import Decimal >>> f = Decimal() >>> import decimal >>> isinstance(f.fromUnicode("1.25"), decimal.Decimal) True >>> float(f.fromUnicode("1.25")) 1.25 >>> f.fromUnicode("1.25.6") Traceback (most recent call last): ... InvalidDecimalLiteral: invalid literal for Decimal(): 1.25.6 Datetime -------- :class:`zope.schema.Datetime` fields contain binary data, represented as a a Python :class:`datetime.datetime`. Date ---- :class:`zope.schema.Date` fields contain binary data, represented as a a Python :class:`datetime.date`. TimeDelta --------- :class:`zope.schema.TimeDelta` fields contain binary data, represented as a a Python :class:`datetime.timedelta`. Time ---- :class:`zope.schema.Time` fields contain binary data, represented as a a Python :class:`datetime.time`. Choice ------ :class:`zope.schema.Choice` fields are constrained to values drawn from a specified set, which can be static or dynamic. Conversion from Unicode enforces the constraint: .. doctest:: >>> from zope.schema.interfaces import IFromUnicode >>> from zope.schema.vocabulary import SimpleVocabulary >>> from zope.schema import Choice >>> t = Choice( ... vocabulary=SimpleVocabulary.fromValues([u'foo',u'bar'])) >>> IFromUnicode.providedBy(t) True >>> t.fromUnicode(u"baz") Traceback (most recent call last): ... ConstraintNotSatisfied: baz >>> result = t.fromUnicode(u"foo") >>> isinstance(result, bytes) False >>> print(result) foo By default, ValueErrors are thrown if duplicate values or tokens are passed in. If you are using this vocabulary as part of a form that is generated from non-pristine data, this may not be the desired behavior. If you want to swallow these exceptions, pass in swallow_duplicates=True when initializing the vocabulary. See the test cases for an example. Text ---- By default NFC unicode normalization is enabled for :class:`zope.schema.Text`. Valid forms are 'NFC', 'NFKC', 'NFD', and 'NFKD'. To set the normalization form, use the parameter ``unicode_normalization`` when creating the field. Set the parameter to a falsy value to disable unicode normalization. URI --- :class:`zope.schema.URI` fields contain native Python strings (``str``), matching the "scheme:data" pattern. Validation ensures that the pattern is matched: .. doctest:: >>> from zope.schema import URI >>> uri = URI(__name__='test') >>> uri.validate("http://www.python.org/foo/bar") >>> uri.validate("DAV:") >>> uri.validate("www.python.org/foo/bar") Traceback (most recent call last): ... InvalidURI: www.python.org/foo/bar Conversion from Unicode: .. doctest:: >>> uri = URI(__name__='test') >>> uri.fromUnicode("http://www.python.org/foo/bar") 'http://www.python.org/foo/bar' >>> uri.fromUnicode(" http://www.python.org/foo/bar") 'http://www.python.org/foo/bar' >>> uri.fromUnicode(" \n http://www.python.org/foo/bar\n") 'http://www.python.org/foo/bar' >>> uri.fromUnicode("http://www.python.org/ foo/bar") Traceback (most recent call last): ... InvalidURI: http://www.python.org/ foo/bar DottedName ---------- :class:`zope.schema.DottedName` fields contain native Python strings (``str``), containing zero or more "dots" separating elements of the name. The minimum and maximum number of dots can be passed to the constructor: .. doctest:: >>> from zope.schema import DottedName >>> DottedName(min_dots=-1) Traceback (most recent call last): ... ValueError: min_dots cannot be less than zero >>> DottedName(max_dots=-1) Traceback (most recent call last): ... ValueError: max_dots cannot be less than min_dots >>> DottedName(max_dots=1, min_dots=2) Traceback (most recent call last): ... ValueError: max_dots cannot be less than min_dots >>> dotted_name = DottedName(max_dots=1, min_dots=1) >>> from zope.interface.verify import verifyObject >>> from zope.schema.interfaces import IDottedName >>> verifyObject(IDottedName, dotted_name) True >>> dotted_name = DottedName(max_dots=1) >>> dotted_name.min_dots 0 >>> dotted_name = DottedName(min_dots=1) >>> dotted_name.max_dots >>> dotted_name.min_dots 1 Validation ensures that the pattern is matched: .. doctest:: >>> dotted_name = DottedName(__name__='test') >>> dotted_name.validate("a.b.c") >>> dotted_name.validate("a") >>> dotted_name.validate(" a") Traceback (most recent call last): ... InvalidDottedName: a >>> dotted_name = DottedName(__name__='test', min_dots=1) >>> dotted_name.validate('a.b') >>> dotted_name.validate('a.b.c.d') >>> dotted_name.validate('a') Traceback (most recent call last): ... InvalidDottedName: ('too few dots; 1 required', 'a') >>> dotted_name = DottedName(__name__='test', max_dots=0) >>> dotted_name.validate('a') >>> dotted_name.validate('a.b') Traceback (most recent call last): ... InvalidDottedName: ('too many dots; no more than 0 allowed', 'a.b') >>> dotted_name = DottedName(__name__='test', max_dots=2) >>> dotted_name.validate('a') >>> dotted_name.validate('a.b') >>> dotted_name.validate('a.b.c') >>> dotted_name.validate('a.b.c.d') Traceback (most recent call last): ... InvalidDottedName: ('too many dots; no more than 2 allowed', 'a.b.c.d') >>> dotted_name = DottedName(__name__='test', max_dots=1, min_dots=1) >>> dotted_name.validate('a.b') >>> dotted_name.validate('a') Traceback (most recent call last): ... InvalidDottedName: ('too few dots; 1 required', 'a') >>> dotted_name.validate('a.b.c') Traceback (most recent call last): ... InvalidDottedName: ('too many dots; no more than 1 allowed', 'a.b.c') Id ## :class:`zope.schema.Id` fields contain native Python strings (``str``), matching either the URI pattern or a "dotted name". Validation ensures that the pattern is matched: .. doctest:: >>> from zope.schema import Id >>> id = Id(__name__='test') >>> id.validate("http://www.python.org/foo/bar") >>> id.validate("zope.app.content") >>> id.validate("zope.app.content/a") Traceback (most recent call last): ... InvalidId: zope.app.content/a >>> id.validate("http://zope.app.content x y") Traceback (most recent call last): ... InvalidId: http://zope.app.content x y Conversion from Unicode: .. doctest:: >>> id = Id(__name__='test') >>> id.fromUnicode("http://www.python.org/foo/bar") 'http://www.python.org/foo/bar' >>> id.fromUnicode(u" http://www.python.org/foo/bar ") 'http://www.python.org/foo/bar' >>> id.fromUnicode("http://www.python.org/ foo/bar") Traceback (most recent call last): ... InvalidId: http://www.python.org/ foo/bar >>> id.fromUnicode(" \n x.y.z \n") 'x.y.z' Collections =========== Normal fields typically describe the API of the attribute -- does it behave as a Python Int, or a Float, or a Bool -- and various constraints to the model, such as a maximum or minimum value. Collection fields have additional requirements because they contain other types, which may also be described and constrained. For instance, imagine a list that contains non-negative floats and enforces uniqueness. In a schema, this might be written as follows: .. doctest:: >>> from zope.interface import Interface >>> from zope.schema import List, Float >>> class IInventoryItem(Interface): ... pricePoints = List( ... title=u"Price Points", ... unique=True, ... value_type=Float(title=u"Price", min=0.0) ... ) This indicates several things. - pricePoints is an attribute of objects that implement IInventoryItem. - The contents of pricePoints can be accessed and manipulated via a Python list API. - Each member of pricePoints must be a non-negative float. - Members cannot be duplicated within pricePoints: each must be must be unique. - The attribute and its contents have descriptive titles. Typically these would be message ids. This declaration creates a field that implements a number of interfaces, among them these: .. doctest:: >>> from zope.schema.interfaces import IList, ISequence, ICollection >>> IList.providedBy(IInventoryItem['pricePoints']) True >>> ISequence.providedBy(IInventoryItem['pricePoints']) True >>> ICollection.providedBy(IInventoryItem['pricePoints']) True Creating a custom collection field ================================== Ideally, custom collection fields have interfaces that inherit appropriately from either zope.schema.interfaces.ISequence or zope.schema.interfaces.IUnorderedCollection. Most collection fields should be able to subclass :class:`zope.schema._field.AbstractCollection` to get the necessary behavior. Notice the behavior of the Set field in zope.schema: this would also be necessary to implement a Bag. Choices and Vocabularies ======================== Choice fields are the schema way of spelling enumerated fields and more. By providing a dynamically generated list of options, the choices available to a choice field can be contextually calculated. Simple choices can directly specify the values they accept: .. doctest:: >>> from zope.schema import Choice >>> f = Choice((640, 1028, 1600)) >>> f.validate(640) >>> f.validate(960) Traceback (most recent call last): ... ConstraintNotSatisfied: 960 >>> f.validate('bing') Traceback (most recent call last): ... ConstraintNotSatisfied: bing More complex choices will want to use *vocabularies*, possibly created from a contextual *vocabulary factory*; this factory can either be directly provided at construction time or *named* and looked up in a registry at binding or validation time. Vocabularies have a simple interface, as defined in `zope.schema.interfaces.IBaseVocabulary`. A vocabulary must minimally be able to determine whether it contains a value, to create a term object for a value, and to return a query interface (or None) to find items in itself. Term objects are an abstraction that wraps a vocabulary value. Many applications that deal with accepting user input and validating it against a choice may need a fuller vocabulary interface that provides "tokens" on its terms: ASCII values that have a one-to-one relationship to the values when the vocabulary is asked to "getTermByToken". If a vocabulary is small, it can also support the `zope.schema.interfaces.IIterableVocabulary` interface. `zope.schema.vocabulary.SimpleVocabulary` is a vocabulary implementation that may do all you need for many simple tasks. The vocabulary interface is simple enough that writing a custom vocabulary is not too difficult itself. See `zope.schema.vocabulary.TreeVocabulary` for another ``IBaseVocabulary`` supporting vocabulary that provides a nested, tree-like structure. Vocabulary Factories -------------------- Sometimes the values for a choice really are dynamic. For example, they might depend on the context object being validated. In that case, we can provide an object that provides `zope.schema.interfaces.IContextSourceBinder` as the ``source`` parameter. When the Choice needs a vocabulary, it will call the ``IContextSourceBinder``, passing in its context. This could be as simple as a function: .. doctest:: >>> from zope.schema.vocabulary import SimpleVocabulary >>> from zope.schema.interfaces import IContextSourceBinder >>> from zope.interface import directlyProvides >>> def myDynamicVocabulary(context): ... v = range(context) ... return SimpleVocabulary.fromValues(v) >>> directlyProvides(myDynamicVocabulary, IContextSourceBinder) >>> f = Choice(source=myDynamicVocabulary) Note that the source is only invoked for fields that have been bound to a context: .. doctest:: >>> f.validate(1) Traceback (most recent call last): ... InvalidVocabularyError: Invalid vocabulary >>> f = f.bind(3) >>> f.validate(1) >>> f.validate(2) >>> f.validate(3) Traceback (most recent call last): ... ConstraintNotSatisfied: 3 Named (Registered) Vocabularies ------------------------------- We can also provide a vocabulary name that will be resolved later against a registry of vocabulary factories (objects that implement :class:`zope.schema.interfaces.IVocabularyFactory`). On the surface, this looks very similar to providing a ``source`` argument: they are both callable objects that take a context and return a vocabulary. The advantage of a named factory is a level of indirection, allowing the same name to be easily used in many different fields, even from packages that aren't aware of each other. For example, an application framework may define choices that use a 'permissions' vocabulary, and individual applications may define their own meaning for that name. A simple version of this is provided in this package using a global vocabulary registry: .. doctest:: >>> from zope.schema.vocabulary import SimpleVocabulary >>> from zope.schema.vocabulary import getVocabularyRegistry >>> from zope.schema.interfaces import IVocabularyFactory >>> from zope.interface import implementer >>> @implementer(IVocabularyFactory) ... class PermissionsVocabulary(object): ... ... def __call__(self, context): ... if context is None: raise AttributeError ... return SimpleVocabulary.fromValues(context.possible_permissions) >>> getVocabularyRegistry().register('permissions', PermissionsVocabulary()) >>> class Context(object): ... possible_permissions = ('read', 'write') Unlike ``IContextSourceBinder``, the factory is invoked even for unbound fields; depending on the factory, this may or may not do anything useful (our factory produces errors): .. doctest:: >>> f = Choice(vocabulary='permissions') >>> f.validate('read') Traceback (most recent call last): ... AttributeError >>> context = Context() >>> f = f.bind(context) >>> f.validate("read") >>> f.validate("write") >>> f.validate("delete") Traceback (most recent call last): ... ConstraintNotSatisfied: ('delete', '') The `zope.vocabularyregistry `_ package provides a registry that keeps factories as named utilities in the `Zope component architecture `_. This is especially useful when combined with the concept of multiple component site managers, as that provides another layer of indirection. Choices and Collections ======================= Choices are a field type and can be used as a ``value_type`` for collections. Just as a collection of an "Int" value_type constrains members to integers, so a choice-based value type constrains members to choices within the Choice's vocabulary. Typically in the Zope application server widgets are found not only for the collection and the choice field but also for the vocabulary on which the choice is based. Using Choice and Collection Fields within a Widget Framework ============================================================ While fields support several use cases, including code documentation and data description and even casting, a significant use case influencing their design is to support form generation -- generating widgets for a field. Choice and collection fields are expected to be used within widget frameworks. The zope.app approach typically (but configurably) uses multiple dispatches to find widgets on the basis of various aspects of the fields. Widgets for all fields are found by looking up a browser view of the field providing an input or display widget view. Typically there is only a single "widget" registered for Choice fields. When it is looked up, it performs another dispatch -- another lookup -- for a widget registered for both the field and the vocabulary. This widget typically has enough information to render without a third dispatch. Collection fields may fire several dispatches. The first is the usual lookup by field. A single "widget" should be registered for ICollection, which does a second lookup by field and value_type constraint, if any, or, theoretically, if value_type is None, renders some absolutely generic collection widget that allows input of any value imaginable: a check-in of such a widget would be unexpected. This second lookup may find a widget that knows how to render, and stop. However, the value_type may be a choice, which will usually fire a third dispatch: a search for a browser widget for the collection field, the value_type field, and the vocabulary. Further lookups may even be configured on the basis of uniqueness and other constraints. This level of indirection may be unnecessary for some applications, and can be disabled with simple ZCML changes within ``zope.app``. zope.schema-6.2.0/docs/hacking.rst0000644000100100000240000002137614133212652016674 0ustar macstaff00000000000000Hacking on :mod:`zope.schema` ============================= Getting the Code ################ The main repository for :mod:`zope.schema` is in the Zope Foundation Github repository: https://github.com/zopefoundation/zope.schema You can get a read-only checkout from there: .. code-block:: sh $ git clone https://github.com/zopefoundation/zope.schema.git or fork it and get a writeable checkout of your fork: .. code-block:: sh $ git clone git@github.com/jrandom/zope.schema.git The project also mirrors the trunk from the Github repository as a Bazaar branch on Launchpad: https://code.launchpad.net/zope.schema You can branch the trunk from there using Bazaar: .. code-block:: sh $ bzr branch lp:zope.schema Working in a ``virtualenv`` ########################### Installing ---------- If you use the ``virtualenv`` package to create lightweight Python development environments, you can run the tests using nothing more than the ``python`` binary in a virtualenv. First, create a scratch environment: .. code-block:: sh $ /path/to/virtualenv --no-site-packages /tmp/hack-zope.schema Next, get this package registered as a "development egg" in the environment: .. code-block:: sh $ /tmp/hack-zope.schema/bin/python setup.py develop Running the tests ----------------- Run the tests using the build-in ``setuptools`` testrunner: .. code-block:: sh $ /tmp/hack-zope.schema/bin/python setup.py test running test ........ ---------------------------------------------------------------------- Ran 400 tests in 0.152s OK If you have the :mod:`nose` package installed in the virtualenv, you can use its testrunner too: .. code-block:: sh $ /tmp/hack-zope.schema/bin/easy_install nose ... $ /tmp/hack-zope.schema/bin/python setup.py nosetests running nosetests ....... ---------------------------------------------------------------------- Ran 400 tests in 0.152s OK or: .. code-block:: sh $ /tmp/hack-zope.schema/bin/nosetests ....... ---------------------------------------------------------------------- Ran 400 tests in 0.152s OK If you have the :mod:`coverage` pacakge installed in the virtualenv, you can see how well the tests cover the code: .. code-block:: sh $ /tmp/hack-zope.schema/bin/easy_install nose coverage ... $ /tmp/hack-zope.schema/bin/python setup.py nosetests \ --with coverage --cover-package=zope.schema running nosetests ... Name Stmts Miss Cover Missing ---------------------------------------------------------------- zope.schema 43 0 100% zope.schema._bootstrapfields 213 0 100% zope.schema._bootstrapinterfaces 40 0 100% zope.schema._compat 4 0 100% zope.schema._field 425 0 100% zope.schema._messageid 2 0 100% zope.schema._schema 45 0 100% zope.schema.accessors 50 0 100% zope.schema.fieldproperty 63 0 100% zope.schema.interfaces 156 0 100% zope.schema.vocabulary 166 0 100% ---------------------------------------------------------------- TOTAL 1207 0 100% ---------------------------------------------------------------------- Ran 410 tests in 1.677s OK Building the documentation -------------------------- :mod:`zope.schema` uses the nifty :mod:`Sphinx` documentation system for building its docs. Using the same virtualenv you set up to run the tests, you can build the docs: .. code-block:: sh $ /tmp/hack-zope.schema/bin/easy_install Sphinx ... $ bin/sphinx-build -b html -d docs/_build/doctrees docs docs/_build/html ... build succeeded. You can also test the code snippets in the documentation: .. code-block:: sh $ bin/sphinx-build -b doctest -d docs/_build/doctrees docs docs/_build/doctest ... Doctest summary =============== 130 tests 0 failures in tests 0 failures in setup code build succeeded. Testing of doctests in the sources finished, look at the \ results in _build/doctest/output.txt. Using :mod:`zc.buildout` ######################## Setting up the buildout ----------------------- :mod:`zope.schema` ships with its own :file:`buildout.cfg` file and :file:`bootstrap.py` for setting up a development buildout: .. code-block:: sh $ /path/to/python2.6 bootstrap.py ... Generated script '.../bin/buildout' $ bin/buildout Develop: '/home/jrandom/projects/Zope/BTK/schema/.' ... Generated script '.../bin/sphinx-quickstart'. Generated script '.../bin/sphinx-build'. Running the tests ----------------- Run the tests: .. code-block:: sh $ bin/test --all Running zope.testing.testrunner.layer.UnitTests tests: Set up zope.testing.testrunner.layer.UnitTests in 0.000 seconds. Ran 400 tests with 0 failures and 0 errors in 0.366 seconds. Tearing down left over layers: Tear down zope.testing.testrunner.layer.UnitTests in 0.000 seconds. Using :mod:`tox` ################ Running Tests on Multiple Python Versions ----------------------------------------- `tox `_ is a Python-based test automation tool designed to run tests against multiple Python versions. It creates a ``virtualenv`` for each configured version, installs the current package and configured dependencies into each ``virtualenv``, and then runs the configured commands. :mod:`zope.schema` configures the following :mod:`tox` environments via its ``tox.ini`` file: - The ``py26``, ``py27``, ``py33``, ``py34``, and ``pypy`` environments builds a ``virtualenv`` with ``pypy``, installs :mod:`zope.schema` and dependencies, and runs the tests via ``python setup.py test -q``. - The ``coverage`` environment builds a ``virtualenv`` with ``python2.6``, installs :mod:`zope.schema`, installs :mod:`nose` and :mod:`coverage`, and runs ``nosetests`` with statement coverage. - The ``docs`` environment builds a virtualenv with ``python2.6``, installs :mod:`zope.schema`, installs ``Sphinx`` and dependencies, and then builds the docs and exercises the doctest snippets. This example requires that you have a working ``python2.6`` on your path, as well as installing ``tox``: .. code-block:: sh $ tox -e py26 GLOB sdist-make: .../zope.interface/setup.py py26 sdist-reinst: .../zope.interface/.tox/dist/zope.interface-4.0.2dev.zip py26 runtests: commands[0] .......... ---------------------------------------------------------------------- Ran 400 tests in 0.152s OK ___________________________________ summary ____________________________________ py26: commands succeeded congratulations :) Running ``tox`` with no arguments runs all the configured environments, including building the docs and testing their snippets: .. code-block:: sh $ tox GLOB sdist-make: .../zope.interface/setup.py py26 sdist-reinst: .../zope.interface/.tox/dist/zope.interface-4.0.2dev.zip py26 runtests: commands[0] ... Doctest summary =============== 140 tests 0 failures in tests 0 failures in setup code 0 failures in cleanup code build succeeded. ___________________________________ summary ____________________________________ py26: commands succeeded py27: commands succeeded py32: commands succeeded pypy: commands succeeded coverage: commands succeeded docs: commands succeeded congratulations :) Contributing to :mod:`zope.schema` ################################## Submitting a Bug Report ----------------------- :mod:`zope.schema` tracks its bugs on Github: https://github.com/zopefoundation/zope.schema/issues Please submit bug reports and feature requests there. Sharing Your Changes -------------------- .. note:: Please ensure that all tests are passing before you submit your code. If possible, your submission should include new tests for new features or bug fixes, although it is possible that you may have tested your new code by updating existing tests. If have made a change you would like to share, the best route is to fork the Githb repository, check out your fork, make your changes on a branch in your fork, and push it. You can then submit a pull request from your branch: https://github.com/zopefoundation/zope.schema/pulls If you branched the code from Launchpad using Bazaar, you have another option: you can "push" your branch to Launchpad: .. code-block:: sh $ bzr push lp:~jrandom/zope.schema/cool_feature After pushing your branch, you can link it to a bug report on Launchpad, or request that the maintainers merge your branch using the Launchpad "merge request" feature. zope.schema-6.2.0/docs/index.rst0000644000100100000240000000044014133212652016364 0ustar macstaff00000000000000Welcome to zope.schema's documentation! ======================================= Contents: .. toctree:: :maxdepth: 2 narr fields sources validation api changelog hacking Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` zope.schema-6.2.0/docs/make.bat0000644000100100000240000001176014133212652016137 0ustar macstaff00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\zopeschema.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\zopeschema.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end zope.schema-6.2.0/docs/narr.rst0000644000100100000240000002315414133212652016226 0ustar macstaff00000000000000============== Zope 3 Schemas ============== Introduction ------------ *This package is intended to be independently reusable in any Python project. It is maintained by the* `Zope Toolkit project `_. Schemas extend the notion of interfaces to detailed descriptions of Attributes (but not methods). Every schema is an interface and specifies the public fields of an object. A *field* roughly corresponds to an attribute of a Python object. But a Field provides space for at least a title and a description. It can also constrain its value and provide a validation method. Besides you can optionally specify characteristics such as its value being read-only or not required. Zope 3 schemas were born when Jim Fulton and Martijn Faassen thought about Formulator for Zope 3 and ``PropertySets`` while at the `Zope 3 sprint`_ at the Zope BBQ in Berlin. They realized that if you strip all view logic from forms then you have something similar to interfaces. And thus schemas were born. .. _Zope 3 sprint: http://dev.zope.org/Zope3/ZopeBBQ2002Sprint Simple Usage ------------ Let's have a look at a simple example. First we write an interface as usual, but instead of describing the attributes of the interface with ``Attribute`` instances, we now use schema fields: .. doctest:: >>> import zope.interface >>> import zope.schema >>> class IBookmark(zope.interface.Interface): ... title = zope.schema.TextLine( ... title=u'Title', ... description=u'The title of the bookmark', ... required=True) ... ... url = zope.schema.URI( ... title=u'Bookmark URL', ... description=u'URL of the Bookmark', ... required=True) ... Now we create a class that implements this interface and create an instance of it: .. doctest:: >>> @zope.interface.implementer(IBookmark) ... class Bookmark(object): ... ... title = None ... url = None >>> bm = Bookmark() We would now like to only add validated values to the class. This can be done by first validating and then setting the value on the object. The first step is to define some data: .. doctest:: >>> title = u'Zope 3 Website' >>> url = 'http://dev.zope.org/Zope3' Now we, get the fields from the interface: .. doctest:: >>> title_field = IBookmark.get('title') >>> url_field = IBookmark.get('url') Next we have to bind these fields to the context, so that instance-specific information can be used for validation: .. doctest:: >>> title_bound = title_field.bind(bm) >>> url_bound = url_field.bind(bm) Now that the fields are bound, we can finally validate the data: .. doctest:: >>> title_bound.validate(title) >>> url_bound.validate(url) If the validation is successful, ``None`` is returned. If a validation error occurs a ``ValidationError`` will be raised; for example: .. doctest:: >>> from zope.schema._compat import non_native_string >>> url_bound.validate(non_native_string('http://zope.org/foo')) Traceback (most recent call last): ... WrongType: ... >>> url_bound.validate('foo.bar') Traceback (most recent call last): ... InvalidURI: foo.bar Now that the data has been successfully validated, we can set it on the object: .. doctest:: >>> title_bound.set(bm, title) >>> url_bound.set(bm, url) That's it. You still might think this is a lot of work to validate and set a value for an object. Note, however, that it is very easy to write helper functions that automate these tasks. If correctly designed, you will never have to worry explicitly about validation again, since the system takes care of it automatically. What is a schema, how does it compare to an interface? ------------------------------------------------------ A schema is an extended interface which defines fields. You can validate that the attributes of an object conform to their fields defined on the schema. With plain interfaces you can only validate that methods conform to their interface specification. So interfaces and schemas refer to different aspects of an object (respectively its code and state). A schema starts out like an interface but defines certain fields to which an object's attributes must conform. Let's look at a stripped down example from the programmer's tutorial: .. doctest:: >>> import re >>> class IContact(zope.interface.Interface): ... """Provides access to basic contact information.""" ... ... first = zope.schema.TextLine(title=u"First name") ... ... last = zope.schema.TextLine(title=u"Last name") ... ... email = zope.schema.TextLine(title=u"Electronic mail address") ... ... address = zope.schema.Text(title=u"Postal address") ... ... postalCode = zope.schema.TextLine( ... title=u"Postal code", ... constraint=re.compile("\d{5,5}(-\d{4,4})?$").match) ``TextLine`` is a field and expresses that an attribute is a single line of Unicode text. ``Text`` expresses an arbitrary Unicode ("text") object. The most interesting part is the last attribute specification. It constrains the ``postalCode`` attribute to only have values that are US postal codes. Now we want a class that adheres to the ``IContact`` schema: .. doctest:: >>> @zope.interface.implementer(IContact) ... class Contact(object): ... ... def __init__(self, first, last, email, address, pc): ... self.first = first ... self.last = last ... self.email = email ... self.address = address ... self.postalCode = pc Now you can see if an instance of ``Contact`` actually implements the schema: .. doctest:: >>> someone = Contact(u'Tim', u'Roberts', u'tim@roberts', u'', ... u'12032-3492') >>> for field in zope.schema.getFields(IContact).values(): ... bound = field.bind(someone) ... bound.validate(bound.get(someone)) Data Modeling Concepts ----------------------- The ``zope.schema`` package provides a core set of field types, including single- and multi-line text fields, binary data fields, integers, floating-point numbers, and date/time values. Selection issues; field type can specify: - "Raw" data value Simple values not constrained by a selection list. - Value from enumeration (options provided by schema) This models a single selection from a list of possible values specified by the schema. The selection list is expected to be the same for all values of the type. Changes to the list are driven by schema evolution. This is done by mixing-in the ``IEnumerated`` interface into the field type, and the Enumerated mix-in for the implementation (or emulating it in a concrete class). - Value from selection list (options provided by an object) This models a single selection from a list of possible values specified by a source outside the schema. The selection list depends entirely on the source of the list, and may vary over time and from object to object. Changes to the list are not related to the schema, but changing how the list is determined is based on schema evolution. There is not currently a spelling of this, but it could be facilitated using alternate mix-ins similar to IEnumerated and Enumerated. - Whether or not the field is read-only If a field value is read-only, it cannot be changed once the object is created. - Whether or not the field is required If a field is designated as required, assigned field values must always be non-missing. See the next section for a description of missing values. - A value designated as ``missing`` Missing values, when assigned to an object, indicate that there is 'no data' for that field. Missing values are analogous to null values in relational databases. For example, a boolean value can be True, False, or missing, in which case its value is unknown. While Python's None is the most likely value to signify 'missing', some fields may use different values. For example, it is common for text fields to use the empty string ('') to signify that a value is missing. Numeric fields may use 0 or -1 instead of None as their missing value. A field that is 'required' signifies that missing values are invalid and should not be assigned. - A default value Default field values are assigned to objects when they are first created. A default factory can be specified to dynamically compute default values. Fields and Widgets ------------------ Widgets are components that display field values and, in the case of writable fields, allow the user to edit those values. Widgets: - Display current field values, either in a read-only format, or in a format that lets the user change the field value. - Update their corresponding field values based on values provided by users. - Manage the relationships between their representation of a field value and the object's field value. For example, a widget responsible for editing a number will likely represent that number internally as a string. For this reason, widgets must be able to convert between the two value formats. In the case of the number-editing widget, string values typed by the user need to be converted to numbers such as int or float. - Support the ability to assign a missing value to a field. For example, a widget may present a ``None`` option for selection that, when selected, indicates that the object should be updated with the field's ``missing`` value. References ---------- - Use case list, http://dev.zope.org/Zope3/Zope3SchemasUseCases - Documented interfaces, zope/schema/interfaces.py - Jim Fulton's Programmers Tutorial; in CVS: Docs/ZopeComponentArchitecture/PythonProgrammerTutorial/Chapter2 zope.schema-6.2.0/docs/sources.rst0000644000100100000240000000606714133212652016753 0ustar macstaff00000000000000======= Sources ======= Concepts -------- Sources are designed with three concepts: - The source itself - an iterable This can return any kind of object it wants. It doesn't have to care for browser representation, encoding, ... - A way to map a value from the iterable to something that can be used for form *values* - this is called a token. A token is commonly a (unique) 7bit representation of the value. - A way to map a value to something that can be displayed to the user - this is called a title The last two elements are dispatched using a so called `term`. The ITitledTokenizedTerm interface contains a triple of (value, token, title). Additionally there are some lookup functions to perform the mapping between values and terms and tokens and terms. Sources that require context use a special factory: a context source binder that is called with the context and instanciates the source when it is actually used. Sources in Fields ----------------- A choice field can be constructed with a source or source name. When a source is used, it will be used as the source for valid values. Create a source for all odd numbers. .. doctest:: >>> from zope import interface >>> from zope.schema.interfaces import ISource, IContextSourceBinder >>> @interface.implementer(ISource) ... class MySource(object): ... divisor = 2 ... def __contains__(self, value): ... return bool(value % self.divisor) >>> my_source = MySource() >>> 1 in my_source True >>> 2 in my_source False >>> from zope.schema import Choice >>> choice = Choice(__name__='number', source=my_source) >>> bound = choice.bind(object()) >>> bound.vocabulary <...MySource...> If a IContextSourceBinder is passed as the `source` argument to Choice, it's `bind` method will be called with the context as its only argument. The result must implement ISource and will be used as the source. .. doctest:: >>> _my_binder_called = [] >>> def my_binder(context): ... _my_binder_called.append(context) ... source = MySource() ... source.divisor = context.divisor ... return source >>> interface.directlyProvides(my_binder, IContextSourceBinder) >>> class Context(object): ... divisor = 3 >>> choice = Choice(__name__='number', source=my_binder) >>> bound = choice.bind(Context()) >>> len(_my_binder_called) 1 >>> bound.vocabulary <...MySource...> >>> bound.vocabulary.divisor 3 When using IContextSourceBinder together with default value, it's impossible to validate it on field initialization. Let's check if initalization doesn't fail in that case. .. doctest:: >>> choice = Choice(__name__='number', source=my_binder, default=2) >>> del _my_binder_called[:] >>> bound = choice.bind(Context()) >>> len(_my_binder_called) 1 >>> bound.validate(bound.default) >>> bound.validate(3) Traceback (most recent call last): ... ConstraintNotSatisfied: 3 It's developer's responsibility to provide a default value that fits the constraints when using context-based sources. zope.schema-6.2.0/docs/validation.rst0000644000100100000240000001147114133212652017415 0ustar macstaff00000000000000================= Schema Validation ================= There are two helper methods to verify schemas and interfaces: .. autofunction:: zope.schema.getValidationErrors .. autofunction:: zope.schema.getSchemaValidationErrors Invariants are `documented by zope.interface `_. Create an interface to validate against: .. doctest:: >>> import zope.interface >>> import zope.schema >>> _a_greater_b_called = [] >>> class ITwoInts(zope.interface.Interface): ... a = zope.schema.Int(max=10) ... b = zope.schema.Int(min=5) ... ... @zope.interface.invariant ... def a_greater_b(obj): ... _a_greater_b_called.append(obj) ... if obj.a <= obj.b: ... raise zope.interface.Invalid("%s<=%s" % (obj.a, obj.b)) ... Create a silly model: .. doctest:: >>> class TwoInts(object): ... pass Create an instance of TwoInts but do not set attributes. We get two errors: .. doctest:: >>> ti = TwoInts() >>> r = zope.schema.getValidationErrors(ITwoInts, ti) >>> r.sort() >>> len(r) 2 >>> r[0][0] 'a' >>> r[0][1].__class__.__name__ 'SchemaNotFullyImplemented' >>> r[0][1].args[0].args ("'TwoInts' object has no attribute 'a'",) >>> r[1][0] 'b' >>> r[1][1].__class__.__name__ 'SchemaNotFullyImplemented' >>> r[1][1].args[0].args ("'TwoInts' object has no attribute 'b'",) The `getSchemaValidationErrors` function returns the same result: .. doctest:: >>> r = zope.schema.getSchemaValidationErrors(ITwoInts, ti) >>> r.sort() >>> len(r) 2 >>> r[0][0] 'a' >>> r[0][1].__class__.__name__ 'SchemaNotFullyImplemented' >>> r[0][1].args[0].args ("'TwoInts' object has no attribute 'a'",) >>> r[1][0] 'b' >>> r[1][1].__class__.__name__ 'SchemaNotFullyImplemented' >>> r[1][1].args[0].args ("'TwoInts' object has no attribute 'b'",) Note that see no error from the invariant because the invariants are not validated if there are other schema errors. When we set a valid value for `a` we still get the same error for `b`: .. doctest:: >>> ti.a = 11 >>> errors = zope.schema.getValidationErrors(ITwoInts, ti) >>> errors.sort() >>> len(errors) 2 >>> errors[0][0] 'a' >>> print(errors[0][1].doc()) Value is too big >>> errors[0][1].__class__.__name__ 'TooBig' >>> errors[0][1].args (11, 10) >>> errors[1][0] 'b' >>> errors[1][1].__class__.__name__ 'SchemaNotFullyImplemented' >>> errors[1][1].args[0].args ("'TwoInts' object has no attribute 'b'",) After setting a valid value for `a` there is only the error for the missing `b` left: .. doctest:: >>> ti.a = 8 >>> r = zope.schema.getValidationErrors(ITwoInts, ti) >>> r [('b', SchemaNotFullyImplemented(...AttributeError...))] >>> r[0][1].args[0].args ("'TwoInts' object has no attribute 'b'",) After setting valid value for `b` the schema is valid so the invariants are checked. As `b>a` the invariant fails: .. doctest:: >>> ti.b = 10 >>> errors = zope.schema.getValidationErrors(ITwoInts, ti) >>> len(errors) 1 >>> errors[0][0] is None True >>> errors[0][1].__class__.__name__ 'Invalid' >>> len(_a_greater_b_called) 1 When using `getSchemaValidationErrors` we do not get an error any more: .. doctest:: >>> zope.schema.getSchemaValidationErrors(ITwoInts, ti) [] Set `b=5` so everything is fine: .. doctest:: >>> ti.b = 5 >>> del _a_greater_b_called[:] >>> zope.schema.getValidationErrors(ITwoInts, ti) [] >>> len(_a_greater_b_called) 1 Compare ValidationError ----------------------- There was an issue with compare validation error with something else then an exceptions. Let's test if we can compare ValidationErrors with different things .. doctest:: >>> from zope.schema._bootstrapinterfaces import ValidationError >>> v1 = ValidationError('one') >>> v2 = ValidationError('one') >>> v3 = ValidationError('another one') A ValidationError with the same arguments compares: .. doctest:: >>> v1 == v2 True but not with an error with different arguments: .. doctest:: >>> v1 == v3 False We can also compare validation errors with other things then errors. This was running into an AttributeError in previous versions of zope.schema. e.g. AttributeError: 'NoneType' object has no attribute 'args' .. doctest:: >>> v1 == None False >>> v1 == object() False >>> v1 == False False >>> v1 == True False >>> v1 == 0 False >>> v1 == 1 False >>> v1 == int False If we compare a ValidationError with another validation error based class, we will get the following result: .. doctest:: >>> from zope.schema._bootstrapinterfaces import RequiredMissing >>> r1 = RequiredMissing('one') >>> v1 == r1 True zope.schema-6.2.0/rtd.txt0000644000100100000240000000005314133212652015125 0ustar macstaff00000000000000repoze.sphinx.autointerface zope.interface zope.schema-6.2.0/setup.cfg0000644000100100000240000000032314133212652015414 0ustar macstaff00000000000000[bdist_wheel] universal = 1 [flake8] doctests = 1 [check-manifest] ignore = .editorconfig .meta.toml docs/_build/html/_sources/* docs/_build/doctest/* docs/_static [egg_info] tag_build = tag_date = 0 zope.schema-6.2.0/setup.py0000644000100100000240000000614214133212652015312 0ustar macstaff00000000000000############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## # This package is developed by the Zope Toolkit project, documented here: # http://docs.zope.org/zopetoolkit # When developing and releasing this package, please follow the documented # Zope Toolkit policies as described by this documentation. ############################################################################## """Setup for zope.schema package """ import os from setuptools import setup, find_packages def read(*rnames): with open(os.path.join(os.path.dirname(__file__), *rnames)) as f: return f.read() REQUIRES = [ 'setuptools', 'zope.interface >= 5.0.0', 'zope.event', ] TESTS_REQUIRE = [ 'zope.i18nmessageid', 'zope.testing', 'zope.testrunner', ] setup( name='zope.schema', version=read('version.txt').strip(), url='https://github.com/zopefoundation/zope.schema', license='ZPL 2.1', description='zope.interface extension for defining data schemas', author='Zope Foundation and Contributors', author_email='zope-dev@zope.org', long_description=(read('README.rst') + '\n\n' + read('CHANGES.rst')), packages=find_packages('src'), package_dir={'': 'src'}, namespace_packages=['zope', ], install_requires=REQUIRES, keywords="zope3 schema field interface typing", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: Zope Public License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Framework :: Zope :: 3", "Topic :: Software Development :: Libraries :: Python Modules", ], python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*', include_package_data=True, zip_safe=False, tests_require=TESTS_REQUIRE, extras_require={ 'docs': [ 'Sphinx', 'repoze.sphinx.autointerface', ], 'test': TESTS_REQUIRE, }, ) zope.schema-6.2.0/src/0000755000100100000240000000000014133212652014364 5ustar macstaff00000000000000zope.schema-6.2.0/src/zope/0000755000100100000240000000000014133212652015341 5ustar macstaff00000000000000zope.schema-6.2.0/src/zope/__init__.py0000644000100100000240000000007014133212652017447 0ustar macstaff00000000000000__import__('pkg_resources').declare_namespace(__name__) zope.schema-6.2.0/src/zope/schema/0000755000100100000240000000000014133212652016601 5ustar macstaff00000000000000zope.schema-6.2.0/src/zope/schema/__init__.py0000644000100100000240000000744114133212652020720 0ustar macstaff00000000000000############################################################################## # # Copyright (c) 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Schema package constructor """ # Field APIs from zope.schema._field import ASCII from zope.schema._field import ASCIILine from zope.schema._field import Bool from zope.schema._field import Bytes from zope.schema._field import BytesLine from zope.schema._field import Choice from zope.schema._field import Collection from zope.schema._field import Complex from zope.schema._field import Container from zope.schema._field import Date from zope.schema._field import Datetime from zope.schema._field import Decimal from zope.schema._field import Dict from zope.schema._field import DottedName from zope.schema._field import Field from zope.schema._field import Float from zope.schema._field import FrozenSet from zope.schema._field import Id from zope.schema._field import Int from zope.schema._field import Integral from zope.schema._field import InterfaceField from zope.schema._field import Iterable from zope.schema._field import List from zope.schema._field import Mapping from zope.schema._field import MinMaxLen from zope.schema._field import MutableMapping from zope.schema._field import MutableSequence from zope.schema._field import NativeString from zope.schema._field import NativeStringLine from zope.schema._field import Number from zope.schema._field import Object from zope.schema._field import Orderable from zope.schema._field import Password from zope.schema._field import PythonIdentifier from zope.schema._field import Rational from zope.schema._field import Real from zope.schema._field import Sequence from zope.schema._field import Set from zope.schema._field import SourceText from zope.schema._field import Text from zope.schema._field import TextLine from zope.schema._field import Time from zope.schema._field import Timedelta from zope.schema._field import Tuple from zope.schema._field import URI # Schema APIs from zope.schema._schema import getFields from zope.schema._schema import getFieldsInOrder from zope.schema._schema import getFieldNames from zope.schema._schema import getFieldNamesInOrder from zope.schema._schema import getValidationErrors from zope.schema._schema import getSchemaValidationErrors # Acessor API from zope.schema.accessors import accessors # Error API from zope.schema.interfaces import ValidationError from zope.schema._bootstrapinterfaces import NO_VALUE __all__ = [ 'ASCII', 'ASCIILine', 'Bool', 'Bytes', 'BytesLine', 'Choice', 'Collection', 'Complex', 'Container', 'Date', 'Datetime', 'Decimal', 'Dict', 'DottedName', 'Field', 'Float', 'FrozenSet', 'Id', 'Int', 'Integral', 'InterfaceField', 'Iterable', 'List', 'Mapping', 'MutableMapping', 'MutableSequence', 'MinMaxLen', 'NativeString', 'NativeStringLine', 'Number', 'Object', 'Orderable', 'PythonIdentifier', 'Password', 'Rational', 'Real', 'Set', 'Sequence', 'SourceText', 'Text', 'TextLine', 'Time', 'Timedelta', 'Tuple', 'URI', 'getFields', 'getFieldsInOrder', 'getFieldNames', 'getFieldNamesInOrder', 'getValidationErrors', 'getSchemaValidationErrors', 'accessors', 'ValidationError', 'NO_VALUE' ] zope.schema-6.2.0/src/zope/schema/_bootstrapfields.py0000644000100100000240000012050014133212652022514 0ustar macstaff00000000000000############################################################################## # # Copyright (c) 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrapping fields """ __docformat__ = 'restructuredtext' import decimal import fractions import numbers import sys import threading import unicodedata from math import isinf from zope.interface import Attribute from zope.interface import Invalid from zope.interface import Interface from zope.interface import providedBy from zope.interface import implementer from zope.interface.interface import InterfaceClass from zope.interface.interfaces import IInterface from zope.interface.interfaces import IMethod from zope.event import notify from zope.schema._bootstrapinterfaces import ConstraintNotSatisfied from zope.schema._bootstrapinterfaces import IBeforeObjectAssignedEvent from zope.schema._bootstrapinterfaces import IContextAwareDefaultFactory from zope.schema._bootstrapinterfaces import IFromBytes from zope.schema._bootstrapinterfaces import IFromUnicode from zope.schema._bootstrapinterfaces import IValidatable from zope.schema._bootstrapinterfaces import NotAContainer from zope.schema._bootstrapinterfaces import NotAnIterator from zope.schema._bootstrapinterfaces import NotAnInterface from zope.schema._bootstrapinterfaces import RequiredMissing from zope.schema._bootstrapinterfaces import SchemaNotCorrectlyImplemented from zope.schema._bootstrapinterfaces import SchemaNotFullyImplemented from zope.schema._bootstrapinterfaces import SchemaNotProvided from zope.schema._bootstrapinterfaces import StopValidation from zope.schema._bootstrapinterfaces import TooBig from zope.schema._bootstrapinterfaces import TooLong from zope.schema._bootstrapinterfaces import TooShort from zope.schema._bootstrapinterfaces import TooSmall from zope.schema._bootstrapinterfaces import ValidationError from zope.schema._bootstrapinterfaces import WrongType from zope.schema._compat import text_type from zope.schema._compat import integer_types from zope.schema._compat import PY2 class _NotGiven(object): def __repr__(self): # pragma: no cover return "" _NotGiven = _NotGiven() class ValidatedProperty(object): def __init__(self, name, check=None, allow_none=False): self._name = name self._check = check self._allow_none = allow_none def __set__(self, inst, value): bypass_validation = ( (value is None and self._allow_none) or value == inst.missing_value ) if not bypass_validation: if self._check is not None: self._check(inst, value) else: inst.validate(value) inst.__dict__[self._name] = value def __get__(self, inst, owner): if inst is None: return self return inst.__dict__[self._name] class DefaultProperty(ValidatedProperty): def __get__(self, inst, owner): if inst is None: return self defaultFactory = inst.__dict__.get('defaultFactory') # If there is no default factory, simply return the default. if defaultFactory is None: return inst.__dict__[self._name] # Get the default value by calling the factory. Some factories might # require a context to produce a value. if IContextAwareDefaultFactory.providedBy(defaultFactory): value = defaultFactory(inst.context) else: value = defaultFactory() # Check that the created value is valid. if self._check is not None: self._check(inst, value) elif value != inst.missing_value: inst.validate(value) return value def getFields(schema): """Return a dictionary containing all the Fields in a schema. """ fields = {} for name in schema: attr = schema[name] if IValidatable.providedBy(attr): fields[name] = attr return fields class _DocStringHelpers(object): # Namespace object to hold methods related to ReST formatting # docstrings @staticmethod def docstring_to_lines(docstring): # Similar to what sphinx.utils.docstrings.prepare_docstring # does. Strip leading equal whitespace, accounting for an initial line # that might not have any. Return a list of lines, with a trailing # blank line. lines = docstring.expandtabs().splitlines() # Find minimum indentation of any non-blank lines after ignored lines. margin = sys.maxsize for line in lines[1:]: content = len(line.lstrip()) if content: indent = len(line) - content margin = min(margin, indent) # Remove indentation from first ignored lines. if len(lines) >= 1: lines[0] = lines[0].lstrip() if margin < sys.maxsize: for i in range(1, len(lines)): lines[i] = lines[i][margin:] # Remove any leading blank lines. while lines and not lines[0]: lines.pop(0) # lines.append('') return lines @staticmethod def make_class_directive(kind): mod = kind.__module__ if kind.__module__ in ('__builtin__', 'builtins'): mod = '' if mod in ('zope.schema._bootstrapfields', 'zope.schema._field'): mod = 'zope.schema' mod += '.' if mod else '' return ':class:`%s%s`' % (mod, kind.__name__) @classmethod def make_field(cls, name, value): return ":%s: %s" % (name, value) @classmethod def make_class_field(cls, name, kind): if isinstance(kind, (type, InterfaceClass)): 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,)) return cls.make_field( name, ', '.join([cls.make_class_directive(t) for t in kind])) class Field(Attribute): # Type restrictions, if any _type = None context = None # If a field has no assigned value, it will be set to missing_value. missing_value = None # This is the default value for the missing_value argument to the # Field constructor. A marker is helpful since we don't want to # overwrite missing_value if it is set differently on a Field # subclass and isn't specified via the constructor. __missing_value_marker = _NotGiven # Note that the "order" field has a dual existance: # 1. The class variable Field.order is used as a source for the # monotonically increasing values used to provide... # 2. The instance variable self.order which provides a # monotonically increasing value that tracks the creation order # of Field (including Field subclass) instances. order = 0 default = DefaultProperty('default') # These were declared as slots in zope.interface, we override them here to # get rid of the descriptors so they don't break .bind() __name__ = None interface = None _Element__tagged_values = None def __init__(self, title=u'', description=u'', __name__='', required=True, readonly=False, constraint=None, default=None, defaultFactory=None, missing_value=__missing_value_marker): """Pass in field values as keyword parameters. Generally, you want to pass either a title and description, or a doc string. If you pass no doc string, it will be computed from the title and description. If you pass a doc string that follows the Python coding style (title line separated from the body by a blank line), the title and description will be computed from the doc string. Unfortunately, the doc string must be passed as a positional argument. Here are some examples: >>> from zope.schema._bootstrapfields import Field >>> f = Field() >>> f.__doc__, str(f.title), str(f.description) ('', '', '') >>> f = Field(title=u'sample') >>> str(f.__doc__), str(f.title), str(f.description) ('sample', 'sample', '') >>> f = Field(title=u'sample', description=u'blah blah\\nblah') >>> str(f.__doc__), str(f.title), str(f.description) ('sample\\n\\nblah blah\\nblah', 'sample', 'blah blah\\nblah') """ __doc__ = '' # Fix leading whitespace that occurs when using multi-line # 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] ) if title: if doc_description: __doc__ = "%s\n\n%s" % (title, doc_description) else: __doc__ = title elif description: __doc__ = doc_description super(Field, self).__init__(__name__, __doc__) self.title = title self.description = description self.required = required self.readonly = readonly if constraint is not None: self.constraint = constraint self.default = default self.defaultFactory = defaultFactory # Keep track of the order of field definitions Field.order += 1 self.order = Field.order if missing_value is not self.__missing_value_marker: self.missing_value = missing_value def constraint(self, value): return True def bind(self, context): clone = self.__class__.__new__(self.__class__) clone.__dict__.update(self.__dict__) clone.context = context return clone def validate(self, value): if value == self.missing_value: if self.required: raise RequiredMissing( self.__name__ ).with_field_and_value(self, value) else: try: self._validate(value) except StopValidation: pass def __get_property_names_to_compare(self): # Return the set of property names to compare, ignoring # order names = {} # used as set of property names, ignoring values for interface in providedBy(self): names.update(getFields(interface)) # order will be different always, don't compare it names.pop('order', None) return names def __hash__(self): # Equal objects should have equal hashes; # equal hashes does not imply equal objects. value = ( (type(self), self.interface) + tuple(self.__get_property_names_to_compare()) ) return hash(value) def __eq__(self, other): # should be the same type and in the same interface (or no interface # at all) if self is other: return True if type(self) != type(other) or self.interface != other.interface: return False # should have the same properties names = self.__get_property_names_to_compare() # XXX: What about the property names of the other object? Even # though it's the same type, it could theoretically have # another interface that it `alsoProvides`. for name in names: if getattr(self, name) != getattr(other, name): return False return True def __ne__(self, other): return not self.__eq__(other) def _validate(self, value): if self._type is not None and not isinstance(value, self._type): raise WrongType( value, self._type, self.__name__ ).with_field_and_value(self, value) try: constraint = self.constraint(value) except ValidationError as e: if e.field is None: e.field = self if e.value is None: e.value = value raise if not constraint: raise ConstraintNotSatisfied( value, self.__name__ ).with_field_and_value(self, value) def get(self, object): return getattr(object, self.__name__) def query(self, object, default=None): return getattr(object, self.__name__, default) def set(self, object, value): if self.readonly: raise TypeError("Can't set values on read-only fields " "(name=%s, class=%s.%s)" % (self.__name__, object.__class__.__module__, object.__class__.__name__)) setattr(object, self.__name__, value) def getExtraDocLines(self): """ Return a list of ReST formatted lines that will be added to the docstring returned by :meth:`getDoc`. By default, this will include information about the various properties of this object, such as required and readonly status, required type, and so on. This implementation uses a field list for this. Subclasses may override or extend. .. versionadded:: 4.6.0 """ lines = [] lines.append(_DocStringHelpers.make_class_field( 'Implementation', type(self))) lines.append(_DocStringHelpers.make_field("Read Only", self.readonly)) lines.append(_DocStringHelpers.make_field("Required", self.required)) if self.defaultFactory: lines.append(_DocStringHelpers.make_field( "Default Factory", repr(self.defaultFactory))) else: lines.append(_DocStringHelpers.make_field( "Default Value", repr(self.default))) if self._type: lines.append(_DocStringHelpers.make_class_field( "Allowed Type", self._type)) # key_type and value_type are commonly used, but don't # have a common superclass to add them, so we do it here. # Using a rubric produces decent formatting for name, rubric in (('key_type', 'Key Type'), ('value_type', 'Value Type')): field = getattr(self, name, None) if hasattr(field, 'getDoc'): lines.append("") lines.append(".. rubric:: " + rubric) lines.append("") lines.append(field.getDoc()) return lines def getDoc(self): doc = super(Field, self).getDoc() lines = _DocStringHelpers.docstring_to_lines(doc) lines += self.getExtraDocLines() lines.append('') return '\n'.join(lines) class Container(Field): def _validate(self, value): super(Container, self)._validate(value) if not hasattr(value, '__contains__'): try: iter(value) except TypeError: raise NotAContainer(value).with_field_and_value(self, value) # XXX This class violates the Liskov Substituability Principle: it # is derived from Container, but cannot be used everywhere an instance # of Container could be, because it's '_validate' is more restrictive. class Iterable(Container): def _validate(self, value): super(Iterable, self)._validate(value) # See if we can get an iterator for it try: iter(value) except TypeError: raise NotAnIterator(value).with_field_and_value(self, value) class Orderable(object): """Values of ordered fields can be sorted. They can be restricted to a range of values. Orderable is a mixin used in combination with Field. """ min = ValidatedProperty('min', allow_none=True) max = ValidatedProperty('max', allow_none=True) def __init__(self, min=None, max=None, default=None, **kw): # Set min and max to None so that we can validate if # one of the super methods invoke validation. self.min = None self.max = None super(Orderable, self).__init__(**kw) # Now really set min and max self.min = min self.max = max # We've taken over setting default so it can be limited by min # and max. self.default = default def _validate(self, value): super(Orderable, self)._validate(value) if self.min is not None and value < self.min: raise TooSmall(value, self.min).with_field_and_value(self, value) if self.max is not None and value > self.max: raise TooBig(value, self.max).with_field_and_value(self, value) class MinMaxLen(object): """Expresses constraints on the length of a field. MinMaxLen is a mixin used in combination with Field. """ min_length = 0 max_length = None 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) def _validate(self, value): super(MinMaxLen, self)._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( self, value) if self.max_length is not None and len(value) > self.max_length: raise TooLong(value, self.max_length).with_field_and_value( self, value) @implementer(IFromUnicode) class Text(MinMaxLen, Field): """A field containing text used for human discourse.""" _type = text_type unicode_normalization = 'NFC' def __init__(self, *args, **kw): self.unicode_normalization = kw.pop( 'unicode_normalization', self.unicode_normalization) super(Text, self).__init__(*args, **kw) def fromUnicode(self, value): """ >>> from zope.schema import Text >>> t = Text(constraint=lambda v: 'x' in v) >>> t.fromUnicode(b"foo x spam") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... zope.schema._bootstrapinterfaces.WrongType: ('foo x spam', , '') >>> result = t.fromUnicode(u"foo x spam") >>> isinstance(result, bytes) False >>> str(result) 'foo x spam' >>> t.fromUnicode(u"foo spam") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... zope.schema._bootstrapinterfaces.ConstraintNotSatisfied: (u'foo spam', '') """ if isinstance(value, text_type): if self.unicode_normalization: value = unicodedata.normalize( self.unicode_normalization, value) self.validate(value) return value class TextLine(Text): """A text field with no newlines.""" def constraint(self, value): return '\n' not in value and '\r' not in value class Password(TextLine): """A text field containing a text used as a password.""" UNCHANGED_PASSWORD = object() def set(self, context, value): """Update the password. We use a special marker value that a widget can use to tell us that the password didn't change. This is needed to support edit forms that don't display the existing password and want to work together with encryption. """ if value is self.UNCHANGED_PASSWORD: return super(Password, self).set(context, value) def validate(self, value): try: existing = bool(self.get(self.context)) except AttributeError: existing = False 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) @implementer(IFromUnicode, IFromBytes) class Bool(Field): """ A field representing a Bool. .. versionchanged:: 4.8.0 Implement :class:`zope.schema.interfaces.IFromBytes` """ _type = bool def _validate(self, value): # Convert integers to bools to they don't get mis-flagged # by the type check later. if isinstance(value, int) and not isinstance(value, bool): value = bool(value) Field._validate(self, value) def set(self, object, value): if isinstance(value, int) and not isinstance(value, bool): value = bool(value) Field.set(self, object, value) def fromUnicode(self, value): """ >>> from zope.schema._bootstrapfields import Bool >>> from zope.schema.interfaces import IFromUnicode >>> b = Bool() >>> IFromUnicode.providedBy(b) True >>> b.fromUnicode('True') True >>> b.fromUnicode('') False >>> b.fromUnicode('true') True >>> b.fromUnicode('false') or b.fromUnicode('False') False >>> b.fromUnicode(u'\u2603') False """ # On Python 2, we're relying on the implicit decoding # that happens during string comparisons of unicode to native # (byte) strings; decoding errors are silently dropped v = value == 'True' or value == 'true' self.validate(v) return v def fromBytes(self, value): """ >>> from zope.schema._bootstrapfields import Bool >>> from zope.schema.interfaces import IFromBytes >>> b = Bool() >>> IFromBytes.providedBy(b) True >>> b.fromBytes(b'True') True >>> b.fromBytes(b'') False >>> b.fromBytes(b'true') True >>> b.fromBytes(b'false') or b.fromBytes(b'False') False >>> b.fromBytes(u'\u2603'.encode('utf-8')) False """ return self.fromUnicode(value.decode("utf-8")) class InvalidNumberLiteral(ValueError, ValidationError): """Invalid number literal.""" @implementer(IFromUnicode, IFromBytes) class Number(Orderable, Field): """ A field representing a :class:`numbers.Number` and implementing :class:`zope.schema.interfaces.INumber`. The :meth:`fromUnicode` method will attempt to use the smallest or strictest possible type to represent incoming strings:: >>> from zope.schema._bootstrapfields import Number >>> f = Number() >>> f.fromUnicode(u"1") 1 >>> f.fromUnicode(u"125.6") 125.6 >>> f.fromUnicode(u"1+0j") (1+0j) >>> f.fromUnicode(u"1/2") Fraction(1, 2) >>> f.fromUnicode(str(2**31234) + '.' + str(2**256)) ... # doctest: +ELLIPSIS Decimal('234...936') >>> f.fromUnicode(u"not a number") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidNumberLiteral: Invalid literal for Decimal: 'not a number' Similarly, :meth:`fromBytes` will do the same for incoming byte strings:: >>> from zope.schema._bootstrapfields import Number >>> f = Number() >>> f.fromBytes(b"1") 1 >>> f.fromBytes(b"125.6") 125.6 >>> f.fromBytes(b"1+0j") (1+0j) >>> f.fromBytes(b"1/2") Fraction(1, 2) >>> f.fromBytes((str(2**31234) + '.' + str(2**256)).encode('ascii')) ... # doctest: +ELLIPSIS Decimal('234...936') >>> f.fromBytes(b"not a number") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidNumberLiteral: Invalid literal for Decimal: 'not a number' .. versionadded:: 4.6.0 .. versionchanged:: 4.8.0 Implement :class:`zope.schema.interfaces.IFromBytes` """ _type = numbers.Number # An ordered sequence of conversion routines. These should accept a # native string and produce an object that is an instance of `_type`, or # raise a ValueError. The order should be most specific/strictest # towards least restrictive (in other words, lowest in the numeric tower # towards highest). We break this rule with fractions, though: a # floating point number is more generally useful and expected than a # fraction, so we attempt to parse as a float before a fraction. _unicode_converters = ( int, float, fractions.Fraction, complex, decimal.Decimal, ) # The type of error we will raise if all conversions fail. _validation_error = InvalidNumberLiteral def fromUnicode(self, value): last_exc = None for converter in self._unicode_converters: try: val = converter(value) if (converter is float and isinf(val) and decimal.Decimal in self._unicode_converters): # Pass this on to decimal, if we're allowed val = decimal.Decimal(value) except (ValueError, decimal.InvalidOperation) as e: last_exc = e else: self.validate(val) return val try: raise self._validation_error(*last_exc.args).with_field_and_value( self, value) finally: last_exc = None # On Python 2, native strings are byte strings, which is # what the converters expect, so we don't need to do any decoding. if PY2: # pragma: PY2 fromBytes = fromUnicode else: # pragma: PY3 def fromBytes(self, value): return self.fromUnicode(value.decode('utf-8')) class Complex(Number): """ A field representing a :class:`numbers.Complex` and implementing :class:`zope.schema.interfaces.IComplex`. The :meth:`fromUnicode` method is like that for :class:`Number`, but doesn't allow Decimals:: >>> from zope.schema._bootstrapfields import Complex >>> f = Complex() >>> f.fromUnicode(u"1") 1 >>> f.fromUnicode(u"125.6") 125.6 >>> f.fromUnicode(u"1+0j") (1+0j) >>> f.fromUnicode(u"1/2") Fraction(1, 2) >>> f.fromUnicode(str(2**31234) + '.' + str(2**256)) ... # doctest: +ELLIPSIS inf >>> f.fromUnicode(u"not a number") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidNumberLiteral: Invalid literal for Decimal: 'not a number' Similarly for :meth:`fromBytes`: >>> from zope.schema._bootstrapfields import Complex >>> f = Complex() >>> f.fromBytes(b"1") 1 >>> f.fromBytes(b"125.6") 125.6 >>> f.fromBytes(b"1+0j") (1+0j) >>> f.fromBytes(b"1/2") Fraction(1, 2) >>> f.fromBytes((str(2**31234) + '.' + str(2**256)).encode('ascii')) ... # doctest: +ELLIPSIS inf >>> f.fromBytes(b"not a number") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidNumberLiteral: Invalid literal for Decimal: 'not a number' .. versionadded:: 4.6.0 """ _type = numbers.Complex _unicode_converters = (int, float, complex, fractions.Fraction) class Real(Complex): """ A field representing a :class:`numbers.Real` and implementing :class:`zope.schema.interfaces.IReal`. The :meth:`fromUnicode` method is like that for :class:`Complex`, but doesn't allow Decimals or complex numbers:: >>> from zope.schema._bootstrapfields import Real >>> f = Real() >>> f.fromUnicode("1") 1 >>> f.fromUnicode("125.6") 125.6 >>> f.fromUnicode("1+0j") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidNumberLiteral: Invalid literal for Fraction: '1+0j' >>> f.fromUnicode("1/2") Fraction(1, 2) >>> f.fromUnicode(str(2**31234) + '.' + str(2**256)) ... # doctest: +ELLIPSIS inf >>> f.fromUnicode("not a number") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidNumberLiteral: Invalid literal for Decimal: 'not a number' .. versionadded:: 4.6.0 """ _type = numbers.Real _unicode_converters = (int, float, fractions.Fraction) class Rational(Real): """ A field representing a :class:`numbers.Rational` and implementing :class:`zope.schema.interfaces.IRational`. The :meth:`fromUnicode` method is like that for :class:`Real`, but does not allow arbitrary floating point numbers:: >>> from zope.schema._bootstrapfields import Rational >>> f = Rational() >>> f.fromUnicode("1") 1 >>> f.fromUnicode("1/2") Fraction(1, 2) >>> f.fromUnicode("125.6") Fraction(628, 5) >>> f.fromUnicode("1+0j") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidNumberLiteral: Invalid literal for Fraction: '1+0j' >>> f.fromUnicode(str(2**31234) + '.' + str(2**256)) ... # doctest: +ELLIPSIS Fraction(777..., 330...) >>> f.fromUnicode("not a number") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidNumberLiteral: Invalid literal for Decimal: 'not a number' .. versionadded:: 4.6.0 """ _type = numbers.Rational _unicode_converters = (int, fractions.Fraction) class InvalidIntLiteral(ValueError, ValidationError): """Invalid int literal.""" class Integral(Rational): """ A field representing a :class:`numbers.Integral` and implementing :class:`zope.schema.interfaces.IIntegral`. The :meth:`fromUnicode` method only allows integral values:: >>> from zope.schema._bootstrapfields import Integral >>> f = Integral() >>> f.fromUnicode("125") 125 >>> f.fromUnicode("125.6") #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidIntLiteral: invalid literal for int(): 125.6 Similarly for :meth:`fromBytes`: >>> from zope.schema._bootstrapfields import Integral >>> f = Integral() >>> f.fromBytes(b"125") 125 >>> f.fromBytes(b"125.6") #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidIntLiteral: invalid literal for int(): 125.6 .. versionadded:: 4.6.0 """ _type = numbers.Integral _unicode_converters = (int,) _validation_error = InvalidIntLiteral class Int(Integral): """A field representing a native integer type. and implementing :class:`zope.schema.interfaces.IInt`. """ _type = integer_types _unicode_converters = (int,) class InvalidDecimalLiteral(ValueError, ValidationError): "Raised by decimal fields" class Decimal(Number): """ A field representing a native :class:`decimal.Decimal` and implementing :class:`zope.schema.interfaces.IDecimal`. The :meth:`fromUnicode` method only accepts values that can be parsed by the ``Decimal`` constructor:: >>> from zope.schema._field import Decimal >>> f = Decimal() >>> f.fromUnicode("1") Decimal('1') >>> f.fromUnicode("125.6") Decimal('125.6') >>> f.fromUnicode("1+0j") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidDecimalLiteral: Invalid literal for Decimal(): 1+0j >>> f.fromUnicode("1/2") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidDecimalLiteral: Invalid literal for Decimal(): 1/2 >>> f.fromUnicode(str(2**31234) + '.' + str(2**256)) ... # doctest: +ELLIPSIS Decimal('2349...936') >>> f.fromUnicode("not a number") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidDecimalLiteral: could not convert string to float: not a number Likewise for :meth:`fromBytes`:: >>> from zope.schema._field import Decimal >>> f = Decimal() >>> f.fromBytes(b"1") Decimal('1') >>> f.fromBytes(b"125.6") Decimal('125.6') >>> f.fromBytes(b"1+0j") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidDecimalLiteral: Invalid literal for Decimal(): 1+0j >>> f.fromBytes(b"1/2") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidDecimalLiteral: Invalid literal for Decimal(): 1/2 >>> f.fromBytes((str(2**31234) + '.' + str(2**256)).encode("ascii")) ... # doctest: +ELLIPSIS Decimal('2349...936') >>> f.fromBytes(b"not a number") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidDecimalLiteral: could not convert string to float: not a number """ _type = decimal.Decimal _unicode_converters = (decimal.Decimal,) _validation_error = InvalidDecimalLiteral class _ObjectsBeingValidated(threading.local): def __init__(self): super(_ObjectsBeingValidated, self).__init__() self.ids_being_validated = set() def get_schema_validation_errors(schema, value, _validating_objects=_ObjectsBeingValidated()): """ Validate that *value* conforms to the schema interface *schema*. All :class:`zope.schema.interfaces.IField` members of the *schema* are validated after being bound to *value*. (Note that we do not check for arbitrary :class:`zope.interface.Attribute` members being present.) :return: A `dict` mapping field names to `ValidationError` subclasses. A non-empty return value means that validation failed. """ errors = {} # Interface can be used as schema property for Object fields that plan to # hold values of any type. # Because Interface does not include any Attribute, it is obviously not # worth looping on its methods and filter them all out. if schema is Interface: return errors # if `value` is part of a cyclic graph, we need to break the cycle to avoid # infinite recursion. Collect validated objects in a thread local dict by # it's python represenation. A previous version was setting a volatile # attribute which didn't work with security proxy id_value = id(value) ids_being_validated = _validating_objects.ids_being_validated if id_value in ids_being_validated: return errors ids_being_validated.add(id_value) # (If we have gotten here, we know that `value` provides an interface # other than zope.interface.Interface; # iow, we can rely on the fact that it is an instance # that supports attribute assignment.) try: for name in schema.names(all=True): attribute = schema[name] if IMethod.providedBy(attribute): continue # pragma: no cover try: if IValidatable.providedBy(attribute): # validate attributes that are fields field_value = getattr(value, name) attribute = attribute.bind(value) attribute.validate(field_value) except ValidationError as error: errors[name] = error except AttributeError as error: # property for the given name is not implemented errors[name] = SchemaNotFullyImplemented( error ).with_field_and_value(attribute, None) finally: ids_being_validated.remove(id_value) return errors def get_validation_errors(schema, value, validate_invariants=True): """ Validate that *value* conforms to the schema interface *schema*. This includes checking for any schema validation errors (using `get_schema_validation_errors`). If that succeeds, and *validate_invariants* is true, then we proceed to check for any declared invariants. Note that this does not include a check to see if the *value* actually provides the given *schema*. :return: If there were any validation errors, either schema or invariant, return a two tuple (schema_error_dict, invariant_error_list). If there were no errors, returns a two-tuple where both members are empty. """ schema_error_dict = get_schema_validation_errors(schema, value) invariant_errors = [] # Only validate invariants if there were no previous errors. Previous # errors could be missing attributes which would most likely make an # invariant raise an AttributeError. if validate_invariants and not schema_error_dict: try: schema.validateInvariants(value, invariant_errors) except Invalid: # validateInvariants raises a wrapper error around # all the errors it got if it got errors, in addition # to appending them to the errors list. We don't want # that, we raise our own error. pass return (schema_error_dict, invariant_errors) class Object(Field): """ Implementation of :class:`zope.schema.interfaces.IObject`. """ schema = None def __init__(self, schema=_NotGiven, **kw): """ Object(schema=, *, validate_invariants=True, **kwargs) Create an `~.IObject` field. The keyword arguments are as for `~.Field`. .. versionchanged:: 4.6.0 Add the keyword argument *validate_invariants*. When true (the default), the schema's ``validateInvariants`` method will be invoked to check the ``@invariant`` properties of the schema. .. versionchanged:: 4.6.0 The *schema* argument can be ommitted in a subclass that specifies a ``schema`` attribute. """ if schema is _NotGiven: schema = self.schema if not IInterface.providedBy(schema): # Note that we don't provide 'self' as the 'field' # by calling with_field_and_value(): We're not fully constructed, # we don't want this instance to escape. raise NotAnInterface(schema, self.__name__) self.schema = schema self.validate_invariants = kw.pop('validate_invariants', True) super(Object, self).__init__(**kw) def getExtraDocLines(self): lines = super(Object, self).getExtraDocLines() lines.append(_DocStringHelpers.make_class_field( "Must Provide", self.schema)) return lines def _validate(self, value): super(Object, self)._validate(value) # schema has to be provided by value if not self.schema.providedBy(value): raise SchemaNotProvided(self.schema, value).with_field_and_value( self, value) # check the value against schema schema_error_dict, invariant_errors = get_validation_errors( self.schema, value, self.validate_invariants ) if schema_error_dict or invariant_errors: errors = list(schema_error_dict.values()) + invariant_errors exception = SchemaNotCorrectlyImplemented( errors, self.__name__, schema_error_dict, invariant_errors ).with_field_and_value(self, value) try: raise exception finally: # Break cycles del exception del invariant_errors del schema_error_dict del errors def set(self, object, value): # Announce that we're going to assign the value to the object. # Motivation: Widgets typically like to take care of policy-specific # actions, like establishing location. event = BeforeObjectAssignedEvent(value, self.__name__, object) notify(event) # 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) @implementer(IBeforeObjectAssignedEvent) class BeforeObjectAssignedEvent(object): """An object is going to be assigned to an attribute on another object.""" def __init__(self, object, name, context): self.object = object self.name = name self.context = context zope.schema-6.2.0/src/zope/schema/_bootstrapinterfaces.py0000644000100100000240000002356714133212652023410 0ustar macstaff00000000000000############################################################################## # # Copyright (c) 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap schema interfaces and exceptions """ from functools import total_ordering import zope.interface from zope.interface import Attribute from zope.interface.interfaces import IInterface from zope.schema._messageid import _ # pylint:disable=inherit-non-class,keyword-arg-before-vararg, # pylint:disable=no-self-argument class StopValidation(Exception): """Raised if the validation is completed early. Note that this exception should be always caught, since it is just a way for the validator to save time. """ @total_ordering class ValidationError(zope.interface.Invalid): """Raised if the Validation process fails.""" #: The field that raised the error, if known. field = None #: The value that failed validation. value = None def with_field_and_value(self, field, value): self.field = field self.value = value return self def doc(self): return self.__class__.__doc__ def __lt__(self, other): # There's no particular reason we choose to sort this way, # it's just the way we used to do it with __cmp__. if not hasattr(other, 'args'): return True return self.args < other.args def __eq__(self, other): if not hasattr(other, 'args'): return False return self.args == other.args # XXX : This is probably inconsistent with __eq__, which is # a violation of the language spec. __hash__ = zope.interface.Invalid.__hash__ # python3 def __repr__(self): # pragma: no cover return '%s(%s)' % ( self.__class__.__name__, ', '.join(repr(arg) for arg in self.args)) class RequiredMissing(ValidationError): __doc__ = _("""Required input is missing.""") class WrongType(ValidationError): __doc__ = _("""Object is of wrong type.""") #: The type or tuple of types that was expected. #: #: .. versionadded:: 4.7.0 expected_type = None def __init__(self, value=None, expected_type=None, name=None, *args): """ WrongType(value, expected_type, name) .. versionchanged:: 4.7.0 Added named arguments to the constructor and the `expected_type` field. """ ValidationError.__init__(self, value, expected_type, name, *args) self.expected_type = expected_type self.value = value class OutOfBounds(ValidationError): """ A value was out of the allowed bounds. This is the common superclass for `OrderableOutOfBounds` and `LenOutOfBounds`, which in turn are the superclasses for `TooBig` and `TooSmall`, and `TooLong` and `TooShort`, respectively. .. versionadded:: 4.7.0 """ #: The value that was exceeded bound = None #: A constant for `violation_direction`. TOO_LARGE = type('TOO_LARGE', (), {'__slots__': ()})() #: A constant for `violation_direction`. TOO_SMALL = type('TOO_SMALL', (), {'__slots__': ()})() #: Whether the value was too large or #: not large enough. One of the values #: defined by the constants `TOO_LARGE` #: or `TOO_SMALL` violation_direction = None def __init__(self, value=None, bound=None, *args): """ OutOfBounds(value, bound) """ super(OutOfBounds, self).__init__(value, bound, *args) self.value = value self.bound = bound class OrderableOutOfBounds(OutOfBounds): """ A value was too big or too small in comparison to another value. .. versionadded:: 4.7.0 """ class TooBig(OrderableOutOfBounds): __doc__ = _("""Value is too big""") violation_direction = OutOfBounds.TOO_LARGE class TooSmall(OrderableOutOfBounds): __doc__ = _("""Value is too small""") violation_direction = OutOfBounds.TOO_SMALL class LenOutOfBounds(OutOfBounds): """ The length of the value was out of bounds. .. versionadded:: 4.7.0 """ class TooLong(LenOutOfBounds): __doc__ = _("""Value is too long""") violation_direction = OutOfBounds.TOO_LARGE class TooShort(LenOutOfBounds): __doc__ = _("""Value is too short""") violation_direction = OutOfBounds.TOO_SMALL class InvalidValue(ValidationError): __doc__ = _("""Invalid value""") class ConstraintNotSatisfied(ValidationError): __doc__ = _("""Constraint not satisfied""") class NotAContainer(ValidationError): __doc__ = _("""Not a container""") class NotAnIterator(ValidationError): __doc__ = _("""Not an iterator""") class WrongContainedType(ValidationError): __doc__ = _("""Wrong contained type""") #: A collection of exceptions raised when validating #: the *value*. #: #: .. versionadded:: 4.7.0 errors = () def __init__(self, errors=None, name=None, *args): """ WrongContainedType(errors, name) .. versionchanged:: 4.7.0 Added named arguments to the constructor, and the `errors` property. """ super(WrongContainedType, self).__init__(errors, name, *args) self.errors = errors class SchemaNotCorrectlyImplemented(WrongContainedType): __doc__ = _("""An object failed schema or invariant validation.""") #: A dictionary mapping failed attribute names of the #: *value* to the underlying exception schema_errors = None #: A list of exceptions from validating the invariants #: of the schema. invariant_errors = () def __init__(self, errors=None, name=None, schema_errors=None, invariant_errors=(), *args): """ SchemaNotCorrectlyImplemented(errors, name, schema_errors, invariant_errors) .. versionchanged:: 4.7.0 Added named arguments to the constructor. """ super(SchemaNotCorrectlyImplemented, self).__init__( errors, name, *args) self.schema_errors = schema_errors self.invariant_errors = invariant_errors class SchemaNotFullyImplemented(ValidationError): __doc__ = _("""Schema not fully implemented""") class SchemaNotProvided(ValidationError): __doc__ = _("""Schema not provided""") #: The interface that the *value* was supposed to provide, #: but does not. schema = None def __init__(self, schema=None, value=None, *args): """ SchemaNotProvided(schema, value) .. versionchanged:: 4.7.0 Added named arguments to the constructor and the `schema` property. """ super(SchemaNotProvided, self).__init__(schema, value, *args) self.schema = schema self.value = value class NotAnInterface(WrongType, SchemaNotProvided): """ Object is not an interface. This is a `WrongType` exception for backwards compatibility with existing ``except`` clauses, but it is raised when ``IInterface.providedBy`` is not true, so it's also a `SchemaNotProvided`. The ``expected_type`` field is filled in as ``IInterface``; this is not actually a `type`, and ``isinstance(thing, IInterface)`` is always false. .. versionadded:: 4.7.0 """ expected_type = IInterface def __init__(self, value, name): super(NotAnInterface, self).__init__(value, IInterface, name) class IFromUnicode(zope.interface.Interface): """Parse a unicode string to a value We will often adapt fields to this interface to support views and other applications that need to convert raw data as unicode values. """ def fromUnicode(value): """Convert a unicode string to a value. """ class IFromBytes(zope.interface.Interface): """ Parse a byte string to a value. If the string needs to be decoded, decoding is done using UTF-8. .. versionadded:: 4.8.0 """ def fromBytes(value): """Convert a byte string to a value. """ class IContextAwareDefaultFactory(zope.interface.Interface): """A default factory that requires a context. The context is the field context. If the field is not bound, context may be ``None``. """ def __call__(context): """Returns a default value for the field.""" class IBeforeObjectAssignedEvent(zope.interface.Interface): """An object is going to be assigned to an attribute on another object. Subscribers to this event can change the object on this event to change what object is going to be assigned. This is useful, e.g. for wrapping or replacing objects before they get assigned to conform to application policy. """ object = Attribute("The object that is going to be assigned.") name = Attribute("The name of the attribute under which the object " "will be assigned.") context = Attribute("The context object where the object will be " "assigned to.") class IValidatable(zope.interface.Interface): # Internal interface, the base for IField, but used to prevent # import recursion. This should *not* be implemented by anything # other than IField. def validate(value): """Validate that the given value is a valid field value. Returns nothing but raises an error if the value is invalid. It checks everything specific to a Field and also checks with the additional constraint. """ class NO_VALUE(object): def __repr__(self): # pragma: no cover return '' NO_VALUE = NO_VALUE() zope.schema-6.2.0/src/zope/schema/_compat.py0000644000100100000240000000162014133212652020574 0ustar macstaff00000000000000import sys PY3 = sys.version_info[0] >= 3 PY2 = not PY3 if PY3: # pragma: no cover string_types = str, text_type = str binary_type = bytes integer_types = int, def non_native_string(x): if isinstance(x, bytes): return x return bytes(x, 'unicode_escape') def make_binary(x): if isinstance(x, bytes): return x return x.encode('ascii') else: # pragma: no cover string_types = (basestring, ) # noqa: F821 text_type = unicode # noqa: F821 binary_type = str # noqa: F821 integer_types = (int, long) # noqa: F821 def non_native_string(x): if isinstance(x, unicode): # noqa: F821 return x return unicode(x, 'unicode_escape') # noqa: F821 def make_binary(x): if isinstance(x, str): return x return x.encode('ascii') zope.schema-6.2.0/src/zope/schema/_field.py0000644000100100000240000007361414133212652020410 0ustar macstaff00000000000000# -*- coding: utf-8 -*- ############################################################################## # Copyright (c) 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Schema Fields """ __docformat__ = 'restructuredtext' try: from collections import abc except ImportError: # pragma: PY2 # Python 2 import collections as abc from datetime import datetime from datetime import date from datetime import timedelta from datetime import time import re from zope.interface import classImplements from zope.interface import classImplementsFirst from zope.interface import implementer from zope.interface import implementedBy from zope.interface.interfaces import IInterface from zope.schema.interfaces import IASCII from zope.schema.interfaces import IASCIILine from zope.schema.interfaces import IBaseVocabulary from zope.schema.interfaces import IBool from zope.schema.interfaces import IBytes from zope.schema.interfaces import IBytesLine from zope.schema.interfaces import IChoice from zope.schema.interfaces import ICollection from zope.schema.interfaces import IComplex from zope.schema.interfaces import IContainer from zope.schema.interfaces import IContextSourceBinder from zope.schema.interfaces import IDate from zope.schema.interfaces import IDatetime from zope.schema.interfaces import IDecimal from zope.schema.interfaces import IDict from zope.schema.interfaces import IDottedName from zope.schema.interfaces import IField from zope.schema.interfaces import IFloat from zope.schema.interfaces import IFromBytes from zope.schema.interfaces import IFromUnicode from zope.schema.interfaces import IFrozenSet from zope.schema.interfaces import IId from zope.schema.interfaces import IIterable from zope.schema.interfaces import IInt from zope.schema.interfaces import IIntegral from zope.schema.interfaces import IInterfaceField from zope.schema.interfaces import IList from zope.schema.interfaces import IMinMaxLen from zope.schema.interfaces import IMapping from zope.schema.interfaces import IMutableMapping from zope.schema.interfaces import IMutableSequence from zope.schema.interfaces import INativeString from zope.schema.interfaces import INativeStringLine from zope.schema.interfaces import IObject from zope.schema.interfaces import INumber from zope.schema.interfaces import IPassword from zope.schema.interfaces import IPythonIdentifier from zope.schema.interfaces import IReal from zope.schema.interfaces import IRational from zope.schema.interfaces import ISet from zope.schema.interfaces import ISequence from zope.schema.interfaces import ISource from zope.schema.interfaces import ISourceText from zope.schema.interfaces import IText from zope.schema.interfaces import ITextLine from zope.schema.interfaces import ITime from zope.schema.interfaces import ITimedelta from zope.schema.interfaces import ITuple from zope.schema.interfaces import IURI from zope.schema.interfaces import ValidationError from zope.schema.interfaces import InvalidValue from zope.schema.interfaces import WrongType from zope.schema.interfaces import WrongContainedType from zope.schema.interfaces import NotUnique from zope.schema.interfaces import NotAnInterface from zope.schema.interfaces import InvalidURI from zope.schema.interfaces import InvalidId from zope.schema.interfaces import InvalidDottedName from zope.schema.interfaces import ConstraintNotSatisfied from zope.schema._bootstrapfields import Field from zope.schema._bootstrapfields import Complex from zope.schema._bootstrapfields import Container # API import for __init__ from zope.schema._bootstrapfields import Iterable from zope.schema._bootstrapfields import Orderable from zope.schema._bootstrapfields import Text from zope.schema._bootstrapfields import TextLine from zope.schema._bootstrapfields import Bool from zope.schema._bootstrapfields import Int from zope.schema._bootstrapfields import Integral from zope.schema._bootstrapfields import Number from zope.schema._bootstrapfields import InvalidDecimalLiteral # noqa: reexport from zope.schema._bootstrapfields import Decimal from zope.schema._bootstrapfields import Password from zope.schema._bootstrapfields import Rational from zope.schema._bootstrapfields import Real from zope.schema._bootstrapfields import MinMaxLen from zope.schema._bootstrapfields import _NotGiven from zope.schema._bootstrapfields import Object from zope.schema.fieldproperty import FieldProperty from zope.schema.vocabulary import getVocabularyRegistry from zope.schema.vocabulary import SimpleVocabulary from zope.schema._compat import text_type from zope.schema._compat import string_types from zope.schema._compat import binary_type from zope.schema._compat import PY3 from zope.schema._compat import make_binary # Fix up bootstrap field types Field.title = FieldProperty(IField['title']) Field.description = FieldProperty(IField['description']) Field.required = FieldProperty(IField['required']) Field.readonly = FieldProperty(IField['readonly']) # Default is already taken care of classImplements(Field, IField) MinMaxLen.min_length = FieldProperty(IMinMaxLen['min_length']) MinMaxLen.max_length = FieldProperty(IMinMaxLen['max_length']) classImplementsFirst(Text, IText) classImplementsFirst(TextLine, ITextLine) classImplementsFirst(Password, IPassword) classImplementsFirst(Bool, IBool) classImplementsFirst(Iterable, IIterable) classImplementsFirst(Container, IContainer) classImplementsFirst(Number, INumber) classImplementsFirst(Complex, IComplex) classImplementsFirst(Real, IReal) classImplementsFirst(Rational, IRational) classImplementsFirst(Integral, IIntegral) classImplementsFirst(Int, IInt) classImplementsFirst(Decimal, IDecimal) classImplementsFirst(Object, IObject) class implementer_if_needed(object): # 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 # statically determine if we need the interface or not, e.g, # because we're picking different base classes under some circumstances. def __init__(self, *ifaces): self._ifaces = ifaces def __call__(self, cls): ifaces_needed = [] implemented = implementedBy(cls) ifaces_needed = [ iface for iface in self._ifaces if not implemented.isOrExtends(iface) ] return implementer(*ifaces_needed)(cls) @implementer(ISourceText) class SourceText(Text): __doc__ = ISourceText.__doc__ _type = text_type @implementer(IBytes, IFromUnicode, IFromBytes) class Bytes(MinMaxLen, Field): __doc__ = IBytes.__doc__ _type = binary_type def fromUnicode(self, value): """ See IFromUnicode. """ return self.fromBytes(make_binary(value)) def fromBytes(self, value): self.validate(value) return value @implementer_if_needed(INativeString, IFromUnicode, IFromBytes) class NativeString(Text if PY3 else Bytes): """ A native string is always the type `str`. In addition to :class:`~zope.schema.interfaces.INativeString`, this implements :class:`~zope.schema.interfaces.IFromUnicode` and :class:`~zope.schema.interfaces.IFromBytes`. .. versionchanged:: 4.9.0 This is now a distinct type instead of an alias for either `Text` or `Bytes`, depending on the platform. """ _type = str if PY3: # pragma: no branch def fromBytes(self, value): value = value.decode('utf-8') self.validate(value) return value @implementer(IASCII) class ASCII(NativeString): __doc__ = IASCII.__doc__ def _validate(self, value): super(ASCII, self)._validate(value) if not value: return if not max(map(ord, value)) < 128: raise InvalidValue().with_field_and_value(self, value) @implementer(IBytesLine) class BytesLine(Bytes): """A `Bytes` field with no newlines.""" def constraint(self, value): # TODO: we should probably use a more general definition of newlines return b'\n' not in value @implementer_if_needed(INativeStringLine, IFromUnicode, IFromBytes) class NativeStringLine(TextLine if PY3 else BytesLine): """ A native string is always the type `str`; this field excludes newlines. In addition to :class:`~zope.schema.interfaces.INativeStringLine`, this implements :class:`~zope.schema.interfaces.IFromUnicode` and :class:`~zope.schema.interfaces.IFromBytes`. .. versionchanged:: 4.9.0 This is now a distinct type instead of an alias for either `TextLine` or `BytesLine`, depending on the platform. """ _type = str if PY3: # pragma: no branch def fromBytes(self, value): value = value.decode('utf-8') self.validate(value) return value @implementer(IASCIILine) class ASCIILine(ASCII): __doc__ = IASCIILine.__doc__ def constraint(self, value): # TODO: we should probably use a more general definition of newlines return '\n' not in value class InvalidFloatLiteral(ValueError, ValidationError): """Raised by Float fields.""" @implementer(IFloat) class Float(Real): """ A field representing a native :class:`float` and implementing :class:`zope.schema.interfaces.IFloat`. The class :class:`zope.schema.Real` is a more general version, accepting floats, integers, and fractions. The :meth:`fromUnicode` method only accepts values that can be parsed by the ``float`` constructor:: >>> from zope.schema._field import Float >>> f = Float() >>> f.fromUnicode("1") 1.0 >>> f.fromUnicode("125.6") 125.6 >>> f.fromUnicode("1+0j") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidFloatLiteral: Invalid literal for float(): 1+0j >>> f.fromUnicode("1/2") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidFloatLiteral: invalid literal for float(): 1/2 >>> f.fromUnicode(str(2**31234) + '.' + str(2**256)) ... # doctest: +ELLIPSIS inf >>> f.fromUnicode("not a number") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidFloatLiteral: could not convert string to float: not a number Likewise for :meth:`fromBytes`:: >>> from zope.schema._field import Float >>> f = Float() >>> f.fromBytes(b"1") 1.0 >>> f.fromBytes(b"125.6") 125.6 >>> f.fromBytes(b"1+0j") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidFloatLiteral: Invalid literal for float(): 1+0j >>> f.fromBytes(b"1/2") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidFloatLiteral: invalid literal for float(): 1/2 >>> f.fromBytes((str(2**31234) + '.' + str(2**256)).encode('ascii')) ... # doctest: +ELLIPSIS inf >>> f.fromBytes(b"not a number") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidFloatLiteral: could not convert string to float: not a number """ _type = float _unicode_converters = (float,) _validation_error = InvalidFloatLiteral @implementer(IDatetime) class Datetime(Orderable, Field): __doc__ = IDatetime.__doc__ _type = datetime def __init__(self, *args, **kw): super(Datetime, self).__init__(*args, **kw) @implementer(IDate) class Date(Orderable, Field): __doc__ = IDate.__doc__ _type = date def _validate(self, value): super(Date, self)._validate(value) if isinstance(value, datetime): raise WrongType( value, self._type, self.__name__ ).with_field_and_value(self, value) @implementer(ITimedelta) class Timedelta(Orderable, Field): __doc__ = ITimedelta.__doc__ _type = timedelta @implementer(ITime) class Time(Orderable, Field): __doc__ = ITime.__doc__ _type = time 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): """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,)) @implementer(IChoice, IFromUnicode) class Choice(Field): """Choice fields can have a value found in a constant or dynamic set of values given by the field definition. """ def __init__(self, values=None, vocabulary=None, source=None, **kw): """Initialize object.""" if vocabulary is not None: if (not isinstance(vocabulary, string_types) and not IBaseVocabulary.providedBy(vocabulary)): raise ValueError('vocabulary must be a string or implement ' 'IBaseVocabulary') if source is not None: raise ValueError( "You cannot specify both source and vocabulary.") elif source is not None: vocabulary = source if (values is None and vocabulary is None): 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." ) self.vocabulary = None self.vocabularyName = None if values is not None: self.vocabulary = SimpleVocabulary.fromValues(values) elif isinstance(vocabulary, string_types): self.vocabularyName = vocabulary else: if (not ISource.providedBy(vocabulary) and not IContextSourceBinder.providedBy(vocabulary)): raise InvalidVocabularyError(vocabulary) self.vocabulary = vocabulary # Before a default value is checked, it is validated. However, a # named vocabulary is usually not complete when these fields are # initialized. Therefore signal the validation method to ignore # default value checks during initialization of a Choice tied to a # registered vocabulary. self._init_field = (bool(self.vocabularyName) or IContextSourceBinder.providedBy(self.vocabulary)) super(Choice, self).__init__(**kw) self._init_field = False source = property(lambda self: self.vocabulary) def _resolve_vocabulary(self, value): # Find the vocabulary we should use, raising # an exception if this isn't possible, and returning # an ISource otherwise. vocabulary = self.vocabulary if (IContextSourceBinder.providedBy(vocabulary) and self.context is not None): vocabulary = vocabulary(self.context) elif vocabulary is None and self.vocabularyName is not None: vr = getVocabularyRegistry() try: 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) if not ISource.providedBy(vocabulary): raise InvalidVocabularyError(vocabulary).with_field_and_value( self, value) return vocabulary def bind(self, context): """See zope.schema._bootstrapinterfaces.IField.""" clone = super(Choice, self).bind(context) # Eagerly get registered vocabulary if needed; # once that's done, just return it vocabulary = clone.vocabulary = clone._resolve_vocabulary(None) clone._resolve_vocabulary = lambda value: vocabulary return clone def fromUnicode(self, value): """ See IFromUnicode. """ self.validate(value) return value def _validate(self, value): # Pass all validations during initialization if self._init_field: return super(Choice, self)._validate(value) vocabulary = self._resolve_vocabulary(value) if value not in vocabulary: raise ConstraintNotSatisfied( value, self.__name__ ).with_field_and_value(self, value) # Both of these are inherited from the parent; re-declaring them # here messes with the __sro__ of subclasses, causing them to be # inconsistent with C3. # @implementer(IFromUnicode, IFromBytes) class _StrippedNativeStringLine(NativeStringLine): _invalid_exc_type = None def fromUnicode(self, value): v = value.strip() # On Python 2, self._type is bytes, so we need to encode # unicode down to ASCII bytes. On Python 3, self._type is # unicode, but we don't want to allow non-ASCII values, to match # Python 2 (our regexs would reject that anyway.) try: v = v.encode('ascii') # bytes except UnicodeEncodeError: raise self._invalid_exc_type(value).with_field_and_value( self, value) if not isinstance(v, self._type): # pragma: no branch v = v.decode('ascii') self.validate(v) return v def fromBytes(self, value): return self.fromUnicode(value.decode('ascii')) _isuri = r"[a-zA-z0-9+.-]+:" # scheme _isuri += r"\S*$" # non space (should be pickier) _isuri = re.compile(_isuri).match @implementer(IURI) class URI(_StrippedNativeStringLine): """ URI schema field. URIs can be validated from both unicode values and bytes values, producing a native text string in both cases:: >>> from zope.schema import URI >>> field = URI() >>> field.fromUnicode(u' https://example.com ') 'https://example.com' >>> field.fromBytes(b' https://example.com ') 'https://example.com' .. versionchanged:: 4.8.0 Implement :class:`zope.schema.interfaces.IFromBytes` """ def _validate(self, value): super(URI, self)._validate(value) if _isuri(value): return raise InvalidURI(value).with_field_and_value(self, value) # An identifier is a letter or underscore, followed by # any number of letters, underscores, and digits. _identifier_pattern = r'[a-zA-Z_]+\w*' # The whole string must match to be an identifier _is_identifier = re.compile('^' + _identifier_pattern + '$').match _isdotted = re.compile( # The start of the line, followed by an identifier, '^' + _identifier_pattern # optionally followed by .identifier any number of times + r"([.]" + _identifier_pattern + r")*" # followed by the end of the line. + r"$").match @implementer(IPythonIdentifier) class PythonIdentifier(_StrippedNativeStringLine): """ This field describes a python identifier, i.e. a variable name. Empty strings are allowed. Identifiers can be validated from both unicode values and bytes values, producing a native text string in both cases:: >>> from zope.schema import PythonIdentifier >>> field = PythonIdentifier() >>> field.fromUnicode(u'zope') 'zope' >>> field.fromBytes(b'_zope') '_zope' >>> field.fromUnicode(u' ') '' .. versionadded:: 4.9.0 """ def _validate(self, value): super(PythonIdentifier, self)._validate(value) if value and not _is_identifier(value): raise InvalidValue(value).with_field_and_value(self, value) @implementer(IDottedName) class DottedName(_StrippedNativeStringLine): """Dotted name field. Values of DottedName fields must be Python-style dotted names. Dotted names can be validated from both unicode values and bytes values, producing a native text string in both cases:: >>> from zope.schema import DottedName >>> field = DottedName() >>> field.fromUnicode(u'zope.schema') 'zope.schema' >>> field.fromBytes(b'zope.schema') 'zope.schema' >>> field.fromUnicode(u'zope._schema') 'zope._schema' .. versionchanged:: 4.8.0 Implement :class:`zope.schema.interfaces.IFromBytes` .. versionchanged:: 4.9.0 Allow leading underscores in each component. """ _invalid_exc_type = InvalidDottedName def __init__(self, *args, **kw): self.min_dots = int(kw.pop("min_dots", 0)) if self.min_dots < 0: raise ValueError("min_dots cannot be less than zero") self.max_dots = kw.pop("max_dots", None) if self.max_dots is not None: 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) def _validate(self, value): """ """ super(DottedName, self)._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) 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) @implementer(IId) class Id(_StrippedNativeStringLine): """Id field Values of id fields must be either uris or dotted names. .. versionchanged:: 4.8.0 Implement :class:`zope.schema.interfaces.IFromBytes` """ _invalid_exc_type = InvalidId def _validate(self, value): super(Id, self)._validate(value) if _isuri(value): return if _isdotted(value) and "." in value: return raise InvalidId(value).with_field_and_value(self, value) @implementer(IInterfaceField) class InterfaceField(Field): __doc__ = IInterfaceField.__doc__ def _validate(self, value): super(InterfaceField, self)._validate(value) if not IInterface.providedBy(value): raise NotAnInterface( value, self.__name__ ).with_field_and_value(self, value) def _validate_sequence(value_type, value, errors=None): """Validates a sequence value. Returns a list of validation errors generated during the validation. If no errors are generated, returns an empty list. value_type is a field. value is the sequence being validated. errors is an optional list of errors that will be prepended to the return value. To illustrate, we'll use a text value type. All values must be unicode. >>> field = TextLine(required=True) To validate a sequence of various values: >>> errors = _validate_sequence(field, (bytearray(b'foo'), u'bar', 1)) >>> errors [WrongType(bytearray(b'foo'), <...>, ''), WrongType(1, <...>, '')] The only valid value in the sequence is the second item. The others generated errors. We can use the optional errors argument to collect additional errors for a new sequence: >>> errors = _validate_sequence(field, (2, u'baz'), errors) >>> errors # doctest: +NORMALIZE_WHITESPACE [WrongType(bytearray(b'foo'), <...>, ''), WrongType(1, <...>, ''), WrongType(2, <...>, '')] """ if errors is None: errors = [] if value_type is None: return errors for item in value: try: value_type.validate(item) except ValidationError as error: errors.append(error) return errors def _validate_uniqueness(self, value): temp_values = [] for item in value: if item in temp_values: raise NotUnique(item).with_field_and_value(self, value) temp_values.append(item) @implementer(ICollection) class Collection(MinMaxLen, Iterable): """ A generic collection implementing :class:`zope.schema.interfaces.ICollection`. Subclasses can define the attribute ``value_type`` to be a field such as an :class:`Object` that will be checked for each member of the collection. This can then be omitted from the constructor call. They can also define the attribute ``_type`` to be a concrete class (or tuple of classes) that the collection itself will be checked to be an instance of. This cannot be set in the constructor. .. versionchanged:: 4.6.0 Add the ability for subclasses to specify ``value_type`` and ``unique``, and allow eliding them from the constructor. """ value_type = None unique = False def __init__(self, value_type=_NotGiven, unique=_NotGiven, **kw): super(Collection, self).__init__(**kw) # whine if value_type is not a field if value_type is not _NotGiven: self.value_type = value_type if (self.value_type is not None and not IField.providedBy(self.value_type)): raise ValueError("'value_type' must be field instance.") if unique is not _NotGiven: self.unique = unique def bind(self, context): """See zope.schema._bootstrapinterfaces.IField.""" clone = super(Collection, self).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: clone.value_type = clone.value_type.bind(context) return clone def _validate(self, value): super(Collection, self)._validate(value) errors = _validate_sequence(self.value_type, value) if errors: try: raise WrongContainedType( errors, self.__name__ ).with_field_and_value(self, value) finally: # Break cycles del errors if self.unique: _validate_uniqueness(self, value) #: An alternate name for :class:`.Collection`. #: #: .. deprecated:: 4.6.0 #: Use :class:`.Collection` instead. AbstractCollection = Collection @implementer(ISequence) class Sequence(Collection): """ A field representing an ordered sequence. .. versionadded:: 4.6.0 """ _type = abc.Sequence @implementer(ITuple) class Tuple(Sequence): """A field representing a Tuple.""" _type = tuple @implementer(IMutableSequence) class MutableSequence(Sequence): """ A field representing a mutable sequence. .. versionadded:: 4.6.0 """ _type = abc.MutableSequence @implementer(IList) class List(MutableSequence): """A field representing a List.""" _type = list class _AbstractSet(Collection): unique = True def __init__(self, *args, **kwargs): super(_AbstractSet, self).__init__(*args, **kwargs) if not self.unique: # set members are always unique raise TypeError( "__init__() got an unexpected keyword argument 'unique'") @implementer(ISet) class Set(_AbstractSet): """A field representing a set.""" _type = set @implementer(IFrozenSet) class FrozenSet(_AbstractSet): _type = frozenset @implementer(IMapping) class Mapping(MinMaxLen, Iterable): """ A field representing a mapping. .. versionadded:: 4.6.0 """ _type = abc.Mapping key_type = None value_type = None def __init__(self, key_type=None, value_type=None, **kw): super(Mapping, self).__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.") if value_type is not None and not IField.providedBy(value_type): raise ValueError("'value_type' must be field instance.") self.key_type = key_type self.value_type = value_type def _validate(self, value): super(Mapping, self)._validate(value) errors = [] if self.value_type: errors = _validate_sequence(self.value_type, value.values(), errors) errors = _validate_sequence(self.key_type, value, errors) if errors: try: 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) # binding value_type is necessary for choices with named vocabularies, # and possibly also for other fields. if clone.key_type is not None: clone.key_type = clone.key_type.bind(object) if clone.value_type is not None: clone.value_type = clone.value_type.bind(object) return clone @implementer(IMutableMapping) class MutableMapping(Mapping): """ A field representing a mutable mapping. .. versionadded:: 4.6.0 """ _type = abc.MutableMapping @implementer(IDict) class Dict(MutableMapping): """A field representing a Dict.""" _type = dict zope.schema-6.2.0/src/zope/schema/_messageid.py0000644000100100000240000000151014133212652021250 0ustar macstaff00000000000000############################################################################## # # Copyright (c) 2000 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## try: from zope.i18nmessageid import MessageFactory except ImportError: # pragma: no cover from zope.schema._compat import text_type as _ else: # pragma: no cover _ = MessageFactory("zope") zope.schema-6.2.0/src/zope/schema/_schema.py0000644000100100000240000000575514133212652020566 0ustar macstaff00000000000000############################################################################## # # Copyright (c) 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Schema convenience functions """ from zope.schema._bootstrapfields import get_validation_errors from zope.schema._bootstrapfields import get_schema_validation_errors from zope.schema._bootstrapfields import getFields __all__ = [ 'getFieldNames', 'getFields', 'getFieldsInOrder', 'getFieldNamesInOrder', 'getValidationErrors', 'getSchemaValidationErrors', ] def getFieldNames(schema): """Return a list of all the Field names in a schema. """ return list(getFields(schema).keys()) def getFieldsInOrder(schema, _field_key=lambda x: x[1].order): """Return a list of (name, value) tuples in native schema order. """ return sorted(getFields(schema).items(), key=_field_key) def getFieldNamesInOrder(schema): """Return a list of all the Field names in a schema in schema order. """ return [name for name, field in getFieldsInOrder(schema)] def getValidationErrors(schema, value): """ Validate that *value* conforms to the schema interface *schema*. This includes checking for any schema validation errors (using `getSchemaValidationErrors`). If that succeeds, then we proceed to check for any declared invariants. Note that this does not include a check to see if the *value* actually provides the given *schema*. :return: A sequence of (name, `zope.interface.Invalid`) tuples, where *name* is None if the error was from an invariant. If the sequence is empty, there were no errors. """ schema_error_dict, invariant_errors = get_validation_errors( schema, value, ) if not schema_error_dict and not invariant_errors: # Valid! Yay! return [] return ( list(schema_error_dict.items()) + [(None, e) for e in invariant_errors] ) def getSchemaValidationErrors(schema, value): """ Validate that *value* conforms to the schema interface *schema*. All :class:`zope.schema.interfaces.IField` members of the *schema* are validated after being bound to *value*. (Note that we do not check for arbitrary :class:`zope.interface.Attribute` members being present.) :return: A sequence of (name, `ValidationError`) tuples. A non-empty sequence indicates validation failed. """ items = get_schema_validation_errors(schema, value).items() return items if isinstance(items, list) else list(items) zope.schema-6.2.0/src/zope/schema/accessors.py0000644000100100000240000001243214133212652021142 0ustar macstaff00000000000000############################################################################## # # Copyright (c) 2003 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """ Field accessors =============== Accessors are used to model methods used to access data defined by fields. Accessors are fields that work by decorating existing fields. To define accessors in an interface, use the accessors function:: class IMyInterface(Interface): getFoo, setFoo = accessors(Text(title=u'Foo', ...)) getBar = accessors(TextLine(title=u'Foo', readonly=True, ...) Normally a read accessor and a write accessor are defined. Only a read accessor is defined for read-only fields. Read accessors function as access method specifications and as field specifications. Write accessors are solely method specifications. """ from zope.interface import providedBy, implementedBy from zope.interface.interface import Method from zope.interface.declarations import Declaration class FieldReadAccessor(Method): """Field read accessor """ def __init__(self, field): self.field = field Method.__init__(self, '') self.__doc__ = 'get %s' % field.__doc__ # A read field accessor is a method and a field. # A read accessor is a decorator of a field, using the given # field's properties to provide meta data. @property def __provides__(self): provided = providedBy(self.field) implemented = implementedBy(FieldReadAccessor) # Declaration.__add__ is not very smart in zope.interface 5.0.0. # It's very easy to produce C3 inconsistent orderings using # it, because it uses itself plus any new interfaces from the # second argument as the ``__bases__``, ignoring their # relative order. # # Here, we can easily work around that. We know that ``field`` # will be some sub-class of Attribute, just as we are # (FieldReadAccessor <- Method <- Attribute). So there will be # overlap, and commonly only IMethod would be added to the end # of the list of bases; but since IMethod extends IAttribute, # having IAttribute earlier in the bases will be inconsistent. # The fix here is to remove those duplicates from the first # element so that we don't get into that situation. provided_list = list(provided) for iface in implemented: if iface in provided_list: provided_list.remove(iface) provided = Declaration(*provided_list) # pylint:disable=broad-except try: return provided + implemented except BaseException as e: # pragma: no cover # Sadly, zope.interface catches and silently ignores # any exceptions raised in ``__providedBy__``, # which is the class descriptor that invokes ``__provides__``. # So, for example, if we're in strict C3 mode and fail to produce # a resolution order, that gets ignored and we fallback to just # what's implemented by the class. # That's not good. Do our best to propagate the exception by # returning it. There will be downstream errors later. return e def getSignatureString(self): return '()' def getSignatureInfo(self): return {'positional': (), 'required': (), 'optional': (), 'varargs': None, 'kwargs': None, } def get(self, object): return getattr(object, self.__name__)() def query(self, object, default=None): try: f = getattr(object, self.__name__) except AttributeError: return default else: return f() def set(self, object, value): if self.readonly: raise TypeError("Can't set values on read-only fields") getattr(object, self.writer.__name__)(value) def __getattr__(self, name): return getattr(self.field, name) def bind(self, object): clone = self.__class__.__new__(self.__class__) clone.__dict__.update(self.__dict__) clone.field = self.field.bind(object) return clone class FieldWriteAccessor(Method): def __init__(self, field): Method.__init__(self, '') self.field = field self.__doc__ = 'set %s' % field.__doc__ def getSignatureString(self): return '(newvalue)' def getSignatureInfo(self): return {'positional': ('newvalue',), 'required': ('newvalue',), 'optional': (), 'varargs': None, 'kwargs': None, } def accessors(field): reader = FieldReadAccessor(field) yield reader if not field.readonly: writer = FieldWriteAccessor(field) reader.writer = writer yield writer zope.schema-6.2.0/src/zope/schema/fieldproperty.py0000644000100100000240000001210114133212652022036 0ustar macstaff00000000000000############################################################################## # # Copyright (c) 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Computed attributes based on schema fields """ from copy import copy import sys import zope.schema from zope import interface from zope import event from zope.schema import interfaces from zope.schema._bootstrapinterfaces import NO_VALUE _marker = object() @interface.implementer(interfaces.IFieldUpdatedEvent) class FieldUpdatedEvent(object): def __init__(self, obj, field, old_value, new_value): self.object = obj self.field = field self.old_value = old_value self.new_value = new_value # The implementation used to differ from the interfaces in that it # declared `self.inst` instead of `self.object`. Leave `self.inst` # in place for backwards compat. inst = property( lambda self: self.object, lambda self, new_value: setattr(self, 'object', new_value)) class FieldProperty(object): """Computed attributes based on schema fields Field properties provide default values, data validation and error messages based on data found in field meta-data. Note that FieldProperties cannot be used with slots. They can only be used for attributes stored in instance dictionaries. """ def __init__(self, field, name=None): if name is None: name = field.__name__ self.__field = field self.__name = name def __get__(self, inst, klass): if inst is None: return self value = inst.__dict__.get(self.__name, _marker) if value is _marker: field = self.__field.bind(inst) value = getattr(field, 'default', _marker) if value is _marker: raise AttributeError(self.__name) return value def queryValue(self, inst, default): value = inst.__dict__.get(self.__name, default) if value is default: field = self.__field.bind(inst) value = getattr(field, 'default', default) return value def __set__(self, inst, value): field = self.__field.bind(inst) field.validate(value) if field.readonly and self.__name in inst.__dict__: raise ValueError(self.__name, 'field is readonly') oldvalue = self.queryValue(inst, NO_VALUE) inst.__dict__[self.__name] = value event.notify(FieldUpdatedEvent(inst, field, oldvalue, value)) def __getattr__(self, name): return getattr(self.__field, name) def createFieldProperties(schema, omit=[]): """For each fields in `schema` create a FieldProperty on the class. schema ... interface those fields should be added to class omit ... list of field names to be omitted in creation Usage:: class A(object): zope.schema.fieldproperty.createFieldProperties(IMySchema) """ frame = sys._getframe(1) for name in zope.schema.getFieldNamesInOrder(schema): if name in omit: continue frame.f_locals[name] = FieldProperty(schema[name]) class FieldPropertyStoredThroughField(object): def __init__(self, field, name=None): if name is None: name = field.__name__ self.field = copy(field) self.field.__name__ = "__st_%s_st" % self.field.__name__ self.__name = name def setValue(self, inst, field, value): field.set(inst, value) def getValue(self, inst, field): return field.query(inst, _marker) def queryValue(self, inst, field, default): return field.query(inst, default) def __getattr__(self, name): return getattr(self.field, name) def __get__(self, inst, klass): if inst is None: return self field = self.field.bind(inst) value = self.getValue(inst, field) if value is _marker: value = getattr(field, 'default', _marker) if value is _marker: raise AttributeError(self.__name) return value def __set__(self, inst, value): field = self.field.bind(inst) field.validate(value) if field.readonly: if self.queryValue(inst, field, _marker) is _marker: field.readonly = False self.setValue(inst, field, value) field.readonly = True return else: raise ValueError(self.__name, 'field is readonly') oldvalue = self.queryValue(inst, field, NO_VALUE) self.setValue(inst, field, value) event.notify(FieldUpdatedEvent(inst, self.field, oldvalue, value)) zope.schema-6.2.0/src/zope/schema/interfaces.py0000644000100100000240000007240114133212652021302 0ustar macstaff00000000000000############################################################################## # # Copyright (c) 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Schema interfaces and exceptions """ __docformat__ = "reStructuredText" from zope.interface import Attribute from zope.interface import Interface from zope.interface.common.mapping import IEnumerableMapping from zope.interface.interfaces import IInterface from zope.schema._bootstrapfields import Bool from zope.schema._bootstrapfields import Complex from zope.schema._bootstrapfields import Decimal from zope.schema._bootstrapfields import Field from zope.schema._bootstrapfields import Int from zope.schema._bootstrapfields import Integral from zope.schema._bootstrapfields import Number from zope.schema._bootstrapfields import Object from zope.schema._bootstrapfields import Rational from zope.schema._bootstrapfields import Real from zope.schema._bootstrapfields import Text from zope.schema._bootstrapfields import TextLine # Import from _bootstrapinterfaces only because other packages will expect # to find these interfaces here. from zope.schema._bootstrapinterfaces import ConstraintNotSatisfied from zope.schema._bootstrapinterfaces import IBeforeObjectAssignedEvent from zope.schema._bootstrapinterfaces import IContextAwareDefaultFactory from zope.schema._bootstrapinterfaces import IFromBytes from zope.schema._bootstrapinterfaces import IFromUnicode from zope.schema._bootstrapinterfaces import IValidatable from zope.schema._bootstrapinterfaces import InvalidValue from zope.schema._bootstrapinterfaces import LenOutOfBounds from zope.schema._bootstrapinterfaces import NotAContainer from zope.schema._bootstrapinterfaces import NotAnInterface from zope.schema._bootstrapinterfaces import NotAnIterator from zope.schema._bootstrapinterfaces import OrderableOutOfBounds from zope.schema._bootstrapinterfaces import OutOfBounds from zope.schema._bootstrapinterfaces import RequiredMissing from zope.schema._bootstrapinterfaces import SchemaNotCorrectlyImplemented from zope.schema._bootstrapinterfaces import SchemaNotFullyImplemented from zope.schema._bootstrapinterfaces import SchemaNotProvided from zope.schema._bootstrapinterfaces import StopValidation from zope.schema._bootstrapinterfaces import TooBig from zope.schema._bootstrapinterfaces import TooLong from zope.schema._bootstrapinterfaces import TooShort from zope.schema._bootstrapinterfaces import TooSmall from zope.schema._bootstrapinterfaces import ValidationError from zope.schema._bootstrapinterfaces import WrongContainedType from zope.schema._bootstrapinterfaces import WrongType from zope.schema._compat import PY3 from zope.schema._messageid import _ __all__ = [ # Exceptions 'ConstraintNotSatisfied', 'InvalidDottedName', 'InvalidId', 'InvalidURI', 'InvalidValue', 'LenOutOfBounds', 'NotAContainer', 'NotAnInterface', 'NotAnIterator', 'NotUnique', 'OrderableOutOfBounds', 'OutOfBounds', 'RequiredMissing', 'SchemaNotCorrectlyImplemented', 'SchemaNotFullyImplemented', 'SchemaNotProvided', 'StopValidation', 'TooBig', 'TooLong', 'TooShort', 'TooSmall', 'Unbound', 'ValidationError', 'WrongContainedType', 'WrongType', # Interfaces 'IASCII', 'IASCIILine', 'IAbstractBag', 'IAbstractSet', 'IBaseVocabulary', 'IBeforeObjectAssignedEvent', 'IBool', 'IBytes', 'IBytesLine', 'IChoice', 'ICollection', 'IComplex', 'IContainer', 'IContextAwareDefaultFactory', 'IContextSourceBinder', 'IDate', 'IDatetime', 'IDecimal', 'IDict', 'IDottedName', 'IField', 'IFieldEvent', 'IFieldUpdatedEvent', 'IFloat', 'IFromBytes', 'IFromUnicode', 'IFrozenSet', 'IId', 'IInt', 'IIntegral', 'IInterfaceField', 'IIterable', 'IIterableSource', 'IIterableVocabulary', 'ILen', 'IList', 'IMapping', 'IMinMax', 'IMinMaxLen', 'IMutableMapping', 'IMutableSequence', 'INativeString', 'INativeStringLine', 'INumber', 'IObject', 'IOrderable', 'IPassword', 'IPythonIdentifier', 'IRational', 'IReal', 'ISequence', 'ISet', 'ISource', 'ISourceQueriables', 'ISourceText', 'ITerm', 'IText', 'ITextLine', 'ITime', 'ITimedelta', 'ITitledTokenizedTerm', 'ITokenizedTerm', 'ITreeVocabulary', 'ITuple', 'IURI', 'IUnorderedCollection', 'IVocabulary', 'IVocabularyFactory', 'IVocabularyRegistry', 'IVocabularyTokenized', ] class NotUnique(ValidationError): __doc__ = _("""One or more entries of sequence are not unique.""") class InvalidURI(ValidationError): __doc__ = _("""The specified URI is not valid.""") class InvalidId(ValidationError): __doc__ = _("""The specified id is not valid.""") class InvalidDottedName(ValidationError): __doc__ = _("""The specified dotted name is not valid.""") class Unbound(Exception): __doc__ = _("""The field is not bound.""") class IField(IValidatable): """Basic Schema Field Interface. Fields are used for Interface specifications. They at least provide a title, description and a default value. You can also specify if they are required and/or readonly. The Field Interface is also used for validation and specifying constraints. We want to make it possible for a IField to not only work on its value but also on the object this value is bound to. This enables a Field implementation to perform validation against an object which also marks a certain place. Note that many fields need information about the object containing a field. For example, when validating a value to be set as an object attribute, it may be necessary for the field to introspect the object's state. This means that the field needs to have access to the object when performing validation:: bound = field.bind(object) bound.validate(value) """ def bind(object): """Return a copy of this field which is bound to context. The copy of the Field will have the 'context' attribute set to 'object'. This way a Field can implement more complex checks involving the object's location/environment. Many fields don't need to be bound. Only fields that condition validation or properties on an object containing the field need to be bound. """ title = TextLine( title=_("Title"), description=_("A short summary or label"), default=u"", required=False, ) description = Text( title=_("Description"), description=_("A description of the field"), default=u"", required=False, ) required = Bool( title=_("Required"), description=(_("Tells whether a field requires its value to exist.")), default=True) readonly = Bool( title=_("Read Only"), description=_("If true, the field's value cannot be changed."), required=False, default=False) default = Field( title=_("Default Value"), description=_("""The field default value may be None or a legal field value""") ) missing_value = Field( title=_("Missing Value"), description=_("""If input for this Field is missing, and that's ok, then this is the value to use""") ) order = Int( title=_("Field Order"), description=_(""" The order attribute can be used to determine the order in which fields in a schema were defined. If one field is created after another (in the same thread), its order will be greater. (Fields in separate threads could have the same order.) """), required=True, readonly=True, ) def constraint(value): """Check a customized constraint on the value. You can implement this method with your Field to require a certain constraint. This relaxes the need to inherit/subclass a Field you to add a simple constraint. Returns true if the given value is within the Field's constraint. """ def validate(value): """Validate that the given value is a valid field value. Returns nothing but raises an error if the value is invalid. It checks everything specific to a Field and also checks with the additional constraint. """ def get(object): """Get the value of the field for the given object.""" def query(object, default=None): """Query the value of the field for the given object. Return the default if the value hasn't been set. """ def set(object, value): """Set the value of the field for the object Raises a type error if the field is a read-only field. """ class IIterable(IField): """Fields with a value that can be iterated over. The value needs to support iteration; the implementation mechanism is not constrained. (Either `__iter__()` or `__getitem__()` may be used.) """ class IContainer(IField): """Fields whose value allows an ``x in value`` check. The value needs to support the `in` operator, but is not constrained in how it does so (whether it defines `__contains__()` or `__getitem__()` is immaterial). """ class IOrderable(IField): """Field requiring its value to be orderable. The set of value needs support a complete ordering; the implementation mechanism is not constrained. Either `__cmp__()` or 'rich comparison' methods may be used. """ class ILen(IField): """A Field requiring its value to have a length. The value needs to have a conventional __len__ method. """ class IMinMax(IOrderable): """Field requiring its value to be between min and max. This implies that the value needs to support the IOrderable interface. """ min = Field( title=_("Start of the range"), required=False, default=None ) max = Field( title=_("End of the range (including the value itself)"), required=False, default=None ) class IMinMaxLen(ILen): """Field requiring the length of its value to be within a range""" min_length = Int( title=_("Minimum length"), description=_(""" Value after whitespace processing cannot have less than `min_length` characters (if a string type) or elements (if another sequence type). If `min_length` is ``None``, there is no minimum. """), required=False, min=0, # needs to be a positive number default=0) max_length = Int( title=_("Maximum length"), description=_(""" Value after whitespace processing cannot have greater or equal than `max_length` characters (if a string type) or elements (if another sequence type). If `max_length` is ``None``, there is no maximum."""), required=False, min=0, # needs to be a positive number default=None) class IInterfaceField(IField): """Fields with a value that is an interface (implementing zope.interface.Interface).""" class IBool(IField): """Boolean Field.""" default = Bool( title=_("Default Value"), description=_("""The field default value may be None or a legal field value""") ) required = Bool( title=_("Required"), description=(_("Tells whether a field requires its value to exist.")), required=False, default=False) class IBytes(IMinMaxLen, IIterable, IField): """Field containing a byte string (like the python str). The value might be constrained to be with length limits. """ class IText(IMinMaxLen, IIterable, IField): """Field containing a unicode string.""" # for things which are of the str type on both Python 2 and 3 class INativeString(IText if PY3 else IBytes): """ A field that always contains the native `str` type. .. versionchanged:: 4.9.0 This is now a distinct type instead of an alias for either `IText` or `IBytes`, depending on the platform. """ class IASCII(INativeString): """Field containing a 7-bit ASCII string. No characters > DEL (chr(127)) are allowed The value might be constrained to be with length limits. """ class IBytesLine(IBytes): """Field containing a byte string without newlines.""" class IASCIILine(IASCII): """Field containing a 7-bit ASCII string without newlines.""" class ISourceText(IText): """Field for source text of object.""" class ITextLine(IText): """Field containing a unicode string without newlines.""" class INativeStringLine(ITextLine if PY3 else IBytesLine): """ A field that always contains the native `str` type, without any newlines. .. versionchanged:: 4.9.0 This is now a distinct type instead of an alias for either `ITextLine` or `IBytesLine`, depending on the platform. """ class IPassword(ITextLine): """Field containing a unicode password string without newlines.""" ### # Numbers ### ## # Abstract numbers ## class INumber(IMinMax, IField): """ Field containing a generic number: :class:`numbers.Number`. .. seealso:: :class:`zope.schema.Number` .. versionadded:: 4.6.0 """ min = Number( title=_("Start of the range"), required=False, default=None ) max = Number( title=_("End of the range (including the value itself)"), required=False, default=None ) default = Number( title=_("Default Value"), description=_("""The field default value may be None or a legal field value""") ) class IComplex(INumber): """ Field containing a complex number: :class:`numbers.Complex`. .. seealso:: :class:`zope.schema.Real` .. versionadded:: 4.6.0 """ min = Complex( title=_("Start of the range"), required=False, default=None ) max = Complex( title=_("End of the range (including the value itself)"), required=False, default=None ) default = Complex( title=_("Default Value"), description=_("""The field default value may be None or a legal field value""") ) class IReal(IComplex): """ Field containing a real number: :class:`numbers.IReal`. .. seealso:: :class:`zope.schema.Real` .. versionadded:: 4.6.0 """ min = Real( title=_("Start of the range"), required=False, default=None ) max = Real( title=_("End of the range (including the value itself)"), required=False, default=None ) default = Real( title=_("Default Value"), description=_("""The field default value may be None or a legal field value""") ) class IRational(IReal): """ Field containing a rational number: :class:`numbers.IRational`. .. seealso:: :class:`zope.schema.Rational` .. versionadded:: 4.6.0 """ min = Rational( title=_("Start of the range"), required=False, default=None ) max = Rational( title=_("End of the range (including the value itself)"), required=False, default=None ) default = Rational( title=_("Default Value"), description=_("""The field default value may be None or a legal field value""") ) class IIntegral(IRational): """ Field containing an integral number: class:`numbers.Integral`. .. seealso:: :class:`zope.schema.Integral` .. versionadded:: 4.6.0 """ min = Integral( title=_("Start of the range"), required=False, default=None ) max = Integral( title=_("End of the range (including the value itself)"), required=False, default=None ) default = Integral( title=_("Default Value"), description=_("""The field default value may be None or a legal field value""") ) ## # Concrete numbers ## class IInt(IIntegral): """ Field containing exactly the native class :class:`int` (or, on Python 2, ``long``). .. seealso:: :class:`zope.schema.Int` """ min = Int( title=_("Start of the range"), required=False, default=None ) max = Int( title=_("End of the range (including the value itself)"), required=False, default=None ) default = Int( title=_("Default Value"), description=_("""The field default value may be None or a legal field value""") ) class IFloat(IReal): """ Field containing exactly the native class :class:`float`. :class:`IReal` is a more general interface, allowing all of floats, ints, and fractions. .. seealso:: :class:`zope.schema.Float` """ class IDecimal(INumber): """Field containing a :class:`decimal.Decimal`""" min = Decimal( title=_("Start of the range"), required=False, default=None ) max = Decimal( title=_("End of the range (including the value itself)"), required=False, default=None ) default = Decimal( title=_("Default Value"), description=_("""The field default value may be None or a legal field value""") ) ### # End numbers ### class IDatetime(IMinMax, IField): """Field containing a datetime.""" class IDate(IMinMax, IField): """Field containing a date.""" class ITimedelta(IMinMax, IField): """Field containing a timedelta.""" class ITime(IMinMax, IField): """Field containing a time.""" def _is_field(value): if not IField.providedBy(value): return False return True def _fields(values): for value in values: if not _is_field(value): return False return True class IURI(INativeStringLine): """A field containing an absolute URI """ class IId(INativeStringLine): """A field containing a unique identifier A unique identifier is either an absolute URI or a dotted name. If it's a dotted name, it should have a module/package name as a prefix. """ class IDottedName(INativeStringLine): """Dotted name field. Values of DottedName fields must be Python-style dotted names. """ min_dots = Int( title=_("Minimum number of dots"), required=True, min=0, default=0 ) max_dots = Int( title=_("Maximum number of dots (should not be less than min_dots)"), required=False, default=None ) class IPythonIdentifier(INativeStringLine): """ A single Python identifier, such as a variable name. .. versionadded:: 4.9.0 """ class IChoice(IField): """Field whose value is contained in a predefined set Only one, values or vocabulary, may be specified for a given choice. """ vocabulary = Field( title=_("Vocabulary or source providing values"), description=_("The ISource, IContextSourceBinder or IBaseVocabulary " "object that provides values for this field."), required=False, default=None ) vocabularyName = TextLine( title=_("Vocabulary name"), description=_("Vocabulary name to lookup in the vocabulary registry"), required=False, default=None ) # Collections: # Abstract class ICollection(IMinMaxLen, IIterable, IContainer): """Abstract interface containing a collection value. The Value must be iterable and may have a min_length/max_length. """ value_type = Object( IField, title=_("Value Type"), description=_("Field value items must conform to the given type, " "expressed via a Field.")) unique = Bool( title=_('Unique Members'), description=_('Specifies whether the members of the collection ' 'must be unique.'), default=False) class ISequence(ICollection): """Abstract interface specifying that the value is ordered""" class IMutableSequence(ISequence): """ Abstract interface specifying that the value is ordered and mutable. .. versionadded:: 4.6.0 """ class IUnorderedCollection(ICollection): """Abstract interface specifying that the value cannot be ordered""" class IAbstractSet(IUnorderedCollection): """An unordered collection of unique values.""" unique = Bool( description="This ICollection interface attribute must be True") class IAbstractBag(IUnorderedCollection): """An unordered collection of values, with no limitations on whether members are unique""" unique = Bool( description="This ICollection interface attribute must be False") # Concrete class ITuple(ISequence): """Field containing a value that implements the API of a conventional Python tuple.""" class IList(IMutableSequence): """Field containing a value that implements the API of a conventional Python list.""" class ISet(IAbstractSet): """Field containing a value that implements the API of a Python2.4+ set. """ class IFrozenSet(IAbstractSet): """Field containing a value that implements the API of a conventional Python 2.4+ frozenset.""" # (end Collections) class IObject(IField): """ Field containing an Object value. .. versionchanged:: 4.6.0 Add the *validate_invariants* attribute. """ schema = Object( IInterface, description=_("The Interface that defines the Fields comprising the " "Object.") ) validate_invariants = Bool( title=_("Validate Invariants"), description=_("A boolean that says whether " "``schema.validateInvariants`` is called from " "``self.validate()``. The default is true."), default=True, ) class IMapping(IMinMaxLen, IIterable, IContainer): """ Field containing an instance of :class:`collections.Mapping`. The *key_type* and *value_type* fields allow specification of restrictions for keys and values contained in the dict. """ key_type = Object( IField, description=_("Field keys must conform to the given type, expressed " "via a Field.") ) value_type = Object( IField, description=_("Field values must conform to the given type, expressed " "via a Field.") ) class IMutableMapping(IMapping): """ Field containing an instance of :class:`collections.MutableMapping`. """ class IDict(IMutableMapping): """Field containing a conventional dict. """ class ITerm(Interface): """Object representing a single value in a vocabulary.""" value = Attribute( "value", "The value used to represent vocabulary term in a field.") class ITokenizedTerm(ITerm): """Object representing a single value in a tokenized vocabulary. """ # Should be a ``zope.schema.ASCIILine``, but `ASCIILine` is not a bootstrap # field. `ASCIILine` is a type of NativeString. token = Attribute( "token", """Token which can be used to represent the value on a stream. The value of this attribute must be a non-empty 7-bit native string (i.e., the ``str`` type on both Python 2 and 3). Control characters, including newline, are not allowed. """) class ITitledTokenizedTerm(ITokenizedTerm): """A tokenized term that includes a title.""" title = TextLine(title=_("Title")) class ISource(Interface): """A set of values from which to choose Sources represent sets of values. They are used to specify the source for choice fields. Sources can be large (even infinite), in which case, they need to be queried to find out what their values are. """ def __contains__(value): """Return whether the value is available in this source """ class ISourceQueriables(Interface): """A collection of objects for querying sources """ def getQueriables(): """Return an iterable of objects that can be queried The returned obects should be two-tuples with: - A unicode id The id must uniquely identify the queriable object within the set of queriable objects. Furthermore, in subsequent calls, the same id should be used for a given queriable object. - A queriable object This is an object for which there is a view provided for searching for items. """ class IContextSourceBinder(Interface): def __call__(context): """Return a context-bound instance that implements ISource. """ class IBaseVocabulary(ISource): """Representation of a vocabulary. At this most basic level, a vocabulary only need to support a test for containment. This can be implemented either by __contains__() or by sequence __getitem__() (the later only being useful for vocabularies which are intrinsically ordered). """ def getTerm(value): """Return the ITerm object for the term 'value'. If 'value' is not a valid term, this method raises LookupError. """ class IIterableSource(ISource): """Source which supports iteration over allowed values. The objects iteration provides must be values from the source. """ def __iter__(): """Return an iterator which provides the values from the source.""" def __len__(): """Return the number of valid values, or sys.maxint.""" # BBB vocabularies are pending deprecation, hopefully in 3.3 class IIterableVocabulary(Interface): """Vocabulary which supports iteration over allowed values. The objects iteration provides must conform to the ITerm interface. """ def __iter__(): """Return an iterator which provides the terms from the vocabulary.""" def __len__(): """Return the number of valid terms, or sys.maxint.""" class IVocabulary(IIterableVocabulary, IBaseVocabulary): """Vocabulary which is iterable.""" class IVocabularyTokenized(IVocabulary): """Vocabulary that provides support for tokenized representation. Terms returned from getTerm() and provided by iteration must conform to ITokenizedTerm. """ def getTermByToken(token): """Return an ITokenizedTerm for the passed-in token. If `token` is not represented in the vocabulary, `LookupError` is raised. """ class ITreeVocabulary(IVocabularyTokenized, IEnumerableMapping): """A tokenized vocabulary with a tree-like structure. The tree is implemented as dictionary, with keys being ITokenizedTerm terms and the values being similar dictionaries. Leaf values are empty dictionaries. """ class IVocabularyRegistry(Interface): """ Registry that provides `IBaseVocabulary` objects for specific fields. The fields of this package use the vocabulary registry that is returned from :func:`~.getVocabularyRegistry`. This is a hook function; by default it returns an instance of :class:`~.VocabularyRegistry`, but the function :func:`~.setVocabularyRegistry` can be used to change this. In particular, the package `zope.vocabularyregistry `_ can be used to install a vocabulary registry that uses the :mod:`zope.component` architecture. """ def get(context, name): """ Return the vocabulary named *name* for the content object *context*. When the vocabulary cannot be found, `LookupError` is raised. """ class IVocabularyFactory(Interface): """ An object that can create `IBaseVocabulary`. Objects that implement this interface can be registered with the default :class:`~.VocabularyRegistry` provided by this package. Alternatively, `zope.vocabularyregistry `_ can be used to install a `IVocabularyRegistry` that looks for named utilities using :func:`zope.component.getUtility` which provide this interface. """ def __call__(context): """The *context* provides a location that the vocabulary can make use of. """ class IFieldEvent(Interface): field = Object( IField, description="The field that has been changed") object = Attribute("The object containing the field") class IFieldUpdatedEvent(IFieldEvent): """ A field has been modified Subscribers will get the old and the new value together with the field """ old_value = Attribute("The value of the field before modification") new_value = Attribute("The value of the field after modification") zope.schema-6.2.0/src/zope/schema/tests/0000755000100100000240000000000014133212652017743 5ustar macstaff00000000000000zope.schema-6.2.0/src/zope/schema/tests/__init__.py0000644000100100000240000000316414133212652022060 0ustar macstaff00000000000000# # This file is necessary to make this directory a package. import re from zope.schema._compat import PY3 from zope.testing import renormalizing def _make_transforms(patterns): return [(re.compile(pattern), repl) for pattern, repl in patterns] if PY3: # pragma: PY3 py3_checker = renormalizing.RENormalizing(_make_transforms([ (r"u'([^']*)'", r"'\1'"), (r"^b'([^']*)'", r"'\1'"), (r"([^'])b'([^']*)'", r"\1'\2'"), (r"", r""), (r"", r""), (r"zope.schema._bootstrapinterfaces.InvalidValue", r"InvalidValue"), (r"zope.schema.interfaces.InvalidId: '([^']*)'", r"InvalidId: \1"), (r"zope.schema.interfaces.InvalidId:", r"InvalidId:"), (r"zope.schema.interfaces.InvalidURI: '([^']*)'", r"InvalidURI: \1"), (r"zope.schema.interfaces.InvalidURI:", r"InvalidURI:"), (r"zope.schema.interfaces.InvalidDottedName: '([^']*)'", r"InvalidDottedName: \1"), (r"zope.schema.interfaces.InvalidDottedName:", r"InvalidDottedName:"), (r"zope.schema._bootstrapinterfaces.ConstraintNotSatisfied: '([^']*)'", r"ConstraintNotSatisfied: \1"), (r"zope.schema._bootstrapinterfaces.ConstraintNotSatisfied:", r"ConstraintNotSatisfied:"), (r"zope.schema._bootstrapinterfaces.WrongType:", r"WrongType:"), ])) else: # pragma: PY2 py3_checker = renormalizing.RENormalizing(_make_transforms([ (r"([^'])b'([^']*)'", r"\1'\2'"), ])) zope.schema-6.2.0/src/zope/schema/tests/states.py0000644000100100000240000000604214133212652021622 0ustar macstaff00000000000000############################################################################## # # Copyright (c) 2003 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Sample vocabulary supporting state abbreviations. """ from zope.interface import implementer from zope.schema import interfaces # 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', } @implementer(interfaces.ITerm) class State(object): __slots__ = 'value', 'title' def __init__(self, value, title): self.value = value self.title = title for v, p in _states.items(): _states[v] = State(v, p) class IStateVocabulary(interfaces.IVocabulary): """Vocabularies that support the states database conform to this.""" @implementer(IStateVocabulary) class StateVocabulary(object): __slots__ = () def __init__(self, object=None): pass def __contains__(self, value): return value in _states def __iter__(self): return iter(_states.values()) def __len__(self): return len(_states) def getTerm(self, value): return _states[value] zope.schema-6.2.0/src/zope/schema/tests/test__bootstrapfields.py0000644000100100000240000017666414133212652024743 0ustar macstaff00000000000000############################################################################## # # Copyright (c) 2012 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## import decimal import doctest import unittest import unicodedata # pylint:disable=protected-access,inherit-non-class,blacklisted-name # pylint:disable=attribute-defined-outside-init class InterfaceConformanceTestsMixin(object): def _getTargetClass(self): raise NotImplementedError def _getTargetInterface(self): raise NotImplementedError def _getTargetInterfaces(self): # Return the primary and any secondary interfaces return [self._getTargetInterface()] def _makeOne(self, *args, **kwargs): return self._makeOneFromClass(self._getTargetClass(), *args, **kwargs) def _makeOneFromClass(self, cls, *args, **kwargs): return cls(*args, **kwargs) def test_class_conforms_to_iface(self): from zope.interface.verify import verifyClass cls = self._getTargetClass() __traceback_info__ = cls for iface in self._getTargetInterfaces(): verifyClass(iface, cls) return verifyClass def test_instance_conforms_to_iface(self): from zope.interface.verify import verifyObject instance = self._makeOne() __traceback_info__ = instance for iface in self._getTargetInterfaces(): verifyObject(iface, instance) return verifyObject def test_iface_is_first_in_sro(self): from zope.interface import implementedBy implemented = implementedBy(self._getTargetClass()) __traceback_info__ = implemented.__sro__ self.assertIs(implemented, implemented.__sro__[0]) self.assertIs(self._getTargetInterface(), implemented.__sro__[1]) def test_implements_consistent__sro__(self): from zope.interface import ro from zope.interface import implementedBy __traceback_info__ = implementedBy(self._getTargetClass()).__sro__ self.assertTrue( ro.is_consistent(implementedBy(self._getTargetClass()))) def test_iface_consistent_ro(self): from zope.interface import ro __traceback_info__ = self._getTargetInterface().__iro__ self.assertTrue(ro.is_consistent(self._getTargetInterface())) class EqualityTestsMixin(InterfaceConformanceTestsMixin): def test_is_hashable(self): field = self._makeOne() hash(field) # doesn't raise def test_equal_instances_have_same_hash(self): # Equal objects should have equal hashes field1 = self._makeOne() field2 = self._makeOne() self.assertIsNot(field1, field2) self.assertEqual(field1, field2) self.assertEqual(hash(field1), hash(field2)) def test_instances_in_different_interfaces_not_equal(self): from zope import interface field1 = self._makeOne() field2 = self._makeOne() self.assertEqual(field1, field2) self.assertEqual(hash(field1), hash(field2)) class IOne(interface.Interface): one = field1 class ITwo(interface.Interface): two = field2 self.assertEqual(field1, field1) self.assertEqual(field2, field2) self.assertNotEqual(field1, field2) self.assertNotEqual(hash(field1), hash(field2)) 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') self.assertIsNot(field1, field2) self.assertNotEqual(field1, field2) self.assertEqual(hash(field1), hash(field2)) d = {field1: 42} self.assertIn(field1, d) self.assertEqual(42, d[field1]) self.assertNotIn(field2, d) with self.assertRaises(KeyError): d.__getitem__(field2) def test___eq___different_type(self): left = self._makeOne() class Derived(self._getTargetClass()): pass right = self._makeOneFromClass(Derived) self.assertNotEqual(left, right) self.assertTrue(left != right) def test___eq___same_type_different_attrs(self): left = self._makeOne(required=True) right = self._makeOne(required=False) self.assertNotEqual(left, right) self.assertTrue(left != right) def test___eq___same_type_same_attrs(self): left = self._makeOne() self.assertEqual(left, left) right = self._makeOne() self.assertEqual(left, right) self.assertFalse(left != right) class OrderableMissingValueMixin(object): mvm_missing_value = -1 mvm_default = 0 def test_missing_value_no_min_or_max(self): # We should be able to provide a missing_value without # also providing a min or max. But note that we must still # provide a default. # See https://github.com/zopefoundation/zope.schema/issues/9 Kind = self._getTargetClass() self.assertTrue(Kind.min._allow_none) self.assertTrue(Kind.max._allow_none) field = self._makeOne(missing_value=self.mvm_missing_value, default=self.mvm_default) self.assertIsNone(field.min) self.assertIsNone(field.max) self.assertEqual(self.mvm_missing_value, field.missing_value) class OrderableTestsMixin(object): def assertRaisesTooBig(self, field, value): from zope.schema.interfaces import TooBig with self.assertRaises(TooBig) as exc: field.validate(value) ex = exc.exception self.assertEqual(value, ex.value) self.assertEqual(field.max, ex.bound) self.assertEqual(TooBig.TOO_LARGE, ex.violation_direction) def assertRaisesTooSmall(self, field, value): from zope.schema.interfaces import TooSmall with self.assertRaises(TooSmall) as exc: field.validate(value) ex = exc.exception self.assertEqual(value, ex.value) self.assertEqual(field.min, ex.bound) self.assertEqual(TooSmall.TOO_SMALL, ex.violation_direction) MIN = 10 MAX = 20 VALID = (10, 11, 19, 20) TOO_SMALL = (9, -10) TOO_BIG = (21, 22) def test_validate_min(self): field = self._makeOne(min=self.MIN) for value in self.VALID + self.TOO_BIG: field.validate(value) for value in self.TOO_SMALL: self.assertRaisesTooSmall(field, value) def test_validate_max(self): field = self._makeOne(max=self.MAX) for value in self.VALID + self.TOO_SMALL: field.validate(value) for value in self.TOO_BIG: self.assertRaisesTooBig(field, value) def test_validate_min_and_max(self): field = self._makeOne(min=self.MIN, max=self.MAX) for value in self.TOO_SMALL: self.assertRaisesTooSmall(field, value) for value in self.VALID: field.validate(value) for value in self.TOO_BIG: self.assertRaisesTooBig(field, value) class LenTestsMixin(object): def assertRaisesTooLong(self, field, value): from zope.schema.interfaces import TooLong with self.assertRaises(TooLong) as exc: field.validate(value) ex = exc.exception self.assertEqual(value, ex.value) self.assertEqual(field.max_length, ex.bound) self.assertEqual(TooLong.TOO_LARGE, ex.violation_direction) def assertRaisesTooShort(self, field, value): from zope.schema.interfaces import TooShort with self.assertRaises(TooShort) as exc: field.validate(value) ex = exc.exception self.assertEqual(value, ex.value) self.assertEqual(field.min_length, ex.bound) self.assertEqual(TooShort.TOO_SMALL, ex.violation_direction) class WrongTypeTestsMixin(object): def assertRaisesWrongType(self, field_or_meth, expected_type, *args, **kwargs): from zope.schema.interfaces import WrongType field = None with self.assertRaises(WrongType) as exc: if hasattr(field_or_meth, 'validate'): field = field_or_meth field.validate(*args, **kwargs) else: field_or_meth(*args, **kwargs) ex = exc.exception self.assertIs(ex.expected_type, expected_type) if field is not None: self.assertIs(ex.field, field) if len(args) == 1 and not kwargs: # Just a value self.assertIs(ex.value, args[0]) if not args and len(kwargs) == 1: # A single keyword argument self.assertIs(ex.value, kwargs.popitem()[1]) def assertAllRaiseWrongType(self, field, expected_type, *values): for value in values: __traceback_info__ = value self.assertRaisesWrongType(field, expected_type, value) class ValidatedPropertyTests(unittest.TestCase): def _getTargetClass(self): from zope.schema._bootstrapfields import ValidatedProperty return ValidatedProperty def _makeOne(self, *args, **kw): return self._getTargetClass()(*args, **kw) def test___set___not_missing_w_check(self): _checked = [] def _check(inst, value): _checked.append((inst, value)) class Test(DummyInst): _prop = None prop = self._makeOne('_prop', _check) inst = Test() inst.prop = 'PROP' self.assertEqual(inst._prop, 'PROP') self.assertEqual(_checked, [(inst, 'PROP')]) def test___set___not_missing_wo_check(self): class Test(DummyInst): _prop = None prop = self._makeOne('_prop') inst = Test(ValueError) def _provoke(inst): inst.prop = 'PROP' self.assertRaises(ValueError, _provoke, inst) self.assertEqual(inst._prop, None) def test___set___w_missing_wo_check(self): class Test(DummyInst): _prop = None prop = self._makeOne('_prop') inst = Test(ValueError) inst.prop = DummyInst.missing_value self.assertEqual(inst._prop, DummyInst.missing_value) def test___get__(self): class Test(DummyInst): _prop = None prop = self._makeOne('_prop') inst = Test() inst._prop = 'PROP' self.assertEqual(inst.prop, 'PROP') class DefaultPropertyTests(unittest.TestCase): def _getTargetClass(self): from zope.schema._bootstrapfields import DefaultProperty return DefaultProperty def _makeOne(self, *args, **kw): return self._getTargetClass()(*args, **kw) def test___get___wo_defaultFactory_miss(self): class Test(DummyInst): _prop = None prop = self._makeOne('_prop') inst = Test() inst.defaultFactory = None def _provoke(inst): return inst.prop self.assertRaises(KeyError, _provoke, inst) def test___get___wo_defaultFactory_hit(self): class Test(DummyInst): _prop = None prop = self._makeOne('_prop') inst = Test() inst.defaultFactory = None inst._prop = 'PROP' self.assertEqual(inst.prop, 'PROP') def test__get___wo_defaultFactory_in_dict(self): class Test(DummyInst): _prop = None prop = self._makeOne('_prop') inst = Test() inst._prop = 'PROP' self.assertEqual(inst.prop, 'PROP') def test___get___w_defaultFactory_not_ICAF_no_check(self): class Test(DummyInst): _prop = None prop = self._makeOne('_prop') inst = Test(ValueError) def _factory(): return 'PROP' inst.defaultFactory = _factory def _provoke(inst): return inst.prop self.assertRaises(ValueError, _provoke, inst) def test___get___w_defaultFactory_w_ICAF_w_check(self): from zope.interface import directlyProvides from zope.schema._bootstrapinterfaces \ import IContextAwareDefaultFactory _checked = [] def _check(inst, value): _checked.append((inst, value)) class Test(DummyInst): _prop = None prop = self._makeOne('_prop', _check) inst = Test(ValueError) inst.context = object() _called_with = [] def _factory(context): _called_with.append(context) return 'PROP' directlyProvides(_factory, IContextAwareDefaultFactory) inst.defaultFactory = _factory self.assertEqual(inst.prop, 'PROP') self.assertEqual(_checked, [(inst, 'PROP')]) self.assertEqual(_called_with, [inst.context]) class FieldTests(EqualityTestsMixin, WrongTypeTestsMixin, unittest.TestCase): def _getTargetClass(self): from zope.schema._bootstrapfields import Field return Field def _getTargetInterface(self): from zope.schema.interfaces import IField return IField def test_getDoc(self): import textwrap field = self._makeOne(readonly=True, required=False) doc = field.getDoc() self.assertIn(':Read Only: True', doc) self.assertIn(':Required: False', doc) self.assertIn(":Default Value:", doc) self.assertNotIn(':Default Factory:', doc) field._type = str doc = field.getDoc() self.assertIn(':Allowed Type: :class:`str`', doc) self.assertNotIn(':Default Factory:', doc) field.defaultFactory = 'default' doc = field.getDoc() self.assertNotIn(":Default Value:", doc) self.assertIn(':Default Factory:', doc) field._type = (str, object) doc = field.getDoc() self.assertIn(':Allowed Type: :class:`str`, :class:`object`', doc) self.assertNotIn('..rubric', doc) # 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') doc = field.getDoc() self.assertIn('.. rubric:: Key Type', doc) self.assertIn('.. rubric:: Value Type', doc) self.assertEqual( doc, textwrap.dedent(""" :Implementation: :class:`zope.schema.Field` :Read Only: True :Required: False :Default Factory: 'default' :Allowed Type: :class:`str`, :class:`object` .. rubric:: Key Type Key Type :Implementation: :class:`zope.schema.Field` :Read Only: False :Required: True :Default Value: None .. rubric:: Value Type :Implementation: :class:`zope.schema.Field` :Read Only: False :Required: True :Default Value: None """) ) field = self._makeOne(title=u'A title', description=u"""Multiline description. Some lines have leading whitespace. It gets stripped. """) doc = field.getDoc() self.assertEqual( field.getDoc(), textwrap.dedent("""\ A title Multiline description. Some lines have leading whitespace. It gets stripped. :Implementation: :class:`zope.schema.Field` :Read Only: False :Required: True :Default Value: None """) ) def test_ctor_description_preserved(self): # The exact value of the description is preserved, # allowing for MessageID objects. import textwrap from zope.i18nmessageid import MessageFactory msg_factory = MessageFactory('zope') description = msg_factory(u"""Multiline description. Some lines have leading whitespace. It gets stripped. """) title = msg_factory(u'A title') field = self._makeOne(title=title, description=description) self.assertIs(field.title, title) self.assertIs(field.description, description) self.assertEqual( field.getDoc(), textwrap.dedent("""\ A title Multiline description. Some lines have leading whitespace. It gets stripped. :Implementation: :class:`zope.schema.Field` :Read Only: False :Required: True :Default Value: None """) ) def test_ctor_description_none(self): # None values for description don't break the docs. import textwrap description = None title = u'A title' field = self._makeOne(title=title, description=description) self.assertIs(field.title, title) self.assertIs(field.description, description) self.assertEqual( field.getDoc(), textwrap.dedent("""\ A title :Implementation: :class:`zope.schema.Field` :Read Only: False :Required: True :Default Value: None """) ) 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.required, True) self.assertEqual(field.readonly, False) self.assertEqual(field.constraint(object()), True) self.assertEqual(field.default, None) self.assertEqual(field.defaultFactory, None) self.assertEqual(field.missing_value, None) self.assertEqual(field.context, None) 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'') 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') 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') def test_ctor_order_madness(self): klass = self._getTargetClass() order_before = klass.order field = self._makeOne() order_after = klass.order self.assertEqual(order_after, order_before + 1) self.assertEqual(field.order, order_after) def test_explicit_required_readonly_missingValue(self): obj = object() field = self._makeOne(required=False, readonly=True, missing_value=obj) self.assertEqual(field.required, False) self.assertEqual(field.readonly, True) self.assertEqual(field.missing_value, obj) def test_explicit_constraint_default(self): _called_with = [] obj = object() def _constraint(value): _called_with.append(value) return value is obj field = self._makeOne( required=False, readonly=True, constraint=_constraint, default=obj ) self.assertEqual(field.required, False) self.assertEqual(field.readonly, True) self.assertEqual(_called_with, [obj]) self.assertEqual(field.constraint(self), False) self.assertEqual(_called_with, [obj, self]) self.assertEqual(field.default, obj) def test_explicit_defaultFactory(self): _called_with = [] obj = object() def _constraint(value): _called_with.append(value) return value is obj def _factory(): return obj field = self._makeOne( required=False, readonly=True, constraint=_constraint, defaultFactory=_factory, ) self.assertEqual(field.required, False) self.assertEqual(field.readonly, True) self.assertEqual(field.constraint(self), False) self.assertEqual(_called_with, [self]) self.assertEqual(field.default, obj) self.assertEqual(_called_with, [self, obj]) self.assertEqual(field.defaultFactory, _factory) def test_explicit_defaultFactory_returning_missing_value(self): def _factory(): return None field = self._makeOne(required=True, defaultFactory=_factory) self.assertEqual(field.default, None) def test_bind(self): obj = object() field = self._makeOne() bound = field.bind(obj) self.assertEqual(bound.context, obj) expected = dict(field.__dict__) found = dict(bound.__dict__) found.pop('context') self.assertEqual(found, expected) self.assertEqual(bound.__class__, field.__class__) def test_validate_missing_not_required(self): missing = object() field = self._makeOne( # pragma: no branch required=False, missing_value=missing, constraint=lambda x: False, ) self.assertEqual(field.validate(missing), None) # doesn't raise def test_validate_missing_and_required(self): from zope.schema._bootstrapinterfaces import RequiredMissing missing = object() field = self._makeOne( # pragma: no branch required=True, missing_value=missing, constraint=lambda x: False, ) self.assertRaises(RequiredMissing, field.validate, missing) def test_validate_wrong_type(self): field = self._makeOne( # pragma: no branch required=True, constraint=lambda x: False, ) field._type = str self.assertRaisesWrongType(field, str, 1) def test_validate_constraint_fails(self): from zope.schema._bootstrapinterfaces import ConstraintNotSatisfied field = self._makeOne(required=True, constraint=lambda x: False) field._type = int self.assertRaises(ConstraintNotSatisfied, field.validate, 1) def test_validate_constraint_raises_StopValidation(self): from zope.schema._bootstrapinterfaces import StopValidation def _fail(value): raise StopValidation field = self._makeOne(required=True, constraint=_fail) field._type = int field.validate(1) # doesn't raise def test_validate_constraint_raises_custom_exception(self): from zope.schema._bootstrapinterfaces import ValidationError def _fail(value): raise ValidationError field = self._makeOne(constraint=_fail) with self.assertRaises(ValidationError) as exc: field.validate(1) self.assertIs(exc.exception.field, field) self.assertEqual(exc.exception.value, 1) def test_validate_constraint_raises_custom_exception_no_overwrite(self): from zope.schema._bootstrapinterfaces import ValidationError def _fail(value): raise ValidationError(value).with_field_and_value(self, self) field = self._makeOne(constraint=_fail) with self.assertRaises(ValidationError) as exc: field.validate(1) self.assertIs(exc.exception.field, self) self.assertIs(exc.exception.value, self) def test_get_miss(self): field = self._makeOne(__name__='nonesuch') inst = DummyInst() self.assertRaises(AttributeError, field.get, inst) def test_get_hit(self): field = self._makeOne(__name__='extant') inst = DummyInst() inst.extant = 'EXTANT' self.assertEqual(field.get(inst), 'EXTANT') def test_query_miss_no_default(self): field = self._makeOne(__name__='nonesuch') inst = DummyInst() self.assertEqual(field.query(inst), None) def test_query_miss_w_default(self): field = self._makeOne(__name__='nonesuch') inst = DummyInst() self.assertEqual(field.query(inst, 'DEFAULT'), 'DEFAULT') def test_query_hit(self): field = self._makeOne(__name__='extant') inst = DummyInst() inst.extant = 'EXTANT' self.assertEqual(field.query(inst), 'EXTANT') def test_set_readonly(self): field = self._makeOne(__name__='lirame', readonly=True) inst = DummyInst() self.assertRaises(TypeError, field.set, inst, 'VALUE') def test_set_hit(self): field = self._makeOne(__name__='extant') inst = DummyInst() inst.extant = 'BEFORE' field.set(inst, 'AFTER') self.assertEqual(inst.extant, 'AFTER') class ContainerTests(EqualityTestsMixin, unittest.TestCase): def _getTargetClass(self): from zope.schema._bootstrapfields import Container return Container def _getTargetInterface(self): from zope.schema.interfaces import IContainer return IContainer def test_validate_not_required(self): field = self._makeOne(required=False) field.validate(None) def test_validate_required(self): from zope.schema.interfaces import RequiredMissing field = self._makeOne() self.assertRaises(RequiredMissing, field.validate, None) def test__validate_not_collection_not_iterable(self): from zope.schema._bootstrapinterfaces import NotAContainer cont = self._makeOne() bad_value = object() with self.assertRaises(NotAContainer) as exc: cont._validate(bad_value) not_cont = exc.exception self.assertIs(not_cont.field, cont) self.assertIs(not_cont.value, bad_value) def test__validate_collection_but_not_iterable(self): cont = self._makeOne() class Dummy(object): def __contains__(self, item): raise AssertionError("Not called") cont._validate(Dummy()) # doesn't raise def test__validate_not_collection_but_iterable(self): cont = self._makeOne() class Dummy(object): def __iter__(self): return iter(()) cont._validate(Dummy()) # doesn't raise def test__validate_w_collections(self): cont = self._makeOne() cont._validate(()) # doesn't raise cont._validate([]) # doesn't raise cont._validate('') # doesn't raise cont._validate({}) # doesn't raise class IterableTests(ContainerTests): def _getTargetClass(self): from zope.schema._bootstrapfields import Iterable return Iterable def _getTargetInterface(self): from zope.schema.interfaces import IIterable return IIterable def test__validate_collection_but_not_iterable(self): from zope.schema._bootstrapinterfaces import NotAnIterator itr = self._makeOne() class Dummy(object): def __contains__(self, item): raise AssertionError("Not called") dummy = Dummy() with self.assertRaises(NotAnIterator) as exc: itr._validate(dummy) not_it = exc.exception self.assertIs(not_it.field, itr) self.assertIs(not_it.value, dummy) class OrderableTests(unittest.TestCase): def _getTargetClass(self): from zope.schema._bootstrapfields import Orderable return Orderable def _makeOne(self, *args, **kw): # Orderable is a mixin for a type derived from Field from zope.schema._bootstrapfields import Field class Mixed(self._getTargetClass(), Field): pass return Mixed(*args, **kw) def test_ctor_defaults(self): ordb = self._makeOne() self.assertEqual(ordb.min, None) self.assertEqual(ordb.max, None) self.assertEqual(ordb.default, None) def test_ctor_default_too_small(self): # This test exercises _validate, too from zope.schema._bootstrapinterfaces import TooSmall self.assertRaises(TooSmall, self._makeOne, min=0, default=-1) def test_ctor_default_too_large(self): # This test exercises _validate, too from zope.schema._bootstrapinterfaces import TooBig self.assertRaises(TooBig, self._makeOne, max=10, default=11) class MinMaxLenTests(LenTestsMixin, unittest.TestCase): def _getTargetClass(self): from zope.schema._bootstrapfields import MinMaxLen return MinMaxLen def _makeOne(self, *args, **kw): # MinMaxLen is a mixin for a type derived from Field from zope.schema._bootstrapfields import Field class Mixed(self._getTargetClass(), Field): pass return Mixed(*args, **kw) def test_ctor_defaults(self): mml = self._makeOne() self.assertEqual(mml.min_length, 0) self.assertEqual(mml.max_length, None) def test_validate_too_short(self): mml = self._makeOne(min_length=1) self.assertRaisesTooShort(mml, ()) def test_validate_too_long(self): mml = self._makeOne(max_length=2) self.assertRaisesTooLong(mml, (0, 1, 2)) class TextTests(EqualityTestsMixin, WrongTypeTestsMixin, unittest.TestCase): def _getTargetClass(self): from zope.schema._bootstrapfields import Text return Text def _getTargetInterface(self): from zope.schema.interfaces import IText return IText def test_ctor_defaults(self): from zope.schema._compat import text_type txt = self._makeOne() self.assertEqual(txt._type, text_type) def test_validate_wrong_types(self): field = self._makeOne() self.assertAllRaiseWrongType( field, field._type, b'', 1, 1.0, (), [], {}, set(), frozenset(), object()) def test_validate_w_invalid_default(self): from zope.schema.interfaces import ValidationError self.assertRaises(ValidationError, self._makeOne, default=b'') 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(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') self.assertRaises(RequiredMissing, field.validate, None) def test_fromUnicode_miss(self): deadbeef = b'DEADBEEF' txt = self._makeOne() self.assertRaisesWrongType(txt.fromUnicode, txt._type, deadbeef) def test_fromUnicode_hit(self): deadbeef = u'DEADBEEF' txt = self._makeOne() self.assertEqual(txt.fromUnicode(deadbeef), deadbeef) def test_normalization(self): deadbeef = unicodedata.normalize( 'NFD', b'\xc3\x84\xc3\x96\xc3\x9c'.decode('utf-8')) txt = self._makeOne() self.assertEqual(txt.unicode_normalization, 'NFC') self.assertEqual( [unicodedata.name(c) for c in txt.fromUnicode(deadbeef)], [ 'LATIN CAPITAL LETTER A WITH DIAERESIS', 'LATIN CAPITAL LETTER O WITH DIAERESIS', 'LATIN CAPITAL LETTER U WITH DIAERESIS', ] ) txt = self._makeOne(unicode_normalization=None) self.assertEqual(txt.unicode_normalization, None) self.assertEqual( [unicodedata.name(c) for c in txt.fromUnicode(deadbeef)], [ 'LATIN CAPITAL LETTER A', 'COMBINING DIAERESIS', 'LATIN CAPITAL LETTER O', 'COMBINING DIAERESIS', 'LATIN CAPITAL LETTER U', 'COMBINING DIAERESIS', ] ) def test_normalization_after_pickle(self): # test an edge case where `Text` is persisted # see https://github.com/zopefoundation/zope.schema/issues/90 import pickle orig_makeOne = self._makeOne def makeOne(**kwargs): result = orig_makeOne(**kwargs) if not kwargs: # We should have no state to preserve result.__dict__.clear() result = pickle.loads(pickle.dumps(result)) return result self._makeOne = makeOne self.test_normalization() class TextLineTests(EqualityTestsMixin, WrongTypeTestsMixin, unittest.TestCase): def _getTargetClass(self): from zope.schema._field import TextLine return TextLine def _getTargetInterface(self): from zope.schema.interfaces import ITextLine return ITextLine def test_validate_wrong_types(self): field = self._makeOne() self.assertAllRaiseWrongType( field, field._type, b'', 1, 1.0, (), [], {}, set(), frozenset(), object()) def test_validate_not_required(self): field = self._makeOne(required=False) field.validate(u'') field.validate(u'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') 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) class PasswordTests(EqualityTestsMixin, WrongTypeTestsMixin, unittest.TestCase): def _getTargetClass(self): from zope.schema._bootstrapfields import Password return Password def _getTargetInterface(self): from zope.schema.interfaces import IPassword return IPassword def test_set_unchanged(self): klass = self._getTargetClass() pw = self._makeOne() inst = DummyInst() before = dict(inst.__dict__) pw.set(inst, klass.UNCHANGED_PASSWORD) # doesn't raise, doesn't write after = dict(inst.__dict__) self.assertEqual(after, before) def test_set_normal(self): pw = self._makeOne(__name__='password') inst = DummyInst() pw.set(inst, 'PASSWORD') self.assertEqual(inst.password, 'PASSWORD') def test_validate_not_required(self): field = self._makeOne(required=False) field.validate(u'') field.validate(u'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') self.assertRaises(RequiredMissing, field.validate, None) def test_validate_unchanged_not_already_set(self): klass = self._getTargetClass() inst = DummyInst() pw = self._makeOne(__name__='password').bind(inst) self.assertRaisesWrongType(pw, pw._type, klass.UNCHANGED_PASSWORD) def test_validate_unchanged_already_set(self): klass = self._getTargetClass() inst = DummyInst() inst.password = 'foobar' pw = self._makeOne(__name__='password').bind(inst) pw.validate(klass.UNCHANGED_PASSWORD) # doesn't raise 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) class BoolTests(EqualityTestsMixin, WrongTypeTestsMixin, unittest.TestCase): def _getTargetClass(self): from zope.schema._bootstrapfields import Bool return Bool def _getTargetInterface(self): from zope.schema.interfaces import IBool return IBool def test_ctor_defaults(self): txt = self._makeOne() self.assertEqual(txt._type, bool) def test_validate_wrong_type(self): boo = self._makeOne() self.assertRaisesWrongType(boo, boo._type, '') def test__validate_w_int(self): boo = self._makeOne() boo._validate(0) # doesn't raise boo._validate(1) # doesn't raise def test__validate_w_bool(self): boo = self._makeOne() boo._validate(False) # doesn't raise boo._validate(True) # doesn't raise def test_set_w_int(self): boo = self._makeOne(__name__='boo') inst = DummyInst() boo.set(inst, 0) self.assertEqual(inst.boo, False) boo.set(inst, 1) self.assertEqual(inst.boo, True) def test_set_w_bool(self): boo = self._makeOne(__name__='boo') inst = DummyInst() boo.set(inst, False) self.assertEqual(inst.boo, False) boo.set(inst, True) self.assertEqual(inst.boo, True) 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) def test_fromUnicode_hit(self): txt = self._makeOne() self.assertEqual(txt.fromUnicode(u'True'), True) self.assertEqual(txt.fromUnicode(u'true'), True) class NumberTests(EqualityTestsMixin, OrderableMissingValueMixin, OrderableTestsMixin, unittest.TestCase): def _getTargetClass(self): from zope.schema._bootstrapfields import Number return Number def _getTargetInterface(self): from zope.schema.interfaces import INumber return INumber def test_class_conforms_to_iface(self): from zope.schema._bootstrapinterfaces import IFromUnicode from zope.schema._bootstrapinterfaces import IFromBytes verifyClass = super(NumberTests, self).test_class_conforms_to_iface() verifyClass(IFromUnicode, self._getTargetClass()) verifyClass(IFromBytes, self._getTargetClass()) def test_instance_conforms_to_iface(self): from zope.schema._bootstrapinterfaces import IFromUnicode from zope.schema._bootstrapinterfaces import IFromBytes verifyObject = ( super(NumberTests, self).test_instance_conforms_to_iface()) verifyObject(IFromUnicode, self._makeOne()) verifyObject(IFromBytes, self._makeOne()) class ComplexTests(NumberTests): def _getTargetClass(self): from zope.schema._bootstrapfields import Complex return Complex def _getTargetInterface(self): from zope.schema.interfaces import IComplex return IComplex class RealTests(WrongTypeTestsMixin, NumberTests): def _getTargetClass(self): from zope.schema._bootstrapfields import Real return Real def _getTargetInterface(self): from zope.schema.interfaces import IReal return IReal def test_ctor_real_min_max(self): from fractions import Fraction self.assertRaisesWrongType( self._makeOne, self._getTargetClass()._type, min='') self.assertRaisesWrongType( self._makeOne, self._getTargetClass()._type, max='') field = self._makeOne(min=Fraction(1, 2), max=2) field.validate(1.0) field.validate(2.0) self.assertRaisesTooSmall(field, 0) self.assertRaisesTooSmall(field, 0.4) self.assertRaisesTooBig(field, 2.1) class RationalTests(NumberTests): def _getTargetClass(self): from zope.schema._bootstrapfields import Rational return Rational def _getTargetInterface(self): from zope.schema.interfaces import IRational return IRational class IntegralTests(RationalTests): def _getTargetClass(self): from zope.schema._bootstrapfields import Integral return Integral def _getTargetInterface(self): from zope.schema.interfaces import IIntegral return IIntegral def test_validate_not_required(self): field = self._makeOne(required=False) field.validate(None) field.validate(10) field.validate(0) field.validate(-1) def test_validate_required(self): from zope.schema.interfaces import RequiredMissing field = self._makeOne() field.validate(10) field.validate(0) field.validate(-1) self.assertRaises(RequiredMissing, field.validate, None) 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') 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) class IntTests(IntegralTests): def _getTargetClass(self): from zope.schema._bootstrapfields import Int return Int def _getTargetInterface(self): from zope.schema.interfaces import IInt return IInt def test_ctor_defaults(self): from zope.schema._compat import integer_types txt = self._makeOne() self.assertEqual(txt._type, integer_types) class DecimalTests(NumberTests): mvm_missing_value = decimal.Decimal("-1") mvm_default = decimal.Decimal("0") MIN = decimal.Decimal(NumberTests.MIN) MAX = decimal.Decimal(NumberTests.MAX) VALID = tuple(decimal.Decimal(x) for x in NumberTests.VALID) TOO_SMALL = tuple(decimal.Decimal(x) for x in NumberTests.TOO_SMALL) TOO_BIG = tuple(decimal.Decimal(x) for x in NumberTests.TOO_BIG) def _getTargetClass(self): from zope.schema._bootstrapfields import Decimal return Decimal def _getTargetInterface(self): from zope.schema.interfaces import IDecimal return IDecimal def test_validate_not_required(self): field = self._makeOne(required=False) field.validate(decimal.Decimal("10.0")) field.validate(decimal.Decimal("0.93")) field.validate(decimal.Decimal("1000.0003")) field.validate(None) def test_validate_required(self): from zope.schema.interfaces import RequiredMissing field = self._makeOne() field.validate(decimal.Decimal("10.0")) field.validate(decimal.Decimal("0.93")) field.validate(decimal.Decimal("1000.0003")) self.assertRaises(RequiredMissing, field.validate, None) 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') with self.assertRaises(ValueError) as exc: flt.fromUnicode(u'1.4G') value_error = exc.exception self.assertIs(value_error.field, flt) self.assertEqual(value_error.value, u'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')) class ObjectTests(EqualityTestsMixin, WrongTypeTestsMixin, unittest.TestCase): def setUp(self): from zope.event import subscribers self._before = subscribers[:] def tearDown(self): from zope.event import subscribers subscribers[:] = self._before def _getTargetClass(self): from zope.schema._field import Object return Object def _getTargetInterface(self): from zope.schema.interfaces import IObject return IObject def _makeOneFromClass(self, cls, schema=None, *args, **kw): if schema is None: schema = self._makeSchema() return super(ObjectTests, self)._makeOneFromClass( cls, schema, *args, **kw) def _makeSchema(self, **kw): from zope.interface import Interface from zope.interface.interface import InterfaceClass return InterfaceClass('ISchema', (Interface,), kw) def _getErrors(self, f, *args, **kw): from zope.schema.interfaces import SchemaNotCorrectlyImplemented with self.assertRaises(SchemaNotCorrectlyImplemented) as e: f(*args, **kw) return e.exception.errors def _makeCycles(self): from zope.interface import Interface from zope.interface import implementer from zope.schema import Object from zope.schema import List from zope.schema._messageid import _ class IUnit(Interface): """A schema that participate to a cycle""" boss = Object( schema=Interface, title=_("Boss"), description=_("Boss description"), required=False, ) members = List( value_type=Object(schema=Interface), title=_("Member List"), description=_("Member list description"), required=False, ) class IPerson(Interface): """A schema that participate to a cycle""" unit = Object( schema=IUnit, title=_("Unit"), description=_("Unit description"), required=False, ) IUnit['boss'].schema = IPerson IUnit['members'].value_type.schema = IPerson @implementer(IUnit) class Unit(object): def __init__(self, person, person_list): self.boss = person self.members = person_list @implementer(IPerson) class Person(object): def __init__(self, unit): self.unit = unit return IUnit, Person, Unit def test_class_conforms_to_IObject(self): from zope.interface.verify import verifyClass from zope.schema.interfaces import IObject verifyClass(IObject, self._getTargetClass()) def test_instance_conforms_to_IObject(self): from zope.interface.verify import verifyObject from zope.schema.interfaces import IObject verifyObject(IObject, self._makeOne()) def test_ctor_w_bad_schema(self): from zope.interface.interfaces import IInterface self.assertRaisesWrongType(self._makeOne, IInterface, object()) def test_validate_not_required(self): schema = self._makeSchema() objf = self._makeOne(schema, required=False) objf.validate(None) # doesn't raise def test_validate_required(self): from zope.schema.interfaces import RequiredMissing field = self._makeOne(required=True) self.assertRaises(RequiredMissing, field.validate, None) def test__validate_w_empty_schema(self): from zope.interface import Interface objf = self._makeOne(Interface) objf.validate(object()) # doesn't raise def test__validate_w_value_not_providing_schema(self): from zope.schema.interfaces import SchemaNotProvided from zope.schema._bootstrapfields import Text schema = self._makeSchema(foo=Text(), bar=Text()) objf = self._makeOne(schema) bad_value = object() with self.assertRaises(SchemaNotProvided) as exc: objf.validate(bad_value) not_provided = exc.exception self.assertIs(not_provided.field, objf) self.assertIs(not_provided.value, bad_value) self.assertEqual(not_provided.args, (schema, bad_value), ) def test__validate_w_value_providing_schema_but_missing_fields(self): from zope.interface import implementer from zope.schema.interfaces import SchemaNotFullyImplemented from zope.schema.interfaces import SchemaNotCorrectlyImplemented from zope.schema._bootstrapfields import Text schema = self._makeSchema(foo=Text(), bar=Text()) @implementer(schema) class Broken(object): pass objf = self._makeOne(schema) broken = Broken() with self.assertRaises(SchemaNotCorrectlyImplemented) as exc: objf.validate(broken) wct = exc.exception self.assertIs(wct.field, objf) self.assertIs(wct.value, broken) self.assertEqual(wct.invariant_errors, []) self.assertEqual( sorted(wct.schema_errors), ['bar', 'foo'] ) for name in ('foo', 'bar'): error = wct.schema_errors[name] self.assertIsInstance(error, SchemaNotFullyImplemented) self.assertEqual(schema[name], error.field) self.assertIsNone(error.value) # The legacy arg[0] errors list errors = self._getErrors(objf.validate, Broken()) self.assertEqual(len(errors), 2) errors = sorted(errors, key=lambda x: (type(x).__name__, str(x.args[0]))) err = errors[0] self.assertIsInstance(err, SchemaNotFullyImplemented) nested = err.args[0] self.assertIsInstance(nested, AttributeError) self.assertIn("'bar'", str(nested)) err = errors[1] self.assertIsInstance(err, SchemaNotFullyImplemented) nested = err.args[0] self.assertIsInstance(nested, AttributeError) self.assertIn("'foo'", str(nested)) def test__validate_w_value_providing_schema_but_invalid_fields(self): from zope.interface import implementer from zope.schema.interfaces import SchemaNotCorrectlyImplemented from zope.schema.interfaces import RequiredMissing from zope.schema.interfaces import WrongType from zope.schema._bootstrapfields import Text from zope.schema._compat import text_type schema = self._makeSchema(foo=Text(), bar=Text()) @implementer(schema) class Broken(object): foo = None bar = 1 objf = self._makeOne(schema) broken = Broken() with self.assertRaises(SchemaNotCorrectlyImplemented) as exc: objf.validate(broken) wct = exc.exception self.assertIs(wct.field, objf) self.assertIs(wct.value, broken) self.assertEqual(wct.invariant_errors, []) self.assertEqual( sorted(wct.schema_errors), ['bar', 'foo'] ) self.assertIsInstance(wct.schema_errors['foo'], RequiredMissing) self.assertIsInstance(wct.schema_errors['bar'], WrongType) # The legacy arg[0] errors list errors = self._getErrors(objf.validate, Broken()) self.assertEqual(len(errors), 2) errors = sorted(errors, key=lambda x: type(x).__name__) err = errors[0] self.assertIsInstance(err, RequiredMissing) self.assertEqual(err.args, ('foo',)) err = errors[1] self.assertIsInstance(err, WrongType) self.assertEqual(err.args, (1, text_type, 'bar')) def test__validate_w_value_providing_schema(self): from zope.interface import implementer from zope.schema._bootstrapfields import Text from zope.schema._field import Choice schema = self._makeSchema( foo=Text(), bar=Text(), baz=Choice(values=[1, 2, 3]), ) @implementer(schema) class OK(object): foo = u'Foo' bar = u'Bar' baz = 2 objf = self._makeOne(schema) objf.validate(OK()) # doesn't raise def test_validate_w_cycles(self): IUnit, Person, Unit = self._makeCycles() field = self._makeOne(schema=IUnit) person1 = Person(None) person2 = Person(None) unit = Unit(person1, [person1, person2]) person1.unit = unit person2.unit = unit field.validate(unit) # doesn't raise def test_validate_w_cycles_object_not_valid(self): from zope.schema.interfaces import SchemaNotCorrectlyImplemented from zope.schema.interfaces import SchemaNotProvided IUnit, Person, Unit = self._makeCycles() field = self._makeOne(schema=IUnit) person1 = Person(None) person2 = Person(None) boss_unit = object() boss = Person(boss_unit) unit = Unit(boss, [person1, person2]) person1.unit = unit person2.unit = unit with self.assertRaises(SchemaNotCorrectlyImplemented) as exc: field.validate(unit) ex = exc.exception self.assertEqual(1, len(ex.schema_errors)) self.assertEqual(1, len(ex.errors)) self.assertEqual(0, len(ex.invariant_errors)) boss_error = ex.schema_errors['boss'] self.assertIsInstance(boss_error, SchemaNotCorrectlyImplemented) self.assertEqual(1, len(boss_error.schema_errors)) self.assertEqual(1, len(boss_error.errors)) self.assertEqual(0, len(boss_error.invariant_errors)) unit_error = boss_error.schema_errors['unit'] self.assertIsInstance(unit_error, SchemaNotProvided) self.assertIs(IUnit, unit_error.schema) self.assertIs(boss_unit, unit_error.value) def test_validate_w_cycles_collection_not_valid(self): from zope.schema.interfaces import SchemaNotCorrectlyImplemented IUnit, Person, Unit = self._makeCycles() field = self._makeOne(schema=IUnit) person1 = Person(None) person2 = Person(None) person3 = Person(object()) unit = Unit(person1, [person2, person3]) person1.unit = unit person2.unit = unit self.assertRaises(SchemaNotCorrectlyImplemented, field.validate, unit) def test_set_emits_IBOAE(self): from zope.event import subscribers from zope.interface import implementer from zope.schema.interfaces import IBeforeObjectAssignedEvent from zope.schema._bootstrapfields import Text from zope.schema._field import Choice schema = self._makeSchema( foo=Text(), bar=Text(), baz=Choice(values=[1, 2, 3]), ) @implementer(schema) class OK(object): foo = u'Foo' bar = u'Bar' baz = 2 log = [] subscribers.append(log.append) objf = self._makeOne(schema, __name__='field') inst = DummyInst() value = OK() objf.set(inst, value) self.assertIs(inst.field, value) self.assertEqual(len(log), 5) self.assertEqual(IBeforeObjectAssignedEvent.providedBy(log[-1]), True) self.assertEqual(log[-1].object, value) self.assertEqual(log[-1].name, 'field') self.assertEqual(log[-1].context, inst) def test_set_allows_IBOAE_subscr_to_replace_value(self): from zope.event import subscribers from zope.interface import implementer from zope.schema._bootstrapfields import Text from zope.schema._field import Choice schema = self._makeSchema( foo=Text(), bar=Text(), baz=Choice(values=[1, 2, 3]), ) @implementer(schema) class OK(object): def __init__(self, foo=u'Foo', bar=u'Bar', baz=2): self.foo = foo self.bar = bar self.baz = baz ok1 = OK() ok2 = OK(u'Foo2', u'Bar2', 3) log = [] subscribers.append(log.append) def _replace(event): event.object = ok2 subscribers.append(_replace) objf = self._makeOne(schema, __name__='field') inst = DummyInst() self.assertEqual(len(log), 4) objf.set(inst, ok1) self.assertIs(inst.field, ok2) self.assertEqual(len(log), 5) self.assertEqual(log[-1].object, ok2) self.assertEqual(log[-1].name, 'field') self.assertEqual(log[-1].context, inst) def test_validates_invariants_by_default(self): from zope.interface import invariant from zope.interface import Interface from zope.interface import implementer from zope.interface import Invalid from zope.schema import Text from zope.schema import Bytes class ISchema(Interface): foo = Text() bar = Bytes() @invariant def check_foo(self): if self.foo == u'bar': raise Invalid("Foo is not valid") @invariant def check_bar(self): if self.bar == b'foo': raise Invalid("Bar is not valid") @implementer(ISchema) class Obj(object): foo = u'' bar = b'' field = self._makeOne(ISchema) inst = Obj() # Fine at first field.validate(inst) inst.foo = u'bar' errors = self._getErrors(field.validate, inst) self.assertEqual(len(errors), 1) self.assertEqual(errors[0].args[0], "Foo is not valid") del inst.foo inst.bar = b'foo' errors = self._getErrors(field.validate, inst) self.assertEqual(len(errors), 1) self.assertEqual(errors[0].args[0], "Bar is not valid") # Both invalid inst.foo = u'bar' errors = self._getErrors(field.validate, inst) self.assertEqual(len(errors), 2) errors.sort(key=lambda i: i.args) self.assertEqual(errors[0].args[0], "Bar is not valid") self.assertEqual(errors[1].args[0], "Foo is not valid") # We can specifically ask for invariants to be turned off. field = self._makeOne(ISchema, validate_invariants=False) field.validate(inst) def test_schema_defined_by_subclass(self): from zope import interface from zope.schema.interfaces import SchemaNotProvided class IValueType(interface.Interface): "The value type schema" class Field(self._getTargetClass()): schema = IValueType field = Field() self.assertIs(field.schema, IValueType) # Non implementation is bad with self.assertRaises(SchemaNotProvided) as exc: field.validate(object()) self.assertIs(IValueType, exc.exception.schema) # Actual implementation works @interface.implementer(IValueType) class ValueType(object): "The value type" field.validate(ValueType()) def test_bound_field_of_collection_with_choice(self): # https://github.com/zopefoundation/zope.schema/issues/17 from zope.interface import Interface, implementer from zope.interface import Attribute from zope.schema import Choice, Object, Set from zope.schema.fieldproperty import FieldProperty from zope.schema.interfaces import IContextSourceBinder from zope.schema.interfaces import WrongContainedType from zope.schema.interfaces import ConstraintNotSatisfied from zope.schema.interfaces import SchemaNotCorrectlyImplemented from zope.schema.vocabulary import SimpleVocabulary @implementer(IContextSourceBinder) class EnumContext(object): def __call__(self, context): return SimpleVocabulary.fromValues(list(context)) class IMultipleChoice(Interface): choices = Set(value_type=Choice(source=EnumContext())) # Provide a regular attribute to prove that binding doesn't # choke. NOTE: We don't actually verify the existence of this # attribute. non_field = Attribute("An attribute") @implementer(IMultipleChoice) class Choices(object): def __init__(self, choices): self.choices = choices def __iter__(self): # EnumContext calls this to make the vocabulary. # Fields of the schema of the IObject are bound to the value # being validated. return iter(range(5)) class IFavorites(Interface): fav = Object(title=u"Favorites number", schema=IMultipleChoice) @implementer(IFavorites) class Favorites(object): fav = FieldProperty(IFavorites['fav']) # must not raise good_choices = Choices({1, 3}) IFavorites['fav'].validate(good_choices) # Ranges outside the context fail bad_choices = Choices({1, 8}) with self.assertRaises(SchemaNotCorrectlyImplemented) as exc: IFavorites['fav'].validate(bad_choices) e = exc.exception self.assertEqual(IFavorites['fav'], e.field) self.assertEqual(bad_choices, e.value) self.assertEqual(1, len(e.schema_errors)) self.assertEqual(0, len(e.invariant_errors)) self.assertEqual(1, len(e.errors)) fav_error = e.schema_errors['choices'] self.assertIs(fav_error, e.errors[0]) self.assertIsInstance(fav_error, WrongContainedType) self.assertNotIsInstance(fav_error, SchemaNotCorrectlyImplemented) # The field is not actually equal to the one in the interface # anymore because its bound. self.assertEqual('choices', fav_error.field.__name__) self.assertEqual(bad_choices, fav_error.field.context) self.assertEqual({1, 8}, fav_error.value) self.assertEqual(1, len(fav_error.errors)) self.assertIsInstance(fav_error.errors[0], ConstraintNotSatisfied) # Validation through field property favorites = Favorites() favorites.fav = good_choices # And validation through a field that wants IFavorites favorites_field = Object(IFavorites) favorites_field.validate(favorites) # Check the field property error with self.assertRaises(SchemaNotCorrectlyImplemented) as exc: favorites.fav = bad_choices e = exc.exception self.assertEqual(IFavorites['fav'], e.field) self.assertEqual(bad_choices, e.value) self.assertEqual(['choices'], list(e.schema_errors)) def test_getDoc(self): field = self._makeOne() doc = field.getDoc() self.assertIn(":Must Provide: :class:", doc) class DummyInst(object): missing_value = object() def __init__(self, exc=None): self._exc = exc def validate(self, value): if self._exc is not None: # pragma: no branch raise self._exc() def test_suite(): import zope.schema._bootstrapfields from zope.testing.renormalizing import IGNORE_EXCEPTION_MODULE_IN_PYTHON2 suite = unittest.defaultTestLoader.loadTestsFromName(__name__) suite.addTests(doctest.DocTestSuite( zope.schema._bootstrapfields, optionflags=doctest.ELLIPSIS | IGNORE_EXCEPTION_MODULE_IN_PYTHON2 )) return suite zope.schema-6.2.0/src/zope/schema/tests/test__bootstrapinterfaces.py0000644000100100000240000000461114133212652025576 0ustar macstaff00000000000000############################################################################## # # Copyright (c) 2012 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## import unittest try: compare = cmp except NameError: def compare(a, b): return -1 if a < b else (0 if a == b else 1) class ValidationErrorTests(unittest.TestCase): def _getTargetClass(self): from zope.schema._bootstrapinterfaces import ValidationError return ValidationError def _makeOne(self, *args, **kw): return self._getTargetClass()(*args, **kw) def test_doc(self): class Derived(self._getTargetClass()): """DERIVED""" inst = Derived() self.assertEqual(inst.doc(), 'DERIVED') def test___cmp___no_args(self): ve = self._makeOne() self.assertEqual(compare(ve, object()), -1) self.assertEqual(compare(object(), ve), 1) def test___cmp___hit(self): left = self._makeOne('abc') right = self._makeOne('def') self.assertEqual(compare(left, right), -1) self.assertEqual(compare(left, left), 0) self.assertEqual(compare(right, left), 1) def test___eq___no_args(self): ve = self._makeOne() self.assertNotEqual(ve, object()) self.assertNotEqual(object(), ve) def test___eq___w_args(self): left = self._makeOne('abc') right = self._makeOne('def') self.assertNotEqual(left, right) self.assertNotEqual(right, left) self.assertEqual(left, left) self.assertEqual(right, right) class TestOutOfBounds(unittest.TestCase): def _getTargetClass(self): from zope.schema._bootstrapinterfaces import OutOfBounds return OutOfBounds def test_TOO_LARGE_repr(self): self.assertIn('TOO_LARGE', repr(self._getTargetClass().TOO_LARGE)) def test_TOO_SMALL_repr(self): self.assertIn('TOO_SMALL', repr(self._getTargetClass().TOO_SMALL)) zope.schema-6.2.0/src/zope/schema/tests/test__field.py0000644000100100000240000016672414133212652022616 0ustar macstaff00000000000000############################################################################## # # Copyright (c) 2012 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## import datetime import doctest import unittest from zope.schema.tests.test__bootstrapfields import EqualityTestsMixin from zope.schema.tests.test__bootstrapfields import LenTestsMixin from zope.schema.tests.test__bootstrapfields import OrderableMissingValueMixin from zope.schema.tests.test__bootstrapfields import OrderableTestsMixin from zope.schema.tests.test__bootstrapfields import WrongTypeTestsMixin from zope.schema.tests.test__bootstrapfields import NumberTests # pylint:disable=protected-access # pylint:disable=too-many-lines # pylint:disable=inherit-non-class # pylint:disable=no-member # pylint:disable=blacklisted-name class BytesTests(EqualityTestsMixin, WrongTypeTestsMixin, unittest.TestCase): def _getTargetClass(self): from zope.schema._field import Bytes return Bytes def _getTargetInterface(self): from zope.schema.interfaces import IBytes return IBytes def _getTargetInterfaces(self): from zope.schema.interfaces import IFromUnicode from zope.schema.interfaces import IFromBytes return [self._getTargetInterface(), IFromUnicode, IFromBytes] def test_validate_wrong_types(self): field = self._makeOne() self.assertAllRaiseWrongType( field, field._type, u'', 1, 1.0, (), [], {}, set(), frozenset(), object()) def test_validate_w_invalid_default(self): from zope.schema.interfaces import ValidationError self.assertRaises(ValidationError, self._makeOne, default=u'') def test_validate_not_required(self): field = self._makeOne(required=False) field.validate(b'') field.validate(b'abc') field.validate(b'abc\ndef') field.validate(None) def test_validate_required(self): from zope.schema.interfaces import RequiredMissing field = self._makeOne() field.validate(b'') field.validate(b'abc') field.validate(b'abc\ndef') self.assertRaises(RequiredMissing, field.validate, None) def test_fromUnicode_miss(self): byt = self._makeOne() self.assertRaises(UnicodeEncodeError, byt.fromUnicode, u'\x81') def test_fromUnicode_hit(self): byt = self._makeOne() self.assertEqual(byt.fromUnicode(u''), b'') self.assertEqual(byt.fromUnicode(u'DEADBEEF'), b'DEADBEEF') def test_fromBytes(self): field = self._makeOne() self.assertEqual(field.fromBytes(b''), b'') self.assertEqual(field.fromBytes(b'DEADBEEF'), b'DEADBEEF') class ASCIITests(EqualityTestsMixin, WrongTypeTestsMixin, unittest.TestCase): def _getTargetClass(self): from zope.schema._field import ASCII return ASCII def _getTargetInterface(self): from zope.schema.interfaces import IASCII return IASCII def test_validate_wrong_types(self): from zope.schema._compat import non_native_string field = self._makeOne() self.assertAllRaiseWrongType( field, field._type, non_native_string(''), 1, 1.0, (), [], {}, set(), frozenset(), object()) def test__validate_empty(self): asc = self._makeOne() asc._validate('') # no error def test__validate_non_empty_miss(self): from zope.schema.interfaces import InvalidValue asc = self._makeOne() with self.assertRaises(InvalidValue) as exc: asc._validate(chr(129)) invalid = exc.exception self.assertIs(invalid.field, asc) self.assertEqual(invalid.value, chr(129)) def test__validate_non_empty_hit(self): asc = self._makeOne() for i in range(128): asc._validate(chr(i)) # doesn't raise class BytesLineTests(EqualityTestsMixin, WrongTypeTestsMixin, unittest.TestCase): def _getTargetClass(self): from zope.schema._field import BytesLine return BytesLine def _getTargetInterface(self): from zope.schema.interfaces import IBytesLine return IBytesLine def _getTargetInterfaces(self): from zope.schema.interfaces import IFromUnicode from zope.schema.interfaces import IFromBytes return [self._getTargetInterface(), IFromUnicode, IFromBytes] def test_validate_wrong_types(self): field = self._makeOne() self.assertAllRaiseWrongType( field, field._type, u'', 1, 1.0, (), [], {}, set(), frozenset(), object()) def test_validate_not_required(self): field = self._makeOne(required=False) field.validate(None) field.validate(b'') field.validate(b'abc') field.validate(b'\xab\xde') def test_validate_required(self): from zope.schema.interfaces import RequiredMissing field = self._makeOne() field.validate(b'') field.validate(b'abc') field.validate(b'\xab\xde') self.assertRaises(RequiredMissing, field.validate, None) def test_constraint(self): field = self._makeOne() self.assertEqual(field.constraint(b''), True) self.assertEqual(field.constraint(b'abc'), True) self.assertEqual(field.constraint(b'abc'), True) self.assertEqual(field.constraint(b'\xab\xde'), True) self.assertEqual(field.constraint(b'abc\ndef'), False) def test_fromBytes(self): field = self._makeOne() self.assertEqual(field.fromBytes(b''), b'') self.assertEqual(field.fromBytes(b'DEADBEEF'), b'DEADBEEF') class ASCIILineTests(EqualityTestsMixin, WrongTypeTestsMixin, unittest.TestCase): def _getTargetClass(self): from zope.schema._field import ASCIILine return ASCIILine def _getTargetInterface(self): from zope.schema.interfaces import IASCIILine return IASCIILine def test_validate_wrong_types(self): from zope.schema._compat import non_native_string field = self._makeOne() self.assertAllRaiseWrongType( field, field._type, non_native_string(''), 1, 1.0, (), [], {}, set(), frozenset(), object()) def test_validate_not_required(self): from zope.schema.interfaces import InvalidValue field = self._makeOne(required=False) field.validate(None) field.validate('') field.validate('abc') self.assertRaises(InvalidValue, field.validate, '\xab\xde') def test_validate_required(self): from zope.schema.interfaces import InvalidValue from zope.schema.interfaces import RequiredMissing field = self._makeOne() field.validate('') field.validate('abc') self.assertRaises(InvalidValue, field.validate, '\xab\xde') self.assertRaises(RequiredMissing, field.validate, None) def test_constraint(self): field = self._makeOne() self.assertEqual(field.constraint(''), True) self.assertEqual(field.constraint('abc'), True) self.assertEqual(field.constraint('abc'), True) # Non-ASCII byltes get checked in '_validate'. self.assertEqual(field.constraint('\xab\xde'), True) self.assertEqual(field.constraint('abc\ndef'), False) class FloatTests(NumberTests): mvm_missing_value = -1.0 mvm_default = 0.0 MIN = float(NumberTests.MIN) MAX = float(NumberTests.MAX) VALID = tuple(float(x) for x in NumberTests.VALID) TOO_SMALL = tuple(float(x) for x in NumberTests.TOO_SMALL) TOO_BIG = tuple(float(x) for x in NumberTests.TOO_BIG) def _getTargetClass(self): from zope.schema._field import Float return Float def _getTargetInterface(self): from zope.schema.interfaces import IFloat return IFloat def test_validate_not_required(self): field = self._makeOne(required=False) field.validate(None) field.validate(10.0) field.validate(0.93) field.validate(1000.0003) def test_validate_required(self): from zope.schema.interfaces import RequiredMissing field = self._makeOne() field.validate(10.0) field.validate(0.93) field.validate(1000.0003) self.assertRaises(RequiredMissing, field.validate, None) 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') 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) class DatetimeTests(OrderableMissingValueMixin, OrderableTestsMixin, EqualityTestsMixin, WrongTypeTestsMixin, unittest.TestCase): mvm_missing_value = datetime.datetime.now() mvm_default = datetime.datetime.now() def _getTargetClass(self): from zope.schema._field import Datetime return Datetime def _getTargetInterface(self): from zope.schema.interfaces import IDatetime return IDatetime def test_validate_wrong_types(self): from datetime import date field = self._makeOne() self.assertAllRaiseWrongType( field, field._type, u'', 1, 1.0, (), [], {}, set(), frozenset(), object(), date.today()) def test_validate_not_required(self): field = self._makeOne(required=False) field.validate(None) # doesn't raise field.validate(datetime.datetime.now()) # doesn't raise def test_validate_required(self): from zope.schema.interfaces import RequiredMissing field = self._makeOne(required=True) self.assertRaises(RequiredMissing, field.validate, None) 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))) class DateTests(OrderableMissingValueMixin, OrderableTestsMixin, EqualityTestsMixin, WrongTypeTestsMixin, unittest.TestCase): mvm_missing_value = datetime.date.today() mvm_default = datetime.date.today() def _getTargetClass(self): from zope.schema._field import Date return Date def _getTargetInterface(self): from zope.schema.interfaces import IDate return IDate def test_validate_wrong_types(self): field = self._makeOne() self.assertAllRaiseWrongType( field, field._type, u'', 1, 1.0, (), [], {}, set(), frozenset(), object(), datetime.datetime.now()) def test_validate_not_required(self): from datetime import date field = self._makeOne(required=False) field.validate(None) field.validate(date.today()) def test_validate_required(self): from zope.schema.interfaces import RequiredMissing field = self._makeOne() field.validate(datetime.datetime.now().date()) self.assertRaises(RequiredMissing, field.validate, None) 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))) class TimedeltaTests(OrderableMissingValueMixin, OrderableTestsMixin, EqualityTestsMixin, unittest.TestCase): mvm_missing_value = datetime.timedelta(minutes=15) mvm_default = datetime.timedelta(minutes=12) def _getTargetClass(self): from zope.schema._field import Timedelta return Timedelta def _getTargetInterface(self): from zope.schema.interfaces import ITimedelta return ITimedelta def test_validate_not_required(self): from datetime import timedelta field = self._makeOne(required=False) field.validate(None) field.validate(timedelta(minutes=15)) def test_validate_required(self): from datetime import timedelta from zope.schema.interfaces import RequiredMissing field = self._makeOne() field.validate(timedelta(minutes=15)) self.assertRaises(RequiredMissing, field.validate, None) MIN = datetime.timedelta(minutes=NumberTests.MIN) MAX = datetime.timedelta(minutes=NumberTests.MAX) VALID = tuple(datetime.timedelta(minutes=x) for x in NumberTests.VALID) TOO_SMALL = tuple( datetime.timedelta(minutes=x) for x in NumberTests.TOO_SMALL) TOO_BIG = tuple(datetime.timedelta(x) for x in NumberTests.TOO_BIG) class TimeTests(OrderableMissingValueMixin, OrderableTestsMixin, EqualityTestsMixin, unittest.TestCase): mvm_missing_value = datetime.time(12, 15, 37) mvm_default = datetime.time(12, 25, 42) def _getTargetClass(self): from zope.schema._field import Time return Time def _getTargetInterface(self): from zope.schema.interfaces import ITime return ITime def test_validate_not_required(self): from datetime import time field = self._makeOne(required=False) field.validate(None) field.validate(time(12, 15, 37)) def test_validate_required(self): from datetime import time from zope.schema.interfaces import RequiredMissing field = self._makeOne() field.validate(time(12, 15, 37)) self.assertRaises(RequiredMissing, field.validate, None) 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))) class ChoiceTests(EqualityTestsMixin, unittest.TestCase): def setUp(self): from zope.schema.vocabulary import _clear _clear() def tearDown(self): from zope.schema.vocabulary import _clear _clear() def _getTargetClass(self): from zope.schema._field import Choice return Choice def _makeOneFromClass(self, cls, *args, **kwargs): if (not args and 'vocabulary' not in kwargs and 'values' not in 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) def _getTargetInterface(self): from zope.schema.interfaces import IChoice return IChoice def test_ctor_wo_values_vocabulary_or_source(self): self.assertRaises(ValueError, self._getTargetClass()) def test_ctor_invalid_vocabulary(self): self.assertRaises(ValueError, self._getTargetClass(), vocabulary=object()) def test_ctor_invalid_source(self): self.assertRaises(ValueError, self._getTargetClass(), source=object()) def test_ctor_both_vocabulary_and_source(self): self.assertRaises( ValueError, self._makeOne, vocabulary='voc.name', source=object() ) def test_ctor_both_vocabulary_and_values(self): self.assertRaises(ValueError, self._makeOne, vocabulary='voc.name', values=[1, 2]) def test_ctor_w_values(self): from zope.schema.vocabulary import SimpleVocabulary choose = self._makeOne(values=[1, 2]) self.assertTrue(isinstance(choose.vocabulary, SimpleVocabulary)) self.assertEqual(sorted(choose.vocabulary.by_value.keys()), [1, 2]) 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'] choose = self._makeOne(values=values) self.assertEqual(sorted(choose.vocabulary.by_value.keys()), sorted(values)) self.assertEqual(sorted(choose.source.by_value.keys()), sorted(values)) self.assertEqual( sorted(choose.vocabulary.by_token.keys()), sorted([x.encode('ascii', 'backslashreplace').decode('ascii') for x in values])) def test_ctor_w_named_vocabulary(self): choose = self._makeOne(vocabulary="vocab") self.assertEqual(choose.vocabularyName, 'vocab') def test_ctor_w_preconstructed_vocabulary(self): v = _makeSampleVocabulary() choose = self._makeOne(vocabulary=v) self.assertTrue(choose.vocabulary is v) self.assertTrue(choose.vocabularyName is None) def test_bind_w_preconstructed_vocabulary(self): from zope.schema.interfaces import ValidationError from zope.schema.vocabulary import setVocabularyRegistry v = _makeSampleVocabulary() setVocabularyRegistry(_makeDummyRegistry(v)) choose = self._makeOne(vocabulary='vocab') bound = choose.bind(None) self.assertEqual(bound.vocabulary, v) self.assertEqual(bound.vocabularyName, 'vocab') bound.default = 1 self.assertEqual(bound.default, 1) def _provoke(bound): bound.default = 42 self.assertRaises(ValidationError, _provoke, bound) def test_bind_w_voc_not_ICSB(self): from zope.interface import implementer from zope.schema.interfaces import ISource from zope.schema.interfaces import IBaseVocabulary @implementer(IBaseVocabulary) @implementer(ISource) class Vocab(object): def __init__(self): pass source = self._makeOne(vocabulary=Vocab()) instance = object() target = source.bind(instance) self.assertIs(target.vocabulary, source.vocabulary) def test_bind_w_voc_is_ICSB(self): from zope.interface import implementer from zope.schema.interfaces import IContextSourceBinder from zope.schema.interfaces import ISource @implementer(IContextSourceBinder) @implementer(ISource) class Vocab(object): def __init__(self, context): self.context = context def __call__(self, context): return self.__class__(context) # Chicken-egg source = self._makeOne(vocabulary='temp') source.vocabulary = Vocab(source) source.vocabularyName = None instance = object() target = source.bind(instance) self.assertIs(target.vocabulary.context, instance) def test_bind_w_voc_is_ICSB_but_not_ISource(self): from zope.interface import implementer from zope.schema.interfaces import IContextSourceBinder @implementer(IContextSourceBinder) class Vocab(object): def __init__(self, context): self.context = context def __call__(self, context): return self.__class__(context) # Chicken-egg source = self._makeOne(vocabulary='temp') source.vocabulary = Vocab(source) source.vocabularyName = None instance = object() self.assertRaises(ValueError, source.bind, instance) 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') with self.assertRaises(ConstraintNotSatisfied) as exc: flt.fromUnicode(u'1.4G') cns = exc.exception self.assertIs(cns.field, flt) self.assertEqual(cns.value, u'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') def test__validate_int(self): from zope.schema.interfaces import ConstraintNotSatisfied choice = self._makeOne(values=[1, 3]) choice._validate(1) # doesn't raise choice._validate(3) # doesn't raise self.assertRaises(ConstraintNotSatisfied, choice._validate, 4) def test__validate_string(self): from zope.schema.interfaces import ConstraintNotSatisfied 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 self.assertRaises(ConstraintNotSatisfied, choice._validate, 'd') def test__validate_tuple(self): from zope.schema.interfaces import ConstraintNotSatisfied choice = self._makeOne(values=[(1, 2), (5, 6)]) choice._validate((1, 2)) # doesn't raise choice._validate((5, 6)) # doesn't raise self.assertRaises(ConstraintNotSatisfied, choice._validate, [5, 6]) self.assertRaises(ConstraintNotSatisfied, choice._validate, ()) def test__validate_mixed(self): from zope.schema.interfaces import ConstraintNotSatisfied choice = self._makeOne(values=[1, 'b', (0.2,)]) choice._validate(1) # doesn't raise choice._validate('b') # doesn't raise choice._validate((0.2,)) # doesn't raise self.assertRaises(ConstraintNotSatisfied, choice._validate, '1') self.assertRaises(ConstraintNotSatisfied, choice._validate, 0.2) def test__validate_w_named_vocabulary_invalid(self): from zope.schema._field import MissingVocabularyError choose = self._makeOne(vocabulary='vocab') with self.assertRaises(MissingVocabularyError) as exc: choose._validate(42) ex = exc.exception self.assertIsInstance(ex, ValueError) self.assertIsInstance(ex, LookupError) self.assertIs(ex.field, choose) self.assertEqual(ex.value, 42) def test__validate_w_named_vocabulary_raises_LookupError(self): # Whether the vocab registry raises VocabularyRegistryError # or the generic LookupError documented by IVocabularyLookup, # we do the same thing from zope.schema.vocabulary import setVocabularyRegistry class Reg(object): def get(self, *args): raise LookupError setVocabularyRegistry(Reg()) self.test__validate_w_named_vocabulary_invalid() def test__validate_w_named_vocabulary_passes_context(self): from zope.schema.vocabulary import setVocabularyRegistry context = object() choice = self._makeOne(vocabulary='vocab') class Reg(object): called_with = () def get(self, *args): self.called_with += args return _makeSampleVocabulary() reg = Reg() setVocabularyRegistry(reg) choice = choice.bind(context) choice._validate(1) self.assertEqual(reg.called_with, (context, 'vocab')) def test__validate_w_named_vocabulary(self): from zope.schema.interfaces import ConstraintNotSatisfied from zope.schema.vocabulary import setVocabularyRegistry v = _makeSampleVocabulary() setVocabularyRegistry(_makeDummyRegistry(v)) choose = self._makeOne(vocabulary='vocab') choose._validate(1) choose._validate(3) self.assertRaises(ConstraintNotSatisfied, choose._validate, 42) def test__validate_source_is_ICSB_unbound(self): from zope.interface import implementer from zope.schema.interfaces import IContextSourceBinder @implementer(IContextSourceBinder) class SampleContextSourceBinder(object): def __call__(self, context): raise AssertionError("This is not called") choice = self._makeOne(source=SampleContextSourceBinder()) self.assertRaises(TypeError, choice.validate, 1) def test__validate_source_is_ICSB_bound(self): from zope.interface import implementer from zope.schema.interfaces import IContextSourceBinder from zope.schema.interfaces import ConstraintNotSatisfied from zope.schema.tests.test_vocabulary import _makeSampleVocabulary @implementer(IContextSourceBinder) class SampleContextSourceBinder(object): def __call__(self, context): return _makeSampleVocabulary() s = SampleContextSourceBinder() choice = self._makeOne(source=s) # raises not iterable with unbound field self.assertRaises(TypeError, choice.validate, 1) o = object() clone = choice.bind(o) clone._validate(1) clone._validate(3) self.assertRaises(ConstraintNotSatisfied, clone._validate, 42) class URITests(EqualityTestsMixin, WrongTypeTestsMixin, unittest.TestCase): def _getTargetClass(self): from zope.schema._field import URI return URI def _getTargetInterface(self): from zope.schema.interfaces import IURI return IURI def _getTargetInterfaces(self): from zope.schema.interfaces import IFromUnicode from zope.schema.interfaces import IFromBytes return [self._getTargetInterface(), IFromUnicode, IFromBytes] def test_validate_wrong_types(self): from zope.schema._compat import non_native_string field = self._makeOne() self.assertAllRaiseWrongType( field, field._type, non_native_string(''), 1, 1.0, (), [], {}, set(), frozenset(), object()) def test_validate_not_required(self): field = self._makeOne(required=False) field.validate('http://example.com/') field.validate(None) def test_validate_required(self): from zope.schema.interfaces import RequiredMissing field = self._makeOne() field.validate('http://example.com/') self.assertRaises(RequiredMissing, field.validate, None) def test_validate_not_a_uri(self): from zope.schema.interfaces import ConstraintNotSatisfied from zope.schema.interfaces import InvalidURI field = self._makeOne() with self.assertRaises(InvalidURI) as exc: field.validate('') invalid = exc.exception self.assertIs(invalid.field, field) self.assertEqual(invalid.value, '') self.assertRaises(InvalidURI, field.validate, 'abc') self.assertRaises(InvalidURI, field.validate, '\xab\xde') self.assertRaises(ConstraintNotSatisfied, field.validate, 'http://example.com/\nDAV:') def test_fromUnicode_ok(self): field = self._makeOne() self.assertEqual(field.fromUnicode(u'http://example.com/'), 'http://example.com/') def test_fromUnicode_invalid(self): from zope.schema.interfaces import ConstraintNotSatisfied from zope.schema.interfaces import InvalidURI field = self._makeOne() self.assertRaises(InvalidURI, field.fromUnicode, u'') self.assertRaises(InvalidURI, field.fromUnicode, u'abc') self.assertRaises(ConstraintNotSatisfied, field.fromUnicode, u'http://example.com/\nDAV:') class PythonIdentifierTests(EqualityTestsMixin, WrongTypeTestsMixin, unittest.TestCase): def _getTargetClass(self): from zope.schema._field import PythonIdentifier return PythonIdentifier def _getTargetInterfaces(self): from zope.schema.interfaces import IFromUnicode from zope.schema.interfaces import IFromBytes return [self._getTargetInterface(), IFromUnicode, IFromBytes] def _getTargetInterface(self): from zope.schema.interfaces import IPythonIdentifier return IPythonIdentifier def test_fromUnicode_empty(self): pi = self._makeOne() self.assertEqual(pi.fromUnicode(u''), '') def test_fromUnicode_normal(self): pi = self._makeOne() self.assertEqual(pi.fromUnicode(u'normal'), 'normal') def test_fromUnicode_strips_ws(self): pi = self._makeOne() self.assertEqual(pi.fromUnicode(u' '), '') self.assertEqual(pi.fromUnicode(u' normal '), 'normal') def test__validate_miss(self): from zope.schema.interfaces import InvalidValue pi = self._makeOne() with self.assertRaises(InvalidValue) as exc: pi._validate('not-an-identifier') ex = exc.exception self.assertIs(ex.field, pi) self.assertEqual(ex.value, 'not-an-identifier') def test__validate_hit(self): pi = self._makeOne() pi._validate('is_an_identifier') class DottedNameTests(EqualityTestsMixin, WrongTypeTestsMixin, unittest.TestCase): def _getTargetClass(self): from zope.schema._field import DottedName return DottedName def _getTargetInterface(self): from zope.schema.interfaces import IDottedName return IDottedName def _getTargetInterfaces(self): from zope.schema.interfaces import IFromUnicode from zope.schema.interfaces import IFromBytes return [self._getTargetInterface(), IFromUnicode, IFromBytes] def test_ctor_defaults(self): dotted = self._makeOne() self.assertEqual(dotted.min_dots, 0) self.assertEqual(dotted.max_dots, None) def test_ctor_min_dots_invalid(self): self.assertRaises(ValueError, self._makeOne, min_dots=-1) def test_ctor_min_dots_valid(self): dotted = self._makeOne(min_dots=1) self.assertEqual(dotted.min_dots, 1) def test_ctor_max_dots_invalid(self): self.assertRaises(ValueError, self._makeOne, min_dots=2, max_dots=1) def test_ctor_max_dots_valid(self): dotted = self._makeOne(max_dots=2) self.assertEqual(dotted.max_dots, 2) def test_validate_wrong_types(self): from zope.schema._compat import non_native_string field = self._makeOne() self.assertAllRaiseWrongType( field, field._type, non_native_string(''), 1, 1.0, (), [], {}, set(), frozenset(), object()) def test_validate_not_required(self): field = self._makeOne(required=False) field.validate('name') field.validate('dotted.name') field.validate(None) def test_validate_required(self): from zope.schema.interfaces import RequiredMissing field = self._makeOne() field.validate('name') field.validate('dotted.name') self.assertRaises(RequiredMissing, field.validate, None) def test_validate_w_min_dots(self): from zope.schema.interfaces import InvalidDottedName field = self._makeOne(min_dots=1) with self.assertRaises(InvalidDottedName) as exc: field.validate('name') invalid = exc.exception self.assertIs(invalid.field, field) self.assertEqual(invalid.value, 'name') field.validate('dotted.name') field.validate('moar.dotted.name') def test_validate_w_max_dots(self): from zope.schema.interfaces import InvalidDottedName field = self._makeOne(max_dots=1) field.validate('name') field.validate('dotted.name') with self.assertRaises(InvalidDottedName) as exc: field.validate('moar.dotted.name') invalid = exc.exception self.assertIs(invalid.field, field) self.assertEqual(invalid.value, 'moar.dotted.name') def test_validate_not_a_dotted_name(self): from zope.schema.interfaces import ConstraintNotSatisfied from zope.schema.interfaces import InvalidDottedName field = self._makeOne() self.assertRaises(InvalidDottedName, field.validate, '') self.assertRaises(InvalidDottedName, field.validate, '\xab\xde') self.assertRaises(ConstraintNotSatisfied, field.validate, 'http://example.com/\nDAV:') def test_fromUnicode_dotted_name_ok(self): field = self._makeOne() self.assertEqual(field.fromUnicode(u'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'), '_leading_underscore') self.assertEqual(field.fromUnicode(u'_dotted.name'), '_dotted.name') self.assertEqual(field.fromUnicode(u'_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'') with self.assertRaises(InvalidDottedName) as exc: field.fromUnicode(u'\u2603') invalid = exc.exception self.assertIs(invalid.field, field) self.assertEqual(invalid.value, u'\u2603') self.assertRaises(ConstraintNotSatisfied, field.fromUnicode, u'http://example.com/\nDAV:') class IdTests(EqualityTestsMixin, WrongTypeTestsMixin, unittest.TestCase): def _getTargetClass(self): from zope.schema._field import Id return Id def _getTargetInterface(self): from zope.schema.interfaces import IId return IId def _getTargetInterfaces(self): from zope.schema.interfaces import IFromUnicode from zope.schema.interfaces import IFromBytes return [self._getTargetInterface(), IFromUnicode, IFromBytes] def test_validate_wrong_types(self): from zope.schema._compat import non_native_string field = self._makeOne() self.assertAllRaiseWrongType( field, field._type, non_native_string(''), 1, 1.0, (), [], {}, set(), frozenset(), object()) def test_validate_not_required(self): field = self._makeOne(required=False) field.validate('http://example.com/') field.validate('dotted.name') field.validate(None) def test_validate_required(self): from zope.schema.interfaces import RequiredMissing field = self._makeOne() field.validate('http://example.com/') field.validate('dotted.name') self.assertRaises(RequiredMissing, field.validate, None) def test_validate_not_a_uri(self): from zope.schema.interfaces import ConstraintNotSatisfied from zope.schema.interfaces import InvalidId field = self._makeOne() with self.assertRaises(InvalidId) as exc: field.validate('') invalid = exc.exception self.assertIs(invalid.field, field) self.assertEqual(invalid.value, '') self.assertRaises(InvalidId, field.validate, 'abc') self.assertRaises(InvalidId, field.validate, '\xab\xde') self.assertRaises(ConstraintNotSatisfied, field.validate, 'http://example.com/\nDAV:') def test_fromUnicode_url_ok(self): field = self._makeOne() self.assertEqual(field.fromUnicode(u'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') 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(ConstraintNotSatisfied, field.fromUnicode, u'http://example.com/\nDAV:') class InterfaceFieldTests(EqualityTestsMixin, WrongTypeTestsMixin, unittest.TestCase): def _getTargetClass(self): from zope.schema._field import InterfaceField return InterfaceField def _getTargetInterface(self): from zope.schema.interfaces import IInterfaceField return IInterfaceField def test_validate_wrong_types(self): from zope.interface.interfaces import IInterface from datetime import date field = self._makeOne() self.assertAllRaiseWrongType( field, IInterface, u'', b'', 1, 1.0, (), [], {}, set(), frozenset(), object(), date.today()) def test_validate_not_required(self): from zope.interface import Interface class DummyInterface(Interface): pass field = self._makeOne(required=False) field.validate(DummyInterface) field.validate(None) def test_validate_required(self): from zope.interface import Interface from zope.schema.interfaces import RequiredMissing class DummyInterface(Interface): pass field = self._makeOne(required=True) field.validate(DummyInterface) self.assertRaises(RequiredMissing, field.validate, None) class CollectionTests(EqualityTestsMixin, LenTestsMixin, unittest.TestCase): _DEFAULT_UNIQUE = False def _getTargetClass(self): from zope.schema._field import Collection return Collection def _getTargetInterface(self): from zope.schema.interfaces import ICollection return ICollection _makeCollection = list def test_schema_defined_by_subclass(self): from zope import interface from zope.schema import Object from zope.schema.interfaces import SchemaNotProvided from zope.schema.interfaces import WrongContainedType class IValueType(interface.Interface): "The value type schema" the_value_type = Object(IValueType) class Field(self._getTargetClass()): value_type = the_value_type field = Field() self.assertIs(field.value_type, the_value_type) # Empty collection is fine field.validate(self._makeCollection([])) # Collection with a non-implemented object is bad with self.assertRaises(WrongContainedType) as exc: field.validate(self._makeCollection([object()])) ex = exc.exception self.assertIs(ex.__class__, WrongContainedType) self.assertEqual(1, len(ex.errors)) self.assertIsInstance(ex.errors[0], SchemaNotProvided) self.assertIs(ex.errors[0].schema, IValueType) # Actual implementation works @interface.implementer(IValueType) class ValueType(object): "The value type" field.validate(self._makeCollection([ValueType()])) def test_ctor_defaults(self): absc = self._makeOne() self.assertEqual(absc.value_type, None) self.assertEqual(absc.unique, self._DEFAULT_UNIQUE) def test_ctor_explicit(self): from zope.schema._bootstrapfields import Text text = Text() absc = self._makeOne(text, True) self.assertEqual(absc.value_type, text) self.assertEqual(absc.unique, True) def test_ctor_w_non_field_value_type(self): class NotAField(object): pass self.assertRaises(ValueError, self._makeOne, NotAField) def test_bind_wo_value_Type(self): absc = self._makeOne() context = object() bound = absc.bind(context) self.assertEqual(bound.context, context) self.assertEqual(bound.value_type, None) self.assertEqual(bound.unique, self._DEFAULT_UNIQUE) def test_bind_w_value_Type(self): from zope.schema._bootstrapfields import Text text = Text() absc = self._makeOne(text, True) context = object() bound = absc.bind(context) self.assertEqual(bound.context, context) self.assertEqual(isinstance(bound.value_type, Text), True) self.assertEqual(bound.value_type.context, context) self.assertEqual(bound.unique, True) def test__validate_wrong_contained_type(self): from zope.schema.interfaces import WrongContainedType from zope.schema.interfaces import WrongType from zope.schema._bootstrapfields import Text text = Text() absc = self._makeOne(text) with self.assertRaises(WrongContainedType) as exc: absc.validate(self._makeCollection([1])) wct = exc.exception self.assertIs(wct.field, absc) self.assertEqual(wct.value, self._makeCollection([1])) self.assertIs(wct.__class__, WrongContainedType) self.assertEqual(1, len(wct.errors)) self.assertIsInstance(wct.errors[0], WrongType) self.assertIs(wct.errors[0].expected_type, text._type) def test__validate_miss_uniqueness(self): from zope.schema.interfaces import NotUnique from zope.schema.interfaces import WrongType from zope.schema._bootstrapfields import Text text = Text() absc = self._makeOne(text, True) with self.assertRaises((NotUnique, WrongType)) as exc: absc.validate([u'a', u'a']) not_uniq = exc.exception self.assertIs(not_uniq.field, absc) self.assertEqual(not_uniq.value, [u'a', u'a']) def test_validate_min_length(self): field = self._makeOne(min_length=2) field.validate(self._makeCollection((1, 2))) field.validate(self._makeCollection((1, 2, 3))) self.assertRaisesTooShort(field, self._makeCollection()) self.assertRaisesTooShort(field, self._makeCollection((1,))) def test_validate_max_length(self): field = self._makeOne(max_length=2) field.validate(self._makeCollection()) field.validate(self._makeCollection((1,))) field.validate(self._makeCollection((1, 2))) self.assertRaisesTooLong(field, self._makeCollection((1, 2, 3, 4))) self.assertRaisesTooLong(field, self._makeCollection((1, 2, 3))) def test_validate_min_length_and_max_length(self): field = self._makeOne(min_length=1, max_length=2) field.validate(self._makeCollection((1,))) field.validate(self._makeCollection((1, 2))) self.assertRaisesTooShort(field, self._makeCollection()) self.assertRaisesTooLong(field, self._makeCollection((1, 2, 3))) def test_validate_not_required(self): field = self._makeOne(required=False) field.validate(self._makeCollection()) field.validate(self._makeCollection((1, 2))) field.validate(self._makeCollection((3,))) field.validate(None) def test_validate_required(self): from zope.schema.interfaces import RequiredMissing field = self._makeOne() field.validate(self._makeCollection()) field.validate(self._makeCollection((1, 2))) field.validate(self._makeCollection((3,))) field.validate(self._makeCollection()) field.validate(self._makeCollection((1, 2))) field.validate(self._makeCollection((3,))) self.assertRaises(RequiredMissing, field.validate, None) class SequenceTests(WrongTypeTestsMixin, CollectionTests): def _getTargetClass(self): from zope.schema._field import Sequence return Sequence def _getTargetInterface(self): from zope.schema.interfaces import ISequence return ISequence def test_validate_wrong_types(self): field = self._makeOne() self.assertAllRaiseWrongType( field, field._type, 1, 1.0, {}, set(), frozenset(), object()) def test_sequence(self): from zope.schema._field import abc class Sequence(abc.Sequence): def __getitem__(self, i): raise AssertionError("Not implemented") def __len__(self): return 0 sequence = Sequence() field = self._makeOne() field.validate(sequence) def test_mutable_sequence(self): from zope.schema._field import abc class MutableSequence(abc.MutableSequence): def insert(self, index, value): raise AssertionError("not implemented") def __getitem__(self, name): raise AssertionError("not implemented") def __iter__(self): return iter(()) def __setitem__(self, name, value): raise AssertionError("Not implemented") def __len__(self): return 0 __delitem__ = __getitem__ sequence = MutableSequence() field = self._makeOne() field.validate(sequence) class TupleTests(SequenceTests): _makeCollection = tuple def _getTargetClass(self): from zope.schema._field import Tuple return Tuple def _getTargetInterface(self): from zope.schema.interfaces import ITuple return ITuple def test_mutable_sequence(self): from zope.schema.interfaces import WrongType with self.assertRaises(WrongType): super(TupleTests, self).test_mutable_sequence() def test_sequence(self): from zope.schema.interfaces import WrongType with self.assertRaises(WrongType): super(TupleTests, self).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() class MutableSequenceTests(SequenceTests): def _getTargetClass(self): from zope.schema._field import MutableSequence return MutableSequence def _getTargetInterface(self): from zope.schema.interfaces import IMutableSequence return IMutableSequence def test_validate_wrong_types(self): field = self._makeOne() self.assertAllRaiseWrongType( field, field._type, u'', b'', ()) super(MutableSequenceTests, self).test_validate_wrong_types() def test_sequence(self): from zope.schema.interfaces import WrongType with self.assertRaises(WrongType): super(MutableSequenceTests, self).test_sequence() class ListTests(MutableSequenceTests): def _getTargetClass(self): from zope.schema._field import List return List def _getTargetInterface(self): from zope.schema.interfaces import IList return IList def test_mutable_sequence(self): from zope.schema.interfaces import WrongType with self.assertRaises(WrongType): super(ListTests, self).test_mutable_sequence() class SetTests(WrongTypeTestsMixin, CollectionTests): _DEFAULT_UNIQUE = True _makeCollection = set _makeWrongSet = frozenset def _getTargetClass(self): from zope.schema._field import Set return Set def _getTargetInterface(self): from zope.schema.interfaces import ISet return ISet def test_ctor_disallows_unique(self): self.assertRaises(TypeError, self._makeOne, unique=False) self._makeOne(unique=True) # restating the obvious is allowed self.assertTrue(self._makeOne().unique) def test_validate_wrong_types(self): field = self._makeOne() self.assertAllRaiseWrongType( field, field._type, u'', b'', 1, 1.0, (), [], {}, self._makeWrongSet(), object()) class FrozenSetTests(SetTests): _makeCollection = frozenset _makeWrongSet = set def _getTargetClass(self): from zope.schema._field import FrozenSet return FrozenSet def _getTargetInterface(self): from zope.schema.interfaces import IFrozenSet return IFrozenSet class MappingTests(EqualityTestsMixin, WrongTypeTestsMixin, LenTestsMixin, unittest.TestCase): def _getTargetClass(self): from zope.schema._field import Mapping return Mapping def _getTargetInterface(self): from zope.schema.interfaces import IMapping return IMapping def test_ctor_key_type_not_IField(self): self.assertRaises(ValueError, self._makeOne, key_type=object()) def test_ctor_value_type_not_IField(self): self.assertRaises(ValueError, self._makeOne, value_type=object()) def test_validate_wrong_types(self): field = self._makeOne() self.assertAllRaiseWrongType( field, field._type, u'', b'', 1, 1.0, (), [], set(), frozenset(), object()) def test_validate_not_required(self): field = self._makeOne(required=False) field.validate({}) field.validate({1: 'b', 2: 'd'}) field.validate({3: 'a'}) field.validate(None) def test_validate_required(self): from zope.schema.interfaces import RequiredMissing field = self._makeOne() field.validate({}) field.validate({1: 'b', 2: 'd'}) field.validate({3: 'a'}) self.assertRaises(RequiredMissing, field.validate, None) def test_validate_invalid_key_type(self): from zope.schema.interfaces import WrongContainedType from zope.schema.interfaces import WrongType from zope.schema._bootstrapfields import Int field = self._makeOne(key_type=Int()) field.validate({}) field.validate({1: 'b', 2: 'd'}) field.validate({3: 'a'}) with self.assertRaises(WrongContainedType) as exc: field.validate({'a': 1}) wct = exc.exception self.assertIs(wct.field, field) self.assertEqual(wct.value, {'a': 1}) self.assertIs(wct.__class__, WrongContainedType) self.assertEqual(1, len(wct.errors)) self.assertIsInstance(wct.errors[0], WrongType) self.assertIs(field.key_type._type, wct.errors[0].expected_type) def test_validate_invalid_value_type(self): from zope.schema.interfaces import WrongContainedType from zope.schema.interfaces import WrongType from zope.schema._bootstrapfields import Int field = self._makeOne(value_type=Int()) field.validate({}) field.validate({'b': 1, 'd': 2}) field.validate({'a': 3}) with self.assertRaises(WrongContainedType) as exc: field.validate({1: 'a'}) wct = exc.exception self.assertIs(wct.field, field) self.assertEqual(wct.value, {1: 'a'}) self.assertIs(wct.__class__, WrongContainedType) self.assertEqual(1, len(wct.errors)) self.assertIsInstance(wct.errors[0], WrongType) self.assertIs(field.value_type._type, wct.errors[0].expected_type) def test_validate_min_length(self): field = self._makeOne(min_length=1) field.validate({1: 'a'}) field.validate({1: 'a', 2: 'b'}) self.assertRaisesTooShort(field, {}) def test_validate_max_length(self): field = self._makeOne(max_length=1) field.validate({}) field.validate({1: 'a'}) self.assertRaisesTooLong(field, {1: 'a', 2: 'b'}) self.assertRaisesTooLong(field, {1: 'a', 2: 'b', 3: 'c'}) def test_validate_min_length_and_max_length(self): field = self._makeOne(min_length=1, max_length=2) field.validate({1: 'a'}) field.validate({1: 'a', 2: 'b'}) self.assertRaisesTooShort(field, {}) self.assertRaisesTooLong(field, {1: 'a', 2: 'b', 3: 'c'}) def test_bind_without_key_and_value_types(self): field = self._makeOne() context = object() field2 = field.bind(context) self.assertIsNone(field2.key_type) self.assertIsNone(field2.value_type) def test_bind_binds_key_and_value_types(self): from zope.schema import Int field = self._makeOne(key_type=Int(), value_type=Int()) context = object() field2 = field.bind(context) self.assertEqual(field2.key_type.context, context) self.assertEqual(field2.value_type.context, context) def test_mapping(self): from zope.schema._field import abc class Mapping(abc.Mapping): def __getitem__(self, name): raise AssertionError("not implemented") def __iter__(self): return iter(()) def __len__(self): return 0 mm = Mapping() field = self._makeOne() field.validate(mm) def test_mutable_mapping(self): from zope.schema._field import abc class MutableMapping(abc.MutableMapping): def __getitem__(self, name): raise AssertionError("not implemented") def __iter__(self): return iter(()) def __setitem__(self, name, value): raise AssertionError("Not implemented") def __len__(self): return 0 __delitem__ = __getitem__ mm = MutableMapping() field = self._makeOne() field.validate(mm) class MutableMappingTests(MappingTests): def _getTargetClass(self): from zope.schema._field import MutableMapping return MutableMapping def _getTargetInterface(self): from zope.schema.interfaces import IMutableMapping return IMutableMapping def test_mapping(self): from zope.schema.interfaces import WrongType with self.assertRaises(WrongType): super(MutableMappingTests, self).test_mapping() class DictTests(MutableMappingTests): def _getTargetClass(self): from zope.schema._field import Dict return Dict def _getTargetInterface(self): from zope.schema.interfaces import IDict return IDict def test_mutable_mapping(self): from zope.schema.interfaces import WrongType with self.assertRaises(WrongType): super(DictTests, self).test_mutable_mapping() class NativeStringTests(EqualityTestsMixin, WrongTypeTestsMixin, unittest.TestCase): def _getTargetClass(self): from zope.schema._field import NativeString return NativeString def _getTargetInterface(self): from zope.schema.interfaces import INativeString return INativeString def _getTargetInterfaces(self): from zope.schema.interfaces import IFromUnicode from zope.schema.interfaces import IFromBytes return [self._getTargetInterface(), IFromUnicode, IFromBytes] def test_fromBytes(self): field = self._makeOne() self.assertEqual(field.fromBytes(b''), '') self.assertEqual(field.fromBytes(b'DEADBEEF'), 'DEADBEEF') 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') class NativeStringLineTests(EqualityTestsMixin, WrongTypeTestsMixin, unittest.TestCase): def _getTargetClass(self): from zope.schema._field import NativeStringLine return NativeStringLine def _getTargetInterface(self): from zope.schema.interfaces import INativeStringLine return INativeStringLine def _getTargetInterfaces(self): from zope.schema.interfaces import IFromUnicode from zope.schema.interfaces import IFromBytes return [self._getTargetInterface(), IFromUnicode, IFromBytes] def test_fromBytes(self): field = self._makeOne() self.assertEqual(field.fromBytes(b''), '') self.assertEqual(field.fromBytes(b'DEADBEEF'), 'DEADBEEF') 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') class StrippedNativeStringLineTests(NativeStringLineTests): def _getTargetClass(self): from zope.schema._field import _StrippedNativeStringLine return _StrippedNativeStringLine def test_strips(self): field = self._makeOne() self.assertEqual(field.fromBytes(b' '), '') self.assertEqual(field.fromUnicode(u' '), '') def test_iface_is_first_in_sro(self): self.skipTest("Not applicable; we inherit implementation but have no " "interface") def _makeSampleVocabulary(): from zope.interface import implementer from zope.schema.interfaces import IVocabulary @implementer(IVocabulary) class SampleVocabulary(object): def __iter__(self): raise AssertionError("Not implemented") def __contains__(self, value): return 0 <= value < 10 def __len__(self): # pragma: no cover return 10 def getTerm(self, value): raise AssertionError("Not implemented") return SampleVocabulary() def _makeDummyRegistry(v): from zope.schema.vocabulary import VocabularyRegistry class DummyRegistry(VocabularyRegistry): def __init__(self, vocabulary): VocabularyRegistry.__init__(self) self._vocabulary = vocabulary def get(self, context, name): return self._vocabulary return DummyRegistry(v) def test_suite(): import zope.schema._field suite = unittest.defaultTestLoader.loadTestsFromName(__name__) suite.addTests(doctest.DocTestSuite( zope.schema._field, optionflags=doctest.ELLIPSIS )) return suite zope.schema-6.2.0/src/zope/schema/tests/test_accessors.py0000644000100100000240000002570014133212652023345 0ustar macstaff00000000000000############################################################################## # # Copyright (c) 2003 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Test Interface accessor methods. """ import unittest # pylint:disable=inherit-non-class class FieldReadAccessorTests(unittest.TestCase): def _getTargetClass(self): from zope.schema.accessors import FieldReadAccessor return FieldReadAccessor def _makeOne(self, field=None): from zope.schema import Text if field is None: field = Text(__name__='testing') return self._getTargetClass()(field) def test_ctor_not_created_inside_interface(self): from zope.schema import Text field = Text(title=u'Hmm') wrapped = self._makeOne(field) self.assertTrue(wrapped.field is field) self.assertEqual(wrapped.__name__, '') # __name__ set when in iface self.assertEqual(wrapped.__doc__, 'get Hmm') def test_ctor_created_inside_interface(self): from zope.interface import Interface from zope.schema import Text field = Text(title=u'Hmm') class IFoo(Interface): getter = self._makeOne(field) getter = IFoo['getter'] self.assertEqual(getter.__name__, 'getter') self.assertEqual(getter.__doc__, 'get Hmm') def test___provides___w_field_no_provides(self): from zope.interface import implementedBy from zope.interface import providedBy wrapped = self._makeOne(object()) self.assertEqual(list(providedBy(wrapped)), list(implementedBy(self._getTargetClass()))) def test___provides___w_field_w_provides(self): from zope.interface import implementedBy from zope.interface import providedBy from zope.interface.interfaces import IAttribute from zope.interface.interfaces import IMethod from zope.schema import Text # When wrapping a field that provides stuff, # we provide the same stuff, with the addition of # IMethod at the correct spot in the IRO (just before # IAttribute). field = Text() field_provides = list(providedBy(field)) wrapped = self._makeOne(field) wrapped_provides = list(providedBy(wrapped)) index_of_attribute = field_provides.index(IAttribute) expected = list(field_provides) expected.insert(index_of_attribute, IMethod) self.assertEqual(expected, wrapped_provides) for iface in list(implementedBy(self._getTargetClass())): self.assertIn(iface, wrapped_provides) def test___provides___w_field_w_provides_strict(self): from zope.interface import ro attr = 'STRICT_IRO' try: getattr(ro.C3, attr) except AttributeError: # pragma: no cover # https://github.com/zopefoundation/zope.interface/issues/194 # zope.interface 5.0.0 used this incorrect spelling. attr = 'STRICT_RO' getattr(ro.C3, attr) setattr(ro.C3, attr, True) try: self.test___provides___w_field_w_provides() finally: setattr(ro.C3, attr, getattr(ro.C3, 'ORIG_' + attr)) def test_getSignatureString(self): wrapped = self._makeOne() self.assertEqual(wrapped.getSignatureString(), '()') def test_getSignatureInfo(self): wrapped = self._makeOne() info = wrapped.getSignatureInfo() self.assertEqual(info['positional'], ()) self.assertEqual(info['required'], ()) self.assertEqual(info['optional'], ()) self.assertEqual(info['varargs'], None) self.assertEqual(info['kwargs'], None) def test_get_miss(self): from zope.interface import Interface class IFoo(Interface): getter = self._makeOne() getter = IFoo['getter'] class Foo(object): pass self.assertRaises(AttributeError, getter.get, Foo()) def test_get_hit(self): from zope.interface import Interface class IFoo(Interface): getter = self._makeOne() getter = IFoo['getter'] class Foo(object): def getter(self): return '123' self.assertEqual(getter.get(Foo()), '123') def test_query_miss_implicit_default(self): from zope.interface import Interface class IFoo(Interface): getter = self._makeOne() getter = IFoo['getter'] class Foo(object): pass self.assertEqual(getter.query(Foo()), None) def test_query_miss_explicit_default(self): from zope.interface import Interface class IFoo(Interface): getter = self._makeOne() getter = IFoo['getter'] class Foo(object): pass self.assertEqual(getter.query(Foo(), 234), 234) def test_query_hit(self): from zope.interface import Interface class IFoo(Interface): getter = self._makeOne() getter = IFoo['getter'] class Foo(object): def getter(self): return '123' self.assertEqual(getter.query(Foo()), '123') def test_set_readonly(self): from zope.interface import Interface from zope.schema import Text field = Text(readonly=True) class IFoo(Interface): getter = self._makeOne(field) getter = IFoo['getter'] class Foo(object): def getter(self): raise AssertionError("Not called") self.assertRaises(TypeError, getter.set, Foo(), '456') def test_set_no_writer(self): from zope.interface import Interface class IFoo(Interface): getter = self._makeOne() getter = IFoo['getter'] class Foo(object): def getter(self): raise AssertionError("Not called") self.assertRaises(AttributeError, getter.set, Foo(), '456') def test_set_w_writer(self): from zope.interface import Interface class IFoo(Interface): getter = self._makeOne() getter = IFoo['getter'] _called_with = [] class Writer(object): pass writer = Writer() # pylint:disable=attribute-defined-outside-init writer.__name__ = 'setMe' # pylint:enable=attribute-defined-outside-init getter.writer = writer class Foo(object): def setMe(self, value): _called_with.append(value) getter.set(Foo(), '456') self.assertEqual(_called_with, ['456']) def test_bind(self): from zope.interface import Interface class IFoo(Interface): getter = self._makeOne() getter = IFoo['getter'] context = object() bound = getter.bind(context) self.assertEqual(bound.__name__, 'getter') self.assertTrue(isinstance(bound.field, getter.field.__class__)) self.assertTrue(bound.field.context is context) class FieldWriteAccessorTests(unittest.TestCase): def _getTargetClass(self): from zope.schema.accessors import FieldWriteAccessor return FieldWriteAccessor def _makeOne(self, field=None): from zope.schema import Text if field is None: field = Text(__name__='testing') return self._getTargetClass()(field) def test_ctor_not_created_inside_interface(self): from zope.schema import Text field = Text(title=u'Hmm') wrapped = self._makeOne(field) self.assertTrue(wrapped.field is field) self.assertEqual(wrapped.__name__, '') # __name__ set when in iface self.assertEqual(wrapped.__doc__, 'set Hmm') def test_ctor_created_inside_interface(self): from zope.interface import Interface from zope.schema import Text field = Text(title=u'Hmm') class IFoo(Interface): setter = self._makeOne(field) setter = IFoo['setter'] self.assertEqual(setter.__name__, 'setter') self.assertEqual(setter.__doc__, 'set Hmm') def test_getSignatureString(self): wrapped = self._makeOne() self.assertEqual(wrapped.getSignatureString(), '(newvalue)') def test_getSignatureInfo(self): wrapped = self._makeOne() info = wrapped.getSignatureInfo() self.assertEqual(info['positional'], ('newvalue',)) self.assertEqual(info['required'], ('newvalue',)) self.assertEqual(info['optional'], ()) self.assertEqual(info['varargs'], None) self.assertEqual(info['kwargs'], None) class Test_accessors(unittest.TestCase): def _callFUT(self, *args, **kw): from zope.schema.accessors import accessors return accessors(*args, **kw) def test_w_only_read_accessor(self): from zope.interface import Interface from zope.schema import Text field = Text(title=u'Hmm', readonly=True) class IFoo(Interface): getter, = self._callFUT(field) getter = IFoo['getter'] self.assertEqual(getter.__name__, 'getter') self.assertEqual(getter.__doc__, 'get Hmm') self.assertEqual(getter.getSignatureString(), '()') info = getter.getSignatureInfo() self.assertEqual(info['positional'], ()) self.assertEqual(info['required'], ()) self.assertEqual(info['optional'], ()) self.assertEqual(info['varargs'], None) self.assertEqual(info['kwargs'], None) def test_w_read_and_write_accessors(self): from zope.interface import Interface from zope.schema import Text field = Text(title=u'Hmm') class IFoo(Interface): getter, setter = self._callFUT(field) getter = IFoo['getter'] self.assertEqual(getter.__name__, 'getter') self.assertEqual(getter.getSignatureString(), '()') info = getter.getSignatureInfo() self.assertEqual(info['positional'], ()) self.assertEqual(info['required'], ()) self.assertEqual(info['optional'], ()) self.assertEqual(info['varargs'], None) self.assertEqual(info['kwargs'], None) setter = IFoo['setter'] self.assertEqual(setter.__name__, 'setter') self.assertEqual(setter.getSignatureString(), '(newvalue)') info = setter.getSignatureInfo() self.assertEqual(info['positional'], ('newvalue',)) self.assertEqual(info['required'], ('newvalue',)) self.assertEqual(info['optional'], ()) self.assertEqual(info['varargs'], None) self.assertEqual(info['kwargs'], None) zope.schema-6.2.0/src/zope/schema/tests/test_equality.py0000644000100100000240000000176614133212652023223 0ustar macstaff00000000000000############################################################################## # # Copyright (c) 2001, 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Field equality tests """ import unittest class FieldEqualityTests(unittest.TestCase): def test_equality(self): from zope.schema import Int from zope.schema import Text def _makeOne(cls): return cls(title=u"Foo", description=u"Bar") for cls in (Int, Text): self.assertEqual(_makeOne(cls), _makeOne(cls)) zope.schema-6.2.0/src/zope/schema/tests/test_fieldproperty.py0000644000100100000240000005175214133212652024256 0ustar macstaff00000000000000############################################################################## # # Copyright (c) 2001, 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Field Properties tests """ import unittest class _Base(unittest.TestCase): def _makeOne(self, field=None, name=None): from zope.schema import Text if field is None: field = Text(__name__='testing') if name is None: return self._getTargetClass()(field) return self._getTargetClass()(field, name) class _Integration(object): def _makeImplementer(self): schema = _getSchema() class _Implementer(object): title = self._makeOne(schema['title']) weight = self._makeOne(schema['weight']) code = self._makeOne(schema['code']) date = self._makeOne(schema['date']) return _Implementer() def test_basic(self): from zope.schema.interfaces import ValidationError c = self._makeImplementer() self.assertEqual(c.title, u'say something') self.assertEqual(c.weight, None) self.assertEqual(c.code, b'xxxxxx') self.assertRaises(ValidationError, setattr, c, 'title', b'foo') self.assertRaises(ValidationError, setattr, c, 'weight', b'foo') self.assertRaises(ValidationError, setattr, c, 'weight', -1.0) 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') c.title = u'c is good' c.weight = 10.0 c.code = b'abcdef' self.assertEqual(c.title, u'c is good') self.assertEqual(c.weight, 10) self.assertEqual(c.code, b'abcdef') def test_readonly(self): c = self._makeImplementer() # The date should be only settable once c.date = 0.0 # Setting the value a second time should fail. self.assertRaises(ValueError, setattr, c, 'date', 1.0) class FieldPropertyTests(_Base, _Integration): def _getTargetClass(self): from zope.schema.fieldproperty import FieldProperty return FieldProperty def test_ctor_defaults(self): from zope.schema import Text field = Text(__name__='testing') cname = self._getTargetClass().__name__ prop = self._makeOne(field) self.assertTrue(getattr(prop, '_%s__field' % cname) is field) self.assertEqual(getattr(prop, '_%s__name' % cname), 'testing') self.assertEqual(prop.__name__, 'testing') self.assertEqual(prop.description, field.description) self.assertEqual(prop.default, field.default) self.assertEqual(prop.readonly, field.readonly) self.assertEqual(prop.required, field.required) def test_ctor_explicit(self): from zope.schema import Text field = Text( __name__='testing', description=u'DESCRIPTION', default=u'DEFAULT', readonly=True, required=True, ) cname = self._getTargetClass().__name__ prop = self._makeOne(field, name='override') self.assertTrue(getattr(prop, '_%s__field' % cname) is field) self.assertEqual(getattr(prop, '_%s__name' % cname), 'override') self.assertEqual(prop.description, field.description) self.assertEqual(prop.default, field.default) self.assertEqual(prop.readonly, field.readonly) self.assertEqual(prop.required, field.required) def test_query_value_with_default(self): from zope.schema import Text field = Text( __name__='testing', description=u'DESCRIPTION', default=u'DEFAULT', readonly=True, required=True, ) prop = self._makeOne(field=field) class Foo(object): testing = prop foo = Foo() self.assertEqual(prop.queryValue(foo, 'test'), u'DEFAULT') foo.testing = u'NO' self.assertEqual(prop.queryValue(foo, 'test'), u'NO') def test_query_value_without_default(self): from zope.schema import Text field = Text( __name__='testing', description=u'DESCRIPTION', readonly=True, required=True, ) prop = self._makeOne(field=field) class Foo(object): testing = prop foo = Foo() # field initialize its default to None if it hasn't any default # it should be zope.schema.NO_VALUE as 'None' has another semantic self.assertEqual(prop.queryValue(foo, 'test'), None) def test___get___from_class(self): prop = self._makeOne() class Foo(object): testing = prop self.assertTrue(Foo.testing is prop) def test___get___from_instance_pseudo_field_wo_default(self): class _Faux(object): def bind(self, other): return self prop = self._makeOne(_Faux(), 'nonesuch') class Foo(object): testing = prop foo = Foo() self.assertRaises(AttributeError, getattr, foo, 'testing') def test___get___from_instance_miss_uses_field_default(self): prop = self._makeOne() class Foo(object): testing = prop foo = Foo() self.assertEqual(foo.testing, None) def test___get___from_instance_hit(self): prop = self._makeOne(name='other') class Foo(object): testing = prop foo = Foo() foo.other = '123' self.assertEqual(foo.testing, '123') def test___get___from_instance_hit_after_bind(self): class _Faux(object): default = '456' def bind(self, other): return self prop = self._makeOne(_Faux(), 'testing') class Foo(object): testing = prop foo = Foo() self.assertEqual(foo.testing, '456') def test___set___not_readonly(self): class _Faux(object): readonly = False default = '456' def bind(self, other): return self faux = _Faux() _validated = [] faux.validate = _validated.append prop = self._makeOne(faux, 'testing') class Foo(object): testing = prop foo = Foo() foo.testing = '123' self.assertEqual(foo.__dict__['testing'], '123') def test___set___w_readonly_not_already_set(self): class _Faux(object): readonly = True default = '456' def bind(self, other): return self faux = _Faux() _validated = [] faux.validate = _validated.append prop = self._makeOne(faux, 'testing') class Foo(object): testing = prop foo = Foo() foo.testing = '123' self.assertEqual(foo.__dict__['testing'], '123') self.assertEqual(_validated, ['123']) def test___set___w_readonly_and_already_set(self): class _Faux(object): readonly = True default = '456' def bind(self, other): return self faux = _Faux() _validated = [] faux.validate = _validated.append prop = self._makeOne(faux, 'testing') class Foo(object): testing = prop foo = Foo() foo.__dict__['testing'] = '789' self.assertRaises(ValueError, setattr, foo, 'testing', '123') self.assertEqual(_validated, ['123']) def test_field_event(self): from zope.schema import Text from zope.interface.verify import verifyObject from zope.event import subscribers from zope.schema.interfaces import IFieldUpdatedEvent from zope.schema.fieldproperty import FieldUpdatedEvent log = [] subscribers.append(log.append) self.assertEqual(log, []) field = Text( __name__='testing', description=u'DESCRIPTION', default=u'DEFAULT', readonly=True, required=True, ) self.assertEqual(len(log), 6) event = log[0] self.assertTrue(isinstance(event, FieldUpdatedEvent)) self.assertTrue(verifyObject(IFieldUpdatedEvent, event)) self.assertEqual(event.object, field) self.assertEqual(event.old_value, 0) self.assertEqual(event.new_value, 0) self.assertEqual( [ev.field.__name__ for ev in log], ['min_length', 'max_length', 'title', 'description', 'required', 'readonly']) # BBB, but test this works. self.assertEqual(event.inst, field) marker = object() event.inst = marker self.assertEqual(event.inst, marker) self.assertEqual(event.object, marker) def test_field_event_update(self): from zope.schema import Text from zope.interface.verify import verifyObject from zope.event import subscribers from zope.schema.interfaces import IFieldUpdatedEvent from zope.schema.fieldproperty import FieldUpdatedEvent field = Text( __name__='testing', description=u'DESCRIPTION', default=u'DEFAULT', required=True, ) prop = self._makeOne(field=field) class Foo(object): testing = prop foo = Foo() log = [] subscribers.append(log.append) foo.testing = u'Bar' foo.testing = u'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') # BBB, but test this works. self.assertEqual(event.inst, foo) marker = object() event.inst = marker self.assertEqual(event.inst, marker) self.assertEqual(event.object, marker) def test_field_Bool_is_required(self): # the Bool field is required by default from zope.schema import Bool field = Bool(__name__='testing') self.assertTrue(field.required) def test_field_Bool_default_is_None(self): # the Bool field has no default set (None) from zope.schema import Bool field = Bool(__name__='testing') self.assertIsNone(field.default) class FieldPropertyStoredThroughFieldTests(_Base, _Integration): def _getTargetClass(self): from zope.schema.fieldproperty import FieldPropertyStoredThroughField return FieldPropertyStoredThroughField def test_ctor_defaults(self): from zope.schema import Text field = Text(__name__='testing') cname = self._getTargetClass().__name__ prop = self._makeOne(field) self.assertTrue(isinstance(prop.field, field.__class__)) self.assertFalse(prop.field is field) self.assertEqual(prop.field.__name__, '__st_testing_st') self.assertEqual(prop.__name__, '__st_testing_st') self.assertEqual(getattr(prop, '_%s__name' % cname), 'testing') self.assertEqual(prop.description, field.description) self.assertEqual(prop.default, field.default) self.assertEqual(prop.readonly, field.readonly) self.assertEqual(prop.required, field.required) def test_ctor_explicit(self): from zope.schema import Text field = Text( __name__='testing', description=u'DESCRIPTION', default=u'DEFAULT', readonly=True, required=True, ) cname = self._getTargetClass().__name__ prop = self._makeOne(field, name='override') self.assertTrue(isinstance(prop.field, field.__class__)) self.assertFalse(prop.field is field) self.assertEqual(prop.field.__name__, '__st_testing_st') self.assertEqual(prop.__name__, '__st_testing_st') self.assertEqual(getattr(prop, '_%s__name' % cname), 'override') self.assertEqual(prop.description, field.description) self.assertEqual(prop.default, field.default) self.assertEqual(prop.readonly, field.readonly) self.assertEqual(prop.required, field.required) def test_setValue(self): from zope.schema import Text class Foo(object): pass foo = Foo() prop = self._makeOne() field = Text(__name__='testing') prop.setValue(foo, field, '123') self.assertEqual(foo.testing, '123') def test_getValue_miss(self): from zope.schema import Text from zope.schema.fieldproperty import _marker class Foo(object): pass foo = Foo() prop = self._makeOne() field = Text(__name__='testing') value = prop.getValue(foo, field) self.assertTrue(value is _marker) def test_getValue_hit(self): from zope.schema import Text class Foo(object): pass foo = Foo() foo.testing = '123' prop = self._makeOne() field = Text(__name__='testing') value = prop.getValue(foo, field) self.assertEqual(value, '123') def test_queryValue_miss(self): from zope.schema import Text class Foo(object): pass foo = Foo() prop = self._makeOne() field = Text(__name__='testing') default = object() value = prop.queryValue(foo, field, default) self.assertTrue(value is default) def test_queryValue_hit(self): from zope.schema import Text class Foo(object): pass foo = Foo() foo.testing = '123' prop = self._makeOne() field = Text(__name__='testing') default = object() value = prop.queryValue(foo, field, default) self.assertEqual(value, '123') def test___get___from_class(self): prop = self._makeOne() class Foo(object): testing = prop self.assertTrue(Foo.testing is prop) def test___get___from_instance_pseudo_field_wo_default(self): class _Faux(object): __name__ = 'Faux' def bind(self, other): return self def query(self, inst, default): return default prop = self._makeOne(_Faux(), 'nonesuch') class Foo(object): testing = prop foo = Foo() self.assertRaises(AttributeError, getattr, foo, 'testing') def test___get___from_instance_miss_uses_field_default(self): prop = self._makeOne() class Foo(object): testing = prop foo = Foo() self.assertEqual(foo.testing, None) def test___get___from_instance_hit(self): from zope.schema import Text field = Text(__name__='testing') prop = self._makeOne(field, name='other') class Foo(object): testing = prop foo = Foo() foo.__dict__['__st_testing_st'] = '456' foo.other = '123' self.assertEqual(foo.testing, '456') def test___set___not_readonly(self): class _Faux(object): __name__ = 'Faux' readonly = False default = '456' def query(self, inst, default): return default def bind(self, other): return self def set(self, inst, value): setattr(inst, 'faux', value) faux = _Faux() _validated = [] faux.validate = _validated.append prop = self._makeOne(faux, 'testing') class Foo(object): testing = prop foo = Foo() foo.testing = '123' self.assertEqual(foo.__dict__['faux'], '123') self.assertEqual(_validated, ['123']) def test___set___w_readonly_not_already_set(self): class _Faux(object): __name__ = 'Faux' readonly = True default = '456' def bind(self, other): return self def query(self, inst, default): return default def set(self, inst, value): if self.readonly: # pragma: no cover raise ValueError setattr(inst, 'faux', value) faux = _Faux() _validated = [] faux.validate = _validated.append prop = self._makeOne(faux, 'testing') class Foo(object): testing = prop foo = Foo() foo.testing = '123' self.assertEqual(foo.__dict__['faux'], '123') self.assertEqual(_validated, ['123']) def test___set___w_readonly_and_already_set(self): class _Faux(object): __name__ = 'Faux' readonly = True default = '456' def bind(self, other): return self def query(self, inst, default): return '789' faux = _Faux() _validated = [] faux.validate = _validated.append prop = self._makeOne(faux, 'testing') class Foo(object): testing = prop foo = Foo() foo.__dict__['testing'] = '789' self.assertRaises(ValueError, setattr, foo, 'testing', '123') def test_field_event_update(self): from zope.schema import Text from zope.event import subscribers from zope.schema.fieldproperty import FieldUpdatedEvent field = Text( __name__='testing', description=u'DESCRIPTION', default=u'DEFAULT', required=True, ) prop = self._makeOne(field=field) class Foo(object): testing = prop foo = Foo() log = [] subscribers.append(log.append) foo.testing = u'Bar' foo.testing = u'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') def test_field_event(self): # fieldproperties are everywhere including in field themselfs # so event are triggered from zope.schema import Text from zope.event import subscribers from zope.schema.fieldproperty import FieldUpdatedEvent log = [] subscribers.append(log.append) self.assertEqual(log, []) field = Text( __name__='testing', description=u'DESCRIPTION', default=u'DEFAULT', readonly=True, required=True, ) self.assertEqual(len(log), 6) # these are fieldproperties in the field self.assertEqual( [ev.field.__name__ for ev in log], ['min_length', 'max_length', 'title', 'description', 'required', 'readonly']) event = log[0] self.assertTrue(isinstance(event, FieldUpdatedEvent)) self.assertEqual(event.object, field) self.assertEqual(event.old_value, 0) self.assertEqual(event.new_value, 0) def _getSchema(): from zope.interface import Interface from zope.schema import Bytes from zope.schema import Float from zope.schema import Text class Schema(Interface): title = Text(description=u"Short summary", default=u'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) return Schema class CreateFieldPropertiesTests(unittest.TestCase): """Testing ..fieldproperty.createFieldProperties.""" def test_creates_fieldproperties_on_class(self): from zope.schema.fieldproperty import createFieldProperties from zope.schema.fieldproperty import FieldProperty schema = _getSchema() class Dummy(object): createFieldProperties(schema) self.assertTrue(isinstance(Dummy.title, FieldProperty)) self.assertTrue(isinstance(Dummy.date, FieldProperty)) self.assertTrue(Dummy.date._FieldProperty__field is schema['date']) def test_fields_in_omit_are_not_created_on_class(self): from zope.schema.fieldproperty import createFieldProperties class Dummy(object): createFieldProperties(_getSchema(), omit=['date', 'code']) self.assertFalse(hasattr(Dummy, 'date')) self.assertFalse(hasattr(Dummy, 'code')) self.assertTrue(hasattr(Dummy, 'title')) zope.schema-6.2.0/src/zope/schema/tests/test_interfaces.py0000644000100100000240000000737114133212652023507 0ustar macstaff00000000000000import unittest class Test__is_field(unittest.TestCase): def _callFUT(self, value): from zope.schema.interfaces import _is_field return _is_field(value) def test_non_fields(self): self.assertEqual(self._callFUT(None), False) self.assertEqual(self._callFUT(0), False) 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(set()), False) self.assertEqual(self._callFUT(frozenset()), False) self.assertEqual(self._callFUT(object()), False) def test_w_normal_fields(self): from zope.schema import Text from zope.schema import Bytes from zope.schema import Int from zope.schema import Float from zope.schema import Decimal self.assertEqual(self._callFUT(Text()), True) self.assertEqual(self._callFUT(Bytes()), True) self.assertEqual(self._callFUT(Int()), True) self.assertEqual(self._callFUT(Float()), True) self.assertEqual(self._callFUT(Decimal()), True) def test_w_explicitly_provided(self): from zope.interface import directlyProvides from zope.schema.interfaces import IField class Foo(object): pass foo = Foo() self.assertEqual(self._callFUT(foo), False) directlyProvides(foo, IField) self.assertEqual(self._callFUT(foo), True) class Test__fields(unittest.TestCase): def _callFUT(self, values): from zope.schema.interfaces import _fields return _fields(values) def test_empty_containers(self): self.assertEqual(self._callFUT(()), True) self.assertEqual(self._callFUT([]), True) def test_w_non_fields(self): self.assertEqual(self._callFUT([None]), False) self.assertEqual(self._callFUT(['']), False) self.assertEqual(self._callFUT([object()]), False) def test_w_fields(self): from zope.schema import Text from zope.schema import Bytes from zope.schema import Int from zope.schema import Float from zope.schema import Decimal self.assertEqual(self._callFUT([Text()]), True) self.assertEqual(self._callFUT([Bytes()]), True) self.assertEqual(self._callFUT([Int()]), True) self.assertEqual(self._callFUT([Float()]), True) self.assertEqual(self._callFUT([Decimal()]), True) self.assertEqual( self._callFUT([Text(), Bytes(), Int(), Float(), Decimal()]), True ) def test_w_mixed(self): from zope.schema import Text from zope.schema import Bytes from zope.schema import Int from zope.schema import Float from zope.schema import Decimal self.assertEqual(self._callFUT([Text(), 0]), False) self.assertEqual( self._callFUT([Text(), Bytes(), Int(), Float(), Decimal(), 0]), False ) def test_bool_not_required(self): """If class Bool is used as a schema itself, it must not be required. """ from zope.schema.interfaces import IBool # treat IBool as schema with fields field = IBool.get("required") self.assertFalse(field.required) def test_bool_defaults_to_false(self): """If class Bool is used as a schema itself, it must default to False """ from zope.schema.interfaces import IBool # treat IBool as schema with fields field = IBool.get("default") self.assertFalse(field.default) zope.schema-6.2.0/src/zope/schema/tests/test_schema.py0000644000100100000240000002044014133212652022614 0ustar macstaff00000000000000############################################################################## # # Copyright (c) 2001, 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Schema field tests """ import unittest def _makeSchema(): from zope.interface import Interface from zope.schema import Bytes class ISchemaTest(Interface): title = Bytes( title=u"Title", description=u"Title", default=b"", required=True) description = Bytes( title=u"Description", description=u"Description", default=b"", required=True) spam = Bytes( title=u"Spam", description=u"Spam", default=b"", required=True) return ISchemaTest def _makeDerivedSchema(): from zope.schema import Bytes base = _makeSchema() class ISchemaTestSubclass(base): foo = Bytes( title=u'Foo', description=u'Fooness', default=b"", required=False) return ISchemaTestSubclass class Test_getFields(unittest.TestCase): def _callFUT(self, schema): from zope.schema import getFields return getFields(schema) def test_simple(self): fields = self._callFUT(_makeSchema()) self.assertTrue('title' in fields) self.assertTrue('description' in fields) self.assertTrue('spam' in fields) # test whether getName() has the right value for key, value in fields.items(): self.assertEqual(key, value.getName()) def test_derived(self): fields = self._callFUT(_makeDerivedSchema()) self.assertTrue('title' in fields) self.assertTrue('description' in fields) self.assertTrue('spam' in fields) self.assertTrue('foo' in fields) # test whether getName() has the right value for key, value in fields.items(): self.assertEqual(key, value.getName()) class Test_getFieldsInOrder(unittest.TestCase): def _callFUT(self, schema): from zope.schema import getFieldsInOrder return getFieldsInOrder(schema) def test_simple(self): fields = self._callFUT(_makeSchema()) field_names = [name for name, field in fields] self.assertEqual(field_names, ['title', 'description', 'spam']) for key, value in fields: self.assertEqual(key, value.getName()) def test_derived(self): fields = self._callFUT(_makeDerivedSchema()) field_names = [name for name, field in fields] self.assertEqual(field_names, ['title', 'description', 'spam', 'foo']) for key, value in fields: self.assertEqual(key, value.getName()) class Test_getFieldNames(unittest.TestCase): def _callFUT(self, schema): from zope.schema import getFieldNames return getFieldNames(schema) def test_simple(self): names = self._callFUT(_makeSchema()) self.assertEqual(len(names), 3) self.assertTrue('title' in names) self.assertTrue('description' in names) self.assertTrue('spam' in names) def test_derived(self): names = self._callFUT(_makeDerivedSchema()) self.assertEqual(len(names), 4) self.assertTrue('title' in names) self.assertTrue('description' in names) self.assertTrue('spam' in names) self.assertTrue('foo' in names) class Test_getFieldNamesInOrder(unittest.TestCase): def _callFUT(self, schema): from zope.schema import getFieldNamesInOrder return getFieldNamesInOrder(schema) def test_simple(self): names = self._callFUT(_makeSchema()) self.assertEqual(names, ['title', 'description', 'spam']) def test_derived(self): names = self._callFUT(_makeDerivedSchema()) self.assertEqual(names, ['title', 'description', 'spam', 'foo']) class Test_getValidationErrors(unittest.TestCase): def _callFUT(self, schema, object): from zope.schema import getValidationErrors return getValidationErrors(schema, object) def test_schema(self): from zope.interface import Interface class IEmpty(Interface): pass errors = self._callFUT(IEmpty, object()) self.assertEqual(len(errors), 0) def test_schema_with_field_errors(self): from zope.interface import Interface from zope.schema import Text from zope.schema.interfaces import SchemaNotFullyImplemented class IWithRequired(Interface): must = Text(required=True) errors = self._callFUT(IWithRequired, object()) self.assertEqual(len(errors), 1) self.assertEqual(errors[0][0], 'must') self.assertEqual(errors[0][1].__class__, SchemaNotFullyImplemented) self.assertIsNone(errors[0][1].value) self.assertEqual(IWithRequired['must'], errors[0][1].field) def test_schema_with_invariant_errors(self): from zope.interface import Interface from zope.interface import invariant from zope.interface.exceptions import Invalid class IWithFailingInvariant(Interface): @invariant def _epic_fail(obj): raise Invalid('testing') errors = self._callFUT(IWithFailingInvariant, object()) self.assertEqual(len(errors), 1) self.assertEqual(errors[0][0], None) self.assertEqual(errors[0][1].__class__, Invalid) def test_schema_with_invariant_ok(self): from zope.interface import Interface from zope.interface import invariant class IWithPassingInvariant(Interface): @invariant def _hall_pass(obj): pass errors = self._callFUT(IWithPassingInvariant, object()) self.assertEqual(len(errors), 0) class Test_getSchemaValidationErrors(unittest.TestCase): def _callFUT(self, schema, object): from zope.schema import getSchemaValidationErrors return getSchemaValidationErrors(schema, object) def test_schema_wo_fields(self): from zope.interface import Interface from zope.interface import Attribute class INoFields(Interface): def method(): "A method." attr = Attribute('ignoreme') errors = self._callFUT(INoFields, object()) self.assertEqual(len(errors), 0) def test_schema_with_fields_ok(self): from zope.interface import Interface from zope.schema import Text class IWithFields(Interface): foo = Text() bar = Text() class Obj(object): foo = u'Foo' bar = u'Bar' errors = self._callFUT(IWithFields, Obj()) self.assertEqual(len(errors), 0) def test_schema_with_missing_field(self): from zope.interface import Interface from zope.schema import Text from zope.schema.interfaces import SchemaNotFullyImplemented class IWithRequired(Interface): must = Text(required=True) errors = self._callFUT(IWithRequired, object()) self.assertEqual(len(errors), 1) self.assertEqual(errors[0][0], 'must') self.assertEqual(errors[0][1].__class__, SchemaNotFullyImplemented) self.assertIsNone(errors[0][1].value) self.assertEqual(IWithRequired['must'], errors[0][1].field) def test_schema_with_invalid_field(self): from zope.interface import Interface from zope.schema import Int from zope.schema.interfaces import TooSmall class IWithMinium(Interface): value = Int(required=True, min=0) class Obj(object): value = -1 errors = self._callFUT(IWithMinium, Obj()) self.assertEqual(len(errors), 1) self.assertEqual(errors[0][0], 'value') self.assertEqual(errors[0][1].__class__, TooSmall) zope.schema-6.2.0/src/zope/schema/tests/test_states.py0000644000100100000240000000722214133212652022662 0ustar macstaff00000000000000############################################################################## # # Copyright (c) 2003 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Tests of the states example. """ import unittest class StateSelectionTest(unittest.TestCase): def setUp(self): from zope.schema.vocabulary import _clear from zope.schema.vocabulary import getVocabularyRegistry from zope.schema.tests.states import StateVocabulary _clear() vr = getVocabularyRegistry() vr.register("states", StateVocabulary) def tearDown(self): from zope.schema.vocabulary import _clear _clear() def _makeSchema(self): from zope.interface import Interface from zope.schema import Choice from zope.schema.tests.states import StateVocabulary class IBirthInfo(Interface): state1 = Choice( title=u'State of Birth', description=u'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.', vocabulary="states", default="AL", ) state3 = Choice( title=u'Favorite State', description=u'The state you like the most.', vocabulary=StateVocabulary(), ) state4 = Choice( title=u"Name", description=u"The name of your new state", vocabulary="states", ) return IBirthInfo def test_default_presentation(self): from zope.interface.verify import verifyObject from zope.schema.interfaces import IVocabulary schema = self._makeSchema() field = schema.getDescriptionFor("state1") bound = field.bind(object()) self.assertTrue(verifyObject(IVocabulary, bound.vocabulary)) self.assertEqual(bound.vocabulary.getTerm("VA").title, "Virginia") def test_contains(self): from zope.interface.verify import verifyObject from zope.schema.interfaces import IVocabulary from zope.schema.tests.states import StateVocabulary vocab = StateVocabulary() self.assertTrue(verifyObject(IVocabulary, vocab)) count = 0 L = list(vocab) for term in L: count += 1 self.assertTrue(term.value in vocab) self.assertEqual(count, len(vocab)) # make sure we get the same values the second time around: L = [term.value for term in L] L.sort() L2 = [term.value for term in vocab] L2.sort() self.assertEqual(L, L2) def test_prebound_vocabulary(self): from zope.interface.verify import verifyObject from zope.schema.interfaces import IVocabulary schema = self._makeSchema() field = schema.getDescriptionFor("state3") bound = field.bind(None) self.assertTrue(bound.vocabularyName is None) self.assertTrue(verifyObject(IVocabulary, bound.vocabulary)) self.assertTrue("AL" in bound.vocabulary) zope.schema-6.2.0/src/zope/schema/tests/test_vocabulary.py0000644000100100000240000006437414133212652023541 0ustar macstaff00000000000000############################################################################## # # Copyright (c) 2003 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Test of the Vocabulary and related support APIs. """ import unittest class SimpleTermTests(unittest.TestCase): def _getTargetClass(self): from zope.schema.vocabulary import SimpleTerm return SimpleTerm def _makeOne(self, *args, **kw): return self._getTargetClass()(*args, **kw) def test_class_conforms_to_ITokenizedTerm(self): from zope.interface.verify import verifyClass from zope.schema.interfaces import ITokenizedTerm verifyClass(ITokenizedTerm, self._getTargetClass()) def test_instance_conforms_to_ITokenizedTerm(self): from zope.interface.verify import verifyObject from zope.schema.interfaces import ITokenizedTerm verifyObject(ITokenizedTerm, self._makeOne('VALUE')) def test_ctor_defaults(self): from zope.schema.interfaces import ITitledTokenizedTerm term = self._makeOne('VALUE') self.assertEqual(term.value, 'VALUE') self.assertEqual(term.token, 'VALUE') self.assertEqual(term.title, None) self.assertFalse(ITitledTokenizedTerm.providedBy(term)) def test_ctor_explicit(self): from zope.schema.interfaces import ITitledTokenizedTerm term = self._makeOne('TERM', 'TOKEN', 'TITLE') self.assertEqual(term.value, 'TERM') self.assertEqual(term.token, 'TOKEN') self.assertEqual(term.title, 'TITLE') self.assertTrue(ITitledTokenizedTerm.providedBy(term)) def test_bytes_value(self): from zope.schema.interfaces import ITitledTokenizedTerm term = self._makeOne(b'term') self.assertEqual(term.value, b'term') self.assertEqual(term.token, 'term') self.assertFalse(ITitledTokenizedTerm.providedBy(term)) def test_bytes_non_ascii_value(self): from zope.schema.interfaces import ITitledTokenizedTerm term = self._makeOne(b'Snowman \xe2\x98\x83') self.assertEqual(term.value, b'Snowman \xe2\x98\x83') self.assertEqual(term.token, 'Snowman \\xe2\\x98\\x83') self.assertFalse(ITitledTokenizedTerm.providedBy(term)) 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') self.assertEqual(term.token, 'Snowman \\u2603') self.assertFalse(ITitledTokenizedTerm.providedBy(term)) def test__eq__and__hash__(self): term = self._makeOne('value') # Equal to itself self.assertEqual(term, term) # Not equal to a different class self.assertNotEqual(term, object()) self.assertNotEqual(object(), term) term2 = self._makeOne('value') # Equal to another with the same value self.assertEqual(term, term2) # equal objects hash the same self.assertEqual(hash(term), hash(term2)) # Providing tokens or titles that differ # changes equality term = self._makeOne('value', 'token') self.assertNotEqual(term, term2) self.assertNotEqual(hash(term), hash(term2)) term2 = self._makeOne('value', 'token') self.assertEqual(term, term2) self.assertEqual(hash(term), hash(term2)) term = self._makeOne('value', 'token', 'title') self.assertNotEqual(term, term2) self.assertNotEqual(hash(term), hash(term2)) term2 = self._makeOne('value', 'token', 'title') self.assertEqual(term, term2) self.assertEqual(hash(term), hash(term2)) class SimpleVocabularyTests(unittest.TestCase): def _getTargetClass(self): from zope.schema.vocabulary import SimpleVocabulary return SimpleVocabulary def _makeOne(self, *args, **kw): return self._getTargetClass()(*args, **kw) def test_class_conforms_to_IVocabularyTokenized(self): from zope.interface.verify import verifyClass from zope.schema.interfaces import IVocabularyTokenized verifyClass(IVocabularyTokenized, self._getTargetClass()) def test_instance_conforms_to_IVocabularyTokenized(self): from zope.interface.verify import verifyObject from zope.schema.interfaces import IVocabularyTokenized verifyObject(IVocabularyTokenized, self._makeOne(())) def test_ctor_additional_interfaces(self): from zope.interface import Interface from zope.schema.vocabulary import SimpleTerm class IStupid(Interface): pass VALUES = [1, 4, 2, 9] vocabulary = self._makeOne([SimpleTerm(x) for x in VALUES], IStupid) self.assertTrue(IStupid.providedBy(vocabulary)) self.assertEqual(len(vocabulary), len(VALUES)) for value, term in zip(VALUES, vocabulary): self.assertEqual(term.value, value) for value in VALUES: self.assertTrue(value in vocabulary) self.assertFalse('ABC' in vocabulary) for term in vocabulary: self.assertIs(vocabulary.getTerm(term.value), term) self.assertIs(vocabulary.getTermByToken(term.token), term) def test_fromValues(self): from zope.interface import Interface from zope.schema.interfaces import ITokenizedTerm class IStupid(Interface): pass VALUES = [1, 4, 2, 9] vocabulary = self._getTargetClass().fromValues(VALUES) self.assertEqual(len(vocabulary), len(VALUES)) for value, term in zip(VALUES, vocabulary): self.assertTrue(ITokenizedTerm.providedBy(term)) self.assertEqual(term.value, value) for value in VALUES: self.assertIn(value, vocabulary) def test_fromItems(self): from zope.interface import Interface from zope.schema.interfaces import ITokenizedTerm class IStupid(Interface): pass ITEMS = [('one', 1), ('two', 2), ('three', 3), ('fore!', 4)] vocabulary = self._getTargetClass().fromItems(ITEMS) self.assertEqual(len(vocabulary), len(ITEMS)) for item, term in zip(ITEMS, vocabulary): self.assertTrue(ITokenizedTerm.providedBy(term)) self.assertEqual(term.token, item[0]) self.assertEqual(term.value, item[1]) for item in ITEMS: self.assertIn(item[1], vocabulary) def test_fromItems_triples(self): from zope.interface import Interface from zope.schema.interfaces import ITitledTokenizedTerm class IStupid(Interface): pass ITEMS = [ ('one', 1, 'title 1'), ('two', 2, 'title 2'), ('three', 3, 'title 3'), ('fore!', 4, 'title four') ] vocabulary = self._getTargetClass().fromItems(ITEMS) self.assertEqual(len(vocabulary), len(ITEMS)) for item, term in zip(ITEMS, vocabulary): self.assertTrue(ITitledTokenizedTerm.providedBy(term)) self.assertEqual(term.token, item[0]) self.assertEqual(term.value, item[1]) self.assertEqual(term.title, item[2]) for item in ITEMS: self.assertIn(item[1], vocabulary) def test_createTerm(self): from zope.schema.vocabulary import SimpleTerm VALUES = [1, 4, 2, 9] for value in VALUES: term = self._getTargetClass().createTerm(value) self.assertTrue(isinstance(term, SimpleTerm)) self.assertEqual(term.value, value) self.assertEqual(term.token, str(value)) def test_getTerm_miss(self): vocabulary = self._makeOne(()) self.assertRaises(LookupError, vocabulary.getTerm, 'nonesuch') def test_getTermByToken_miss(self): vocabulary = self._makeOne(()) self.assertRaises(LookupError, vocabulary.getTermByToken, 'nonesuch') def test_nonunique_tokens(self): klass = self._getTargetClass() self.assertRaises(ValueError, klass.fromValues, [2, '2']) self.assertRaises( ValueError, klass.fromItems, [(1, 'one'), ('1', 'another one')] ) self.assertRaises( ValueError, klass.fromItems, [(0, 'one'), (1, 'one')] ) def test_nonunique_tokens_swallow(self): klass = self._getTargetClass() items = [(0, 'one'), (1, 'one')] terms = [klass.createTerm(value, token) for (token, value) in items] vocab = self._getTargetClass()(terms, swallow_duplicates=True) self.assertEqual(vocab.getTerm('one').token, '1') def test_nonunique_token_message(self): try: self._getTargetClass().fromValues([2, '2']) except ValueError as e: self.assertEqual(str(e), "term tokens must be unique: '2'") def test_nonunique_token_messages(self): try: self._getTargetClass().fromItems([(0, 'one'), (1, 'one')]) except ValueError as e: self.assertEqual(str(e), "term values must be unique: 'one'") def test_overriding_createTerm(self): class MyTerm(object): def __init__(self, value): self.value = value self.token = repr(value) self.nextvalue = value + 1 class MyVocabulary(self._getTargetClass()): def createTerm(cls, value): return MyTerm(value) createTerm = classmethod(createTerm) vocab = MyVocabulary.fromValues([1, 2, 3]) for term in vocab: self.assertEqual(term.value + 1, term.nextvalue) def test__eq__and__hash__(self): from zope import interface values = [1, 4, 2, 9] vocabulary = self._getTargetClass().fromValues(values) # Equal to itself self.assertEqual(vocabulary, vocabulary) # Not to other classes self.assertNotEqual(vocabulary, object()) self.assertNotEqual(object(), vocabulary) # Equal to another object with the same values vocabulary2 = self._getTargetClass().fromValues(values) self.assertEqual(vocabulary, vocabulary2) self.assertEqual(hash(vocabulary), hash(vocabulary2)) # Changing the values or the interfaces changes # equality class IFoo(interface.Interface): "an interface" vocabulary = self._getTargetClass().fromValues(values, IFoo) self.assertNotEqual(vocabulary, vocabulary2) # Interfaces are not taken into account in the hash; that's # OK: equal hashes do not imply equal objects self.assertEqual(hash(vocabulary), hash(vocabulary2)) vocabulary2 = self._getTargetClass().fromValues(values, IFoo) self.assertEqual(vocabulary, vocabulary2) self.assertEqual(hash(vocabulary), hash(vocabulary2)) # Test _createTermTree via TreeVocabulary.fromDict class TreeVocabularyTests(unittest.TestCase): def _getTargetClass(self): from zope.schema.vocabulary import TreeVocabulary return TreeVocabulary def tree_vocab_2(self): region_tree = { ('regions', 'Regions'): { ('aut', 'Austria'): { ('tyr', 'Tyrol'): { ('auss', 'Ausserfern'): {}, } }, ('ger', 'Germany'): { ('bav', 'Bavaria'): {} }, } } return self._getTargetClass().fromDict(region_tree) def business_tree(self): return { ('services', 'services', 'Services'): { ('reservations', 'reservations', 'Reservations'): { ('res_host', 'res_host', 'Res Host'): {}, ('res_gui', 'res_gui', 'Res GUI'): {}, }, ('check_in', 'check_in', 'Check-in'): { ('dcs_host', 'dcs_host', 'DCS Host'): {}, }, }, ('infrastructure', 'infrastructure', 'Infrastructure'): { ('communication_network', 'communication_network', 'Communication/Network'): { ('messaging', 'messaging', 'Messaging'): {}, }, ('data_transaction', 'data_transaction', 'Data/Transaction'): { ('database', 'database', 'Database'): {}, }, ('security', 'security', 'Security'): {}, }, } def tree_vocab_3(self): return self._getTargetClass().fromDict(self.business_tree()) def test_only_titled_if_triples(self): from zope.schema.interfaces import ITitledTokenizedTerm no_titles = self.tree_vocab_2() for term in no_titles: self.assertIsNone(term.title) self.assertFalse(ITitledTokenizedTerm.providedBy(term)) all_titles = self.tree_vocab_3() for term in all_titles: self.assertIsNotNone(term.title) self.assertTrue(ITitledTokenizedTerm.providedBy(term)) def test_implementation(self): from zope.interface.verify import verifyObject from zope.interface.common.mapping import IEnumerableMapping from zope.schema.interfaces import ITreeVocabulary from zope.schema.interfaces import IVocabulary from zope.schema.interfaces import IVocabularyTokenized for v in [self.tree_vocab_2(), self.tree_vocab_3()]: self.assertTrue(verifyObject(IEnumerableMapping, v)) self.assertTrue(verifyObject(IVocabulary, v)) self.assertTrue(verifyObject(IVocabularyTokenized, v)) self.assertTrue(verifyObject(ITreeVocabulary, v)) def test_additional_interfaces(self): from zope.interface import Interface class IStupid(Interface): pass v = self._getTargetClass().fromDict({('one', '1'): {}}, IStupid) self.assertTrue(IStupid.providedBy(v)) def test_ordering(self): # The TreeVocabulary makes use of an OrderedDict to store its # internal tree representation. # # Check that the keys are indeed ordered. from collections import OrderedDict d = { (1, 'new_york', 'New York'): { (2, 'ny_albany', 'Albany'): {}, (3, 'ny_new_york', 'New York'): {}, }, (4, 'california', 'California'): { (5, 'ca_los_angeles', 'Los Angeles'): {}, (6, 'ca_san_francisco', 'San Francisco'): {}, }, (7, 'texas', 'Texas'): {}, (8, 'florida', 'Florida'): {}, (9, 'utah', 'Utah'): {}, } dict_ = OrderedDict(sorted(d.items(), key=lambda t: t[0])) vocab = self._getTargetClass().fromDict(dict_) # Test keys self.assertEqual( [k.token for k in vocab.keys()], ['1', '4', '7', '8', '9'] ) # Test __iter__ self.assertEqual( [k.token for k in vocab], ['1', '4', '7', '8', '9'] ) self.assertEqual( [k.token for k in vocab[[k for k in vocab.keys()][0]].keys()], ['2', '3'] ) self.assertEqual( [k.token for k in vocab[[k for k in vocab.keys()][1]].keys()], ['5', '6'] ) def test_indexes(self): # TreeVocabulary creates three indexes for quick lookups, # term_by_value, term_by_value and path_by_value. tv2 = self.tree_vocab_2() self.assertEqual( [k for k in sorted(tv2.term_by_value.keys())], ['Ausserfern', 'Austria', 'Bavaria', 'Germany', 'Regions', 'Tyrol'] ) self.assertEqual( [k for k in sorted(tv2.term_by_token.keys())], ['auss', 'aut', 'bav', 'ger', 'regions', 'tyr'] ) self.assertEqual( [k for k in sorted(tv2.path_by_value.keys())], ['Ausserfern', 'Austria', 'Bavaria', 'Germany', 'Regions', 'Tyrol'] ) self.assertEqual( [k for k in sorted(tv2.path_by_value.values())], [ ['Regions'], ['Regions', 'Austria'], ['Regions', 'Austria', 'Tyrol'], ['Regions', 'Austria', 'Tyrol', 'Ausserfern'], ['Regions', 'Germany'], ['Regions', 'Germany', 'Bavaria'], ] ) self.assertEqual( [k for k in sorted(self.tree_vocab_3().term_by_value.keys())], [ 'check_in', 'communication_network', 'data_transaction', 'database', 'dcs_host', 'infrastructure', 'messaging', 'res_gui', 'res_host', 'reservations', 'security', 'services', ] ) self.assertEqual( [k for k in sorted(self.tree_vocab_3().term_by_token.keys())], [ 'check_in', 'communication_network', 'data_transaction', 'database', 'dcs_host', 'infrastructure', 'messaging', 'res_gui', 'res_host', 'reservations', 'security', 'services', ] ) self.assertEqual( [k for k in sorted(self.tree_vocab_3().path_by_value.values())], [ ['infrastructure'], ['infrastructure', 'communication_network'], ['infrastructure', 'communication_network', 'messaging'], ['infrastructure', 'data_transaction'], ['infrastructure', 'data_transaction', 'database'], ['infrastructure', 'security'], ['services'], ['services', 'check_in'], ['services', 'check_in', 'dcs_host'], ['services', 'reservations'], ['services', 'reservations', 'res_gui'], ['services', 'reservations', 'res_host'], ] ) def test_termpath(self): tv2 = self.tree_vocab_2() tv3 = self.tree_vocab_3() self.assertEqual( tv2.getTermPath('Bavaria'), ['Regions', 'Germany', 'Bavaria'] ) self.assertEqual( tv2.getTermPath('Austria'), ['Regions', 'Austria'] ) self.assertEqual( tv2.getTermPath('Ausserfern'), ['Regions', 'Austria', 'Tyrol', 'Ausserfern'] ) self.assertEqual( tv2.getTermPath('Non-existent'), [] ) self.assertEqual( tv3.getTermPath('database'), ["infrastructure", "data_transaction", "database"] ) def test_len(self): # len returns the number of all nodes in the dict self.assertEqual(len(self.tree_vocab_2()), 1) self.assertEqual(len(self.tree_vocab_3()), 2) def test_contains(self): tv2 = self.tree_vocab_2() self.assertTrue('Regions' in tv2 and 'Austria' in tv2 and 'Bavaria' in tv2) self.assertTrue('bav' not in tv2) self.assertTrue('foo' not in tv2) self.assertTrue({} not in tv2) # not hashable tv3 = self.tree_vocab_3() self.assertTrue('database' in tv3 and 'security' in tv3 and 'services' in tv3) self.assertTrue('Services' not in tv3) self.assertTrue('Database' not in tv3) self.assertTrue({} not in tv3) # not hashable def test_values_and_items(self): for v in (self.tree_vocab_2(), self.tree_vocab_3()): for term in v: self.assertEqual([i for i in v.values()], [i for i in v._terms.values()]) self.assertEqual([i for i in v.items()], [i for i in v._terms.items()]) def test_get(self): for v in [self.tree_vocab_2(), self.tree_vocab_3()]: for key, value in v.items(): self.assertEqual(v.get(key), value) self.assertEqual(v[key], value) def test_get_term(self): for v in (self.tree_vocab_2(), self.tree_vocab_3()): for term in v: self.assertTrue(v.getTerm(term.value) is term) self.assertTrue(v.getTermByToken(term.token) is term) self.assertRaises(LookupError, v.getTerm, 'non-present-value') self.assertRaises(LookupError, v.getTermByToken, 'non-present-token') def test_nonunique_values_and_tokens(self): # Since we do term and value lookups, all terms' values and tokens # must be unique. This rule applies recursively. self.assertRaises( ValueError, self._getTargetClass().fromDict, { ('one', '1'): {}, ('two', '1'): {}, }) self.assertRaises( ValueError, self._getTargetClass().fromDict, { ('one', '1'): {}, ('one', '2'): {}, }) # Even nested tokens must be unique. self.assertRaises( ValueError, self._getTargetClass().fromDict, { ('new_york', 'New York'): { ('albany', 'Albany'): {}, ('new_york', 'New York'): {}, }, }) # The same applies to nested values. self.assertRaises( ValueError, self._getTargetClass().fromDict, { ('1', 'new_york'): { ('2', 'albany'): {}, ('3', 'new_york'): {}, }, }) # The title attribute does however not have to be unique. self._getTargetClass().fromDict({ ('1', 'new_york', 'New York'): { ('2', 'ny_albany', 'Albany'): {}, ('3', 'ny_new_york', 'New York'): {}, }, }) self._getTargetClass().fromDict({ ('one', '1', 'One'): {}, ('two', '2', 'One'): {}, }) def test_nonunique_value_message(self): try: self._getTargetClass().fromDict({ ('one', '1'): {}, ('two', '1'): {}, }) except ValueError as e: self.assertEqual(str(e), "Term values must be unique: '1'") def test_nonunique_token_message(self): try: self._getTargetClass().fromDict({ ('one', '1'): {}, ('one', '2'): {}, }) except ValueError as e: self.assertEqual(str(e), "Term tokens must be unique: 'one'") def test_recursive_methods(self): # Test the _createTermTree and _getPathToTreeNode methods from zope.schema.vocabulary import _createTermTree tree = _createTermTree({}, self.business_tree()) vocab = self._getTargetClass().fromDict(self.business_tree()) term_path = vocab._getPathToTreeNode(tree, "infrastructure") vocab_path = vocab._getPathToTreeNode(vocab, "infrastructure") self.assertEqual(term_path, vocab_path) self.assertEqual(term_path, ["infrastructure"]) term_path = vocab._getPathToTreeNode(tree, "security") vocab_path = vocab._getPathToTreeNode(vocab, "security") self.assertEqual(term_path, vocab_path) self.assertEqual(term_path, ["infrastructure", "security"]) term_path = vocab._getPathToTreeNode(tree, "database") vocab_path = vocab._getPathToTreeNode(vocab, "database") self.assertEqual(term_path, vocab_path) self.assertEqual(term_path, ["infrastructure", "data_transaction", "database"]) term_path = vocab._getPathToTreeNode(tree, "dcs_host") vocab_path = vocab._getPathToTreeNode(vocab, "dcs_host") self.assertEqual(term_path, vocab_path) self.assertEqual(term_path, ["services", "check_in", "dcs_host"]) term_path = vocab._getPathToTreeNode(tree, "dummy") vocab_path = vocab._getPathToTreeNode(vocab, "dummy") self.assertEqual(term_path, vocab_path) self.assertEqual(term_path, []) class RegistryTests(unittest.TestCase): # Tests of the simple vocabulary and presentation registries. def setUp(self): from zope.schema.vocabulary import _clear _clear() def tearDown(self): from zope.schema.vocabulary import _clear _clear() def test_setVocabularyRegistry(self): from zope.schema.vocabulary import setVocabularyRegistry from zope.schema.vocabulary import getVocabularyRegistry r = _makeDummyRegistry() setVocabularyRegistry(r) self.assertTrue(getVocabularyRegistry() is r) def test_getVocabularyRegistry(self): from zope.schema.interfaces import IVocabularyRegistry from zope.schema.vocabulary import getVocabularyRegistry r = getVocabularyRegistry() self.assertTrue(IVocabularyRegistry.providedBy(r)) # TODO: still need to test the default implementation def _makeSampleVocabulary(): from zope.interface import implementer from zope.schema.interfaces import IVocabulary class SampleTerm(object): pass @implementer(IVocabulary) class SampleVocabulary(object): def __iter__(self): raise AssertionError("Not called") def __contains__(self, value): return 0 <= value < 10 def __len__(self): # pragma: no cover return 10 def getTerm(self, value): raise AssertionError("Not called.") return SampleVocabulary() def _makeDummyRegistry(): from zope.schema.vocabulary import VocabularyRegistry class DummyRegistry(VocabularyRegistry): def get(self, object, name): raise AssertionError("Not called") return DummyRegistry() zope.schema-6.2.0/src/zope/schema/vocabulary.py0000644000100100000240000004057314133212652021333 0ustar macstaff00000000000000############################################################################## # # Copyright (c) 2003 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Vocabulary support for schema. """ from collections import OrderedDict from zope.interface import directlyProvides from zope.interface import implementer from zope.interface import providedBy from zope.schema._compat import text_type from zope.schema.interfaces import ITitledTokenizedTerm from zope.schema.interfaces import ITokenizedTerm from zope.schema.interfaces import ITreeVocabulary from zope.schema.interfaces import IVocabularyRegistry from zope.schema.interfaces import IVocabularyTokenized # simple vocabularies performing enumerated-like tasks _marker = object() @implementer(ITokenizedTerm) class SimpleTerm(object): """ Simple tokenized term used by SimpleVocabulary. .. versionchanged:: 4.6.0 Implement equality and hashing based on the value, token and title. """ def __init__(self, value, token=None, title=None): """Create a term for *value* and *token*. If *token* is omitted, str(value) is used for the token, escaping any non-ASCII characters. If *title* is provided, term implements :class:`zope.schema.interfaces.ITitledTokenizedTerm`. """ self.value = value if token is None: token = value # In Python 3 str(bytes) returns str(repr(bytes)), which is not what # we want here. On the other hand, we want to try to keep the token as # readable as possible. On both 2 and 3, self.token should be a native # string (ASCIILine). if isinstance(token, bytes): token = token.decode('raw_unicode_escape') elif not isinstance(token, (str, text_type)): # Nothing we recognize as intended to be textual data. # Get its str() as promised token = str(token) if isinstance(token, text_type): # pragma: PY2 token = token.encode('ascii', 'backslashreplace') # Token should be bytes at this point. Now back to native string, # if needed. if not isinstance(token, str): # pragma: PY2 token = token.decode('ascii') self.token = token self.title = title if title is not None: directlyProvides(self, ITitledTokenizedTerm) def __eq__(self, other): if other is self: return True if not isinstance(other, SimpleTerm): return False return ( self.value == other.value and self.token == other.token and self.title == other.title ) def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash((self.value, self.token, self.title)) @implementer(IVocabularyTokenized) class SimpleVocabulary(object): """ Vocabulary that works from a sequence of terms. .. versionchanged:: 4.6.0 Implement equality and hashing based on the terms list and interfaces implemented by this object. """ def __init__(self, terms, *interfaces, **kwargs): """Initialize the vocabulary given a list of terms. The vocabulary keeps a reference to the list of terms passed in; it should never be modified while the vocabulary is used. One or more interfaces may also be provided so that alternate widgets may be bound without subclassing. By default, ValueErrors are thrown if duplicate values or tokens are passed in. If you want to swallow these exceptions, pass in ``swallow_duplicates=True``. In this case, the values will override themselves. """ self.by_value = {} self.by_token = {} self._terms = terms swallow_dupes = kwargs.get('swallow_duplicates', False) 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)) if term.token in self.by_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: directlyProvides(self, *interfaces) @classmethod def fromItems(cls, items, *interfaces): """ Construct a vocabulary from a list of (token, value) pairs or (token, value, title) triples. The list does not have to be homogeneous. The order of the items is preserved as the order of the terms in the vocabulary. Terms are created by calling the class method :meth:`createTerm`` with the pair or triple. One or more interfaces may also be provided so that alternate widgets may be bound without subclassing. .. 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] return cls(terms, *interfaces) @classmethod def fromValues(cls, values, *interfaces): """Construct a vocabulary from a simple list. Values of the list become both the tokens and values of the terms in the vocabulary. The order of the values is preserved as the order of the terms in the vocabulary. Tokens are created by calling the class method :meth:`createTerm()` with the value as the only parameter. One or more interfaces may also be provided so that alternate widgets may be bound without subclassing. """ terms = [cls.createTerm(value) for value in values] return cls(terms, *interfaces) @classmethod def createTerm(cls, *args): """Create a single term from data. Subclasses may override this with a class method that creates a term of the appropriate type from the arguments. """ return SimpleTerm(*args) def __contains__(self, value): """See zope.schema.interfaces.IBaseVocabulary""" try: return value in self.by_value except TypeError: # sometimes values are not hashable return False def getTerm(self, value): """See zope.schema.interfaces.IBaseVocabulary""" try: return self.by_value[value] except KeyError: raise LookupError(value) def getTermByToken(self, token): """See zope.schema.interfaces.IVocabularyTokenized""" try: return self.by_token[token] except KeyError: raise LookupError(token) def __iter__(self): """See zope.schema.interfaces.IIterableVocabulary""" return iter(self._terms) def __len__(self): """See zope.schema.interfaces.IIterableVocabulary""" return len(self.by_value) def __eq__(self, other): if other is self: return True if not isinstance(other, SimpleVocabulary): return False return ( self._terms == other._terms and providedBy(self) == providedBy(other) ) def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash(tuple(self._terms)) def _createTermTree(ttree, dict_): """ Helper method that creates a tree-like dict with ITokenizedTerm objects as keys from a similar tree with tuples as keys. See fromDict for more details. """ for key in sorted(dict_.keys()): term = SimpleTerm(key[1], key[0], *key[2:]) ttree[term] = TreeVocabulary.terms_factory() _createTermTree(ttree[term], dict_[key]) return ttree @implementer(ITreeVocabulary) class TreeVocabulary(object): """ Vocabulary that relies on a tree (i.e nested) structure. """ # The default implementation uses a dict to create the tree structure. This # can however be overridden in a subclass by any other IEnumerableMapping # compliant object type. Python 2.7's OrderedDict for example. terms_factory = OrderedDict def __init__(self, terms, *interfaces): """Initialize the vocabulary given a recursive dict (i.e a tree) with ITokenizedTerm objects for keys and self-similar dicts representing the branches for values. Refer to the method fromDict for more details. Concerning the ITokenizedTerm keys, the 'value' and 'token' attributes of each key (including nested ones) must be unique. One or more interfaces may also be provided so that alternate widgets may be bound without subclassing. """ self._terms = self.terms_factory() self._terms.update(terms) self.path_by_value = {} self.term_by_value = {} self.term_by_token = {} self._populateIndexes(terms) if interfaces: directlyProvides(self, *interfaces) def __contains__(self, value): """ See zope.schema.interfaces.IBaseVocabulary D.__contains__(k) -> True if D has a key k, else False """ try: return value in self.term_by_value except TypeError: # sometimes values are not hashable return False def __getitem__(self, key): """x.__getitem__(y) <==> x[y] """ return self._terms.__getitem__(key) def __iter__(self): """See zope.schema.interfaces.IIterableVocabulary x.__iter__() <==> iter(x) """ return self._terms.__iter__() def __len__(self): """x.__len__() <==> len(x) """ return self._terms.__len__() def get(self, key, default=None): """Get a value for a key The default is returned if there is no value for the key. """ return self._terms.get(key, default) def keys(self): """Return the keys of the mapping object. """ return self._terms.keys() def values(self): """Return the values of the mapping object. """ return self._terms.values() def items(self): """Return the items of the mapping object. """ return self._terms.items() @classmethod def fromDict(cls, dict_, *interfaces): """Constructs a vocabulary from a dictionary-like object (like dict or OrderedDict), that has tuples for keys. The tuples should have either 2 or 3 values, i.e: (token, value, title) or (token, value). Only tuples that have three values will create a :class:`zope.schema.interfaces.ITitledTokenizedTerm`. For example, a dict with 2-valued tuples:: dict_ = { ('exampleregions', 'Regions used in ATVocabExample'): { ('aut', 'Austria'): { ('tyr', 'Tyrol'): { ('auss', 'Ausserfern'): {}, } }, ('ger', 'Germany'): { ('bav', 'Bavaria'):{} }, } } One or more interfaces may also be provided so that alternate widgets may be bound without subclassing. .. versionchanged:: 4.6.0 Only create ``ITitledTokenizedTerm`` when a title is actually provided. """ return cls(_createTermTree(cls.terms_factory(), dict_), *interfaces) def _populateIndexes(self, tree): """ The TreeVocabulary contains three helper indexes for quick lookups. They are: term_by_value, term_by_token and path_by_value This method recurses through the tree and populates these indexes. tree: The tree (a nested/recursive dictionary). """ for term in tree.keys(): value = getattr(term, 'value') token = getattr(term, 'token') if value in self.term_by_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) 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._populateIndexes(tree[term]) def getTerm(self, value): """See zope.schema.interfaces.IBaseVocabulary""" try: return self.term_by_value[value] except KeyError: raise LookupError(value) def getTermByToken(self, token): """See zope.schema.interfaces.IVocabularyTokenized""" try: return self.term_by_token[token] except KeyError: raise LookupError(token) def _getPathToTreeNode(self, tree, node): """Helper method that computes the path in the tree from the root to the given node. The tree must be a recursive IEnumerableMapping object. """ path = [] for parent, child in tree.items(): if node == parent.value: return [node] path = self._getPathToTreeNode(child, node) if path: path.insert(0, parent.value) break return path def getTermPath(self, value): """Returns a list of strings representing the path from the root node to the node with the given value in the tree. Returns an empty string if no node has that value. """ return self.path_by_value.get(value, []) # registry code class VocabularyRegistryError(LookupError): """ A specialized subclass of `LookupError` raised for unknown (unregistered) vocabularies. .. seealso:: `VocabularyRegistry` """ def __init__(self, name): self.name = name super(VocabularyRegistryError, self).__init__(str(self)) def __str__(self): return "unknown vocabulary: %r" % self.name @implementer(IVocabularyRegistry) class VocabularyRegistry(object): """ Default implementation of :class:`zope.schema.interfaces.IVocabularyRegistry`. An instance of this class is used by default by :func:`getVocabularyRegistry`, which in turn is used by :class:`~.Choice` fields. Named vocabularies must be manually registered with this object using :meth:`register`. This associates a vocabulary name with a :class:`zope.schema.interfaces.IVocabularyFactory`. An alternative to this is to use the :mod:`zope.component` registry via `zope.vocabularyregistry `_. """ __slots__ = ('_map',) def __init__(self): self._map = {} def get(self, context, name): """See zope.schema.interfaces.IVocabularyRegistry""" try: vtype = self._map[name] except KeyError: raise VocabularyRegistryError(name) return vtype(context) def register(self, name, factory): """Register a *factory* for the vocabulary with the given *name*.""" self._map[name] = factory _vocabularies = None def getVocabularyRegistry(): """Return the vocabulary registry. If the registry has not been created yet, an instance of VocabularyRegistry will be installed and used. """ if _vocabularies is None: setVocabularyRegistry(VocabularyRegistry()) return _vocabularies def setVocabularyRegistry(registry): """Set the vocabulary registry.""" global _vocabularies _vocabularies = registry def _clear(): """Remove the registries (for use by tests).""" global _vocabularies _vocabularies = None try: from zope.testing.cleanup import addCleanUp except ImportError: # pragma: no cover # don't have that part of Zope pass else: # pragma: no cover addCleanUp(_clear) del addCleanUp zope.schema-6.2.0/src/zope.schema.egg-info/0000755000100100000240000000000014133212652020272 5ustar macstaff00000000000000zope.schema-6.2.0/src/zope.schema.egg-info/PKG-INFO0000644000100100000240000007115114133212652021374 0ustar macstaff00000000000000Metadata-Version: 2.1 Name: zope.schema Version: 6.2.0 Summary: zope.interface extension for defining data schemas Home-page: https://github.com/zopefoundation/zope.schema Author: Zope Foundation and Contributors Author-email: zope-dev@zope.org License: ZPL 2.1 Description: ============= zope.schema ============= .. image:: https://img.shields.io/pypi/v/zope.schema.svg :target: https://pypi.org/project/zope.schema/ :alt: Latest Version .. image:: https://img.shields.io/pypi/pyversions/zope.schema.svg :target: https://pypi.org/project/zope.schema/ :alt: Supported Python versions .. image:: https://github.com/zopefoundation/zope.schema/workflows/tests/badge.svg :target: https://github.com/zopefoundation/zope.schema/actions?query=workflow%3Atests :alt: Tests Status .. image:: https://readthedocs.org/projects/zopeschema/badge/?version=latest :target: https://zopeschema.readthedocs.org/en/latest/ :alt: Documentation Status .. image:: https://coveralls.io/repos/github/zopefoundation/zope.schema/badge.svg :target: https://coveralls.io/github/zopefoundation/zope.schema :alt: Code Coverage Schemas extend the notion of interfaces to detailed descriptions of Attributes (but not methods). Every schema is an interface and specifies the public fields of an object. A *field* roughly corresponds to an attribute of a Python object. But a Field provides space for at least a title and a description. It can also constrain its value and provide a validation method. Besides you can optionally specify characteristics such as its value being read-only or not required. See https://zopeschema.readthedocs.io/ for more information. ========= Changes ========= 6.2.0 (2021-10-18) ================== - Add support for Python 3.10. 6.1.1 (2021-10-13) ================== - Fix incompatibility introduced in 6.1.0: The `Bool` field constructor implicitly set required to False if not given. While this is the desired behavior in most common cases, it broke special cases. See `issue 104 `_ (scroll down, it is around the *reopen*). 6.1.0 (2021-02-09) ================== - Fix ``IField.required`` to not be required by default. See `issue 104 `_. 6.0.1 (2021-01-25) ================== - Bring branch coverage to 100%. - Add support for Python 3.9. - Fix FieldUpdateEvent implementation by having an ``object`` attribute as the ``IFieldUpdatedEvent`` interfaces claims there should be. 6.0.0 (2020-03-21) ================== - Require zope.interface 5.0. - Ensure the resolution orders of all fields are consistent and make sense. In particular, ``Bool`` fields now correctly implement ``IBool`` before ``IFromUnicode``. See `issue 80 `_. - Add support for Python 3.8. - Drop support for Python 3.4. 5.0.1 (2020-03-06) ================== - Fix: add ``Text.unicode_normalization = 'NFC'`` as default, because some are persisting schema fields. Setting that attribute only in ``__init__`` breaks loading old objects. 5.0 (2020-03-06) ================ - Set ``IDecimal`` attributes ``min``, ``max`` and ``default`` as ``Decimal`` type instead of ``Number``. See `issue 88 `_. - Enable unicode normalization for ``Text`` fields. The default is NFC normalization. Valid forms are 'NFC', 'NFKC', 'NFD', and 'NFKD'. To disable normalization, set ``unicode_normalization`` to ``False`` or ``None`` when calling ``__init__`` of the ``Text`` field. See `issue 86 `_. 4.9.3 (2018-10-12) ================== - Fix a ReST error in getDoc() results when having "subfields" with titles. 4.9.2 (2018-10-11) ================== - Make sure that the title for ``IObject.validate_invariants`` is a unicode string. 4.9.1 (2018-10-05) ================== - Fix ``SimpleTerm`` token for non-ASCII bytes values. 4.9.0 (2018-09-24) ================== - Make ``NativeString`` and ``NativeStringLine`` distinct types that implement the newly-distinct interfaces ``INativeString`` and ``INativeStringLine``. Previously these were just aliases for either ``Text`` (on Python 3) or ``Bytes`` (on Python 2). - Fix ``Field.getDoc()`` when ``value_type`` or ``key_type`` is present. Previously it could produce ReST that generated Sphinx warnings. See `issue 76 `_. - Make ``DottedName`` accept leading underscores for each segment. - Add ``PythonIdentifier``, which accepts one segment of a dotted name, e.g., a python variable or class. 4.8.0 (2018-09-19) ================== - Add the interface ``IFromBytes``, which is implemented by the numeric and bytes fields, as well as ``URI``, ``DottedName``, and ``Id``. - Fix passing ``None`` as the description to a field constructor. See `issue 69 `_. 4.7.0 (2018-09-11) ================== - Make ``WrongType`` have an ``expected_type`` field. - Add ``NotAnInterface``, an exception derived from ``WrongType`` and ``SchemaNotProvided`` and raised by the constructor of ``Object`` and when validation fails for ``InterfaceField``. - Give ``SchemaNotProvided`` a ``schema`` field. - Give ``WrongContainedType`` an ``errors`` list. - Give ``TooShort``, ``TooLong``, ``TooBig`` and ``TooSmall`` a ``bound`` field and the common superclasses ``LenOutOfBounds``, ``OrderableOutOfBounds``, respectively, both of which inherit from ``OutOfBounds``. 4.6.2 (2018-09-10) ================== - Fix checking a field's constraint to set the ``field`` and ``value`` properties if the constraint raises a ``ValidationError``. See `issue 66 `_. 4.6.1 (2018-09-10) ================== - Fix the ``Field`` constructor to again allow ``MessageID`` values for the ``description``. This was a regression introduced with the fix for `issue 60 `_. See `issue 63 `_. 4.6.0 (2018-09-07) ================== - Add support for Python 3.7. - ``Object`` instances call their schema's ``validateInvariants`` method by default to collect errors from functions decorated with ``@invariant`` when validating. This can be disabled by passing ``validate_invariants=False`` to the ``Object`` constructor. See `issue 10 `_. - ``ValidationError`` can be sorted on Python 3. - ``DottedName`` and ``Id`` consistently handle non-ASCII unicode values on Python 2 and 3 by raising ``InvalidDottedName`` and ``InvalidId`` in ``fromUnicode`` respectively. Previously, a ``UnicodeEncodeError`` would be raised on Python 2 while Python 3 would raise the descriptive exception. - ``Field`` instances are hashable on Python 3, and use a defined hashing algorithm that matches what equality does on all versions of Python. Previously, on Python 2, fields were hashed based on their identity. This violated the rule that equal objects should have equal hashes, and now they do. Since having equal hashes does not imply that the objects are equal, this is not expected to be a compatibility problem. See `issue 36 `_. - ``Field`` instances are only equal when their ``.interface`` is equal. In practice, this means that two otherwise identical fields of separate schemas are not equal, do not hash the same, and can both be members of the same ``dict`` or ``set``. Prior to this release, when hashing was identity based but only worked on Python 2, that was the typical behaviour. (Field objects that are *not* members of a schema continue to compare and hash equal if they have the same attributes and interfaces.) See `issue 40 `_. - Orderable fields, including ``Int``, ``Float``, ``Decimal``, ``Timedelta``, ``Date`` and ``Time``, can now have a ``missing_value`` without needing to specify concrete ``min`` and ``max`` values (they must still specify a ``default`` value). See `issue 9 `_. - ``Choice``, ``SimpleVocabulary`` and ``SimpleTerm`` all gracefully handle using Unicode token values with non-ASCII characters by encoding them with the ``backslashreplace`` error handler. See `issue 15 `_ and `PR 6 `_. - All instances of ``ValidationError`` have a ``field`` and ``value`` attribute that is set to the field that raised the exception and the value that failed validation. - ``Float``, ``Int`` and ``Decimal`` fields raise ``ValidationError`` subclasses for literals that cannot be parsed. These subclasses also subclass ``ValueError`` for backwards compatibility. - Add a new exception ``SchemaNotCorrectlyImplemented``, a subclass of ``WrongContainedType`` that is raised by the ``Object`` field. It has a dictionary (``schema_errors``) mapping invalid schema attributes to their corresponding exception, and a list (``invariant_errors``) containing the exceptions raised by validating invariants. See `issue 16 `_. - Add new fields ``Mapping`` and ``MutableMapping``, corresponding to the collections ABCs of the same name; ``Dict`` now extends and specializes ``MutableMapping`` to only accept instances of ``dict``. - Add new fields ``Sequence`` and ``MutableSequence``, corresponding to the collections ABCs of the same name; ``Tuple`` now extends ``Sequence`` and ``List`` now extends ``MutableSequence``. - Add new field ``Collection``, implementing ``ICollection``. This is the base class of ``Sequence``. Previously this was known as ``AbstractCollection`` and was not public. It can be subclassed to add ``value_type``, ``_type`` and ``unique`` attributes at the class level, enabling a simpler constructor call. See `issue 23 `_. - Make ``Object`` respect a ``schema`` attribute defined by a subclass, enabling a simpler constructor call. See `issue 23 `_. - Add fields and interfaces representing Python's numeric tower. In descending order of generality these are ``Number``, ``Complex``, ``Real``, ``Rational`` and ``Integral``. The ``Int`` class extends ``Integral``, the ``Float`` class extends ``Real``, and the ``Decimal`` class extends ``Number``. See `issue 49 `_. - Make ``Iterable`` and ``Container`` properly implement ``IIterable`` and ``IContainer``, respectively. - Make ``SimpleVocabulary.fromItems`` accept triples to allow specifying the title of terms. See `issue 18 `_. - Make ``TreeVocabulary.fromDict`` only create ``ITitledTokenizedTerms`` when a title is actually provided. - Make ``Choice`` fields reliably raise a ``ValidationError`` when a named vocabulary cannot be found; for backwards compatibility this is also a ``ValueError``. Previously this only worked when the default ``VocabularyRegistry`` was in use, not when it was replaced with `zope.vocabularyregistry `_. See `issue 55 `_. - Make ``SimpleVocabulary`` and ``SimpleTerm`` have value-based equality and hashing methods. - All fields of the schema of an ``Object`` field are bound to the top-level value being validated before attempting validation of their particular attribute. Previously only ``IChoice`` fields were bound. See `issue 17 `_. - Share the internal logic of ``Object`` field validation and ``zope.schema.getValidationErrors``. See `issue 57 `_. - Make ``Field.getDoc()`` return more information about the properties of the field, such as its required and readonly status. Subclasses can add more information using the new method ``Field.getExtraDocLines()``. This is used to generate Sphinx documentation when using `repoze.sphinx.autointerface `_. See `issue 60 `_. 4.5.0 (2017-07-10) ================== - Drop support for Python 2.6, 3.2, and 3.3. - Add support for Python 3.5 and 3.6. - Drop support for 'setup.py test'. Use zope.testrunner instead. 4.4.2 (2014-09-04) ================== - Fix description of min max field: max value is included, not excluded. 4.4.1 (2014-03-19) ================== - Add support for Python 3.4. 4.4.0 (2014-01-22) ================== - Add an event on field properties to notify that a field has been updated. This event enables definition of subscribers based on an event, a context and a field. The event contains also the old value and the new value. (also see package ``zope.schemaevent`` that define a field event handler) 4.3.3 (2014-01-06) ================== - PEP 8 cleanup. - Don't raise RequiredMissing if a field's defaultFactory returns the field's missing_value. - Update ``boostrap.py`` to version 2.2. - Add the ability to swallow ValueErrors when rendering a SimpleVocabulary, allowing for cases where vocabulary items may be duplicated (e.g., due to user input). - Include the field name in ``ConstraintNotSatisfied``. 4.3.2 (2013-02-24) ================== - Fix Python 2.6 support. (Forgot to run tox with all environments before last release.) 4.3.1 (2013-02-24) ================== - Make sure that we do not fail during bytes decoding of term token when generated from a bytes value by ignoring all errors. (Another option would have been to hexlify the value, but that would break way too many tests.) 4.3.0 (2013-02-24) ================== - Fix a bug where bytes values were turned into tokens inproperly in Python 3. - Add ``zope.schema.fieldproperty.createFieldProperties()`` function which maps schema fields into ``FieldProperty`` instances. 4.2.2 (2012-11-21) ================== - Add support for Python 3.3. 4.2.1 (2012-11-09) ================== - Fix the default property of fields that have no defaultFactory attribute. 4.2.0 (2012-05-12) ================== - Automate build of Sphinx HTML docs and running doctest snippets via tox. - Drop explicit support for Python 3.1. - Introduce NativeString and NativeStringLine which are equal to Bytes and BytesLine on Python 2 and Text and TextLine on Python 3. - Change IURI from a Bytes string to a "native" string. This is a backwards incompatibility which only affects Python 3. - Bring unit test coverage to 100%. - Move doctests from the package and wired up as normal Sphinx documentation. - Add explicit support for PyPy. - Add support for continuous integration using ``tox`` and ``jenkins``. - Drop the external ``six`` dependency in favor of a much-trimmed ``zope.schema._compat`` module. - Ensure tests pass when run under ``nose``. - Add ``setup.py dev`` alias (runs ``setup.py develop`` plus installs ``nose`` and ``coverage``). - Add ``setup.py docs`` alias (installs ``Sphinx`` and dependencies). 4.1.1 (2012-03-23) ================== - Remove trailing slash in MANIFEST.in, it causes Winbot to crash. 4.1.0 (2012-03-23) ================== - Add TreeVocabulary for nested tree-like vocabularies. - Fix broken Object field validation where the schema contains a Choice with ICountextSourceBinder source. In this case the vocabulary was not iterable because the field was not bound and the source binder didn't return the real vocabulary. Added simple test for IContextSourceBinder validation. But a test with an Object field with a schema using a Choice with IContextSourceBinder is still missing. 4.0.1 (2011-11-14) ================== - Fix bug in ``fromUnicode`` method of ``DottedName`` which would fail validation on being given unicode. Introduced in 4.0.0. 4.0.0 (2011-11-09) ================== - Fix deprecated unittest methods. - Port to Python 3. This adds a dependency on six and removes support for Python 2.5. 3.8.1 (2011-09-23) ================== - Fix broken Object field validation. Previous version was using a volatile property on object field values which ends in a ForbiddenAttribute error on security proxied objects. 3.8.0 (2011-03-18) ================== - Implement a ``defaultFactory`` attribute for all fields. It is a callable that can be used to compute default values. The simplest case is:: Date(defaultFactory=datetime.date.today) If the factory needs a context to compute a sensible default value, then it must provide ``IContextAwareDefaultFactory``, which can be used as follows:: @provider(IContextAwareDefaultFactory) def today(context): return context.today() Date(defaultFactory=today) 3.7.1 (2010-12-25) ================== - Rename the validation token, used in the validation of schema with Object Field to avoid infinite recursion: ``__schema_being_validated`` became ``_v_schema_being_validated``, a volatile attribute, to avoid persistency and therefore, read/write conflicts. - Don't allow "[\]^`" in DottedName. https://bugs.launchpad.net/zope.schema/+bug/191236 3.7.0 (2010-09-12) ================== - Improve error messages when term tokens or values are duplicates. - Fix the buildout so the tests run. 3.6.4 (2010-06-08) ================== - fix validation of schema with Object Field that specify Interface schema. 3.6.3 (2010-04-30) ================== - Prefer the standard libraries doctest module to the one from zope.testing. 3.6.2 (2010-04-30) ================== - Avoid maximum recursion when validating Object field that points to cycles - Make the dependency on ``zope.i18nmessageid`` optional. 3.6.1 (2010-01-05) ================== - Allow "setup.py test" to run at least a subset of the tests runnable via ``bin/test`` (227 for ``setup.py test`` vs. 258. for ``bin/test``) - Make ``zope.schema._bootstrapfields.ValidatedProperty`` descriptor work under Jython. - Make "setup.py test" tests pass on Jython. 3.6.0 (2009-12-22) ================== - Prefer zope.testing.doctest over doctestunit. - Extend validation error to hold the field name. - Add FieldProperty class that uses Field.get and Field.set methods instead of storing directly on the instance __dict__. 3.5.4 (2009-03-25) ================== - Don't fail trying to validate default value for Choice fields with IContextSourceBinder object given as a source. See https://bugs.launchpad.net/zope3/+bug/340416. - Add an interface for ``DottedName`` field. - Add ``vocabularyName`` attribute to the ``IChoice`` interface, change "vocabulary" attribute description to be more sensible, making it ``zope.schema.Field`` instead of plain ``zope.interface.Attribute``. - Make IBool interface of Bool more important than IFromUnicode so adapters registered for IBool take precendence over adapters registered for IFromUnicode. 3.5.3 (2009-03-10) ================== - Make Choice and Bool fields implement IFromUnicode interface, because they do provide the ``fromUnicode`` method. - Change package's mailing list address to zope-dev at zope.org, as zope3-dev at zope.org is now retired. - Fix package's documentation formatting. Change package's description. - Add buildout part that builds Sphinx-generated documentation. - Remove zpkg-related file. 3.5.2 (2009-02-04) ================== - Made validation tests compatible with Python 2.5 again (hopefully not breaking Python 2.4) - Add an __all__ package attribute to expose documentation. 3.5.1 (2009-01-31) ================== - Stop using the old old set type. - Make tests compatible and silent with Python 2.4. - Fix __cmp__ method in ValidationError. Show some side effects based on the existing __cmp__ implementation. See validation.txt - Make 'repr' of the ValidationError and its subclasses more sensible. This may require you to adapt your doctests for the new style, but now it makes much more sense for debugging for developers. 3.5.0a2 (2008-12-11) ==================== - Move zope.testing to "test" extras_require, as it is not needed for zope.schema itself. - Change the order of classes in SET_TYPES tuple, introduced in previous release to one that was in 3.4 (SetType, set), because third-party code could be dependent on that order. The one example is z3c.form's converter. 3.5.0a1 (2008-10-10) ==================== - Add the doctests to the long description. - Remove use of deprecated 'sets' module when running under Python 2.6. - Remove spurious doctest failure when running under Python 2.6. - Add support to bootstrap on Jython. - Add helper methods for schema validation: ``getValidationErrors`` and ``getSchemaValidationErrors``. - zope.schema now works on Python2.5 3.4.0 (2007-09-28) ================== Add BeforeObjectAssignedEvent that is triggered before the object field sets a value. 3.3.0 (2007-03-15) ================== Corresponds to the version of the zope.schema package shipped as part of the Zope 3.3.0 release. 3.2.1 (2006-03-26) ================== Corresponds to the version of the zope.schema package shipped as part of the Zope 3.2.1 release. Fix missing import of 'VocabularyRegistryError'. See http://www.zope.org/Collectors/Zope3-dev/544 . 3.2.0 (2006-01-05) ================== Corresponds to the version of the zope.schema package shipped as part of the Zope 3.2.0 release. Add "iterable" sources to replace vocabularies, which are now deprecated and scheduled for removal in Zope 3.3. 3.1.0 (2005-10-03) ================== Corresponds to the version of the zope.schema package shipped as part of the Zope 3.1.0 release. Allow 'Choice' fields to take either a 'vocabulary' or a 'source' argument (sources are a simpler implementation). Add 'TimeDelta' and 'ASCIILine' field types. 3.0.0 (2004-11-07) ================== Corresponds to the version of the zope.schema package shipped as part of the Zope X3.0.0 release. Keywords: zope3 schema field interface typing Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Zope Public License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Framework :: Zope :: 3 Classifier: Topic :: Software Development :: Libraries :: Python Modules Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.* Provides-Extra: docs Provides-Extra: test zope.schema-6.2.0/src/zope.schema.egg-info/SOURCES.txt0000644000100100000240000000260114133212652022155 0ustar macstaff00000000000000CHANGES.rst COPYRIGHT.txt LICENSE.txt MANIFEST.in README.rst buildout.cfg rtd.txt setup.cfg setup.py tox.ini version.txt docs/Makefile docs/api.rst docs/changelog.rst docs/conf.py docs/fields.rst docs/hacking.rst docs/index.rst docs/make.bat docs/narr.rst docs/sources.rst docs/validation.rst src/zope/__init__.py src/zope.schema.egg-info/PKG-INFO src/zope.schema.egg-info/SOURCES.txt src/zope.schema.egg-info/dependency_links.txt src/zope.schema.egg-info/namespace_packages.txt src/zope.schema.egg-info/not-zip-safe src/zope.schema.egg-info/requires.txt src/zope.schema.egg-info/top_level.txt src/zope/schema/__init__.py src/zope/schema/_bootstrapfields.py src/zope/schema/_bootstrapinterfaces.py src/zope/schema/_compat.py src/zope/schema/_field.py src/zope/schema/_messageid.py src/zope/schema/_schema.py src/zope/schema/accessors.py src/zope/schema/fieldproperty.py src/zope/schema/interfaces.py src/zope/schema/vocabulary.py src/zope/schema/tests/__init__.py src/zope/schema/tests/states.py src/zope/schema/tests/test__bootstrapfields.py src/zope/schema/tests/test__bootstrapinterfaces.py src/zope/schema/tests/test__field.py src/zope/schema/tests/test_accessors.py src/zope/schema/tests/test_equality.py src/zope/schema/tests/test_fieldproperty.py src/zope/schema/tests/test_interfaces.py src/zope/schema/tests/test_schema.py src/zope/schema/tests/test_states.py src/zope/schema/tests/test_vocabulary.pyzope.schema-6.2.0/src/zope.schema.egg-info/dependency_links.txt0000644000100100000240000000000114133212652024340 0ustar macstaff00000000000000 zope.schema-6.2.0/src/zope.schema.egg-info/namespace_packages.txt0000644000100100000240000000000514133212652024620 0ustar macstaff00000000000000zope zope.schema-6.2.0/src/zope.schema.egg-info/not-zip-safe0000644000100100000240000000000114133212652022520 0ustar macstaff00000000000000 zope.schema-6.2.0/src/zope.schema.egg-info/requires.txt0000644000100100000240000000021714133212652022672 0ustar macstaff00000000000000setuptools zope.interface>=5.0.0 zope.event [docs] Sphinx repoze.sphinx.autointerface [test] zope.i18nmessageid zope.testing zope.testrunner zope.schema-6.2.0/src/zope.schema.egg-info/top_level.txt0000644000100100000240000000000514133212652023017 0ustar macstaff00000000000000zope zope.schema-6.2.0/tox.ini0000644000100100000240000000321314133212652015107 0ustar macstaff00000000000000# Generated from: # https://github.com/zopefoundation/meta/tree/master/config/pure-python [tox] minversion = 3.18 envlist = lint py27 py35 py36 py37 py38 py39 py310 pypy pypy3 docs coverage [testenv] usedevelop = true deps = commands = zope-testrunner --test-path=src {posargs:-vc} !py27-!pypy: sphinx-build -b doctest -d {envdir}/.cache/doctrees docs {envdir}/.cache/doctest extras = test docs [testenv:lint] basepython = python3 skip_install = true deps = flake8 check-manifest check-python-versions >= 0.19.1 wheel commands = flake8 src setup.py check-manifest check-python-versions [testenv:docs] basepython = python3 skip_install = false commands_pre = commands = sphinx-build -b html -d docs/_build/doctrees docs docs/_build/html sphinx-build -b doctest -d docs/_build/doctrees docs docs/_build/doctest [testenv:coverage] basepython = python3 allowlist_externals = mkdir deps = coverage coverage-python-version commands = mkdir -p {toxinidir}/parts/htmlcov coverage run -m zope.testrunner --test-path=src {posargs:-vc} coverage run -a -m sphinx -b doctest -d {envdir}/.cache/doctrees docs {envdir}/.cache/doctest coverage html coverage report -m --fail-under=100 [coverage:run] branch = True plugins = coverage_python_version source = zope.schema omit = src/zope/__init__.py [coverage:report] precision = 2 exclude_lines = pragma: no cover pragma: nocover except ImportError: raise NotImplementedError if __name__ == '__main__': self.fail raise AssertionError [coverage:html] directory = parts/htmlcov zope.schema-6.2.0/version.txt0000644000100100000240000000000614133212652016017 0ustar macstaff000000000000006.2.0