[Checkins] SVN: zope.schema/trunk/ Merge tseaver-test_cleanup branch to trunk.
Tres Seaver
cvs-admin at zope.org
Fri May 4 23:47:36 UTC 2012
Log message for revision 125654:
Merge tseaver-test_cleanup branch to trunk.
Includes the hand-merge of the jinty-native_string branch.
Changed:
_U zope.schema/trunk/
U zope.schema/trunk/.bzrignore
U zope.schema/trunk/CHANGES.txt
U zope.schema/trunk/README.txt
U zope.schema/trunk/buildout.cfg
A zope.schema/trunk/docs/
U zope.schema/trunk/docs/Makefile
U zope.schema/trunk/docs/conf.py
U zope.schema/trunk/docs/fields.rst
U zope.schema/trunk/docs/index.rst
U zope.schema/trunk/docs/make.bat
U zope.schema/trunk/docs/narr.rst
U zope.schema/trunk/docs/sources.rst
U zope.schema/trunk/docs/validation.rst
A zope.schema/trunk/setup.cfg
U zope.schema/trunk/setup.py
D zope.schema/trunk/src/zope/schema/README.txt
U zope.schema/trunk/src/zope/schema/__init__.py
U zope.schema/trunk/src/zope/schema/_bootstrapfields.py
U zope.schema/trunk/src/zope/schema/_bootstrapinterfaces.py
A zope.schema/trunk/src/zope/schema/_compat.py
U zope.schema/trunk/src/zope/schema/_field.py
U zope.schema/trunk/src/zope/schema/_messageid.py
U zope.schema/trunk/src/zope/schema/_schema.py
D zope.schema/trunk/src/zope/schema/fields.txt
D zope.schema/trunk/src/zope/schema/index.txt
U zope.schema/trunk/src/zope/schema/interfaces.py
D zope.schema/trunk/src/zope/schema/sources.txt
U zope.schema/trunk/src/zope/schema/tests/__init__.py
U zope.schema/trunk/src/zope/schema/tests/states.py
A zope.schema/trunk/src/zope/schema/tests/test__bootstrapfields.py
A zope.schema/trunk/src/zope/schema/tests/test__bootstrapinterfaces.py
A zope.schema/trunk/src/zope/schema/tests/test__field.py
U zope.schema/trunk/src/zope/schema/tests/test_accessors.py
D zope.schema/trunk/src/zope/schema/tests/test_boolfield.py
D zope.schema/trunk/src/zope/schema/tests/test_choice.py
D zope.schema/trunk/src/zope/schema/tests/test_containerfield.py
D zope.schema/trunk/src/zope/schema/tests/test_date.py
D zope.schema/trunk/src/zope/schema/tests/test_datetime.py
D zope.schema/trunk/src/zope/schema/tests/test_decimalfield.py
D zope.schema/trunk/src/zope/schema/tests/test_dictfield.py
D zope.schema/trunk/src/zope/schema/tests/test_docs.py
D zope.schema/trunk/src/zope/schema/tests/test_dotted_name.py
U zope.schema/trunk/src/zope/schema/tests/test_equality.py
D zope.schema/trunk/src/zope/schema/tests/test_field.py
U zope.schema/trunk/src/zope/schema/tests/test_fieldproperty.py
D zope.schema/trunk/src/zope/schema/tests/test_floatfield.py
D zope.schema/trunk/src/zope/schema/tests/test_interfacefield.py
A zope.schema/trunk/src/zope/schema/tests/test_interfaces.py
D zope.schema/trunk/src/zope/schema/tests/test_intfield.py
D zope.schema/trunk/src/zope/schema/tests/test_iterablefield.py
D zope.schema/trunk/src/zope/schema/tests/test_listfield.py
D zope.schema/trunk/src/zope/schema/tests/test_objectfield.py
U zope.schema/trunk/src/zope/schema/tests/test_schema.py
D zope.schema/trunk/src/zope/schema/tests/test_setfield.py
U zope.schema/trunk/src/zope/schema/tests/test_states.py
D zope.schema/trunk/src/zope/schema/tests/test_strfield.py
D zope.schema/trunk/src/zope/schema/tests/test_timedelta.py
D zope.schema/trunk/src/zope/schema/tests/test_tuplefield.py
U zope.schema/trunk/src/zope/schema/tests/test_vocabulary.py
D zope.schema/trunk/src/zope/schema/validation.txt
U zope.schema/trunk/src/zope/schema/vocabulary.py
A zope.schema/trunk/tox.ini
-=-
Property changes on: zope.schema/trunk
___________________________________________________________________
Added: svn:mergeinfo
+ /zope.schema/branches/tseaver-test_cleanup:125196,125200-125206,125210-125217,125222-125226,125241-125263,125282-125292,125312-125314,125647-125653
Added: svk:merge
+ 62d5b8a3-27da-0310-9561-8e5933582275:/zope.schema/branches/tseaver-test_cleanup:125653
Modified: zope.schema/trunk/.bzrignore
===================================================================
--- zope.schema/trunk/.bzrignore 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/.bzrignore 2012-05-04 23:47:32 UTC (rev 125654)
@@ -5,3 +5,9 @@
./docs
./parts
*.egg-info
+.coverage
+__pycache__
+nosetests.xml
+coverage.xml
+.tox
+docs/_build
Modified: zope.schema/trunk/CHANGES.txt
===================================================================
--- zope.schema/trunk/CHANGES.txt 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/CHANGES.txt 2012-05-04 23:47:32 UTC (rev 125654)
@@ -2,12 +2,34 @@
CHANGES
=======
-4.1.2 (unreleased)
+4.2.0 (unreleased)
------------------
-- Nothing changed yet.
+- 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.
+- 100% unit test coverage.
+
+- Doctests moved from the package and wired up as normal Sphinx documentation.
+
+- Added explicit support for PyPy.
+
+- Added support for continuous integration using ``tox`` and ``jenkins``.
+
+- Dropped the external ``six`` dependency in favor of a much-trimmed
+ ``zope.schema._compat`` module.
+
+- Tests now pass when run under ``nose``.
+
+- Added ``setup.py dev`` alias (runs ``setup.py develop`` plus installs
+ ``nose`` and ``coverage``).
+
+- Added ``setup.py docs`` alias (installs ``Sphinx`` and dependencies).
+
+
4.1.1 (2012-03-23)
------------------
Modified: zope.schema/trunk/README.txt
===================================================================
--- zope.schema/trunk/README.txt 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/README.txt 2012-05-04 23:47:32 UTC (rev 125654)
@@ -11,4 +11,4 @@
specify characteristics such as its value being read-only or not
required.
-See 'src/zope/schema/README.txt' for more information.
+See 'docs/index.rst' for more information.
Modified: zope.schema/trunk/buildout.cfg
===================================================================
--- zope.schema/trunk/buildout.cfg 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/buildout.cfg 2012-05-04 23:47:32 UTC (rev 125654)
@@ -5,10 +5,3 @@
[test]
recipe = zc.recipe.testrunner
eggs = zope.schema [test]
-
-[docs]
-recipe = z3c.recipe.sphinxdoc
-eggs = zope.schema [docs]
-build-dir = ${buildout:directory}/docs
-default.css =
-layout.html =
Copied: zope.schema/trunk/setup.cfg (from rev 125653, zope.schema/branches/tseaver-test_cleanup/setup.cfg)
===================================================================
--- zope.schema/trunk/setup.cfg (rev 0)
+++ zope.schema/trunk/setup.cfg 2012-05-04 23:47:32 UTC (rev 125654)
@@ -0,0 +1,11 @@
+[nosetests]
+nocapture=1
+cover-package=zope.schema
+cover-erase=1
+with-doctest=0
+where=src
+
+[aliases]
+dev = develop easy_install zope.schema[testing]
+docs = easy_install zope.schema[docs]
+
Modified: zope.schema/trunk/setup.py
===================================================================
--- zope.schema/trunk/setup.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/setup.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -65,33 +65,26 @@
'setuptools',
'zope.interface >= 3.6.0',
'zope.event',
- 'six',
]
if sys.version_info < (2, 7):
REQUIRES += ['ordereddict']
+TESTS_REQUIRE = ['zope.testing']
+
setup(name='zope.schema',
- version='4.1.2.dev0',
+ version='4.2.0.dev',
url='http://pypi.python.org/pypi/zope.schema',
license='ZPL 2.1',
description='zope.interface extension for defining data schemas',
author='Zope Foundation and Contributors',
author_email='zope-dev at zope.org',
- long_description=(read('src', 'zope', 'schema', 'README.txt')
- + '\n\n' +
- read('src', 'zope', 'schema', 'fields.txt')
- + '\n\n' +
- read('src', 'zope', 'schema', 'sources.txt')
- + '\n\n' +
- read('src', 'zope', 'schema', 'validation.txt')
- + '\n\n' +
- read('CHANGES.txt')),
+ long_description=(read('README.txt') + '\n\n' + read('CHANGES.txt')),
packages=find_packages('src'),
package_dir = {'': 'src'},
namespace_packages=['zope',],
- extras_require={'test': ['zope.testing'],
- 'docs': ['z3c.recipe.sphinxdoc']},
+ #extras_require={
+ # 'docs': ['z3c.recipe.sphinxdoc']},
install_requires=REQUIRES,
classifiers=[
"Development Status :: 5 - Production/Stable",
@@ -103,10 +96,17 @@
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.1",
"Programming Language :: Python :: 3.2",
+ "Programming Language :: Python :: Implementation :: CPython",
+ "Programming Language :: Python :: Implementation :: PyPy",
"Topic :: Software Development :: Libraries :: Python Modules",
],
include_package_data = True,
zip_safe = False,
test_suite='__main__.alltests',
- tests_require='zope.testing',
- )
+ tests_require=TESTS_REQUIRE,
+ extras_require={
+ 'docs': ['Sphinx'],
+ 'test': TESTS_REQUIRE,
+ 'testing': TESTS_REQUIRE + ['nose', 'coverage'],
+ },
+)
Deleted: zope.schema/trunk/src/zope/schema/README.txt
===================================================================
--- zope.schema/trunk/src/zope/schema/README.txt 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/README.txt 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,276 +0,0 @@
-==============
-Zope 3 Schemas
-==============
-
-Introduction
-------------
-
-*This package is intended to be independently reusable in any Python
-project. It is maintained by the* `Zope Toolkit project <http://docs.zope.org/zopetoolkit/>`_.
-
-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
-
-.. contents::
-
-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:
-
- >>> import zope.interface
- >>> import zope.schema
- >>> from six import u, b
-
- >>> 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:
-
- >>> @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:
-
- >>> title = u('Zope 3 Website')
- >>> url = b('http://dev.zope.org/Zope3')
-
-Now we, get the fields from the interface:
-
- >>> 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:
-
- >>> title_bound = title_field.bind(bm)
- >>> url_bound = url_field.bind(bm)
-
-Now that the fields are bound, we can finally validate the data:
-
- >>> 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:
-
- >>> url_bound.validate(u('http://zope.org/foo'))
- Traceback (most recent call last):
- ...
- WrongType: (u'http://zope.org/foo', <type 'str'>, 'url')
-
- >>> url_bound.validate(b('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:
-
- >>> 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:
-
- >>> 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:
-
- >>> class Contact(object):
- ... zope.interface.implements(IContact)
- ...
- ... 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:
-
- >>> someone = Contact(u('Tim'), u('Roberts'), u('tim at 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
Modified: zope.schema/trunk/src/zope/schema/__init__.py
===================================================================
--- zope.schema/trunk/src/zope/schema/__init__.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/__init__.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -13,19 +13,52 @@
##############################################################################
"""Schema package constructor
"""
-from zope.schema._field import Field, Container, Iterable, Orderable
-from zope.schema._field import MinMaxLen, Choice
-from zope.schema._field import Bytes, ASCII, BytesLine, ASCIILine
-from zope.schema._field import Text, TextLine, Bool, Int, Float, Decimal
-from zope.schema._field import Tuple, List, Set, FrozenSet
-from zope.schema._field import Password, Dict, Datetime, Date, Timedelta
-from zope.schema._field import Time, SourceText
-from zope.schema._field import Object, URI, Id, DottedName
+# 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 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 InterfaceField
-from zope.schema._schema import (
- getFields, getFieldsInOrder, getFieldNames, getFieldNamesInOrder,
- getValidationErrors, getSchemaValidationErrors)
+from zope.schema._field import Iterable
+from zope.schema._field import List
+from zope.schema._field import MinMaxLen
+from zope.schema._field import NativeString
+from zope.schema._field import NativeStringLine
+from zope.schema._field import Object
+from zope.schema._field import Orderable
+from zope.schema._field import Password
+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
-
-__all__ = tuple(name for name in globals() if not name.startswith('_'))
Modified: zope.schema/trunk/src/zope/schema/_bootstrapfields.py
===================================================================
--- zope.schema/trunk/src/zope/schema/_bootstrapfields.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/_bootstrapfields.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -15,19 +15,26 @@
"""
__docformat__ = 'restructuredtext'
-import sys
+from zope.interface import Attribute
+from zope.interface import providedBy
+from zope.interface import implementer
-from six import u, b, text_type, integer_types
-from zope.interface import Attribute, providedBy, implementer
-from zope.schema._bootstrapinterfaces import StopValidation
-from zope.schema._bootstrapinterfaces import IFromUnicode
-from zope.schema._bootstrapinterfaces import RequiredMissing, WrongType
from zope.schema._bootstrapinterfaces import ConstraintNotSatisfied
-from zope.schema._bootstrapinterfaces import NotAContainer, NotAnIterator
-from zope.schema._bootstrapinterfaces import TooSmall, TooBig
-from zope.schema._bootstrapinterfaces import TooShort, TooLong
-from zope.schema._bootstrapinterfaces import InvalidValue
from zope.schema._bootstrapinterfaces import IContextAwareDefaultFactory
+from zope.schema._bootstrapinterfaces import IFromUnicode
+from zope.schema._bootstrapinterfaces import NotAContainer
+from zope.schema._bootstrapinterfaces import NotAnIterator
+from zope.schema._bootstrapinterfaces import RequiredMissing
+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 WrongType
+from zope.schema._compat import u
+from zope.schema._compat import b # used in docstring doctests
+from zope.schema._compat import text_type
+from zope.schema._compat import integer_types
from zope.schema._schema import getFields
@@ -232,6 +239,9 @@
raise NotAContainer(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):
@@ -371,26 +381,20 @@
class Bool(Field):
"""A field representing a Bool."""
- _type = type(True)
+ _type = bool
- if _type is not type(1):
- # Python 2.2.1 and newer 2.2.x releases, True and False are
- # integers, and bool() returns either 1 or 0. We need to
- # support using integers here so we don't invalidate schema
- # that were perfectly valid with older versions of Python.
+ def _validate(self, value):
+ # Convert integers to bools to they don't get mis-flagged
+ # by the type check later.
+ if isinstance(value, int):
+ value = bool(value)
+ Field._validate(self, value)
- def _validate(self, value):
- # Convert integers to bools to they don't get mis-flagged
- # by the type check later.
- if isinstance(value, int):
- value = bool(value)
- Field._validate(self, value)
+ def set(self, object, value):
+ if isinstance(value, int):
+ value = bool(value)
+ Field.set(self, object, value)
- def set(self, object, value):
- if isinstance(value, int):
- value = bool(value)
- Field.set(self, object, value)
-
def fromUnicode(self, str):
"""
>>> b = Bool()
Modified: zope.schema/trunk/src/zope/schema/_bootstrapinterfaces.py
===================================================================
--- zope.schema/trunk/src/zope/schema/_bootstrapinterfaces.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/_bootstrapinterfaces.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -42,7 +42,7 @@
__hash__ = zope.interface.Invalid.__hash__ # python3
- def __repr__(self):
+ def __repr__(self): #pragma NO COVER
return '%s(%s)' % (self.__class__.__name__,
', '.join(repr(arg) for arg in self.args))
Copied: zope.schema/trunk/src/zope/schema/_compat.py (from rev 125653, zope.schema/branches/tseaver-test_cleanup/src/zope/schema/_compat.py)
===================================================================
--- zope.schema/trunk/src/zope/schema/_compat.py (rev 0)
+++ zope.schema/trunk/src/zope/schema/_compat.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -0,0 +1,44 @@
+import sys
+
+PY3 = sys.version_info[0] >= 3
+
+try:
+ from collections import OrderedDict
+except ImportError: #pragma NO COVER
+ from ordereddict import OrderedDict
+
+if PY3: #pragma NO COVER
+ import builtins
+ def b(s):
+ return s.encode("latin-1")
+ def u(s):
+ return s
+ 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
+ def b(s):
+ return s
+ def u(s):
+ return unicode(s, "unicode_escape")
+ string_types = basestring,
+ text_type = unicode
+ binary_type = str
+ integer_types = (int, long)
+ def non_native_string(x):
+ if isinstance(x, unicode):
+ return x
+ return unicode(x, 'unicode_escape')
+ def make_binary(x):
+ if isinstance(x, str):
+ return x
+ return x.encode('ascii')
Modified: zope.schema/trunk/src/zope/schema/_field.py
===================================================================
--- zope.schema/trunk/src/zope/schema/_field.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/_field.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -13,48 +13,94 @@
##############################################################################
"""Schema Fields
"""
-
__docformat__ = 'restructuredtext'
+from datetime import datetime
+from datetime import date
+from datetime import timedelta
+from datetime import time
+import decimal
import re
-import decimal
import threading
-from datetime import datetime, date, timedelta, time
+
from zope.event import notify
+from zope.interface import classImplements
+from zope.interface import implementer
+from zope.interface import Interface
+from zope.interface.interfaces import IInterface
+from zope.interface.interfaces import IMethod
-from zope.interface import classImplements, implementer, Interface
-from zope.interface.interfaces import IInterface, IMethod
-from six import u, b, text_type, string_types, binary_type, PY3
-
+from zope.schema.interfaces import IASCII
+from zope.schema.interfaces import IASCIILine
+from zope.schema.interfaces import IBaseVocabulary
+from zope.schema.interfaces import IBeforeObjectAssignedEvent
+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 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 IMinMaxLen, IText, ITextLine
+from zope.schema.interfaces import IFloat
+from zope.schema.interfaces import IFromUnicode
+from zope.schema.interfaces import IFrozenSet
+from zope.schema.interfaces import IId
+from zope.schema.interfaces import IInt
+from zope.schema.interfaces import IInterfaceField
+from zope.schema.interfaces import IList
+from zope.schema.interfaces import IMinMaxLen
+from zope.schema.interfaces import IObject
+from zope.schema.interfaces import IPassword
+from zope.schema.interfaces import ISet
+from zope.schema.interfaces import ISource
from zope.schema.interfaces import ISourceText
-from zope.schema.interfaces import IInterfaceField
-from zope.schema.interfaces import IBytes, IASCII, IBytesLine, IASCIILine
-from zope.schema.interfaces import IBool, IInt, IFloat, IDatetime, IFrozenSet
-from zope.schema.interfaces import IChoice, ITuple, IList, ISet, IDict
-from zope.schema.interfaces import IPassword, IDate, ITimedelta
-from zope.schema.interfaces import IObject, IBeforeObjectAssignedEvent
-from zope.schema.interfaces import ITime, IDecimal
-from zope.schema.interfaces import IURI, IId, IDottedName, IFromUnicode
-from zope.schema.interfaces import ISource, IBaseVocabulary
-from zope.schema.interfaces import IContextSourceBinder
+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, InvalidValue
-from zope.schema.interfaces import WrongType, WrongContainedType, NotUnique
-from zope.schema.interfaces import SchemaNotProvided, SchemaNotFullyImplemented
-from zope.schema.interfaces import InvalidURI, InvalidId, InvalidDottedName
+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 SchemaNotProvided
+from zope.schema.interfaces import SchemaNotFullyImplemented
+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, Container, Iterable, Orderable
-from zope.schema._bootstrapfields import Text, TextLine, Bool, Int, Password
+from zope.schema._bootstrapfields import Field
+from zope.schema._bootstrapfields import Container
+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 Password
from zope.schema._bootstrapfields import MinMaxLen
from zope.schema.fieldproperty import FieldProperty
from zope.schema.vocabulary import getVocabularyRegistry
from zope.schema.vocabulary import VocabularyRegistryError
from zope.schema.vocabulary import SimpleVocabulary
+from zope.schema._compat import u # used in docstring doctests
+from zope.schema._compat import b
+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'])
@@ -86,7 +132,7 @@
_type = binary_type
- def fromUnicode(self, u):
+ def fromUnicode(self, uc):
"""
>>> obj = Bytes(constraint=lambda v: b('x') in v)
@@ -98,21 +144,18 @@
ConstraintNotSatisfied: foo y.z bat
"""
- if PY3:
- v = b(u)
- else:
- v = str(u)
+ v = make_binary(uc)
self.validate(v)
return v
# for things which are of the str type on both Python 2 and 3
-if PY3:
- _Str = Text
-else:
- _Str = Bytes
+if PY3: #pragma NO COVER
+ NativeString = Text
+else: #pragma NO COVER
+ NativeString = Bytes
@implementer(IASCII)
-class ASCII(_Str):
+class ASCII(NativeString):
__doc__ = IASCII.__doc__
def _validate(self, value):
@@ -151,10 +194,10 @@
return b('\n') not in value
# for things which are of the str type on both Python 2 and 3
-if PY3:
- _StrLine = TextLine
-else:
- _StrLine = BytesLine
+if PY3: #pragma NO COVER
+ NativeStringLine = TextLine
+else: #pragma NO COVER
+ NativeStringLine = BytesLine
@implementer(IASCIILine)
class ASCIILine(ASCII):
@@ -162,7 +205,7 @@
def constraint(self, value):
# TODO: we should probably use a more general definition of newlines
- return b('\n') not in value
+ return '\n' not in value
@implementer(IFloat, IFromUnicode)
@@ -173,7 +216,7 @@
def __init__(self, *args, **kw):
super(Float, self).__init__(*args, **kw)
- def fromUnicode(self, u):
+ def fromUnicode(self, uc):
"""
>>> f = Float()
>>> f.fromUnicode("1.25")
@@ -183,7 +226,7 @@
...
ValueError: invalid literal for float(): 1.25.6
"""
- v = float(u)
+ v = float(uc)
self.validate(v)
return v
@@ -196,7 +239,7 @@
def __init__(self, *args, **kw):
super(Decimal, self).__init__(*args, **kw)
- def fromUnicode(self, u):
+ def fromUnicode(self, uc):
"""
>>> f = Decimal()
>>> import decimal
@@ -210,9 +253,9 @@
ValueError: invalid literal for Decimal(): 1.25.6
"""
try:
- v = decimal.Decimal(u)
+ v = decimal.Decimal(uc)
except decimal.InvalidOperation:
- raise ValueError('invalid literal for Decimal(): %s' % u)
+ raise ValueError('invalid literal for Decimal(): %s' % uc)
self.validate(v)
return v
@@ -258,16 +301,21 @@
def __init__(self, values=None, vocabulary=None, source=None, **kw):
"""Initialize object."""
if vocabulary is not None:
- assert (isinstance(vocabulary, string_types)
- or IBaseVocabulary.providedBy(vocabulary))
- assert source is None, (
- "You cannot specify both source and vocabulary.")
+ 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
- assert not (values is None and vocabulary is None), (
+ if (values is None and vocabulary is None):
+ raise ValueError(
"You must specify either values or vocabulary.")
- assert values is None or vocabulary is None, (
+ if values is not None and vocabulary is not None:
+ raise ValueError(
"You cannot specify both values and vocabulary.")
self.vocabulary = None
@@ -277,8 +325,9 @@
elif isinstance(vocabulary, string_types):
self.vocabularyName = vocabulary
else:
- assert (ISource.providedBy(vocabulary) or
- IContextSourceBinder.providedBy(vocabulary))
+ if (not ISource.providedBy(vocabulary) and
+ not IContextSourceBinder.providedBy(vocabulary)):
+ raise ValueError('Invalid 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
@@ -298,12 +347,13 @@
# get registered vocabulary if needed:
if IContextSourceBinder.providedBy(self.vocabulary):
clone.vocabulary = self.vocabulary(object)
- assert ISource.providedBy(clone.vocabulary)
elif clone.vocabulary is None and self.vocabularyName is not None:
vr = getVocabularyRegistry()
clone.vocabulary = vr.get(object, self.vocabularyName)
- assert ISource.providedBy(clone.vocabulary)
+ if not ISource.providedBy(clone.vocabulary):
+ raise ValueError('Invalid clone vocabulary')
+
return clone
def fromUnicode(self, str):
@@ -360,19 +410,19 @@
To illustrate, we'll use a text value type. All values must be unicode.
- >>> field = TextLine(required=True)
+ >>> field = TextLine(required=True)
- To validate a sequence of various values:
+ To validate a sequence of various values:
- >>> errors = _validate_sequence(field, (b('foo'), u('bar'), 1))
- >>> errors
- [WrongType(b'foo', <type 'unicode'>, ''), WrongType(1, <type 'unicode'>, '')]
+ >>> errors = _validate_sequence(field, (b('foo'), u('bar'), 1))
+ >>> errors
+ [WrongType(b'foo', <type 'unicode'>, ''), WrongType(1, <type 'unicode'>, '')]
- The only valid value in the sequence is the second item. The others
- generated errors.
+ 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:
+ We can use the optional errors argument to collect additional errors
+ for a new sequence:
>>> errors = _validate_sequence(field, (2, u('baz')), errors)
>>> errors
@@ -601,12 +651,10 @@
_isuri = r"[a-zA-z0-9+.-]+:" # scheme
_isuri += r"\S*$" # non space (should be pickier)
-
-_isuri_bytes = re.compile(_isuri.encode('ascii')).match
_isuri = re.compile(_isuri).match
@implementer(IURI, IFromUnicode)
-class URI(BytesLine):
+class URI(NativeStringLine):
"""URI schema field
"""
@@ -622,7 +670,7 @@
"""
super(URI, self)._validate(value)
- if _isuri_bytes(value):
+ if _isuri(value):
return
raise InvalidURI(value)
@@ -641,7 +689,7 @@
...
InvalidURI: http://www.python.org/ foo/bar
"""
- v = value.strip().encode('ascii')
+ v = str(value.strip())
self.validate(v)
return v
@@ -654,7 +702,7 @@
@implementer(IId, IFromUnicode)
-class Id(_StrLine):
+class Id(NativeStringLine):
"""Id field
Values of id fields must be either uris or dotted names.
@@ -705,7 +753,7 @@
@implementer(IDottedName)
-class DottedName(_StrLine):
+class DottedName(NativeStringLine):
"""Dotted name field.
Values of DottedName fields must be Python-style dotted names.
Modified: zope.schema/trunk/src/zope/schema/_messageid.py
===================================================================
--- zope.schema/trunk/src/zope/schema/_messageid.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/_messageid.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -14,8 +14,7 @@
try:
from zope.i18nmessageid import MessageFactory
-except ImportError:
- from six import text_type
- _ = lambda x: text_type(x)
-else:
+except ImportError: #pragma NO COVER
+ from zope.schema._compat import text_type as _
+else: #pragma NO COVER
_ = MessageFactory("zope")
Modified: zope.schema/trunk/src/zope/schema/_schema.py
===================================================================
--- zope.schema/trunk/src/zope/schema/_schema.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/_schema.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -50,7 +50,6 @@
def getValidationErrors(schema, object):
"""Return a list of all validation errors.
-
"""
errors = getSchemaValidationErrors(schema, object)
if errors:
Deleted: zope.schema/trunk/src/zope/schema/fields.txt
===================================================================
--- zope.schema/trunk/src/zope/schema/fields.txt 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/fields.txt 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,163 +0,0 @@
-======
-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").
-
-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:
-
- >>> from zope.interface import Interface
- >>> from zope.schema import List, Float
- >>> from six import u
- >>> 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:
-
- >>> 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 zope.schema._field.AbstractCollection to get the necessary
-behavior. Notice the behavior of the Set field in zope.schema._field: 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 vocabulary, the choices available to a
-choice field can be contextually calculated.
-
-Simple choices do not have to explicitly use vocabularies:
-
- >>> 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 registered vocabularies. 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.
-
-The Zope application server typically needs a fuller 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 IIterableVocabulary interface.
-
-If a vocabulary has been registered, then the choice merely needs to pass the
-vocabulary identifier to the "vocabulary" argument of the choice during
-instantiation.
-
-A start to a vocabulary implementation that may do all you need for many simple
-tasks may be found in zope.schema.vocabulary.SimpleVocabulary. Because
-registered vocabularies are simply callables passed a context, many
-registered vocabularies can simply be functions that rely on SimpleVocabulary:
-
- >>> from zope.schema.vocabulary import SimpleVocabulary
- >>> def myDynamicVocabulary(context):
- ... v = dynamic_context_calculation_that_returns_an_iterable(context)
- ... return SimpleVocabulary.fromValues(v)
- ...
-
-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.
-
-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`.
-
Deleted: zope.schema/trunk/src/zope/schema/index.txt
===================================================================
--- zope.schema/trunk/src/zope/schema/index.txt 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/index.txt 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,19 +0,0 @@
-Welcome to zope.schema's documentation!
-=======================================
-
-Contents:
-
-.. toctree::
- :maxdepth: 2
-
- README
- fields
- sources
- validation
-
-Indices and tables
-==================
-
-* :ref:`genindex`
-* :ref:`modindex`
-* :ref:`search`
Modified: zope.schema/trunk/src/zope/schema/interfaces.py
===================================================================
--- zope.schema/trunk/src/zope/schema/interfaces.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/interfaces.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -17,9 +17,7 @@
from zope.interface import Interface, Attribute
from zope.interface.common.mapping import IEnumerableMapping
-from six import u, PY3
-from zope.schema._messageid import _
# Import from _bootstrapinterfaces only because other packages will expect
# to find these interfaces here.
@@ -45,7 +43,11 @@
from zope.schema._bootstrapinterfaces import InvalidValue
from zope.schema._bootstrapinterfaces import IContextAwareDefaultFactory
+from zope.schema._compat import PY3
+from zope.schema._compat import u
+from zope.schema._messageid import _
+
class WrongContainedType(ValidationError):
__doc__ = _("""Wrong contained type""")
@@ -290,12 +292,12 @@
"""Field containing a unicode string."""
# for things which are of the str type on both Python 2 and 3
-if PY3:
- _IStr = IText
-else:
- _IStr = IBytes
+if PY3: #pragma NO COVER
+ INativeString = IText
+else: #pragma NO COVER
+ INativeString = IBytes
-class IASCII(_IStr):
+class IASCII(INativeString):
"""Field containing a 7-bit ASCII string. No characters > DEL
(chr(127)) are allowed
@@ -314,10 +316,10 @@
class ITextLine(IText):
"""Field containing a unicode string without newlines."""
-if PY3:
- _IStrLine = ITextLine
-else:
- _IStrLine = IBytesLine
+if PY3: #pragma NO COVER
+ INativeStringLine = ITextLine
+else: #pragma NO COVER
+ INativeStringLine = IBytesLine
class IPassword(ITextLine):
"Field containing a unicode string without newlines that is a password."
@@ -373,18 +375,18 @@
return True
-class IURI(IBytesLine):
+class IURI(INativeStringLine):
"""A field containing an absolute URI
"""
-class IId(_IStrLine):
+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(_IStrLine):
+class IDottedName(INativeStringLine):
"""Dotted name field.
Values of DottedName fields must be Python-style dotted names.
Deleted: zope.schema/trunk/src/zope/schema/sources.txt
===================================================================
--- zope.schema/trunk/src/zope/schema/sources.txt 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/sources.txt 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,98 +0,0 @@
-=======
-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.
-
- >>> 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.
-
- >>> from six import print_
- >>> def my_binder(context):
- ... print_("Binder was called.")
- ... 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())
- Binder was called.
- >>> 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.
-
- >>> choice = Choice(__name__='number', source=my_binder, default=2)
-
- >>> bound = choice.bind(Context())
- Binder was called.
-
- >>> 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.
Modified: zope.schema/trunk/src/zope/schema/tests/__init__.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/__init__.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/__init__.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -3,7 +3,7 @@
import re
-from six import PY3
+from zope.schema._compat import PY3
from zope.testing import renormalizing
if PY3:
@@ -32,9 +32,12 @@
r"InvalidDottedName: \1"),
(re.compile(r"zope.schema.interfaces.InvalidDottedName:"),
r"InvalidDottedName:"),
- (re.compile(r"zope.schema._bootstrapinterfaces.ConstraintNotSatisfied: '([^']*)'"),
+ (re.compile(
+ r"zope.schema._bootstrapinterfaces.ConstraintNotSatisfied: '([^']*)'"
+ ),
r"ConstraintNotSatisfied: \1"),
- (re.compile(r"zope.schema._bootstrapinterfaces.ConstraintNotSatisfied:"),
+ (re.compile(
+ r"zope.schema._bootstrapinterfaces.ConstraintNotSatisfied:"),
r"ConstraintNotSatisfied:"),
(re.compile(r"zope.schema._bootstrapinterfaces.WrongType:"),
r"WrongType:"),
Modified: zope.schema/trunk/src/zope/schema/tests/states.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/states.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/states.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -13,7 +13,7 @@
##############################################################################
"""Sample vocabulary supporting state abbreviations.
"""
-from six import u
+from zope.schema._compat import u
from zope.interface import implementer
from zope.schema import interfaces
from zope.schema import Choice
Copied: zope.schema/trunk/src/zope/schema/tests/test__bootstrapfields.py (from rev 125653, zope.schema/branches/tseaver-test_cleanup/src/zope/schema/tests/test__bootstrapfields.py)
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test__bootstrapfields.py (rev 0)
+++ zope.schema/trunk/src/zope/schema/tests/test__bootstrapfields.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -0,0 +1,794 @@
+##############################################################################
+#
+# 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
+
+
+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___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(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._bootstrapfields import Field
+ return Field
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_ctor_defaults(self):
+ from zope.schema._compat import u
+ 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):
+ from zope.schema._compat import u
+ 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):
+ from zope.schema._compat import u
+ 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):
+ from zope.schema._compat import u
+ 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_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()
+ def _fail(value):
+ return False
+ field = self._makeOne(required=False,
+ missing_value=missing,
+ constraint=_fail,
+ )
+ self.assertEqual(field.validate(missing), None) #doesn't raise
+
+ def test_validate_missing_and_required(self):
+ from zope.schema._bootstrapinterfaces import RequiredMissing
+ missing = object()
+ def _fail(value):
+ return False
+ field = self._makeOne(required=True,
+ missing_value=missing,
+ constraint=_fail,
+ )
+ self.assertRaises(RequiredMissing, field.validate, missing)
+
+ def test_validate_wrong_type(self):
+ from zope.schema._bootstrapinterfaces import WrongType
+ def _fail(value):
+ return False
+ field = self._makeOne(required=True,
+ constraint=_fail,
+ )
+ field._type = str
+ self.assertRaises(WrongType, field.validate, 1)
+
+ def test_validate_constraint_fails(self):
+ from zope.schema._bootstrapinterfaces import ConstraintNotSatisfied
+ def _fail(value):
+ return False
+ field = self._makeOne(required=True,
+ constraint=_fail,
+ )
+ 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___eq___different_type(self):
+ left = self._makeOne()
+ class Derived(self._getTargetClass()):
+ pass
+ right = Derived()
+ self.assertEqual(left == right, False)
+ self.assertEqual(left != right, True)
+
+ def test___eq___same_type_different_attrs(self):
+ left = self._makeOne(required=True)
+ right = self._makeOne(required=False)
+ self.assertEqual(left == right, False)
+ self.assertEqual(left != right, True)
+
+ def test___eq___same_type_same_attrs(self):
+ left = self._makeOne()
+ right = self._makeOne()
+ self.assertEqual(left == right, True)
+ self.assertEqual(left != right, False)
+
+ 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(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._bootstrapfields import Container
+ return Container
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ 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()
+ self.assertRaises(NotAContainer, cont._validate, object())
+
+ def test__validate_collection_but_not_iterable(self):
+ cont = self._makeOne()
+ class Dummy(object):
+ def __contains__(self, item):
+ return False
+ 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 test__validate_collection_but_not_iterable(self):
+ from zope.schema._bootstrapinterfaces import NotAnIterator
+ itr = self._makeOne()
+ class Dummy(object):
+ def __contains__(self, item):
+ return False
+ self.assertRaises(NotAnIterator, itr._validate, 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(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):
+ from zope.schema._bootstrapinterfaces import TooShort
+ mml = self._makeOne(min_length=1)
+ self.assertRaises(TooShort, mml._validate, ())
+
+ def test_validate_too_long(self):
+ from zope.schema._bootstrapinterfaces import TooLong
+ mml = self._makeOne(max_length=2)
+ self.assertRaises(TooLong, mml._validate, (0, 1, 2))
+
+
+class TextTests(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._bootstrapfields import Text
+ return Text
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ 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):
+ from zope.schema.interfaces import WrongType
+ from zope.schema._compat import b
+ field = self._makeOne()
+ self.assertRaises(WrongType, field.validate, b(''))
+ self.assertRaises(WrongType, field.validate, 1)
+ self.assertRaises(WrongType, field.validate, 1.0)
+ self.assertRaises(WrongType, field.validate, ())
+ self.assertRaises(WrongType, field.validate, [])
+ self.assertRaises(WrongType, field.validate, {})
+ self.assertRaises(WrongType, field.validate, set())
+ self.assertRaises(WrongType, field.validate, frozenset())
+ self.assertRaises(WrongType, field.validate, object())
+
+ def test_validate_w_invalid_default(self):
+ from zope.schema._compat import b
+ from zope.schema.interfaces import ValidationError
+ self.assertRaises(ValidationError, self._makeOne, default=b(''))
+
+ def test_validate_not_required(self):
+ from zope.schema._compat import u
+ 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
+ from zope.schema._compat import u
+ 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):
+ from zope.schema._bootstrapinterfaces import WrongType
+ from zope.schema._compat import b
+ deadbeef = b('DEADBEEF')
+ txt = self._makeOne()
+ self.assertRaises(WrongType, txt.fromUnicode, deadbeef)
+
+ def test_fromUnicode_hit(self):
+ from zope.schema._compat import u
+ deadbeef = u('DEADBEEF')
+ txt = self._makeOne()
+ self.assertEqual(txt.fromUnicode(deadbeef), deadbeef)
+
+
+class TextLineTests(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._field import TextLine
+ return TextLine
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_class_conforms_to_ITextLine(self):
+ from zope.interface.verify import verifyClass
+ from zope.schema.interfaces import ITextLine
+ verifyClass(ITextLine, self._getTargetClass())
+
+ def test_instance_conforms_to_ITextLine(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import ITextLine
+ verifyObject(ITextLine, self._makeOne())
+
+ def test_validate_wrong_types(self):
+ from zope.schema.interfaces import WrongType
+ from zope.schema._compat import b
+ field = self._makeOne()
+ self.assertRaises(WrongType, field.validate, b(''))
+ self.assertRaises(WrongType, field.validate, 1)
+ self.assertRaises(WrongType, field.validate, 1.0)
+ self.assertRaises(WrongType, field.validate, ())
+ self.assertRaises(WrongType, field.validate, [])
+ self.assertRaises(WrongType, field.validate, {})
+ self.assertRaises(WrongType, field.validate, set())
+ self.assertRaises(WrongType, field.validate, frozenset())
+ self.assertRaises(WrongType, field.validate, object())
+
+ def test_validate_not_required(self):
+ from zope.schema._compat import u
+ 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
+ from zope.schema._compat import u
+ field = self._makeOne()
+ field.validate(u(''))
+ field.validate(u('abc'))
+ self.assertRaises(RequiredMissing, field.validate, None)
+
+ def test_constraint(self):
+ from zope.schema._compat import u
+ 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(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._bootstrapfields import Password
+ return Password
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ 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):
+ klass = self._getTargetClass()
+ pw = self._makeOne(__name__='password')
+ inst = DummyInst()
+ pw.set(inst, 'PASSWORD')
+ self.assertEqual(inst.password, 'PASSWORD')
+
+ def test_validate_not_required(self):
+ from zope.schema._compat import u
+ 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
+ from zope.schema._compat import u
+ field = self._makeOne()
+ field.validate(u(''))
+ field.validate(u('abc'))
+ self.assertRaises(RequiredMissing, field.validate, None)
+
+ def test_validate_unchanged_not_already_set(self):
+ from zope.schema._bootstrapinterfaces import WrongType
+ klass = self._getTargetClass()
+ inst = DummyInst()
+ pw = self._makeOne(__name__= 'password').bind(inst)
+ self.assertRaises(WrongType,
+ pw.validate, 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):
+ from zope.schema._compat import u
+ 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(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._bootstrapfields import Bool
+ return Bool
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_ctor_defaults(self):
+ txt = self._makeOne()
+ self.assertEqual(txt._type, bool)
+
+ def test__validate_w_int(self):
+ boo = self._makeOne()
+ boo._validate(0) #doesn't raise
+ boo._validate(1) #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_fromUnicode_miss(self):
+ from zope.schema._compat import u
+ 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):
+ from zope.schema._compat import u
+ txt = self._makeOne()
+ self.assertEqual(txt.fromUnicode(u('True')), True)
+ self.assertEqual(txt.fromUnicode(u('true')), True)
+
+
+class IntTests(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._bootstrapfields import Int
+ return Int
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_ctor_defaults(self):
+ from zope.schema._compat import integer_types
+ txt = self._makeOne()
+ self.assertEqual(txt._type, integer_types)
+
+ 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_validate_min(self):
+ from zope.schema.interfaces import TooSmall
+ field = self._makeOne(min=10)
+ field.validate(10)
+ field.validate(20)
+ self.assertRaises(TooSmall, field.validate, 9)
+ self.assertRaises(TooSmall, field.validate, -10)
+
+ def test_validate_max(self):
+ from zope.schema.interfaces import TooBig
+ field = self._makeOne(max=10)
+ field.validate(5)
+ field.validate(9)
+ field.validate(10)
+ self.assertRaises(TooBig, field.validate, 11)
+ self.assertRaises(TooBig, field.validate, 20)
+
+ def test_validate_min_and_max(self):
+ from zope.schema.interfaces import TooBig
+ from zope.schema.interfaces import TooSmall
+ field = self._makeOne(min=0, max=10)
+ field.validate(0)
+ field.validate(5)
+ field.validate(10)
+ self.assertRaises(TooSmall, field.validate, -10)
+ self.assertRaises(TooSmall, field.validate, -1)
+ self.assertRaises(TooBig, field.validate, 11)
+ self.assertRaises(TooBig, field.validate, 20)
+
+ def test_fromUnicode_miss(self):
+ from zope.schema._compat import u
+ 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):
+ from zope.schema._compat import u
+ 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 DummyInst(object):
+ missing_value = object()
+
+ def __init__(self, exc=None):
+ self._exc = exc
+
+ def validate(self, value):
+ if self._exc is not None:
+ raise self._exc()
+
+
+def test_suite():
+ return unittest.TestSuite((
+ unittest.makeSuite(ValidatedPropertyTests),
+ unittest.makeSuite(DefaultPropertyTests),
+ unittest.makeSuite(FieldTests),
+ unittest.makeSuite(ContainerTests),
+ unittest.makeSuite(IterableTests),
+ unittest.makeSuite(OrderableTests),
+ unittest.makeSuite(MinMaxLenTests),
+ unittest.makeSuite(TextTests),
+ unittest.makeSuite(TextLineTests),
+ unittest.makeSuite(PasswordTests),
+ unittest.makeSuite(BoolTests),
+ unittest.makeSuite(IntTests),
+ ))
Copied: zope.schema/trunk/src/zope/schema/tests/test__bootstrapinterfaces.py (from rev 125653, zope.schema/branches/tseaver-test_cleanup/src/zope/schema/tests/test__bootstrapinterfaces.py)
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test__bootstrapinterfaces.py (rev 0)
+++ zope.schema/trunk/src/zope/schema/tests/test__bootstrapinterfaces.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -0,0 +1,67 @@
+##############################################################################
+#
+# 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
+
+
+def _skip_under_py3(testcase):
+ from zope.schema._compat import PY3
+ if not PY3:
+ return testcase
+
+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')
+
+ @_skip_under_py3
+ def test___cmp___no_args(self):
+ # Py3k??
+ ve = self._makeOne()
+ self.assertEqual(cmp(ve, object()), -1)
+
+ @_skip_under_py3
+ def test___cmp___hit(self):
+ # Py3k??
+ left = self._makeOne('abc')
+ right = self._makeOne('def')
+ self.assertEqual(cmp(left, right), -1)
+ self.assertEqual(cmp(left, left), 0)
+ self.assertEqual(cmp(right, left), 1)
+
+ def test___eq___no_args(self):
+ ve = self._makeOne()
+ self.assertEqual(ve == object(), False)
+
+ def test___eq___w_args(self):
+ left = self._makeOne('abc')
+ right = self._makeOne('def')
+ self.assertEqual(left == right, False)
+ self.assertEqual(left == left, True)
+ self.assertEqual(right == right, True)
+
+
+def test_suite():
+ return unittest.TestSuite((
+ unittest.makeSuite(ValidationErrorTests),
+ ))
Copied: zope.schema/trunk/src/zope/schema/tests/test__field.py (from rev 125653, zope.schema/branches/tseaver-test_cleanup/src/zope/schema/tests/test__field.py)
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test__field.py (rev 0)
+++ zope.schema/trunk/src/zope/schema/tests/test__field.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -0,0 +1,2088 @@
+##############################################################################
+#
+# 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
+
+
+class BytesTests(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._field import Bytes
+ return Bytes
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_class_conforms_to_IBytes(self):
+ from zope.interface.verify import verifyClass
+ from zope.schema.interfaces import IBytes
+ verifyClass(IBytes, self._getTargetClass())
+
+ def test_instance_conforms_to_IBytes(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import IBytes
+ verifyObject(IBytes, self._makeOne())
+
+ def test_validate_wrong_types(self):
+ from zope.schema.interfaces import WrongType
+ from zope.schema._compat import u
+ field = self._makeOne()
+ self.assertRaises(WrongType, field.validate, u(''))
+ self.assertRaises(WrongType, field.validate, 1)
+ self.assertRaises(WrongType, field.validate, 1.0)
+ self.assertRaises(WrongType, field.validate, ())
+ self.assertRaises(WrongType, field.validate, [])
+ self.assertRaises(WrongType, field.validate, {})
+ self.assertRaises(WrongType, field.validate, set())
+ self.assertRaises(WrongType, field.validate, frozenset())
+ self.assertRaises(WrongType, field.validate, object())
+
+ def test_validate_w_invalid_default(self):
+ from zope.schema._compat import u
+ from zope.schema.interfaces import ValidationError
+ self.assertRaises(ValidationError, self._makeOne, default=u(''))
+
+ def test_validate_not_required(self):
+ from zope.schema._compat import b
+ 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
+ from zope.schema._compat import b
+ 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):
+ from zope.schema._compat import u
+ byt = self._makeOne()
+ self.assertRaises(UnicodeEncodeError, byt.fromUnicode, u(chr(129)))
+
+ def test_fromUnicode_hit(self):
+ from zope.schema._compat import u
+ from zope.schema._compat import b
+ byt = self._makeOne()
+ self.assertEqual(byt.fromUnicode(u('')), b(''))
+ self.assertEqual(byt.fromUnicode(u('DEADBEEF')), b('DEADBEEF'))
+
+
+class ASCIITests(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._field import ASCII
+ return ASCII
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_class_conforms_to_IASCII(self):
+ from zope.interface.verify import verifyClass
+ from zope.schema.interfaces import IASCII
+ verifyClass(IASCII, self._getTargetClass())
+
+ def test_instance_conforms_to_IASCII(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import IASCII
+ verifyObject(IASCII, self._makeOne())
+
+ def test_validate_wrong_types(self):
+ from zope.schema.interfaces import WrongType
+ from zope.schema._compat import non_native_string
+ field = self._makeOne()
+ self.assertRaises(WrongType, field.validate, non_native_string(''))
+ self.assertRaises(WrongType, field.validate, 1)
+ self.assertRaises(WrongType, field.validate, 1.0)
+ self.assertRaises(WrongType, field.validate, ())
+ self.assertRaises(WrongType, field.validate, [])
+ self.assertRaises(WrongType, field.validate, {})
+ self.assertRaises(WrongType, field.validate, set())
+ self.assertRaises(WrongType, field.validate, frozenset())
+ self.assertRaises(WrongType, field.validate, 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()
+ self.assertRaises(InvalidValue, asc._validate, 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(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._field import BytesLine
+ return BytesLine
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_class_conforms_to_IBytesLine(self):
+ from zope.interface.verify import verifyClass
+ from zope.schema.interfaces import IBytesLine
+ verifyClass(IBytesLine, self._getTargetClass())
+
+ def test_instance_conforms_to_IBytesLine(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import IBytesLine
+ verifyObject(IBytesLine, self._makeOne())
+
+ def test_validate_wrong_types(self):
+ from zope.schema.interfaces import WrongType
+ from zope.schema._compat import u
+ field = self._makeOne()
+ self.assertRaises(WrongType, field.validate, u(''))
+ self.assertRaises(WrongType, field.validate, 1)
+ self.assertRaises(WrongType, field.validate, 1.0)
+ self.assertRaises(WrongType, field.validate, ())
+ self.assertRaises(WrongType, field.validate, [])
+ self.assertRaises(WrongType, field.validate, {})
+ self.assertRaises(WrongType, field.validate, set())
+ self.assertRaises(WrongType, field.validate, frozenset())
+ self.assertRaises(WrongType, field.validate, object())
+
+ def test_validate_not_required(self):
+ from zope.schema._compat import b
+ 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
+ from zope.schema._compat import b
+ 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):
+ from zope.schema._compat import b
+ 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)
+
+
+class ASCIILineTests(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._field import ASCIILine
+ return ASCIILine
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_class_conforms_to_IASCIILine(self):
+ from zope.interface.verify import verifyClass
+ from zope.schema.interfaces import IASCIILine
+ verifyClass(IASCIILine, self._getTargetClass())
+
+ def test_instance_conforms_to_IASCIILine(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import IASCIILine
+ verifyObject(IASCIILine, self._makeOne())
+
+ def test_validate_wrong_types(self):
+ from zope.schema.interfaces import WrongType
+ from zope.schema._compat import non_native_string
+ field = self._makeOne()
+ self.assertRaises(WrongType, field.validate, non_native_string(''))
+ self.assertRaises(WrongType, field.validate, 1)
+ self.assertRaises(WrongType, field.validate, 1.0)
+ self.assertRaises(WrongType, field.validate, ())
+ self.assertRaises(WrongType, field.validate, [])
+ self.assertRaises(WrongType, field.validate, {})
+ self.assertRaises(WrongType, field.validate, set())
+ self.assertRaises(WrongType, field.validate, frozenset())
+ self.assertRaises(WrongType, field.validate, 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(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._field import Float
+ return Float
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_class_conforms_to_IFloat(self):
+ from zope.interface.verify import verifyClass
+ from zope.schema.interfaces import IFloat
+ verifyClass(IFloat, self._getTargetClass())
+
+ def test_instance_conforms_to_IFloat(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import IFloat
+ verifyObject(IFloat, self._makeOne())
+
+ 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_validate_min(self):
+ from zope.schema.interfaces import TooSmall
+ field = self._makeOne(min=10.5)
+ field.validate(10.6)
+ field.validate(20.2)
+ self.assertRaises(TooSmall, field.validate, -9.0)
+ self.assertRaises(TooSmall, field.validate, 10.4)
+
+ def test_validate_max(self):
+ from zope.schema.interfaces import TooBig
+ field = self._makeOne(max=10.5)
+ field.validate(5.3)
+ field.validate(-9.1)
+ self.assertRaises(TooBig, field.validate, 10.51)
+ self.assertRaises(TooBig, field.validate, 20.7)
+
+ def test_validate_min_and_max(self):
+ from zope.schema.interfaces import TooBig
+ from zope.schema.interfaces import TooSmall
+ field = self._makeOne(min=-0.6, max=10.1)
+ field.validate(0.0)
+ field.validate(-0.03)
+ field.validate(10.0001)
+ self.assertRaises(TooSmall, field.validate, -10.0)
+ self.assertRaises(TooSmall, field.validate, -1.6)
+ self.assertRaises(TooBig, field.validate, 11.45)
+ self.assertRaises(TooBig, field.validate, 20.02)
+
+ def test_fromUnicode_miss(self):
+ from zope.schema._compat import u
+ 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):
+ from zope.schema._compat import u
+ 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 DecimalTests(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._field import Decimal
+ return Decimal
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_class_conforms_to_IDecimal(self):
+ from zope.interface.verify import verifyClass
+ from zope.schema.interfaces import IDecimal
+ verifyClass(IDecimal, self._getTargetClass())
+
+ def test_instance_conforms_to_IDecimal(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import IDecimal
+ verifyObject(IDecimal, self._makeOne())
+
+ def test_validate_not_required(self):
+ import decimal
+ 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):
+ import decimal
+ 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_validate_min(self):
+ import decimal
+ from zope.schema.interfaces import TooSmall
+ field = self._makeOne(min=decimal.Decimal("10.5"))
+ field.validate(decimal.Decimal("10.6"))
+ field.validate(decimal.Decimal("20.2"))
+ self.assertRaises(TooSmall, field.validate, decimal.Decimal("-9.0"))
+ self.assertRaises(TooSmall, field.validate, decimal.Decimal("10.4"))
+
+ def test_validate_max(self):
+ import decimal
+ from zope.schema.interfaces import TooBig
+ field = self._makeOne(max=decimal.Decimal("10.5"))
+ field.validate(decimal.Decimal("5.3"))
+ field.validate(decimal.Decimal("-9.1"))
+ self.assertRaises(TooBig, field.validate, decimal.Decimal("10.51"))
+ self.assertRaises(TooBig, field.validate, decimal.Decimal("20.7"))
+
+ def test_validate_min_and_max(self):
+ import decimal
+ from zope.schema.interfaces import TooBig
+ from zope.schema.interfaces import TooSmall
+ field = self._makeOne(min=decimal.Decimal("-0.6"),
+ max=decimal.Decimal("10.1"))
+ field.validate(decimal.Decimal("0.0"))
+ field.validate(decimal.Decimal("-0.03"))
+ field.validate(decimal.Decimal("10.0001"))
+ self.assertRaises(TooSmall, field.validate, decimal.Decimal("-10.0"))
+ self.assertRaises(TooSmall, field.validate, decimal.Decimal("-1.6"))
+ self.assertRaises(TooBig, field.validate, decimal.Decimal("11.45"))
+ self.assertRaises(TooBig, field.validate, decimal.Decimal("20.02"))
+
+ def test_fromUnicode_miss(self):
+ from zope.schema._compat import u
+ flt = self._makeOne()
+ self.assertRaises(ValueError, flt.fromUnicode, u(''))
+ self.assertRaises(ValueError, flt.fromUnicode, u('abc'))
+ self.assertRaises(ValueError, flt.fromUnicode, u('1.4G'))
+
+ def test_fromUnicode_hit(self):
+ from decimal import Decimal
+ from zope.schema._compat import u
+ 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 DatetimeTests(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._field import Datetime
+ return Datetime
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_class_conforms_to_IDatetime(self):
+ from zope.interface.verify import verifyClass
+ from zope.schema.interfaces import IDatetime
+ verifyClass(IDatetime, self._getTargetClass())
+
+ def test_instance_conforms_to_IDatetime(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import IDatetime
+ verifyObject(IDatetime, self._makeOne())
+
+ def test_validate_wrong_types(self):
+ from datetime import date
+ from zope.schema.interfaces import WrongType
+ from zope.schema._compat import u
+ from zope.schema._compat import b
+ field = self._makeOne()
+ self.assertRaises(WrongType, field.validate, u(''))
+ self.assertRaises(WrongType, field.validate, b(''))
+ self.assertRaises(WrongType, field.validate, 1)
+ self.assertRaises(WrongType, field.validate, 1.0)
+ self.assertRaises(WrongType, field.validate, ())
+ self.assertRaises(WrongType, field.validate, [])
+ self.assertRaises(WrongType, field.validate, {})
+ self.assertRaises(WrongType, field.validate, set())
+ self.assertRaises(WrongType, field.validate, frozenset())
+ self.assertRaises(WrongType, field.validate, object())
+ self.assertRaises(WrongType, field.validate, date.today())
+
+ def test_validate_not_required(self):
+ from datetime import datetime
+ field = self._makeOne(required=False)
+ field.validate(None) #doesn't raise
+ field.validate(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)
+
+ def test_validate_w_min(self):
+ from datetime import datetime
+ from zope.schema.interfaces import TooSmall
+ d1 = datetime(2000,10,1)
+ d2 = datetime(2000,10,2)
+ field = self._makeOne(min=d1)
+ field.validate(d1) #doesn't raise
+ field.validate(d2) #doesn't raise
+ self.assertRaises(TooSmall, field.validate, datetime(2000,9,30))
+
+ def test_validate_w_max(self):
+ from datetime import datetime
+ from zope.schema.interfaces import TooBig
+ d1 = datetime(2000,10,1)
+ d2 = datetime(2000,10,2)
+ d3 = datetime(2000,10,3)
+ field = self._makeOne(max=d2)
+ field.validate(d1) #doesn't raise
+ field.validate(d2) #doesn't raise
+ self.assertRaises(TooBig, field.validate, d3)
+
+ def test_validate_w_min_and_max(self):
+ from datetime import datetime
+ from zope.schema.interfaces import TooBig
+ from zope.schema.interfaces import TooSmall
+ d1 = datetime(2000,10,1)
+ d2 = datetime(2000,10,2)
+ d3 = datetime(2000,10,3)
+ d4 = datetime(2000,10,4)
+ d5 = datetime(2000,10,5)
+ field = self._makeOne(min=d2, max=d4)
+ field.validate(d2) #doesn't raise
+ field.validate(d3) #doesn't raise
+ field.validate(d4) #doesn't raise
+ self.assertRaises(TooSmall, field.validate, d1)
+ self.assertRaises(TooBig, field.validate, d5)
+
+
+class DateTests(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._field import Date
+ return Date
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_class_conforms_to_IDate(self):
+ from zope.interface.verify import verifyClass
+ from zope.schema.interfaces import IDate
+ verifyClass(IDate, self._getTargetClass())
+
+ def test_instance_conforms_to_IDate(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import IDate
+ verifyObject(IDate, self._makeOne())
+
+ def test_validate_wrong_types(self):
+ from datetime import datetime
+ from zope.schema.interfaces import WrongType
+ from zope.schema._compat import u
+ from zope.schema._compat import b
+ field = self._makeOne()
+ self.assertRaises(WrongType, field.validate, u(''))
+ self.assertRaises(WrongType, field.validate, b(''))
+ self.assertRaises(WrongType, field.validate, 1)
+ self.assertRaises(WrongType, field.validate, 1.0)
+ self.assertRaises(WrongType, field.validate, ())
+ self.assertRaises(WrongType, field.validate, [])
+ self.assertRaises(WrongType, field.validate, {})
+ self.assertRaises(WrongType, field.validate, set())
+ self.assertRaises(WrongType, field.validate, frozenset())
+ self.assertRaises(WrongType, field.validate, object())
+ self.assertRaises(WrongType, field.validate, 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 datetime import datetime
+ from zope.schema.interfaces import RequiredMissing
+ field = self._makeOne()
+ field.validate(datetime.now().date())
+ self.assertRaises(RequiredMissing, field.validate, None)
+
+ def test_validate_w_min(self):
+ from datetime import date
+ from datetime import datetime
+ from zope.schema.interfaces import TooSmall
+ d1 = date(2000,10,1)
+ d2 = date(2000,10,2)
+ field = self._makeOne(min=d1)
+ field.validate(d1)
+ field.validate(d2)
+ field.validate(datetime.now().date())
+ self.assertRaises(TooSmall, field.validate, date(2000,9,30))
+
+ def test_validate_w_max(self):
+ from datetime import date
+ from zope.schema.interfaces import TooBig
+ d1 = date(2000,10,1)
+ d2 = date(2000,10,2)
+ d3 = date(2000,10,3)
+ field = self._makeOne(max=d2)
+ field.validate(d1)
+ field.validate(d2)
+ self.assertRaises(TooBig, field.validate, d3)
+
+ def test_validate_w_min_and_max(self):
+ from datetime import date
+ from zope.schema.interfaces import TooBig
+ from zope.schema.interfaces import TooSmall
+ d1 = date(2000,10,1)
+ d2 = date(2000,10,2)
+ d3 = date(2000,10,3)
+ d4 = date(2000,10,4)
+ d5 = date(2000,10,5)
+ field = self._makeOne(min=d2, max=d4)
+ field.validate(d2)
+ field.validate(d3)
+ field.validate(d4)
+ self.assertRaises(TooSmall, field.validate, d1)
+ self.assertRaises(TooBig, field.validate, d5)
+
+
+class TimedeltaTests(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._field import Timedelta
+ return Timedelta
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_class_conforms_to_ITimedelta(self):
+ from zope.interface.verify import verifyClass
+ from zope.schema.interfaces import ITimedelta
+ verifyClass(ITimedelta, self._getTargetClass())
+
+ def test_instance_conforms_to_ITimedelta(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import ITimedelta
+ verifyObject(ITimedelta, self._makeOne())
+
+ 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)
+
+ def test_validate_min(self):
+ from datetime import timedelta
+ from zope.schema.interfaces import TooSmall
+ t1 = timedelta(hours=2)
+ t2 = timedelta(hours=3)
+ field = self._makeOne(min=t1)
+ field.validate(t1)
+ field.validate(t2)
+ self.assertRaises(TooSmall, field.validate, timedelta(hours=1))
+
+ def test_validate_max(self):
+ from datetime import timedelta
+ from zope.schema.interfaces import TooBig
+ t1 = timedelta(minutes=1)
+ t2 = timedelta(minutes=2)
+ t3 = timedelta(minutes=3)
+ field = self._makeOne(max=t2)
+ field.validate(t1)
+ field.validate(t2)
+ self.assertRaises(TooBig, field.validate, t3)
+
+ def test_validate_min_and_max(self):
+ from datetime import timedelta
+ from zope.schema.interfaces import TooBig
+ from zope.schema.interfaces import TooSmall
+ t1 = timedelta(days=1)
+ t2 = timedelta(days=2)
+ t3 = timedelta(days=3)
+ t4 = timedelta(days=4)
+ t5 = timedelta(days=5)
+ field = self._makeOne(min=t2, max=t4)
+ field.validate(t2)
+ field.validate(t3)
+ field.validate(t4)
+ self.assertRaises(TooSmall, field.validate, t1)
+ self.assertRaises(TooBig, field.validate, t5)
+
+
+class TimeTests(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._field import Time
+ return Time
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_class_conforms_to_ITime(self):
+ from zope.interface.verify import verifyClass
+ from zope.schema.interfaces import ITime
+ verifyClass(ITime, self._getTargetClass())
+
+ def test_instance_conforms_to_ITime(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import ITime
+ verifyObject(ITime, self._makeOne())
+
+ 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)
+
+ def test_validate_min(self):
+ from datetime import time
+ from zope.schema.interfaces import TooSmall
+ t1 = time(12,15,37)
+ t2 = time(12,25,18)
+ t3 = time(12,42,43)
+ field = self._makeOne(min=t2)
+ field.validate(t2)
+ field.validate(t3)
+ self.assertRaises(TooSmall, field.validate, t1)
+
+ def test_validate_max(self):
+ from datetime import time
+ from zope.schema.interfaces import TooBig
+ t1 = time(12,15,37)
+ t2 = time(12,25,18)
+ t3 = time(12,42,43)
+ field = self._makeOne(max=t2)
+ field.validate(t1)
+ field.validate(t2)
+ self.assertRaises(TooBig, field.validate, t3)
+
+ def test_validate_min_and_max(self):
+ from datetime import time
+ from zope.schema.interfaces import TooBig
+ from zope.schema.interfaces import TooSmall
+ t1 = time(12,15,37)
+ t2 = time(12,25,18)
+ t3 = time(12,42,43)
+ t4 = time(13,7,12)
+ t5 = time(14,22,9)
+ field = self._makeOne(min=t2, max=t4)
+ field.validate(t2)
+ field.validate(t3)
+ field.validate(t4)
+ self.assertRaises(TooSmall, field.validate, t1)
+ self.assertRaises(TooBig, field.validate, t5)
+
+
+class ChoiceTests(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 _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_class_conforms_to_IChoice(self):
+ from zope.interface.verify import verifyClass
+ from zope.schema.interfaces import IChoice
+ verifyClass(IChoice, self._getTargetClass())
+
+ def test_instance_conforms_to_IChoice(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import IChoice
+ verifyObject(IChoice, self._makeOne(values=[1, 2, 3]))
+
+ def test_ctor_wo_values_vocabulary_or_source(self):
+ self.assertRaises(ValueError, self._makeOne)
+
+ def test_ctor_invalid_vocabulary(self):
+ self.assertRaises(ValueError, self._makeOne, vocabulary=object())
+
+ def test_ctor_invalid_source(self):
+ self.assertRaises(ValueError, self._makeOne, 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_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 = DummyInstance()
+ target = source.bind(instance)
+ self.assertTrue(target.vocabulary is 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 = DummyInstance()
+ target = source.bind(instance)
+ self.assertEqual(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 = DummyInstance()
+ self.assertRaises(ValueError, source.bind, instance)
+
+ def test_fromUnicode_miss(self):
+ from zope.schema.interfaces import ConstraintNotSatisfied
+ from zope.schema._compat import u
+ flt = self._makeOne(values=(u('foo'), u('bar'), u('baz')))
+ self.assertRaises(ConstraintNotSatisfied, flt.fromUnicode, u(''))
+ self.assertRaises(ConstraintNotSatisfied, flt.fromUnicode, u('abc'))
+ self.assertRaises(ConstraintNotSatisfied, flt.fromUnicode, u('1.4G'))
+
+ def test_fromUnicode_hit(self):
+ from zope.schema._compat import u
+ 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._compat import u
+ 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):
+ choose = self._makeOne(vocabulary='vocab')
+ self.assertRaises(ValueError, choose._validate, 42)
+
+ 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):
+ pass
+ 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 InterfaceFieldTests(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._field import InterfaceField
+ return InterfaceField
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_class_conforms_to_IInterfaceField(self):
+ from zope.interface.verify import verifyClass
+ from zope.schema.interfaces import IInterfaceField
+ verifyClass(IInterfaceField, self._getTargetClass())
+
+ def test_instance_conforms_to_IInterfaceField(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import IInterfaceField
+ verifyObject(IInterfaceField, self._makeOne())
+
+ def test_validate_wrong_types(self):
+ from datetime import date
+ from zope.schema.interfaces import WrongType
+ from zope.schema._compat import u
+ from zope.schema._compat import b
+ field = self._makeOne()
+ self.assertRaises(WrongType, field.validate, u(''))
+ self.assertRaises(WrongType, field.validate, b(''))
+ self.assertRaises(WrongType, field.validate, 1)
+ self.assertRaises(WrongType, field.validate, 1.0)
+ self.assertRaises(WrongType, field.validate, ())
+ self.assertRaises(WrongType, field.validate, [])
+ self.assertRaises(WrongType, field.validate, {})
+ self.assertRaises(WrongType, field.validate, set())
+ self.assertRaises(WrongType, field.validate, frozenset())
+ self.assertRaises(WrongType, field.validate, object())
+ self.assertRaises(WrongType, field.validate, 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 AbstractCollectionTests(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._field import AbstractCollection
+ return AbstractCollection
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_ctor_defaults(self):
+ absc = self._makeOne()
+ self.assertEqual(absc.value_type, None)
+ self.assertEqual(absc.unique, False)
+
+ 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, False)
+
+ 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._bootstrapfields import Text
+ text = Text()
+ absc = self._makeOne(text)
+ self.assertRaises(WrongContainedType, absc.validate, [1])
+
+ def test__validate_miss_uniqueness(self):
+ from zope.schema.interfaces import NotUnique
+ from zope.schema._bootstrapfields import Text
+ from zope.schema._compat import u
+ text = Text()
+ absc = self._makeOne(text, True)
+ self.assertRaises(NotUnique, absc.validate, [u('a'), u('a')])
+
+
+class TupleTests(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._field import Tuple
+ return Tuple
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_class_conforms_to_ITuple(self):
+ from zope.interface.verify import verifyClass
+ from zope.schema.interfaces import ITuple
+ verifyClass(ITuple, self._getTargetClass())
+
+ def test_instance_conforms_to_ITuple(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import ITuple
+ verifyObject(ITuple, self._makeOne())
+
+ def test_validate_wrong_types(self):
+ from zope.schema.interfaces import WrongType
+ from zope.schema._compat import u
+ from zope.schema._compat import b
+ field = self._makeOne()
+ self.assertRaises(WrongType, field.validate, u(''))
+ self.assertRaises(WrongType, field.validate, b(''))
+ self.assertRaises(WrongType, field.validate, 1)
+ self.assertRaises(WrongType, field.validate, 1.0)
+ self.assertRaises(WrongType, field.validate, [])
+ self.assertRaises(WrongType, field.validate, {})
+ self.assertRaises(WrongType, field.validate, set())
+ self.assertRaises(WrongType, field.validate, frozenset())
+ self.assertRaises(WrongType, field.validate, object())
+
+ def test_validate_not_required(self):
+ field = self._makeOne(required=False)
+ field.validate(())
+ field.validate((1, 2))
+ field.validate((3,))
+ field.validate(None)
+
+ def test_validate_required(self):
+ from zope.schema.interfaces import RequiredMissing
+ field = self._makeOne()
+ field.validate(())
+ field.validate((1, 2))
+ field.validate((3,))
+ self.assertRaises(RequiredMissing, field.validate, None)
+
+ def test_validate_min_length(self):
+ from zope.schema.interfaces import TooShort
+ field = self._makeOne(min_length=2)
+ field.validate((1, 2))
+ field.validate((1, 2, 3))
+ self.assertRaises(TooShort, field.validate, ())
+ self.assertRaises(TooShort, field.validate, (1,))
+
+ def test_validate_max_length(self):
+ from zope.schema.interfaces import TooLong
+ field = self._makeOne(max_length=2)
+ field.validate(())
+ field.validate((1, 2))
+ self.assertRaises(TooLong, field.validate, (1, 2, 3, 4))
+ self.assertRaises(TooLong, field.validate, (1, 2, 3))
+
+ def test_validate_min_length_and_max_length(self):
+ from zope.schema.interfaces import TooLong
+ from zope.schema.interfaces import TooShort
+ field = self._makeOne(min_length=1, max_length=2)
+ field.validate((1, ))
+ field.validate((1, 2))
+ self.assertRaises(TooShort, field.validate, ())
+ self.assertRaises(TooLong, field.validate, (1, 2, 3))
+
+
+class ListTests(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._field import List
+ return List
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_class_conforms_to_IList(self):
+ from zope.interface.verify import verifyClass
+ from zope.schema.interfaces import IList
+ verifyClass(IList, self._getTargetClass())
+
+ def test_instance_conforms_to_IList(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import IList
+ verifyObject(IList, self._makeOne())
+
+ def test_validate_wrong_types(self):
+ from zope.schema.interfaces import WrongType
+ from zope.schema._compat import u
+ from zope.schema._compat import b
+ field = self._makeOne()
+ self.assertRaises(WrongType, field.validate, u(''))
+ self.assertRaises(WrongType, field.validate, b(''))
+ self.assertRaises(WrongType, field.validate, 1)
+ self.assertRaises(WrongType, field.validate, 1.0)
+ self.assertRaises(WrongType, field.validate, ())
+ self.assertRaises(WrongType, field.validate, {})
+ self.assertRaises(WrongType, field.validate, set())
+ self.assertRaises(WrongType, field.validate, frozenset())
+ self.assertRaises(WrongType, field.validate, object())
+
+ def test_validate_not_required(self):
+ field = self._makeOne(required=False)
+ field.validate([])
+ field.validate([1, 2])
+ field.validate([3])
+ field.validate(None)
+
+ def test_validate_required(self):
+ from zope.schema.interfaces import RequiredMissing
+ field = self._makeOne()
+ field.validate([])
+ field.validate([1, 2])
+ field.validate([3])
+ self.assertRaises(RequiredMissing, field.validate, None)
+
+ def test_validate_min_length(self):
+ from zope.schema.interfaces import TooShort
+ field = self._makeOne(min_length=2)
+ field.validate([1, 2])
+ field.validate([1, 2, 3])
+ self.assertRaises(TooShort, field.validate, [])
+ self.assertRaises(TooShort, field.validate, [1,])
+
+ def test_validate_max_length(self):
+ from zope.schema.interfaces import TooLong
+ field = self._makeOne(max_length=2)
+ field.validate([])
+ field.validate([1])
+ field.validate([1, 2])
+ self.assertRaises(TooLong, field.validate, [1, 2, 3, 4])
+ self.assertRaises(TooLong, field.validate, [1, 2, 3])
+
+ def test_validate_min_length_and_max_length(self):
+ from zope.schema.interfaces import TooLong
+ from zope.schema.interfaces import TooShort
+ field = self._makeOne(min_length=1, max_length=2)
+ field.validate([1])
+ field.validate([1, 2])
+ self.assertRaises(TooShort, field.validate, [])
+ self.assertRaises(TooLong, field.validate, [1, 2, 3])
+
+
+class SetTests(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._field import Set
+ return Set
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_class_conforms_to_ISet(self):
+ from zope.interface.verify import verifyClass
+ from zope.schema.interfaces import ISet
+ verifyClass(ISet, self._getTargetClass())
+
+ def test_instance_conforms_to_ISet(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import ISet
+ verifyObject(ISet, self._makeOne())
+
+ def test_ctor_disallows_unique(self):
+ self.assertRaises(TypeError, self._makeOne, unique=False)
+ self.assertRaises(TypeError, self._makeOne, unique=True)
+ self.assertTrue(self._makeOne().unique)
+
+ def test_validate_wrong_types(self):
+ from zope.schema.interfaces import WrongType
+ from zope.schema._compat import u
+ from zope.schema._compat import b
+ field = self._makeOne()
+ self.assertRaises(WrongType, field.validate, u(''))
+ self.assertRaises(WrongType, field.validate, b(''))
+ self.assertRaises(WrongType, field.validate, 1)
+ self.assertRaises(WrongType, field.validate, 1.0)
+ self.assertRaises(WrongType, field.validate, ())
+ self.assertRaises(WrongType, field.validate, [])
+ self.assertRaises(WrongType, field.validate, {})
+ self.assertRaises(WrongType, field.validate, frozenset())
+ self.assertRaises(WrongType, field.validate, object())
+
+ def test_validate_not_required(self):
+ field = self._makeOne(required=False)
+ field.validate(set())
+ field.validate(set((1, 2)))
+ field.validate(set((3,)))
+ field.validate(None)
+
+ def test_validate_required(self):
+ from zope.schema.interfaces import RequiredMissing
+ field = self._makeOne()
+ field.validate(set())
+ field.validate(set((1, 2)))
+ field.validate(set((3,)))
+ field.validate(set())
+ field.validate(set((1, 2)))
+ field.validate(set((3,)))
+ self.assertRaises(RequiredMissing, field.validate, None)
+
+ def test_validate_min_length(self):
+ from zope.schema.interfaces import TooShort
+ field = self._makeOne(min_length=2)
+ field.validate(set((1, 2)))
+ field.validate(set((1, 2, 3)))
+ self.assertRaises(TooShort, field.validate, set())
+ self.assertRaises(TooShort, field.validate, set((1,)))
+
+ def test_validate_max_length(self):
+ from zope.schema.interfaces import TooLong
+ field = self._makeOne(max_length=2)
+ field.validate(set())
+ field.validate(set((1,)))
+ field.validate(set((1, 2)))
+ self.assertRaises(TooLong, field.validate, set((1, 2, 3, 4)))
+ self.assertRaises(TooLong, field.validate, set((1, 2, 3)))
+
+ def test_validate_min_length_and_max_length(self):
+ from zope.schema.interfaces import TooLong
+ from zope.schema.interfaces import TooShort
+ field = self._makeOne(min_length=1, max_length=2)
+ field.validate(set((1,)))
+ field.validate(set((1, 2)))
+ self.assertRaises(TooShort, field.validate, set())
+ self.assertRaises(TooLong, field.validate, set((1, 2, 3)))
+
+
+class FrozenSetTests(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._field import FrozenSet
+ return FrozenSet
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_class_conforms_to_IFrozenSet(self):
+ from zope.interface.verify import verifyClass
+ from zope.schema.interfaces import IFrozenSet
+ verifyClass(IFrozenSet, self._getTargetClass())
+
+ def test_instance_conforms_to_IFrozenSet(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import IFrozenSet
+ verifyObject(IFrozenSet, self._makeOne())
+
+ def test_ctor_disallows_unique(self):
+ self.assertRaises(TypeError, self._makeOne, unique=False)
+ self.assertRaises(TypeError, self._makeOne, unique=True)
+ self.assertTrue(self._makeOne().unique)
+
+ def test_validate_wrong_types(self):
+ from zope.schema.interfaces import WrongType
+ from zope.schema._compat import u
+ from zope.schema._compat import b
+ field = self._makeOne()
+ self.assertRaises(WrongType, field.validate, u(''))
+ self.assertRaises(WrongType, field.validate, b(''))
+ self.assertRaises(WrongType, field.validate, 1)
+ self.assertRaises(WrongType, field.validate, 1.0)
+ self.assertRaises(WrongType, field.validate, ())
+ self.assertRaises(WrongType, field.validate, [])
+ self.assertRaises(WrongType, field.validate, {})
+ self.assertRaises(WrongType, field.validate, set())
+ self.assertRaises(WrongType, field.validate, object())
+
+ def test_validate_not_required(self):
+ field = self._makeOne(required=False)
+ field.validate(frozenset())
+ field.validate(frozenset((1, 2)))
+ field.validate(frozenset((3,)))
+ field.validate(None)
+
+ def test_validate_required(self):
+ from zope.schema.interfaces import RequiredMissing
+ field = self._makeOne()
+ field.validate(frozenset())
+ field.validate(frozenset((1, 2)))
+ field.validate(frozenset((3,)))
+ self.assertRaises(RequiredMissing, field.validate, None)
+
+ def test_validate_min_length(self):
+ from zope.schema.interfaces import TooShort
+ field = self._makeOne(min_length=2)
+ field.validate(frozenset((1, 2)))
+ field.validate(frozenset((1, 2, 3)))
+ self.assertRaises(TooShort, field.validate, frozenset())
+ self.assertRaises(TooShort, field.validate, frozenset((1,)))
+
+ def test_validate_max_length(self):
+ from zope.schema.interfaces import TooLong
+ field = self._makeOne(max_length=2)
+ field.validate(frozenset())
+ field.validate(frozenset((1,)))
+ field.validate(frozenset((1, 2)))
+ self.assertRaises(TooLong, field.validate, frozenset((1, 2, 3, 4)))
+ self.assertRaises(TooLong, field.validate, frozenset((1, 2, 3)))
+
+ def test_validate_min_length_and_max_length(self):
+ from zope.schema.interfaces import TooLong
+ from zope.schema.interfaces import TooShort
+ field = self._makeOne(min_length=1, max_length=2)
+ field.validate(frozenset((1,)))
+ field.validate(frozenset((1, 2)))
+ self.assertRaises(TooShort, field.validate, frozenset())
+ self.assertRaises(TooLong, field.validate, frozenset((1, 2, 3)))
+
+
+class ObjectTests(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 _makeOne(self, schema=None, *args, **kw):
+ if schema is None:
+ schema = self._makeSchema()
+ return self._getTargetClass()(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 WrongContainedType
+ try:
+ f(*args, **kw)
+ except WrongContainedType as e:
+ try:
+ return e.args[0]
+ except:
+ return []
+ self.fail('Expected WrongContainedType Error')
+
+ 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.schema.interfaces import WrongType
+ self.assertRaises(WrongType, self._makeOne, 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)
+ self.assertRaises(SchemaNotProvided, objf.validate, object())
+
+ 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 WrongContainedType
+ from zope.schema._bootstrapfields import Text
+ schema = self._makeSchema(foo=Text(), bar=Text())
+ @implementer(schema)
+ class Broken(object):
+ pass
+ objf = self._makeOne(schema)
+ self.assertRaises(WrongContainedType, objf.validate, Broken())
+ errors = self._getErrors(objf.validate, Broken())
+ self.assertEqual(len(errors), 2)
+ err = errors[0]
+ self.assertEqual(isinstance(err, SchemaNotFullyImplemented), True)
+ nested = err.args[0]
+ self.assertEqual(isinstance(nested, AttributeError), True)
+ self.assertEqual("'foo'" in str(nested), True)
+ err = errors[1]
+ self.assertEqual(isinstance(err, SchemaNotFullyImplemented), True)
+ nested = err.args[0]
+ self.assertEqual(isinstance(nested, AttributeError), True)
+ self.assertEqual("'bar'" in str(nested), True)
+
+ def test__validate_w_value_providing_schema_but_invalid_fields(self):
+ from zope.interface import implementer
+ from zope.schema.interfaces import WrongContainedType
+ 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)
+ self.assertRaises(WrongContainedType, objf.validate, Broken())
+ errors = self._getErrors(objf.validate, Broken())
+ self.assertEqual(len(errors), 2)
+ err = errors[0]
+ self.assertEqual(isinstance(err, RequiredMissing), True)
+ self.assertEqual(err.args, ('foo',))
+ err = errors[1]
+ self.assertEqual(isinstance(err, WrongType), True)
+ 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
+ from zope.schema._compat import u
+ 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 WrongContainedType
+ IUnit, Person, Unit = self._makeCycles()
+ field = self._makeOne(schema=IUnit)
+ person1 = Person(None)
+ person2 = Person(None)
+ person3 = Person(DummyInstance())
+ unit = Unit(person3, [person1, person2])
+ person1.unit = unit
+ person2.unit = unit
+ self.assertRaises(WrongContainedType, field.validate, unit)
+
+ def test_validate_w_cycles_collection_not_valid(self):
+ from zope.schema.interfaces import WrongContainedType
+ IUnit, Person, Unit = self._makeCycles()
+ field = self._makeOne(schema=IUnit)
+ person1 = Person(None)
+ person2 = Person(None)
+ person3 = Person(DummyInstance())
+ unit = Unit(person1, [person2, person3])
+ person1.unit = unit
+ person2.unit = unit
+ self.assertRaises(WrongContainedType, 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
+ from zope.schema._compat import u
+ 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 = DummyInstance()
+ value = OK()
+ objf.set(inst, value)
+ self.assertEqual(inst.field is value, True)
+ self.assertEqual(len(log), 1)
+ self.assertEqual(IBeforeObjectAssignedEvent.providedBy(log[0]), True)
+ self.assertEqual(log[0].object, value)
+ self.assertEqual(log[0].name, 'field')
+ self.assertEqual(log[0].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
+ from zope.schema._compat import u
+ 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 = DummyInstance()
+ objf.set(inst, ok1)
+ self.assertEqual(inst.field is ok2, True)
+ self.assertEqual(len(log), 1)
+ self.assertEqual(log[0].object, ok2)
+ self.assertEqual(log[0].name, 'field')
+ self.assertEqual(log[0].context, inst)
+
+
+class DictTests(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._field import Dict
+ return Dict
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_class_conforms_to_IDict(self):
+ from zope.interface.verify import verifyClass
+ from zope.schema.interfaces import IDict
+ verifyClass(IDict, self._getTargetClass())
+
+ def test_instance_conforms_to_IDict(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import IDict
+ verifyObject(IDict, self._makeOne())
+
+ 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):
+ from zope.schema.interfaces import WrongType
+ from zope.schema._compat import u
+ from zope.schema._compat import b
+ field = self._makeOne()
+ self.assertRaises(WrongType, field.validate, u(''))
+ self.assertRaises(WrongType, field.validate, b(''))
+ self.assertRaises(WrongType, field.validate, 1)
+ self.assertRaises(WrongType, field.validate, 1.0)
+ self.assertRaises(WrongType, field.validate, ())
+ self.assertRaises(WrongType, field.validate, [])
+ self.assertRaises(WrongType, field.validate, set())
+ self.assertRaises(WrongType, field.validate, frozenset())
+ self.assertRaises(WrongType, field.validate, 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._bootstrapfields import Int
+ field = self._makeOne(key_type=Int())
+ field.validate({})
+ field.validate({1: 'b', 2: 'd'})
+ field.validate({3: 'a'})
+ self.assertRaises(WrongContainedType, field.validate, {'a': 1})
+
+ def test_validate_invalid_value_type(self):
+ from zope.schema.interfaces import WrongContainedType
+ from zope.schema._bootstrapfields import Int
+ field = self._makeOne(value_type=Int())
+ field.validate({})
+ field.validate({'b': 1, 'd': 2})
+ field.validate({'a': 3})
+ self.assertRaises(WrongContainedType, field.validate, {1: 'a'})
+
+ def test_validate_min_length(self):
+ from zope.schema.interfaces import TooShort
+ field = self._makeOne(min_length=1)
+ field.validate({1: 'a'})
+ field.validate({1: 'a', 2: 'b'})
+ self.assertRaises(TooShort, field.validate, {})
+
+ def test_validate_max_length(self):
+ from zope.schema.interfaces import TooLong
+ field = self._makeOne(max_length=1)
+ field.validate({})
+ field.validate({1: 'a'})
+ self.assertRaises(TooLong, field.validate, {1: 'a', 2: 'b'})
+ self.assertRaises(TooLong, field.validate, {1: 'a', 2: 'b', 3: 'c'})
+
+ def test_validate_min_length_and_max_length(self):
+ from zope.schema.interfaces import TooLong
+ from zope.schema.interfaces import TooShort
+ field = self._makeOne(min_length=1, max_length=2)
+ field.validate({1: 'a'})
+ field.validate({1: 'a', 2: 'b'})
+ self.assertRaises(TooShort, field.validate, {})
+ self.assertRaises(TooLong, field.validate, {1: 'a', 2: 'b', 3: 'c'})
+
+ def test_bind_binds_key_and_value_types(self):
+ from zope.schema import Int
+ field = self._makeOne(key_type=Int(), value_type=Int())
+ context = DummyInstance()
+ field2 = field.bind(context)
+ self.assertEqual(field2.key_type.context, context)
+ self.assertEqual(field2.value_type.context, context)
+
+
+class URITests(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._field import URI
+ return URI
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_class_conforms_to_IURI(self):
+ from zope.interface.verify import verifyClass
+ from zope.schema.interfaces import IURI
+ verifyClass(IURI, self._getTargetClass())
+
+ def test_instance_conforms_to_IURI(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import IURI
+ verifyObject(IURI, self._makeOne())
+
+ def test_validate_wrong_types(self):
+ from zope.schema.interfaces import WrongType
+ from zope.schema._compat import non_native_string
+ field = self._makeOne()
+ self.assertRaises(WrongType, field.validate, non_native_string(''))
+ self.assertRaises(WrongType, field.validate, 1)
+ self.assertRaises(WrongType, field.validate, 1.0)
+ self.assertRaises(WrongType, field.validate, ())
+ self.assertRaises(WrongType, field.validate, [])
+ self.assertRaises(WrongType, field.validate, {})
+ self.assertRaises(WrongType, field.validate, set())
+ self.assertRaises(WrongType, field.validate, frozenset())
+ self.assertRaises(WrongType, field.validate, 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()
+ self.assertRaises(InvalidURI, field.validate, '')
+ 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):
+ from zope.schema._compat import u
+ 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
+ from zope.schema._compat import u
+ 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 IdTests(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._field import Id
+ return Id
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_class_conforms_to_IId(self):
+ from zope.interface.verify import verifyClass
+ from zope.schema.interfaces import IId
+ verifyClass(IId, self._getTargetClass())
+
+ def test_instance_conforms_to_IId(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import IId
+ verifyObject(IId, self._makeOne())
+
+ def test_validate_wrong_types(self):
+ from zope.schema.interfaces import WrongType
+ from zope.schema._compat import non_native_string
+ field = self._makeOne()
+ self.assertRaises(WrongType, field.validate, non_native_string(''))
+ self.assertRaises(WrongType, field.validate, 1)
+ self.assertRaises(WrongType, field.validate, 1.0)
+ self.assertRaises(WrongType, field.validate, ())
+ self.assertRaises(WrongType, field.validate, [])
+ self.assertRaises(WrongType, field.validate, {})
+ self.assertRaises(WrongType, field.validate, set())
+ self.assertRaises(WrongType, field.validate, frozenset())
+ self.assertRaises(WrongType, field.validate, 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()
+ self.assertRaises(InvalidId, field.validate, '')
+ 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):
+ from zope.schema._compat import u
+ field = self._makeOne()
+ self.assertEqual(field.fromUnicode(u('http://example.com/')),
+ 'http://example.com/')
+
+ def test_fromUnicode_dotted_name_ok(self):
+ from zope.schema._compat import u
+ 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
+ from zope.schema._compat import u
+ field = self._makeOne()
+ self.assertRaises(InvalidId, field.fromUnicode, u(''))
+ self.assertRaises(InvalidId, field.fromUnicode, u('abc'))
+ self.assertRaises(ConstraintNotSatisfied,
+ field.fromUnicode, u('http://example.com/\nDAV:'))
+
+
+class DottedNameTests(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from zope.schema._field import DottedName
+ return DottedName
+
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
+
+ def test_class_conforms_to_IDottedName(self):
+ from zope.interface.verify import verifyClass
+ from zope.schema.interfaces import IDottedName
+ verifyClass(IDottedName, self._getTargetClass())
+
+ def test_instance_conforms_to_IDottedName(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import IDottedName
+ verifyObject(IDottedName, self._makeOne())
+
+ 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.interfaces import WrongType
+ from zope.schema._compat import non_native_string
+ field = self._makeOne()
+ self.assertRaises(WrongType, field.validate, non_native_string(''))
+ self.assertRaises(WrongType, field.validate, 1)
+ self.assertRaises(WrongType, field.validate, 1.0)
+ self.assertRaises(WrongType, field.validate, ())
+ self.assertRaises(WrongType, field.validate, [])
+ self.assertRaises(WrongType, field.validate, {})
+ self.assertRaises(WrongType, field.validate, set())
+ self.assertRaises(WrongType, field.validate, frozenset())
+ self.assertRaises(WrongType, field.validate, 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)
+ self.assertRaises(InvalidDottedName, field.validate, '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')
+ self.assertRaises(InvalidDottedName,
+ field.validate, '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):
+ from zope.schema._compat import u
+ 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 InvalidDottedName
+ from zope.schema._compat import u
+ field = self._makeOne()
+ self.assertRaises(InvalidDottedName, field.fromUnicode, u(''))
+ self.assertRaises(ConstraintNotSatisfied,
+ field.fromUnicode, u('http://example.com/\nDAV:'))
+
+
+class DummyInstance(object):
+ pass
+
+
+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):
+ return iter([self.getTerm(x) for x in range(0, 10)])
+
+ def __contains__(self, value):
+ return 0 <= value < 10
+
+ def __len__(self):
+ return 10
+
+ def getTerm(self, value):
+ if value in self:
+ t = SampleTerm()
+ t.value = value
+ t.double = 2 * value
+ return t
+ raise LookupError("no such value: %r" % value)
+
+ return SampleVocabulary()
+
+def _makeDummyRegistry(v):
+ from zope.schema.vocabulary import VocabularyRegistry
+ class DummyRegistry(VocabularyRegistry):
+ def __init__(self, vocabulary):
+ self._vocabulary = vocabulary
+ def get(self, object, name):
+ return self._vocabulary
+ return DummyRegistry(v)
+
+
+def test_suite():
+ return unittest.TestSuite((
+ unittest.makeSuite(BytesTests),
+ unittest.makeSuite(ASCIITests),
+ unittest.makeSuite(BytesLineTests),
+ unittest.makeSuite(ASCIILineTests),
+ unittest.makeSuite(FloatTests),
+ unittest.makeSuite(DecimalTests),
+ unittest.makeSuite(DatetimeTests),
+ unittest.makeSuite(DateTests),
+ unittest.makeSuite(TimedeltaTests),
+ unittest.makeSuite(TimeTests),
+ unittest.makeSuite(ChoiceTests),
+ unittest.makeSuite(InterfaceFieldTests),
+ unittest.makeSuite(AbstractCollectionTests),
+ unittest.makeSuite(TupleTests),
+ unittest.makeSuite(ListTests),
+ unittest.makeSuite(SetTests),
+ unittest.makeSuite(FrozenSetTests),
+ unittest.makeSuite(ObjectTests),
+ unittest.makeSuite(DictTests),
+ unittest.makeSuite(URITests),
+ unittest.makeSuite(IdTests),
+ unittest.makeSuite(DottedNameTests),
+ ))
+
Modified: zope.schema/trunk/src/zope/schema/tests/test_accessors.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_accessors.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_accessors.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -14,113 +14,271 @@
"""Test Interface accessor methods.
"""
import unittest
-from zope.interface import Interface, implementer
-from six import u
-from zope.schema import Text, accessors
-from zope.schema.interfaces import IText
-from zope.schema.accessors import FieldReadAccessor, FieldWriteAccessor
-from zope.interface.verify import verifyClass, verifyObject
-from zope.interface import document
-from zope.interface.interfaces import IMethod
-class Test(unittest.TestCase):
- def test(self):
+class FieldReadAccessorTests(unittest.TestCase):
- field = Text(title=u("Foo thing"))
+ def _getTargetClass(self):
+ from zope.schema.accessors import FieldReadAccessor
+ return FieldReadAccessor
- class I(Interface):
+ def _makeOne(self, field=None):
+ from zope.schema import Text
+ if field is None:
+ field = Text(__name__='testing')
+ return self._getTargetClass()(field)
- getFoo, setFoo = accessors(field)
+ def test_ctor_not_created_inside_interface(self):
+ from zope.schema import Text
+ from zope.schema._compat import u
+ field = Text(title=u('Hmm'))
+ wrapped = self._makeOne(field)
+ self.assertTrue(wrapped.field is field)
+ self.assertEqual(wrapped.__name__, '') #__name__ set when in interface
+ self.assertEqual(wrapped.__doc__, 'get Hmm')
- @implementer(I)
- class Bad(object):
+ def test_ctor_created_inside_interface(self):
+ from zope.interface import Interface
+ from zope.schema import Text
+ from zope.schema._compat import u
+ 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.schema import Text
+ field = Text()
+ field_provides = list(providedBy(field))
+ wrapped = self._makeOne(field)
+ wrapped_provides = list(providedBy(wrapped))
+ self.assertEqual(wrapped_provides[:len(field_provides)],
+ list(providedBy(field)))
+ for iface in list(implementedBy(self._getTargetClass())):
+ self.assertTrue(iface in wrapped_provides)
+
+ 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())
- @implementer(I)
- class Good(object):
-
- def __init__(self):
- self.set = 0
+ 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 getFoo(self):
- return u("foo")
+ 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 setFoo(self, v):
- self.set += 1
+ 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)
- names = I.names()
- names.sort()
- self.assertEqual(names, ['getFoo', 'setFoo'])
- self.assertEqual(I['getFoo'].field, field)
- self.assertEqual(I['getFoo'].__name__, 'getFoo')
- self.assertEqual(I['getFoo'].__doc__, u('get Foo thing'))
- self.assertEqual(I['getFoo'].__class__, FieldReadAccessor)
- self.assertEqual(I['getFoo'].writer, I['setFoo'])
+ 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')
- # test some field attrs
- for attr in ('title', 'description', 'readonly'):
- self.assertEqual(getattr(I['getFoo'], attr), getattr(field, attr))
+ 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):
+ return '123'
+ self.assertRaises(TypeError, getter.set, Foo(), '456')
- self.assertTrue(IText.providedBy(I['getFoo']))
-
- self.assertTrue(IMethod.providedBy(I['getFoo']))
- self.assertTrue(IMethod.providedBy(I['setFoo']))
+ 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):
+ return '123'
+ self.assertRaises(AttributeError, getter.set, Foo(), '456')
- self.assertEqual(I['setFoo'].field, field)
- self.assertEqual(I['setFoo'].__name__, 'setFoo')
- self.assertEqual(I['setFoo'].__doc__, u('set Foo thing'))
- self.assertEqual(I['setFoo'].__class__, FieldWriteAccessor)
+ 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()
+ writer.__name__ = 'setMe'
+ getter.writer = writer
+ class Foo(object):
+ def setMe(self, value):
+ _called_with.append(value)
+ getter.set(Foo(), '456')
+ self.assertEqual(_called_with, ['456'])
- self.assertRaises(Exception, verifyClass, I, Bad)
- self.assertRaises(Exception, verifyObject, I, Bad())
-
- self.assertEqual(I['getFoo'].query(Bad(), 42), 42)
- self.assertRaises(AttributeError, I['getFoo'].get, Bad())
+ 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)
- verifyClass(I, Good)
- verifyObject(I, Good())
- self.assertEqual(I['getFoo'].query(Good(), 42), u('foo'))
- self.assertEqual(I['getFoo'].get(Good()), u('foo'))
- instance = Good()
- I['getFoo'].set(instance, u('whatever'))
- self.assertEqual(instance.set, 1)
+class FieldWriteAccessorTests(unittest.TestCase):
- def test_doc(self):
+ def _getTargetClass(self):
+ from zope.schema.accessors import FieldWriteAccessor
+ return FieldWriteAccessor
- field = Text(title=u("Foo thing"))
+ def _makeOne(self, field=None):
+ from zope.schema import Text
+ if field is None:
+ field = Text(__name__='testing')
+ return self._getTargetClass()(field)
- class I(Interface):
+ def test_ctor_not_created_inside_interface(self):
+ from zope.schema import Text
+ from zope.schema._compat import u
+ field = Text(title=u('Hmm'))
+ wrapped = self._makeOne(field)
+ self.assertTrue(wrapped.field is field)
+ self.assertEqual(wrapped.__name__, '') #__name__ set when in interface
+ self.assertEqual(wrapped.__doc__, 'set Hmm')
- getFoo, setFoo = accessors(field)
- def bar(): pass
- x = Text()
+ def test_ctor_created_inside_interface(self):
+ from zope.interface import Interface
+ from zope.schema import Text
+ from zope.schema._compat import u
+ 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')
- d = document.asStructuredText(I)
- self.assertEqual(d,
- "I\n"
- "\n"
- " Attributes:\n"
- "\n"
- " x -- no documentation\n"
- "\n"
- " Methods:\n"
- "\n"
- " bar() -- no documentation\n"
- "\n"
- " getFoo() -- get Foo thing\n"
- "\n"
- " setFoo(newvalue) -- set Foo thing\n"
- "\n"
- )
+ 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)
-def test_suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(Test))
- return suite
+class Test_accessors(unittest.TestCase):
-if __name__ == '__main__':
- unittest.main()
+ 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
+ from zope.schema._compat import u
+ 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
+ from zope.schema._compat import u
+ 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)
+
+
+def test_suite():
+ return unittest.TestSuite((
+ unittest.makeSuite(FieldReadAccessorTests),
+ unittest.makeSuite(FieldWriteAccessorTests),
+ unittest.makeSuite(Test_accessors),
+ ))
Deleted: zope.schema/trunk/src/zope/schema/tests/test_boolfield.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_boolfield.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_boolfield.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,71 +0,0 @@
-##############################################################################
-#
-# 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.
-#
-##############################################################################
-"""Boolean field tests
-"""
-from unittest import main, makeSuite
-
-from six import u
-from zope.schema import Bool
-from zope.schema.interfaces import RequiredMissing, IBool, IFromUnicode
-from zope.schema.tests.test_field import FieldTestBase
-import zope.interface.adapter
-import zope.interface
-
-
-class BoolTest(FieldTestBase):
- """Test the Bool Field."""
-
- _Field_Factory = Bool
-
- def testValidate(self):
- field = Bool(title=u('Bool field'), description=u(''),
- readonly=False, required=False)
- field.validate(None)
- field.validate(True)
- field.validate(False)
-
- def testValidateRequired(self):
- field = Bool(title=u('Bool field'), description=u(''),
- readonly=False, required=True)
- field.validate(True)
- field.validate(False)
-
- self.assertRaises(RequiredMissing, field.validate, None)
-
- def testIBoolIsMoreImportantThanIFromUnicode(self):
- registry = zope.interface.adapter.AdapterRegistry()
-
- def adapt_bool(context):
- return 'bool'
-
- def adapt_from_unicode(context):
- return 'unicode'
-
- class IAdaptTo(zope.interface.Interface):
- pass
-
- registry.register((IBool,), IAdaptTo, u(''), adapt_bool)
- registry.register((IFromUnicode,), IAdaptTo, u(''), adapt_from_unicode)
-
- field = Bool(title=u('Bool field'), description=u(''),
- readonly=False, required=True)
-
- self.assertEqual('bool', registry.queryAdapter(field, IAdaptTo))
-
-
-def test_suite():
- return makeSuite(BoolTest)
-
-if __name__ == '__main__':
- main(defaultTest='test_suite')
Deleted: zope.schema/trunk/src/zope/schema/tests/test_choice.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_choice.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_choice.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,151 +0,0 @@
-##############################################################################
-#
-# 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 Choice field.
-"""
-import unittest
-
-from six import u
-from zope.interface import implementer
-from zope.schema import vocabulary
-from zope.schema import Choice
-from zope.schema.interfaces import ConstraintNotSatisfied
-from zope.schema.interfaces import ValidationError
-from zope.schema.interfaces import InvalidValue, NotAContainer, NotUnique
-from zope.schema.interfaces import IContextSourceBinder
-
-from zope.schema.tests.test_vocabulary import SampleVocabulary, DummyRegistry
-
-
-class Value_ChoiceFieldTests(unittest.TestCase):
- """Tests of the Choice Field using values."""
-
- def test_create_vocabulary(self):
- choice = Choice(values=[1, 3])
- self.assertEqual([term.value for term in choice.vocabulary], [1, 3])
-
- def test_validate_int(self):
- choice = Choice(values=[1, 3])
- choice.validate(1)
- choice.validate(3)
- self.assertRaises(ConstraintNotSatisfied, choice.validate, 4)
-
- def test_validate_string(self):
- choice = Choice(values=['a', 'c'])
- choice.validate('a')
- choice.validate('c')
- choice.validate(u('c'))
- self.assertRaises(ConstraintNotSatisfied, choice.validate, 'd')
-
- def test_validate_tuple(self):
- choice = Choice(values=[(1, 2), (5, 6)])
- choice.validate((1, 2))
- choice.validate((5, 6))
- self.assertRaises(ConstraintNotSatisfied, choice.validate, [5, 6])
- self.assertRaises(ConstraintNotSatisfied, choice.validate, ())
-
- def test_validate_mixed(self):
- choice = Choice(values=[1, 'b', (0.2,)])
- choice.validate(1)
- choice.validate('b')
- choice.validate((0.2,))
- self.assertRaises(ConstraintNotSatisfied, choice.validate, '1')
- self.assertRaises(ConstraintNotSatisfied, choice.validate, 0.2)
-
-class Vocabulary_ChoiceFieldTests(unittest.TestCase):
- """Tests of the Choice Field using vocabularies."""
-
- def setUp(self):
- vocabulary._clear()
-
- def tearDown(self):
- vocabulary._clear()
-
- def check_preconstructed(self, cls, okval, badval):
- v = SampleVocabulary()
- field = cls(vocabulary=v)
- self.assertTrue(field.vocabulary is v)
- self.assertTrue(field.vocabularyName is None)
- bound = field.bind(None)
- self.assertTrue(bound.vocabulary is v)
- self.assertTrue(bound.vocabularyName is None)
- bound.default = okval
- self.assertEqual(bound.default, okval)
- self.assertRaises(ValidationError, setattr, bound, "default", badval)
-
- def test_preconstructed_vocabulary(self):
- self.check_preconstructed(Choice, 1, 42)
-
- def check_constructed(self, cls, okval, badval):
- vocabulary.setVocabularyRegistry(DummyRegistry())
- field = cls(vocabulary="vocab")
- self.assertTrue(field.vocabulary is None)
- self.assertEqual(field.vocabularyName, "vocab")
- o = object()
- bound = field.bind(o)
- self.assertTrue(isinstance(bound.vocabulary, SampleVocabulary))
- bound.default = okval
- self.assertEqual(bound.default, okval)
- self.assertRaises(ValidationError, setattr, bound, "default", badval)
-
- def test_constructed_vocabulary(self):
- self.check_constructed(Choice, 1, 42)
-
- def test_create_vocabulary(self):
- vocabulary.setVocabularyRegistry(DummyRegistry())
- field = Choice(vocabulary="vocab")
- o = object()
- bound = field.bind(o)
- self.assertEqual([term.value for term in bound.vocabulary],
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
-
- def test_undefined_vocabulary(self):
- choice = Choice(vocabulary="unknown")
- self.assertRaises(ValueError, choice.validate, "value")
-
-
- at implementer(IContextSourceBinder)
-class SampleContextSourceBinder(object):
- def __call__(self, context):
- return SampleVocabulary()
-
-class ContextSourceBinder_ChoiceFieldTests(unittest.TestCase):
- """Tests of the Choice Field using IContextSourceBinder as source."""
-
- def setUp(self):
- vocabulary._clear()
-
- def tearDown(self):
- vocabulary._clear()
-
- def test_validate_source(self):
- s = SampleContextSourceBinder()
- choice = Choice(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)
-
-
-def test_suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(Vocabulary_ChoiceFieldTests))
- suite.addTest(unittest.makeSuite(Value_ChoiceFieldTests))
- suite.addTest(unittest.makeSuite(ContextSourceBinder_ChoiceFieldTests))
- return suite
-
-if __name__ == "__main__":
- unittest.main(defaultTest="test_suite")
Deleted: zope.schema/trunk/src/zope/schema/tests/test_containerfield.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_containerfield.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_containerfield.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,58 +0,0 @@
-##############################################################################
-#
-# 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.
-#
-##############################################################################
-"""Container field tests
-"""
-from six import PY3, u
-if not PY3:
- from UserDict import UserDict
-else:
- #python3
- from collections import UserDict
-from unittest import main, makeSuite
-from zope.schema import Container
-from zope.schema.interfaces import RequiredMissing, NotAContainer
-from zope.schema.tests.test_field import FieldTestBase
-
-class ContainerTest(FieldTestBase):
- """Test the Container Field."""
-
- _Field_Factory = Container
-
- def testValidate(self):
- field = self._Field_Factory(title=u('test field'), description=u(''),
- readonly=False, required=False)
- field.validate(None)
- field.validate('')
- field.validate('abc')
- field.validate([1, 2, 3])
- field.validate({'a': 1, 'b': 2})
- field.validate(UserDict())
-
- self.assertRaises(NotAContainer, field.validate, 1)
- self.assertRaises(NotAContainer, field.validate, True)
-
- def testValidateRequired(self):
- field = self._Field_Factory(title=u('test field'), description=u(''),
- readonly=False, required=True)
-
- field.validate('')
-
- self.assertRaises(RequiredMissing, field.validate, None)
-
-
-def test_suite():
- return makeSuite(ContainerTest)
-
-if __name__ == '__main__':
- main(defaultTest='test_suite')
Deleted: zope.schema/trunk/src/zope/schema/tests/test_date.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_date.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_date.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,97 +0,0 @@
-##############################################################################
-#
-# 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.
-#
-##############################################################################
-"""Date field tests
-"""
-from unittest import main, makeSuite
-
-from six import u
-from zope.schema import Date
-from zope.schema.interfaces import RequiredMissing, InvalidValue, WrongType
-from zope.schema.interfaces import TooSmall, TooBig
-from zope.schema.tests.test_field import FieldTestBase
-from datetime import datetime, date
-
-class DateTest(FieldTestBase):
- """Test the Date Field."""
-
- _Field_Factory = Date
-
- def testInterface(self):
- from zope.interface.verify import verifyObject
- from zope.schema.interfaces import IDate
- verifyObject(IDate, self._Field_Factory())
-
- def testValidate(self):
- field = self._Field_Factory(title=u('Date field'), description=u(''),
- readonly=False, required=False)
- field.validate(None)
- field.validate(datetime.now().date())
- self.assertRaises(WrongType, field.validate, datetime.now())
-
- def testValidateRequired(self):
- field = self._Field_Factory(title=u('Date field'), description=u(''),
- readonly=False, required=True)
- field.validate(datetime.now().date())
-
- self.assertRaises(RequiredMissing, field.validate, None)
-
- def testValidateMin(self):
- d1 = date(2000,10,1)
- d2 = date(2000,10,2)
- field = self._Field_Factory(title=u('Date field'), description=u(''),
- readonly=False, required=False, min=d1)
- field.validate(None)
- field.validate(d1)
- field.validate(d2)
- field.validate(datetime.now().date())
-
- self.assertRaises(TooSmall, field.validate, date(2000,9,30))
-
- def testValidateMax(self):
- d1 = date(2000,10,1)
- d2 = date(2000,10,2)
- d3 = date(2000,10,3)
- field = self._Field_Factory(title=u('Date field'), description=u(''),
- readonly=False, required=False, max=d2)
- field.validate(None)
- field.validate(d1)
- field.validate(d2)
-
- self.assertRaises(TooBig, field.validate, d3)
-
- def testValidateMinAndMax(self):
- d1 = date(2000,10,1)
- d2 = date(2000,10,2)
- d3 = date(2000,10,3)
- d4 = date(2000,10,4)
- d5 = date(2000,10,5)
-
- field = self._Field_Factory(title=u('Date field'), description=u(''),
- readonly=False, required=False,
- min=d2, max=d4)
- field.validate(None)
- field.validate(d2)
- field.validate(d3)
- field.validate(d4)
-
- self.assertRaises(TooSmall, field.validate, d1)
- self.assertRaises(TooBig, field.validate, d5)
-
-
-def test_suite():
- suite = makeSuite(DateTest)
- return suite
-
-if __name__ == '__main__':
- main(defaultTest='test_suite')
Deleted: zope.schema/trunk/src/zope/schema/tests/test_datetime.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_datetime.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_datetime.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,91 +0,0 @@
-##############################################################################
-#
-# 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.
-#
-##############################################################################
-"""Datetime Field tests
-"""
-from unittest import main, makeSuite
-
-from six import u
-from zope.schema import Datetime
-from zope.schema.interfaces import RequiredMissing, InvalidValue
-from zope.schema.interfaces import TooSmall, TooBig
-from zope.schema.tests.test_field import FieldTestBase
-from datetime import datetime
-
-class DatetimeTest(FieldTestBase):
- """Test the Datetime Field."""
-
- _Field_Factory = Datetime
-
- def testValidate(self):
- field = self._Field_Factory(title=u('Datetime field'), description=u(''),
- readonly=False, required=False)
- field.validate(None)
- field.validate(datetime.now())
-
- def testValidateRequired(self):
- field = self._Field_Factory(title=u('Datetime field'), description=u(''),
- readonly=False, required=True)
- field.validate(datetime.now())
-
- self.assertRaises(RequiredMissing, field.validate, None)
-
- def testValidateMin(self):
- d1 = datetime(2000,10,1)
- d2 = datetime(2000,10,2)
- field = self._Field_Factory(title=u('Datetime field'), description=u(''),
- readonly=False, required=False, min=d1)
- field.validate(None)
- field.validate(d1)
- field.validate(d2)
- field.validate(datetime.now())
-
- self.assertRaises(TooSmall, field.validate, datetime(2000,9,30))
-
- def testValidateMax(self):
- d1 = datetime(2000,10,1)
- d2 = datetime(2000,10,2)
- d3 = datetime(2000,10,3)
- field = self._Field_Factory(title=u('Datetime field'), description=u(''),
- readonly=False, required=False, max=d2)
- field.validate(None)
- field.validate(d1)
- field.validate(d2)
-
- self.assertRaises(TooBig, field.validate, d3)
-
- def testValidateMinAndMax(self):
- d1 = datetime(2000,10,1)
- d2 = datetime(2000,10,2)
- d3 = datetime(2000,10,3)
- d4 = datetime(2000,10,4)
- d5 = datetime(2000,10,5)
-
- field = self._Field_Factory(title=u('Datetime field'), description=u(''),
- readonly=False, required=False,
- min=d2, max=d4)
- field.validate(None)
- field.validate(d2)
- field.validate(d3)
- field.validate(d4)
-
- self.assertRaises(TooSmall, field.validate, d1)
- self.assertRaises(TooBig, field.validate, d5)
-
-
-def test_suite():
- suite = makeSuite(DatetimeTest)
- return suite
-
-if __name__ == '__main__':
- main(defaultTest='test_suite')
Deleted: zope.schema/trunk/src/zope/schema/tests/test_decimalfield.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_decimalfield.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_decimalfield.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,90 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002, 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.
-#
-##############################################################################
-"""Decimal field tests
-"""
-import decimal
-
-from six import u
-from unittest import main, makeSuite
-from zope.schema import Decimal
-from zope.schema.interfaces import RequiredMissing, InvalidValue
-from zope.schema.interfaces import TooSmall, TooBig
-from zope.schema.tests.test_field import FieldTestBase
-
-class DecimalTest(FieldTestBase):
- """Test the Decimal Field."""
-
- _Field_Factory = Decimal
-
- def testValidate(self):
- field = self._Field_Factory(title=u('Decimal field'), description=u(''),
- readonly=False, required=False)
- field.validate(None)
- field.validate(decimal.Decimal("10.0"))
- field.validate(decimal.Decimal("0.93"))
- field.validate(decimal.Decimal("1000.0003"))
-
- def testValidateRequired(self):
- field = self._Field_Factory(title=u('Decimal field'), description=u(''),
- readonly=False, required=True)
- 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 testValidateMin(self):
- field = self._Field_Factory(title=u('Decimal field'), description=u(''),
- readonly=False, required=False,
- min=decimal.Decimal("10.5"))
- field.validate(None)
- field.validate(decimal.Decimal("10.6"))
- field.validate(decimal.Decimal("20.2"))
-
- self.assertRaises(TooSmall, field.validate, decimal.Decimal("-9.0"))
- self.assertRaises(TooSmall, field.validate, decimal.Decimal("10.4"))
-
- def testValidateMax(self):
- field = self._Field_Factory(title=u('Decimal field'), description=u(''),
- readonly=False, required=False,
- max=decimal.Decimal("10.5"))
- field.validate(None)
- field.validate(decimal.Decimal("5.3"))
- field.validate(decimal.Decimal("-9.1"))
-
- self.assertRaises(TooBig, field.validate, decimal.Decimal("10.51"))
- self.assertRaises(TooBig, field.validate, decimal.Decimal("20.7"))
-
- def testValidateMinAndMax(self):
- field = self._Field_Factory(title=u('Decimal field'), description=u(''),
- readonly=False, required=False,
- min=decimal.Decimal("-0.6"),
- max=decimal.Decimal("10.1"))
- field.validate(None)
- field.validate(decimal.Decimal("0.0"))
- field.validate(decimal.Decimal("-0.03"))
- field.validate(decimal.Decimal("10.0001"))
-
- self.assertRaises(TooSmall, field.validate, decimal.Decimal("-10.0"))
- self.assertRaises(TooSmall, field.validate, decimal.Decimal("-1.6"))
- self.assertRaises(TooBig, field.validate, decimal.Decimal("11.45"))
- self.assertRaises(TooBig, field.validate, decimal.Decimal("20.02"))
-
-
-def test_suite():
- suite = makeSuite(DecimalTest)
- return suite
-
-if __name__ == '__main__':
- main(defaultTest='test_suite')
Deleted: zope.schema/trunk/src/zope/schema/tests/test_dictfield.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_dictfield.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_dictfield.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,125 +0,0 @@
-##############################################################################
-#
-# 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.
-#
-##############################################################################
-"""Dictionary field tests
-"""
-from unittest import main, makeSuite
-
-from six import u
-from zope.schema import Dict, Int
-from zope.schema.interfaces import RequiredMissing, WrongContainedType
-from zope.schema.interfaces import TooShort, TooLong
-from zope.schema.tests.test_field import FieldTestBase
-
-class DictTest(FieldTestBase):
- """Test the Dict Field."""
-
- _Field_Factory = Dict
-
- def testValidate(self):
- field = Dict(title=u('Dict field'),
- description=u(''), readonly=False, required=False)
- field.validate(None)
- field.validate({})
- field.validate({1: 'foo'})
- field.validate({'a': 1})
-
- def testValidateRequired(self):
- field = Dict(title=u('Dict field'),
- description=u(''), readonly=False, required=True)
- field.validate({})
- field.validate({1: 'foo'})
- field.validate({'a': 1})
-
- self.assertRaises(RequiredMissing, field.validate, None)
-
- def testValidateMinValues(self):
- field = Dict(title=u('Dict field'),
- description=u(''), readonly=False, required=False,
- min_length=1)
- field.validate(None)
- field.validate({1: 'a'})
- field.validate({1: 'a', 2: 'b'})
-
- self.assertRaises(TooShort, field.validate, {})
-
- def testValidateMaxValues(self):
- field = Dict(title=u('Dict field'),
- description=u(''), readonly=False, required=False,
- max_length=1)
- field.validate(None)
- field.validate({})
- field.validate({1: 'a'})
-
- self.assertRaises(TooLong, field.validate, {1: 'a', 2: 'b'})
- self.assertRaises(TooLong, field.validate, {1: 'a', 2: 'b', 3: 'c'})
-
- def testValidateMinValuesAndMaxValues(self):
- field = Dict(title=u('Dict field'),
- description=u(''), readonly=False, required=False,
- min_length=1, max_length=2)
- field.validate(None)
- field.validate({1: 'a'})
- field.validate({1: 'a', 2: 'b'})
-
- self.assertRaises(TooShort, field.validate, {})
- self.assertRaises(TooLong, field.validate, {1: 'a', 2: 'b', 3: 'c'})
-
- def testValidateValueType(self):
- field = Dict(title=u('Dict field'),
- description=u(''), readonly=False, required=False,
- value_type=Int())
- field.validate(None)
- field.validate({'a': 5})
- field.validate({'a': 2, 'b': 3})
-
- self.assertRaises(WrongContainedType, field.validate, {1: ''} )
- self.assertRaises(WrongContainedType, field.validate, {1: 3.14159} )
- self.assertRaises(WrongContainedType, field.validate, {'a': ()} )
-
- def testValidateKeyTypes(self):
- field = Dict(title=u('Dict field'),
- description=u(''), readonly=False, required=False,
- key_type=Int())
- field.validate(None)
- field.validate({5: 'a'})
- field.validate({2: 'a', 2: 'b'})
-
- self.assertRaises(WrongContainedType, field.validate, {'': 1} )
- self.assertRaises(WrongContainedType, field.validate, {3.14159: 1} )
- self.assertRaises(WrongContainedType, field.validate, {(): 'a'} )
-
-
- def test_bind_binds_key_and_value_types(self):
- field = self._Field_Factory(
- __name__ = 'x',
- title=u('Not required field'), description=u(''),
- readonly=False, required=False,
- key_type=Int(),
- value_type=Int(),
- )
-
- class C(object):
- x=None
-
- c = C()
- field2 = field.bind(c)
-
- self.assertEqual(field2.key_type.context, c)
- self.assertEqual(field2.value_type.context, c)
-
-def test_suite():
- return makeSuite(DictTest)
-
-if __name__ == '__main__':
- main(defaultTest='test_suite')
Deleted: zope.schema/trunk/src/zope/schema/tests/test_docs.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_docs.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_docs.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,38 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2004 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 for the schema package's documentation files
-"""
-import doctest
-import re
-import unittest
-
-from zope.testing import renormalizing
-import zope.schema.tests
-
-def test_suite():
- checker = renormalizing.RENormalizing([
- (re.compile(r"\[\(None, Invalid\('8<=10',\)\)\]"),
- r"[(None, <zope.interface.exceptions.Invalid instance at 0x...>)]",)
- ])
- checker = checker + zope.schema.tests.py3_checker
- return unittest.TestSuite((
- doctest.DocFileSuite('../sources.txt',
- optionflags=doctest.ELLIPSIS,
- checker=zope.schema.tests.py3_checker),
- doctest.DocFileSuite('../fields.txt', checker=zope.schema.tests.py3_checker),
- doctest.DocFileSuite('../README.txt', checker=zope.schema.tests.py3_checker),
- doctest.DocFileSuite(
- '../validation.txt', checker=checker,
- optionflags=doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS),
- ))
Deleted: zope.schema/trunk/src/zope/schema/tests/test_dotted_name.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_dotted_name.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_dotted_name.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,57 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2010 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.
-#
-##############################################################################
-"""DottedName field tests
-"""
-from unittest import main, makeSuite
-
-from six import b, u
-from zope.schema import DottedName
-from zope.schema.tests.test_field import FieldTestBase
-from zope.schema.interfaces import InvalidDottedName, RequiredMissing
-
-class DottedNameTest(FieldTestBase):
- """Test the DottedName Field."""
-
- _Field_Factory = DottedName
-
- def testValidate(self):
- field = self._Field_Factory(required=False)
-
- field.validate(None)
- field.validate('foo.bar')
- field.validate('foo.bar0')
- field.validate('foo0.bar')
-
- # We used to incorrectly allow ^: https://bugs.launchpad.net/zope.schema/+bug/191236
- self.assertRaises(InvalidDottedName, field.validate, 'foo.bar^foobar')
- self.assertRaises(InvalidDottedName, field.validate, 'foo^foobar.bar')
- # dotted names cannot start with digits
- self.assertRaises(InvalidDottedName, field.validate, 'foo.0bar')
- self.assertRaises(InvalidDottedName, field.validate, '0foo.bar')
-
- def testValidateRequired(self):
- field = self._Field_Factory(required=True)
-
- field.validate('foo.bar')
-
- self.assertRaises(RequiredMissing, field.validate, None)
-
- def testFromUnicode(self):
- field = self._Field_Factory()
- self.assertEquals(field.fromUnicode(u('foo')), 'foo')
-
-
-def test_suite():
- suite = makeSuite(DottedNameTest)
- return suite
Modified: zope.schema/trunk/src/zope/schema/tests/test_equality.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_equality.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_equality.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -13,22 +13,26 @@
##############################################################################
"""Field equality tests
"""
-from unittest import TestCase, TestSuite, makeSuite
+import unittest
-from six import u
-from zope.schema import Text, Int
-class FieldEqualityTests(TestCase):
+class FieldEqualityTests(unittest.TestCase):
- equality = [
- 'Text(title=u("Foo"), description=u("Bar"))',
- 'Int(title=u("Foo"), description=u("Bar"))',
+ def test_equality(self):
+
+ from zope.schema._compat import u
+ from zope.schema import Int
+ from zope.schema import Text
+
+ equality = [
+ 'Text(title=u("Foo"), description=u("Bar"))',
+ 'Int(title=u("Foo"), description=u("Bar"))',
]
-
- def test_equality(self):
- for text in self.equality:
+ for text in equality:
self.assertEqual(eval(text), eval(text))
+
def test_suite():
- return TestSuite(
- [makeSuite(FieldEqualityTests)])
+ return unittest.TestSuite((
+ unittest.makeSuite(FieldEqualityTests),
+ ))
Deleted: zope.schema/trunk/src/zope/schema/tests/test_field.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_field.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_field.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,187 +0,0 @@
-##############################################################################
-#
-# 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.
-#
-##############################################################################
-"""Generic field tests
-"""
-
-import re
-
-from doctest import DocTestSuite
-from unittest import TestCase, TestSuite, makeSuite
-
-from six import u, b
-from zope.interface import Interface, provider
-from zope.schema import Field, Text, Int
-from zope.schema.interfaces import IContextAwareDefaultFactory
-from zope.schema.interfaces import ValidationError, RequiredMissing
-from zope.schema.interfaces import ConstraintNotSatisfied, WrongType
-from zope.testing import renormalizing
-import zope.schema.tests
-
-class FieldTestBase(TestCase):
-
- def test_bind(self):
- field = self._Field_Factory(
- __name__ = 'x',
- title=u('Not required field'), description=u(''),
- readonly=False, required=False)
-
- field.interface = Interface
- field.setTaggedValue('a', 'b')
-
- class C(object):
- x=None
-
- c = C()
- field2 = field.bind(c)
-
- self.assertEqual(field2.context, c)
- self.assertEqual(field.queryTaggedValue('a'), field2.queryTaggedValue('a'))
- for n in ('__class__', '__name__', '__doc__', 'title', 'description',
- 'readonly', 'required', 'interface'):
- self.assertEqual(getattr(field2, n), getattr(field, n), n)
-
- def testValidate(self):
- field = self._Field_Factory(
- title=u('Not required field'), description=u(''),
- readonly=False, required=False)
- field.validate(None)
- field.validate('foo')
- field.validate(1)
- field.validate(0)
- field.validate('')
-
- def testValidateRequired(self):
- field = self._Field_Factory(
- title=u('Required field'), description=u(''),
- readonly=False, required=True)
- field.validate('foo')
- field.validate(1)
- field.validate(0)
- field.validate('')
-
- self.assertRaises(RequiredMissing, field.validate, None)
-
-class CollectionFieldTestBase(FieldTestBase):
-
- def test_bind_binds_value_type(self):
- field = self._Field_Factory(
- __name__ = 'x',
- title=u('Not required field'), description=u(''),
- readonly=False, required=False,
- value_type=Int(),
- )
-
- class C(object):
- x=None
-
- c = C()
- field2 = field.bind(c)
-
- self.assertEqual(field2.value_type.context, c)
-
-class FieldTest(FieldTestBase):
- """Test generic Field."""
-
- _Field_Factory = Field
-
- def testSillyDefault(self):
- self.assertRaises(ValidationError, Text, default=b(""))
-
- def test__doc__(self):
- field = Text(title=u("test fiield"),
- description=(
- u("To make sure that\n"
- "doc strings are working correctly\n")
- )
- )
- self.assertEqual(
- field.__doc__,
- u("test fiield\n\n"
- "To make sure that\n"
- "doc strings are working correctly\n")
- )
-
- def testOrdering(self):
-
- from zope.interface import Interface
-
- class S1(Interface):
- a = Text()
- b = Text()
-
- self.assertTrue(S1['a'].order < S1['b'].order)
-
- class S2(Interface):
- b = Text()
- a = Text()
-
- self.assertTrue(S2['a'].order > S2['b'].order)
-
- def testConstraint(self):
- def isodd(x):
- return x % 2 == 1
-
- i = Int(title=u('my constrained integer'),
- constraint=isodd)
-
- i.validate(11)
- self.assertRaises(ConstraintNotSatisfied, i.validate, 10)
-
- def testSimpleDefaultFactory(self):
- field = Int(defaultFactory=lambda: 42)
- self.assertEqual(field.default, 42)
-
- # The default factory always wins against a default value.
- field = Int(default=41, defaultFactory=lambda: 42)
- self.assertEqual(field.default, 42)
-
- def testContextAwareDefaultFactory(self):
- @provider(IContextAwareDefaultFactory)
- def getAnswerToUniverse(context):
- if context is None:
- return 0
- return context.answer
-
- field = Int(defaultFactory=getAnswerToUniverse)
- self.assertEqual(field.default, 0)
-
- class Context(object):
- answer = 42
-
- bound = field.bind(Context())
- self.assertEqual(bound.default, 42)
-
- def testBadValueDefaultFactory(self):
- field = Int(defaultFactory=lambda: '42')
- self.assertRaises(WrongType, lambda: field.default)
-
-class FieldDefaultBehaviour(TestCase):
- def test_required_defaults_to_true(self):
- class MyField(Field):
- pass
- field = MyField(title=u('my'))
- self.assertTrue(field.required)
-
-def test_suite():
- checker = renormalizing.RENormalizing([
- (re.compile(r" with base 10: '125.6'"),
- r': 125.6')
- ])
- checker = checker + zope.schema.tests.py3_checker
- return TestSuite((
- makeSuite(FieldTest),
- makeSuite(FieldDefaultBehaviour),
- DocTestSuite("zope.schema._field", checker=zope.schema.tests.py3_checker),
- DocTestSuite("zope.schema._bootstrapfields",checker=checker),
- ))
Modified: zope.schema/trunk/src/zope/schema/tests/test_fieldproperty.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_fieldproperty.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_fieldproperty.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -14,37 +14,36 @@
"""Field Properties tests
"""
-from unittest import TestCase, TestSuite, main, makeSuite
+import unittest
-from six import u, b
-from zope.interface import Interface
-from zope.schema import Float, Text, Bytes
-from zope.schema.interfaces import ValidationError
-from zope.schema.fieldproperty import (FieldProperty,
- FieldPropertyStoredThroughField)
+class _Base(unittest.TestCase):
-class I(Interface):
+ 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)
- 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)
+class _Integration(object):
-class C(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()
- title = FieldProperty(I['title'])
- weight = FieldProperty(I['weight'])
- code = FieldProperty(I['code'])
- date = FieldProperty(I['date'])
-
-
-class Test(TestCase):
- klass = C
-
def test_basic(self):
- c = self.klass()
+ from zope.schema._compat import b
+ from zope.schema._compat import u
+ 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'))
@@ -65,30 +64,361 @@
self.assertEqual(c.code, b('abcdef'))
def test_readonly(self):
- c = self.klass()
+ 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 D(object):
+class FieldPropertyTests(_Base, _Integration):
- title = FieldPropertyStoredThroughField(I['title'])
- weight = FieldPropertyStoredThroughField(I['weight'])
- code = FieldPropertyStoredThroughField(I['code'])
- date = FieldPropertyStoredThroughField(I['date'])
+ 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)
-class TestStoredThroughField(Test):
- klass = D
+ def test_ctor_explicit(self):
+ from zope.schema import Text
+ from zope.schema._compat import u
+ 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___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'])
+
+
+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
+ from zope.schema._compat import u
+ 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 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:
+ 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 _getSchema():
+ from zope.interface import Interface
+ from zope.schema import Bytes
+ from zope.schema import Float
+ from zope.schema import Text
+ from zope.schema._compat import b
+ from zope.schema._compat import u
+
+ 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
+
+
def test_suite():
- return TestSuite((
- makeSuite(Test),
- makeSuite(TestStoredThroughField),
- ))
-
-if __name__ == '__main__':
- main(defaultTest='test_suite')
+ return unittest.TestSuite((
+ unittest.makeSuite(FieldPropertyTests),
+ unittest.makeSuite(FieldPropertyStoredThroughFieldTests),
+ ))
Deleted: zope.schema/trunk/src/zope/schema/tests/test_floatfield.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_floatfield.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_floatfield.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,86 +0,0 @@
-##############################################################################
-#
-# 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.
-#
-##############################################################################
-"""Float field tests
-"""
-from unittest import main, makeSuite
-
-from six import u
-from zope.schema import Float
-from zope.schema.interfaces import RequiredMissing, InvalidValue
-from zope.schema.interfaces import TooSmall, TooBig
-from zope.schema.tests.test_field import FieldTestBase
-
-class FloatTest(FieldTestBase):
- """Test the Float Field."""
-
- _Field_Factory = Float
-
- def testValidate(self):
- field = self._Field_Factory(title=u('Float field'), description=u(''),
- readonly=False, required=False)
- field.validate(None)
- field.validate(10.0)
- field.validate(0.93)
- field.validate(1000.0003)
-
- def testValidateRequired(self):
- field = self._Field_Factory(title=u('Float field'), description=u(''),
- readonly=False, required=True)
- field.validate(10.0)
- field.validate(0.93)
- field.validate(1000.0003)
-
- self.assertRaises(RequiredMissing, field.validate, None)
-
- def testValidateMin(self):
- field = self._Field_Factory(title=u('Float field'), description=u(''),
- readonly=False, required=False, min=10.5)
- field.validate(None)
- field.validate(10.6)
- field.validate(20.2)
-
- self.assertRaises(TooSmall, field.validate, -9.0)
- self.assertRaises(TooSmall, field.validate, 10.4)
-
- def testValidateMax(self):
- field = self._Field_Factory(title=u('Float field'), description=u(''),
- readonly=False, required=False, max=10.5)
- field.validate(None)
- field.validate(5.3)
- field.validate(-9.1)
-
- self.assertRaises(TooBig, field.validate, 10.51)
- self.assertRaises(TooBig, field.validate, 20.7)
-
- def testValidateMinAndMax(self):
- field = self._Field_Factory(title=u('Float field'), description=u(''),
- readonly=False, required=False,
- min=-0.6, max=10.1)
- field.validate(None)
- field.validate(0.0)
- field.validate(-0.03)
- field.validate(10.0001)
-
- self.assertRaises(TooSmall, field.validate, -10.0)
- self.assertRaises(TooSmall, field.validate, -1.6)
- self.assertRaises(TooBig, field.validate, 11.45)
- self.assertRaises(TooBig, field.validate, 20.02)
-
-
-def test_suite():
- suite = makeSuite(FloatTest)
- return suite
-
-if __name__ == '__main__':
- main(defaultTest='test_suite')
Deleted: zope.schema/trunk/src/zope/schema/tests/test_interfacefield.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_interfacefield.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_interfacefield.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,48 +0,0 @@
-##############################################################################
-#
-# 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.
-#
-##############################################################################
-"""Interface field tests
-"""
-from unittest import main, makeSuite
-
-from six import u
-from zope.schema import InterfaceField
-from zope.schema.interfaces import RequiredMissing, WrongType
-from zope.schema.tests.test_field import FieldTestBase
-from zope.interface import Interface
-
-class DummyInterface(Interface):
- pass
-
-class InterfaceTest(FieldTestBase):
- """Test the Bool Field."""
-
- _Field_Factory = InterfaceField
-
- def testValidate(self):
- field = InterfaceField(title=u('Interface field'), description=u(''),
- readonly=False, required=False)
- field.validate(DummyInterface)
- self.assertRaises(WrongType, field.validate, object())
-
- def testValidateRequired(self):
- field = InterfaceField(title=u('Interface field'), description=u(''),
- readonly=False, required=True)
- self.assertRaises(RequiredMissing, field.validate, None)
-
-
-def test_suite():
- return makeSuite(InterfaceTest)
-
-if __name__ == '__main__':
- main(defaultTest='test_suite')
Copied: zope.schema/trunk/src/zope/schema/tests/test_interfaces.py (from rev 125653, zope.schema/branches/tseaver-test_cleanup/src/zope/schema/tests/test_interfaces.py)
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_interfaces.py (rev 0)
+++ zope.schema/trunk/src/zope/schema/tests/test_interfaces.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -0,0 +1,94 @@
+import 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):
+ from zope.schema._compat import b
+ from zope.schema._compat import u
+ 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_suite():
+ return unittest.TestSuite((
+ unittest.makeSuite(Test__is_field),
+ unittest.makeSuite(Test__fields),
+ ))
Deleted: zope.schema/trunk/src/zope/schema/tests/test_intfield.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_intfield.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_intfield.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,87 +0,0 @@
-##############################################################################
-#
-# 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.
-#
-##############################################################################
-"""Integer field tests
-"""
-from unittest import main, makeSuite
-
-from six import u
-from zope.schema import Int
-from zope.schema.interfaces import RequiredMissing, InvalidValue
-from zope.schema.interfaces import TooSmall, TooBig
-from zope.schema.tests.test_field import FieldTestBase
-
-class IntTest(FieldTestBase):
- """Test the Int Field."""
-
- _Field_Factory = Int
-
- def testValidate(self):
- field = self._Field_Factory(title=u('Int field'), description=u(''),
- readonly=False, required=False)
- field.validate(None)
- field.validate(10)
- field.validate(0)
- field.validate(-1)
-
- def testValidateRequired(self):
- field = self._Field_Factory(title=u('Int field'), description=u(''),
- readonly=False, required=True)
- field.validate(10)
- field.validate(0)
- field.validate(-1)
-
- self.assertRaises(RequiredMissing, field.validate, None)
-
- def testValidateMin(self):
- field = self._Field_Factory(title=u('Int field'), description=u(''),
- readonly=False, required=False, min=10)
- field.validate(None)
- field.validate(10)
- field.validate(20)
-
- self.assertRaises(TooSmall, field.validate, 9)
- self.assertRaises(TooSmall, field.validate, -10)
-
- def testValidateMax(self):
- field = self._Field_Factory(title=u('Int field'), description=u(''),
- readonly=False, required=False, max=10)
- field.validate(None)
- field.validate(5)
- field.validate(9)
- field.validate(10)
-
- self.assertRaises(TooBig, field.validate, 11)
- self.assertRaises(TooBig, field.validate, 20)
-
- def testValidateMinAndMax(self):
- field = self._Field_Factory(title=u('Int field'), description=u(''),
- readonly=False, required=False,
- min=0, max=10)
- field.validate(None)
- field.validate(0)
- field.validate(5)
- field.validate(10)
-
- self.assertRaises(TooSmall, field.validate, -10)
- self.assertRaises(TooSmall, field.validate, -1)
- self.assertRaises(TooBig, field.validate, 11)
- self.assertRaises(TooBig, field.validate, 20)
-
-
-def test_suite():
- suite = makeSuite(IntTest)
- return suite
-
-if __name__ == '__main__':
- main(defaultTest='test_suite')
Deleted: zope.schema/trunk/src/zope/schema/tests/test_iterablefield.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_iterablefield.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_iterablefield.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,60 +0,0 @@
-##############################################################################
-#
-# 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.
-#
-##############################################################################
-"""Iterable field tests
-"""
-from six import PY3, u
-if not PY3:
- from UserDict import UserDict, IterableUserDict
-else:
- #python3
- from collections import UserDict as IterableUserDict, UserDict
-from unittest import main, makeSuite
-from zope.schema import Iterable
-from zope.schema.interfaces import RequiredMissing
-from zope.schema.interfaces import NotAContainer, NotAnIterator
-from zope.schema.tests.test_field import FieldTestBase
-
-class IterableTest(FieldTestBase):
- """Test the Iterable Field."""
-
- _Field_Factory = Iterable
-
- def testValidate(self):
- field = self._Field_Factory(title=u('test field'), description=u(''),
- readonly=False, required=False)
- field.validate(None)
- field.validate('')
- field.validate('abc')
- field.validate([1, 2, 3])
- field.validate({'a': 1, 'b': 2})
- field.validate(IterableUserDict())
-
- self.assertRaises(NotAContainer, field.validate, 1)
- self.assertRaises(NotAContainer, field.validate, True)
- self.assertRaises(NotAnIterator, field.validate, UserDict)
-
- def testValidateRequired(self):
- field = self._Field_Factory(title=u('test field'), description=u(''),
- readonly=False, required=True)
-
- field.validate('')
-
- self.assertRaises(RequiredMissing, field.validate, None)
-
-
-def test_suite():
- return makeSuite(IterableTest)
-
-if __name__ == '__main__':
- main(defaultTest='test_suite')
Deleted: zope.schema/trunk/src/zope/schema/tests/test_listfield.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_listfield.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_listfield.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,123 +0,0 @@
-##############################################################################
-#
-# 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.
-#
-##############################################################################
-"""List field tests
-"""
-from unittest import main, makeSuite
-
-from six import u
-from zope.interface import implementer
-from zope.schema import Field, List, Int
-from zope.schema.interfaces import IField
-from zope.schema.interfaces import ICollection, ISequence, IList
-from zope.schema.interfaces import NotAContainer, RequiredMissing
-from zope.schema.interfaces import WrongContainedType, WrongType, NotUnique
-from zope.schema.interfaces import TooShort, TooLong
-from zope.schema.tests.test_field import CollectionFieldTestBase
-
-class ListTest(CollectionFieldTestBase):
- """Test the List Field."""
-
- _Field_Factory = List
-
- def testValidate(self):
- field = List(title=u('List field'), description=u(''),
- readonly=False, required=False)
- field.validate(None)
- field.validate([])
- field.validate([1, 2])
- field.validate([3,])
-
- def testValidateRequired(self):
- field = List(title=u('List field'), description=u(''),
- readonly=False, required=True)
- field.validate([])
- field.validate([1, 2])
- field.validate([3,])
-
- self.assertRaises(RequiredMissing, field.validate, None)
-
- def testValidateMinValues(self):
- field = List(title=u('List field'), description=u(''),
- readonly=False, required=False, min_length=2)
- field.validate(None)
- field.validate([1, 2])
- field.validate([1, 2, 3])
-
- self.assertRaises(TooShort, field.validate, [])
- self.assertRaises(TooShort, field.validate, [1,])
-
- def testValidateMaxValues(self):
- field = List(title=u('List field'), description=u(''),
- readonly=False, required=False, max_length=2)
- field.validate(None)
- field.validate([])
- field.validate([1, 2])
-
- self.assertRaises(TooLong, field.validate, [1, 2, 3, 4])
- self.assertRaises(TooLong, field.validate, [1, 2, 3])
-
- def testValidateMinValuesAndMaxValues(self):
- field = List(title=u('List field'), description=u(''),
- readonly=False, required=False,
- min_length=1, max_length=2)
- field.validate(None)
- field.validate([1, ])
- field.validate([1, 2])
-
- self.assertRaises(TooShort, field.validate, [])
- self.assertRaises(TooLong, field.validate, [1, 2, 3])
-
- def testValidateValueTypes(self):
- field = List(title=u('List field'), description=u(''),
- readonly=False, required=False,
- value_type=Int())
- field.validate(None)
- field.validate([5,])
- field.validate([2, 3])
-
- self.assertRaises(WrongContainedType, field.validate, ['',] )
- self.assertRaises(WrongContainedType, field.validate, [3.14159,] )
-
- def testCorrectValueType(self):
- # TODO: We should not allow for a None valeu type.
- List(value_type=None)
-
- # do not allow arbitrary value types
- self.assertRaises(ValueError, List, value_type=object())
- self.assertRaises(ValueError, List, value_type=Field)
-
- # however, allow anything that implements IField
- List(value_type=Field())
- @implementer(IField)
- class FakeField(object):
- pass
- List(value_type=FakeField())
-
- def testUnique(self):
- field = self._Field_Factory(title=u('test field'), description=u(''),
- readonly=False, required=True, unique=True)
- field.validate([1, 2])
- self.assertRaises(NotUnique, field.validate, [1, 2, 1])
-
- def testImplements(self):
- field = List()
- self.assertTrue(IList.providedBy(field))
- self.assertTrue(ISequence.providedBy(field))
- self.assertTrue(ICollection.providedBy(field))
-
-def test_suite():
- return makeSuite(ListTest)
-
-if __name__ == '__main__':
- main(defaultTest='test_suite')
Deleted: zope.schema/trunk/src/zope/schema/tests/test_objectfield.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_objectfield.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_objectfield.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,324 +0,0 @@
-from zope.schema import List
-##############################################################################
-#
-# 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.
-#
-##############################################################################
-"""This set of tests exercises Object fields.
-"""
-from unittest import TestSuite, main, makeSuite
-
-from six import u
-import zope.event
-from zope.interface import Attribute, Interface, implementer
-from zope.schema import Object, TextLine
-from zope.schema.fieldproperty import FieldProperty
-from zope.schema.interfaces import ValidationError
-from zope.schema.interfaces import RequiredMissing, WrongContainedType
-from zope.schema.interfaces import WrongType, SchemaNotFullyImplemented
-from zope.schema.tests.test_field import FieldTestBase
-from zope.schema.interfaces import IBeforeObjectAssignedEvent
-from zope.testing.cleanup import CleanUp
-
-from zope.schema._messageid import _
-
-
-class ITestSchema(Interface):
- """A test schema"""
-
- foo = TextLine(
- title=_("Foo"),
- description=_("Foo description"),
- default=u(""),
- required=True)
-
- bar = TextLine(
- title=_("Bar"),
- description=_("Bar description"),
- default=u(""),
- required=False)
-
- attribute = Attribute("Test attribute, an attribute can't be validated.")
-
-
- at implementer(ITestSchema)
-class TestClass(object):
-
- _foo = u('')
- _bar = u('')
- _attribute = u('')
-
- def getfoo(self):
- return self._foo
-
- def setfoo(self, value):
- self._foo = value
-
- foo = property(getfoo, setfoo, None, u('foo'))
-
- def getbar(self):
- return self._bar
-
- def setbar(self, value):
- self._bar = value
-
- bar = property(getbar, setbar, None, u('foo'))
-
- def getattribute(self):
- return self._attribute
-
- def setattribute(self, value):
- self._attribute = value
-
- attribute = property(getattribute, setattribute, None, u('attribute'))
-
-
- at implementer(ITestSchema)
-class FieldPropertyTestClass(object):
-
-
- foo = FieldProperty(ITestSchema['foo'])
- bar = FieldProperty(ITestSchema['bar'])
- attribute = FieldProperty(ITestSchema['attribute'])
-
-
- at implementer(ITestSchema)
-class NotFullyImplementedTestClass(object):
-
- foo = FieldProperty(ITestSchema['foo'])
- # bar = FieldProperty(ITestSchema['bar']): bar is not implemented
- # attribute
-
-
-class ISchemaWithObjectFieldAsInterface(Interface):
-
- obj = Object(
- schema=Interface,
- title=_("Object"),
- description=_("object description"),
- required=False)
-
-
- at implementer(ISchemaWithObjectFieldAsInterface)
-class ClassWithObjectFieldAsInterface(object):
-
- _obj = None
-
- def getobj(self):
- return self._obj
-
- def setobj(self, value):
- self._obj = value
-
- obj = property(getobj, setobj, None, u('obj'))
-
-
-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
-
-
- at implementer(IUnit)
-class Unit(object):
-
- def __init__(self, person, person_list):
- self.boss = person
- self.members = person_list
-
-
- at implementer(IPerson)
-class Person(object):
-
- def __init__(self, unit):
- self.unit = unit
-
-
-class ObjectTest(CleanUp, FieldTestBase):
- """Test the Object Field."""
-
- def getErrors(self, f, *args, **kw):
- try:
- f(*args, **kw)
- except WrongContainedType as e:
- try:
- return e.args[0]
- except:
- return []
- self.fail('Expected WrongContainedType Error')
-
- def makeTestObject(self, **kw):
- kw['schema'] = kw.get('schema', Interface)
- return Object(**kw)
-
- _Field_Factory = makeTestObject
-
- def makeTestData(self):
- return TestClass()
-
- def makeFieldPropertyTestClass(self):
- return FieldPropertyTestClass()
-
- def makeNotFullyImplementedTestData(self):
- return NotFullyImplementedTestClass()
-
- def invalidSchemas(self):
- return ['foo', 1, 0, {}, [], None]
-
- def validSchemas(self):
- return [Interface, ITestSchema]
-
- def test_init(self):
- for schema in self.validSchemas():
- Object(schema=schema)
- for schema in self.invalidSchemas():
- self.assertRaises(ValidationError, Object, schema=schema)
- self.assertRaises(WrongType, Object, schema=schema)
-
- def testValidate(self):
- # this test of the base class is not applicable
- pass
-
- def testValidateRequired(self):
- # this test of the base class is not applicable
- pass
-
- def test_validate_required(self):
- field = self._Field_Factory(
- title=u('Required field'), description=u(''),
- readonly=False, required=True)
- self.assertRaises(RequiredMissing, field.validate, None)
-
- def test_validate_TestData(self):
- field = self.makeTestObject(schema=ITestSchema, required=False)
- data = self.makeTestData()
- field.validate(data)
- field = self.makeTestObject(schema=ITestSchema)
- field.validate(data)
- data.foo = None
- self.assertRaises(ValidationError, field.validate, data)
- self.assertRaises(WrongContainedType, field.validate, data)
- errors = self.getErrors(field.validate, data)
- self.assertEqual(errors[0], RequiredMissing('foo'))
-
- def test_validate_FieldPropertyTestData(self):
- field = self.makeTestObject(schema=ITestSchema, required=False)
- data = self.makeFieldPropertyTestClass()
- field.validate(data)
- field = self.makeTestObject(schema=ITestSchema)
- field.validate(data)
- self.assertRaises(ValidationError, setattr, data, 'foo', None)
- self.assertRaises(RequiredMissing, setattr, data, 'foo', None)
-
- def test_validate_NotFullyImplementedTestData(self):
- field = self.makeTestObject(schema=ITestSchema, required=False)
- data = self.makeNotFullyImplementedTestData()
- self.assertRaises(ValidationError, field.validate, data)
- self.assertRaises(WrongContainedType, field.validate, data)
- errors = self.getErrors(field.validate, data)
- self.assertTrue(isinstance(errors[0], SchemaNotFullyImplemented))
-
- def test_validate_with_non_object_value(self):
- field = self.makeTestObject(
- schema=ISchemaWithObjectFieldAsInterface,
- required=False)
- instance = ClassWithObjectFieldAsInterface()
- instance.obj = (1, 1)
- field.validate(instance)
-
- def test_beforeAssignEvent(self):
- field = self.makeTestObject(schema=ITestSchema, required=False,
- __name__='object_field')
- data = self.makeTestData()
- events = []
-
- def register_event(event):
- events.append(event)
- zope.event.subscribers.append(register_event)
-
- class Dummy(object):
- pass
- context = Dummy()
- field.set(context, data)
- self.assertEqual(1, len(events))
- event = events[0]
- self.assertTrue(IBeforeObjectAssignedEvent.providedBy(event))
- self.assertEqual(data, event.object)
- self.assertEqual('object_field', event.name)
- self.assertEqual(context, event.context)
-
- # cycles
-
- def test_with_cycles_validate(self):
- field = self.makeTestObject(schema=IUnit)
- person1 = Person(None)
- person2 = Person(None)
- unit = Unit(person1, [person1, person2])
- person1.unit = unit
- person2.unit = unit
- field.validate(unit)
-
- def test_with_cycles_object_not_valid(self):
- field = self.makeTestObject(schema=IUnit)
- data = self.makeTestData()
- person1 = Person(None)
- person2 = Person(None)
- person3 = Person(data)
- unit = Unit(person3, [person1, person2])
- person1.unit = unit
- person2.unit = unit
- self.assertRaises(WrongContainedType, field.validate, unit)
-
- def test_with_cycles_collection_not_valid(self):
- field = self.makeTestObject(schema=IUnit)
- data = self.makeTestData()
- person1 = Person(None)
- person2 = Person(None)
- person3 = Person(data)
- unit = Unit(person1, [person2, person3])
- person1.unit = unit
- person2.unit = unit
- self.assertRaises(WrongContainedType, field.validate, unit)
-
-
-def test_suite():
- suite = TestSuite()
- suite.addTest(makeSuite(ObjectTest))
- return suite
-
-if __name__ == '__main__':
- main(defaultTest='test_suite')
Modified: zope.schema/trunk/src/zope/schema/tests/test_schema.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_schema.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_schema.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -13,60 +13,57 @@
##############################################################################
"""Schema field tests
"""
-from unittest import TestCase, main, makeSuite
-from six import u, b
-from zope.interface import Interface
-from zope.schema import Bytes
-from zope.schema import getFields, getFieldsInOrder
-from zope.schema import getFieldNames, getFieldNamesInOrder
+import unittest
-class ISchemaTest(Interface):
- title = Bytes(
- title=u("Title"),
- description=u("Title"),
- default=b(""),
- required=True)
+def _makeSchema():
+ from zope.schema._compat import b
+ from zope.schema._compat import u
+ from zope.interface import Interface
+ from zope.schema import Bytes
- description = Bytes(
- title=u("Description"),
- description=u("Description"),
- default=b(""),
- required=True)
+ 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
- spam = Bytes(
- title=u("Spam"),
- description=u("Spam"),
- default=b(""),
- required=True)
+def _makeDerivedSchema(base=None):
+ from zope.schema._compat import b
+ from zope.schema._compat import u
+ from zope.schema import Bytes
+ if base is None:
+ base = _makeSchema()
-class ISchemaTestSubclass(ISchemaTest):
- foo = Bytes(
- title=u('Foo'),
- description=u('Fooness'),
- default=b(""),
- required=False)
+ class ISchemaTestSubclass(base):
+ foo = Bytes(
+ title=u('Foo'),
+ description=u('Fooness'),
+ default=b(""),
+ required=False)
+ return ISchemaTestSubclass
-class SchemaTest(TestCase):
+class Test_getFields(unittest.TestCase):
- def test_getFieldNames(self):
- names = getFieldNames(ISchemaTest)
- self.assertEqual(len(names),3)
- self.assertTrue('title' in names)
- self.assertTrue('description' in names)
- self.assertTrue('spam' in names)
+ def _callFUT(self, schema):
+ from zope.schema import getFields
+ return getFields(schema)
- def test_getFieldNamesAll(self):
- names = getFieldNames(ISchemaTestSubclass)
- 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)
+ def test_simple(self):
+ fields = self._callFUT(_makeSchema())
- def test_getFields(self):
- fields = getFields(ISchemaTest)
-
self.assertTrue('title' in fields)
self.assertTrue('description' in fields)
self.assertTrue('spam' in fields)
@@ -75,8 +72,8 @@
for key, value in fields.items():
self.assertEqual(key, value.getName())
- def test_getFieldsAll(self):
- fields = getFields(ISchemaTestSubclass)
+ def test_derived(self):
+ fields = self._callFUT(_makeDerivedSchema())
self.assertTrue('title' in fields)
self.assertTrue('description' in fields)
@@ -87,30 +84,173 @@
for key, value in fields.items():
self.assertEqual(key, value.getName())
- def test_getFieldsInOrder(self):
- fields = getFieldsInOrder(ISchemaTest)
+
+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_getFieldsInOrderAll(self):
- fields = getFieldsInOrder(ISchemaTestSubclass)
+ 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())
- def test_getFieldsNamesInOrder(self):
- names = getFieldNamesInOrder(ISchemaTest)
+
+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_getFieldsNamesInOrderAll(self):
- names = getFieldNamesInOrder(ISchemaTestSubclass)
+ 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)
+
+ 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():
+ pass
+ 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
+ from zope.schema._compat import u
+ 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)
+
+ 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)
+
+
def test_suite():
- return makeSuite(SchemaTest)
-
-if __name__ == '__main__':
- main(defaultTest='test_suite')
+ return unittest.TestSuite((
+ unittest.makeSuite(Test_getFields),
+ unittest.makeSuite(Test_getFieldsInOrder),
+ unittest.makeSuite(Test_getFieldNames),
+ unittest.makeSuite(Test_getFieldNamesInOrder),
+ unittest.makeSuite(Test_getValidationErrors),
+ unittest.makeSuite(Test_getSchemaValidationErrors),
+ ))
Deleted: zope.schema/trunk/src/zope/schema/tests/test_setfield.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_setfield.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_setfield.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,293 +0,0 @@
-##############################################################################
-#
-# 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.
-#
-##############################################################################
-"""Set field tests.
-"""
-from unittest import TestSuite, main, makeSuite
-
-from six import u
-from zope.interface import implementer, providedBy
-from zope.schema import Field, Set, Int, FrozenSet
-from zope.schema.interfaces import IField
-from zope.schema.interfaces import (
- ICollection, IUnorderedCollection, ISet, IFrozenSet, IAbstractSet)
-from zope.schema.interfaces import NotAContainer, RequiredMissing
-from zope.schema.interfaces import WrongContainedType, WrongType, NotUnique
-from zope.schema.interfaces import TooShort, TooLong
-from zope.schema.tests.test_field import CollectionFieldTestBase
-
-
-class SetTest(CollectionFieldTestBase):
- """Test the Tuple Field."""
-
- _Field_Factory = Set
-
- def testValidate(self):
- field = Set(title=u('Set field'), description=u(''),
- readonly=False, required=False)
- field.validate(None)
- field.validate(set())
- field.validate(set((1, 2)))
- field.validate(set((3,)))
- field.validate(set())
- field.validate(set((1, 2)))
- field.validate(set((3,)))
-
- self.assertRaises(WrongType, field.validate, [1, 2, 3])
- self.assertRaises(WrongType, field.validate, 'abc')
- self.assertRaises(WrongType, field.validate, 1)
- self.assertRaises(WrongType, field.validate, {})
- self.assertRaises(WrongType, field.validate, (1, 2, 3))
- self.assertRaises(WrongType, field.validate, frozenset((1, 2, 3)))
-
- def testValidateRequired(self):
- field = Set(title=u('Set field'), description=u(''),
- readonly=False, required=True)
- field.validate(set())
- field.validate(set((1, 2)))
- field.validate(set((3,)))
- field.validate(set())
- field.validate(set((1, 2)))
- field.validate(set((3,)))
-
- self.assertRaises(RequiredMissing, field.validate, None)
-
- def testValidateRequiredAltMissingValue(self):
- missing = object()
- field = Set(required=True, missing_value=missing)
- field.validate(set())
- field.validate(set())
-
- self.assertRaises(RequiredMissing, field.validate, missing)
-
- def testValidateDefault(self):
- field = Set(required=True)
- field.default = None
-
- def testValidateDefaultAltMissingValue(self):
- missing = object()
- field = Set(required=True, missing_value=missing)
- field.default = missing
-
- def testValidateMinValues(self):
- field = Set(title=u('Set field'), description=u(''),
- readonly=False, required=False, min_length=2)
- field.validate(None)
- field.validate(set((1, 2)))
- field.validate(set((1, 2, 3)))
- field.validate(set((1, 2)))
- field.validate(set((1, 2, 3)))
-
- self.assertRaises(TooShort, field.validate, set(()))
- self.assertRaises(TooShort, field.validate, set((3,)))
- self.assertRaises(TooShort, field.validate, set(()))
- self.assertRaises(TooShort, field.validate, set((3,)))
-
- def testValidateMaxValues(self):
- field = Set(title=u('Set field'), description=u(''),
- readonly=False, required=False, max_length=2)
- field.validate(None)
- field.validate(set())
- field.validate(set((1, 2)))
- field.validate(set())
- field.validate(set((1, 2)))
-
- self.assertRaises(TooLong, field.validate, set((1, 2, 3, 4)))
- self.assertRaises(TooLong, field.validate, set((1, 2, 3)))
- self.assertRaises(TooLong, field.validate, set((1, 2, 3, 4)))
- self.assertRaises(TooLong, field.validate, set((1, 2, 3)))
-
- def testValidateMinValuesAndMaxValues(self):
- field = Set(title=u('Set field'), description=u(''),
- readonly=False, required=False,
- min_length=1, max_length=2)
- field.validate(None)
- field.validate(set((3,)))
- field.validate(set((1, 2)))
- field.validate(set((3,)))
- field.validate(set((1, 2)))
-
- self.assertRaises(TooShort, field.validate, set())
- self.assertRaises(TooLong, field.validate, set((1, 2, 3)))
- self.assertRaises(TooShort, field.validate, set())
- self.assertRaises(TooLong, field.validate, set((1, 2, 3)))
-
- def testValidateValueTypes(self):
- field = Set(title=u('Set field'), description=u(''),
- readonly=False, required=False,
- value_type=Int())
- field.validate(None)
- field.validate(set((5,)))
- field.validate(set((2, 3)))
- field.validate(set((5,)))
- field.validate(set((2, 3)))
-
- self.assertRaises(WrongContainedType, field.validate,
- set(('',)))
- self.assertRaises(WrongContainedType,
- field.validate, set((3.14159,)))
- self.assertRaises(WrongContainedType, field.validate, set(('',)))
- self.assertRaises(WrongContainedType,
- field.validate, set((3.14159,)))
-
- def testCorrectValueType(self):
- # TODO: We should not allow for a None value type.
- Set(value_type=None)
-
- # do not allow arbitrary value types
- self.assertRaises(ValueError, Set, value_type=object())
- self.assertRaises(ValueError, Set, value_type=Field)
-
- # however, allow anything that implements IField
- Set(value_type=Field())
- @implementer(IField)
- class FakeField(object):
- pass
- Set(value_type=FakeField())
-
- def testNoUniqueArgument(self):
- self.assertRaises(TypeError, Set, unique=False)
- self.assertRaises(TypeError, Set, unique=True)
- self.assertTrue(Set().unique)
-
- def testImplements(self):
- field = Set()
- self.assertTrue(ISet.providedBy(field))
- self.assertTrue(IUnorderedCollection.providedBy(field))
- self.assertTrue(IAbstractSet.providedBy(field))
- self.assertTrue(ICollection.providedBy(field))
-
-class FrozenSetTest(CollectionFieldTestBase):
- """Test the Tuple Field."""
-
- _Field_Factory = FrozenSet
-
- def testValidate(self):
- field = FrozenSet(title=u('Set field'), description=u(''),
- readonly=False, required=False)
- field.validate(None)
- field.validate(frozenset())
- field.validate(frozenset((1, 2)))
- field.validate(frozenset((3,)))
-
- self.assertRaises(WrongType, field.validate, [1, 2, 3])
- self.assertRaises(WrongType, field.validate, 'abc')
- self.assertRaises(WrongType, field.validate, 1)
- self.assertRaises(WrongType, field.validate, {})
- self.assertRaises(WrongType, field.validate, (1, 2, 3))
- self.assertRaises(WrongType, field.validate, set((1, 2, 3)))
- self.assertRaises(WrongType, field.validate, set((1, 2, 3)))
-
- def testValidateRequired(self):
- field = FrozenSet(title=u('Set field'), description=u(''),
- readonly=False, required=True)
- field.validate(frozenset())
- field.validate(frozenset((1, 2)))
- field.validate(frozenset((3,)))
-
- self.assertRaises(RequiredMissing, field.validate, None)
-
- def testValidateRequiredAltMissingValue(self):
- missing = object()
- field = FrozenSet(required=True, missing_value=missing)
- field.validate(frozenset())
-
- self.assertRaises(RequiredMissing, field.validate, missing)
-
- def testValidateDefault(self):
- field = FrozenSet(required=True)
- field.default = None
-
- def testValidateDefaultAltMissingValue(self):
- missing = object()
- field = FrozenSet(required=True, missing_value=missing)
- field.default = missing
-
- def testValidateMinValues(self):
- field = FrozenSet(title=u('FrozenSet field'), description=u(''),
- readonly=False, required=False, min_length=2)
- field.validate(None)
- field.validate(frozenset((1, 2)))
- field.validate(frozenset((1, 2, 3)))
-
- self.assertRaises(TooShort, field.validate, frozenset(()))
- self.assertRaises(TooShort, field.validate, frozenset((3,)))
-
- def testValidateMaxValues(self):
- field = FrozenSet(title=u('FrozenSet field'), description=u(''),
- readonly=False, required=False, max_length=2)
- field.validate(None)
- field.validate(frozenset())
- field.validate(frozenset((1, 2)))
-
- self.assertRaises(TooLong, field.validate, frozenset((1, 2, 3, 4)))
- self.assertRaises(TooLong, field.validate, frozenset((1, 2, 3)))
-
- def testValidateMinValuesAndMaxValues(self):
- field = FrozenSet(title=u('FrozenSet field'), description=u(''),
- readonly=False, required=False,
- min_length=1, max_length=2)
- field.validate(None)
- field.validate(frozenset((3,)))
- field.validate(frozenset((1, 2)))
-
- self.assertRaises(TooShort, field.validate, frozenset())
- self.assertRaises(TooLong, field.validate, frozenset((1, 2, 3)))
-
- def testValidateValueTypes(self):
- field = FrozenSet(title=u('FrozenSet field'), description=u(''),
- readonly=False, required=False,
- value_type=Int())
- field.validate(None)
- field.validate(frozenset((5,)))
- field.validate(frozenset((2, 3)))
-
- self.assertRaises(WrongContainedType, field.validate, frozenset(('',)))
- self.assertRaises(WrongContainedType,
- field.validate, frozenset((3.14159,)))
-
- def testCorrectValueType(self):
- # TODO: We should not allow for a None value type.
- FrozenSet(value_type=None)
-
- # do not allow arbitrary value types
- self.assertRaises(ValueError, FrozenSet, value_type=object())
- self.assertRaises(ValueError, FrozenSet, value_type=Field)
-
- # however, allow anything that implements IField
- FrozenSet(value_type=Field())
- @implementer(IField)
- class FakeField(object):
- pass
- FrozenSet(value_type=FakeField())
-
- def testNoUniqueArgument(self):
- self.assertRaises(TypeError, FrozenSet, unique=False)
- self.assertRaises(TypeError, FrozenSet, unique=True)
- self.assertTrue(FrozenSet().unique)
-
- def testImplements(self):
- field = FrozenSet()
- self.assertTrue(IFrozenSet.providedBy(field))
- self.assertTrue(IAbstractSet.providedBy(field))
- self.assertTrue(IUnorderedCollection.providedBy(field))
- self.assertTrue(ICollection.providedBy(field))
-
-def test_suite():
- suite = TestSuite()
- suite.addTest(makeSuite(SetTest))
- suite.addTest(makeSuite(FrozenSetTest))
- return suite
-
-if __name__ == '__main__':
- main(defaultTest='test_suite')
Modified: zope.schema/trunk/src/zope/schema/tests/test_states.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_states.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_states.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -15,58 +15,65 @@
"""
import unittest
-from six import u
-from zope.interface import Interface
-from zope.interface.verify import verifyObject
-from zope.schema import vocabulary
-from zope.schema import Choice
-from zope.schema.interfaces import IVocabulary
-from zope.schema.tests import states
+class StateSelectionTest(unittest.TestCase):
-
-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=states.StateVocabulary(),
- )
- state4 = Choice(
- title=u("Name"),
- description=u("The name of your new state"),
- vocabulary="states",
- )
-
-
-class StateSelectionTest(unittest.TestCase):
def setUp(self):
- vocabulary._clear()
- vr = vocabulary.getVocabularyRegistry()
- vr.register("states", states.StateVocabulary)
+ 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):
- vocabulary._clear()
+ from zope.schema.vocabulary import _clear
+ _clear()
+ def _makeSchema(self):
+ from zope.schema._compat import u
+ 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):
- field = IBirthInfo.getDescriptionFor("state1")
+ 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):
- vocab = states.StateVocabulary()
+ 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)
@@ -82,7 +89,10 @@
self.assertEqual(L, L2)
def test_prebound_vocabulary(self):
- field = IBirthInfo.getDescriptionFor("state3")
+ 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))
@@ -90,7 +100,6 @@
def test_suite():
- return unittest.makeSuite(StateSelectionTest)
-
-if __name__ == "__main__":
- unittest.main(defaultTest="test_suite")
+ return unittest.TestSuite((
+ unittest.makeSuite(StateSelectionTest),
+ ))
Deleted: zope.schema/trunk/src/zope/schema/tests/test_strfield.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_strfield.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_strfield.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,167 +0,0 @@
-##############################################################################
-#
-# 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.
-#
-##############################################################################
-"""String field tests
-"""
-from unittest import TestSuite, main, makeSuite
-from six import b, u
-from zope.schema import Bytes, BytesLine, Text, TextLine, Password
-from zope.schema.interfaces import ValidationError, WrongType
-from zope.schema.interfaces import RequiredMissing, InvalidValue
-from zope.schema.interfaces import TooShort, TooLong, ConstraintNotSatisfied
-from zope.schema.tests.test_field import FieldTestBase
-
-class StrTest(FieldTestBase):
- """Test the Str Field."""
-
- def testValidate(self):
- field = self._Field_Factory(title=u('Str field'), description=u(''),
- readonly=False, required=False)
- field.validate(None)
- field.validate(self._convert('foo'))
- field.validate(self._convert(''))
-
- def testValidateRequired(self):
-
- # Note that if we want to require non-empty strings,
- # we need to set the min-length to 1.
-
- field = self._Field_Factory(
- title=u('Str field'), description=u(''),
- readonly=False, required=True, min_length=1)
- field.validate(self._convert('foo'))
-
- self.assertRaises(RequiredMissing, field.validate, None)
- self.assertRaises(TooShort, field.validate, self._convert(''))
-
- def testValidateMinLength(self):
- field = self._Field_Factory(
- title=u('Str field'), description=u(''),
- readonly=False, required=False, min_length=3)
- field.validate(None)
- field.validate(self._convert('333'))
- field.validate(self._convert('55555'))
-
- self.assertRaises(TooShort, field.validate, self._convert(''))
- self.assertRaises(TooShort, field.validate, self._convert('22'))
- self.assertRaises(TooShort, field.validate, self._convert('1'))
-
- def testValidateMaxLength(self):
- field = self._Field_Factory(
- title=u('Str field'), description=u(''),
- readonly=False, required=False, max_length=5)
- field.validate(None)
- field.validate(self._convert(''))
- field.validate(self._convert('333'))
- field.validate(self._convert('55555'))
-
- self.assertRaises(TooLong, field.validate, self._convert('666666'))
- self.assertRaises(TooLong, field.validate, self._convert('999999999'))
-
- def testValidateMinLengthAndMaxLength(self):
- field = self._Field_Factory(
- title=u('Str field'), description=u(''),
- readonly=False, required=False,
- min_length=3, max_length=5)
-
- field.validate(None)
- field.validate(self._convert('333'))
- field.validate(self._convert('4444'))
- field.validate(self._convert('55555'))
-
- self.assertRaises(TooShort, field.validate, self._convert('22'))
- self.assertRaises(TooShort, field.validate, self._convert('22'))
- self.assertRaises(TooLong, field.validate, self._convert('666666'))
- self.assertRaises(TooLong, field.validate, self._convert('999999999'))
-
-
-class MultiLine(object):
-
- def test_newlines(self):
- field = self._Field_Factory(title=u('Str field'))
- field.validate(self._convert('hello\nworld'))
-
-
-class BytesTest(StrTest, MultiLine):
- _Field_Factory = Bytes
-
- def _convert(self, v):
- return b(v)
-
- def testBadStringType(self):
- field = self._Field_Factory()
- self.assertRaises(ValidationError, field.validate, u('hello'))
-
-
-class TextTest(StrTest, MultiLine):
- _Field_Factory = Text
- def _convert(self, v):
- return u(v)
-
- def testBadStringType(self):
- field = self._Field_Factory()
- self.assertRaises(ValidationError, field.validate, b('hello'))
-
-class SingleLine(object):
-
- def test_newlines(self):
- field = self._Field_Factory(title=u('Str field'))
- self.assertRaises(ConstraintNotSatisfied,
- field.validate,
- self._convert('hello\nworld'))
-
-class PasswordTest(SingleLine, TextTest):
- _Field_Factory = Password
-
- def test_existingValue(self):
- class Dummy(object):
- password = None
- dummy = Dummy()
-
- field = self._Field_Factory(title=u('Str field'), description=u(''),
- readonly=False, required=True, __name__='password')
- field = field.bind(dummy)
-
- # Using UNCHANGED_PASSWORD is not allowed if no password was set yet
- self.assertRaises(WrongType, field.validate, field.UNCHANGED_PASSWORD)
-
- dummy.password = 'asdf'
- field.validate(field.UNCHANGED_PASSWORD)
-
- # Using a normal value, the field gets updated
- field.set(dummy, u('test'))
- self.assertEqual(u('test'), dummy.password)
-
- # Using UNCHANGED_PASSWORD the field is not updated.
- field.set(dummy, field.UNCHANGED_PASSWORD)
- self.assertEqual(u('test'), dummy.password)
-
-
-class LineTest(SingleLine, BytesTest):
- _Field_Factory = BytesLine
-
-class TextLineTest(SingleLine, TextTest):
- _Field_Factory = TextLine
-
-
-def test_suite():
- return TestSuite((
- makeSuite(BytesTest),
- makeSuite(TextTest),
- makeSuite(LineTest),
- makeSuite(TextLineTest),
- makeSuite(PasswordTest),
- ))
-
-if __name__ == '__main__':
- main(defaultTest='test_suite')
Deleted: zope.schema/trunk/src/zope/schema/tests/test_timedelta.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_timedelta.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_timedelta.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,95 +0,0 @@
-##############################################################################
-#
-# 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.
-#
-##############################################################################
-"""Timedelta Field tests
-"""
-from unittest import main, makeSuite
-
-from six import u
-from zope.schema import Timedelta
-from zope.schema.interfaces import RequiredMissing, InvalidValue
-from zope.schema.interfaces import TooSmall, TooBig
-from zope.schema.tests.test_field import FieldTestBase
-from datetime import timedelta
-
-class TimedeltaTest(FieldTestBase):
- """Test the Timedelta Field."""
-
- _Field_Factory = Timedelta
-
- def testInterface(self):
- from zope.interface.verify import verifyObject
- from zope.schema.interfaces import ITimedelta
- verifyObject(ITimedelta, self._Field_Factory())
-
- def testValidate(self):
- field = self._Field_Factory(title=u('Timedelta field'), description=u(''),
- readonly=False, required=False)
- field.validate(None)
- field.validate(timedelta(minutes=15))
-
- def testValidateRequired(self):
- field = self._Field_Factory(title=u('Timedelta field'), description=u(''),
- readonly=False, required=True)
- field.validate(timedelta(minutes=15))
-
- self.assertRaises(RequiredMissing, field.validate, None)
-
- def testValidateMin(self):
- t1 = timedelta(hours=2)
- t2 = timedelta(hours=3)
- field = self._Field_Factory(title=u('Timedelta field'), description=u(''),
- readonly=False, required=False, min=t1)
- field.validate(None)
- field.validate(t1)
- field.validate(t2)
-
- self.assertRaises(TooSmall, field.validate, timedelta(hours=1))
-
- def testValidateMax(self):
- t1 = timedelta(minutes=1)
- t2 = timedelta(minutes=2)
- t3 = timedelta(minutes=3)
- field = self._Field_Factory(title=u('Timedelta field'), description=u(''),
- readonly=False, required=False, max=t2)
- field.validate(None)
- field.validate(t1)
- field.validate(t2)
-
- self.assertRaises(TooBig, field.validate, t3)
-
- def testValidateMinAndMax(self):
- t1 = timedelta(days=1)
- t2 = timedelta(days=2)
- t3 = timedelta(days=3)
- t4 = timedelta(days=4)
- t5 = timedelta(days=5)
-
- field = self._Field_Factory(title=u('Timedelta field'), description=u(''),
- readonly=False, required=False,
- min=t2, max=t4)
- field.validate(None)
- field.validate(t2)
- field.validate(t3)
- field.validate(t4)
-
- self.assertRaises(TooSmall, field.validate, t1)
- self.assertRaises(TooBig, field.validate, t5)
-
-
-def test_suite():
- suite = makeSuite(TimedeltaTest)
- return suite
-
-if __name__ == '__main__':
- main(defaultTest='test_suite')
Deleted: zope.schema/trunk/src/zope/schema/tests/test_tuplefield.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_tuplefield.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_tuplefield.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,130 +0,0 @@
-##############################################################################
-#
-# 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.
-#
-##############################################################################
-"""Tuple field tests.
-"""
-from unittest import TestSuite, main, makeSuite
-
-from six import u
-from zope.interface import implementer
-from zope.schema import Field, Tuple, Int
-from zope.schema.interfaces import IField
-from zope.schema.interfaces import ICollection, ISequence, ITuple
-from zope.schema.interfaces import NotAContainer, RequiredMissing
-from zope.schema.interfaces import WrongContainedType, WrongType, NotUnique
-from zope.schema.interfaces import TooShort, TooLong
-from zope.schema.tests.test_field import CollectionFieldTestBase
-
-class TupleTest(CollectionFieldTestBase):
- """Test the Tuple Field."""
-
- _Field_Factory = Tuple
-
- def testValidate(self):
- field = Tuple(title=u('Tuple field'), description=u(''),
- readonly=False, required=False)
- field.validate(None)
- field.validate(())
- field.validate((1, 2))
- field.validate((3,))
-
- self.assertRaises(WrongType, field.validate, [1, 2, 3])
- self.assertRaises(WrongType, field.validate, 'abc')
- self.assertRaises(WrongType, field.validate, 1)
- self.assertRaises(WrongType, field.validate, {})
-
- def testValidateRequired(self):
- field = Tuple(title=u('Tuple field'), description=u(''),
- readonly=False, required=True)
- field.validate(())
- field.validate((1, 2))
- field.validate((3,))
-
- self.assertRaises(RequiredMissing, field.validate, None)
-
- def testValidateMinValues(self):
- field = Tuple(title=u('Tuple field'), description=u(''),
- readonly=False, required=False, min_length=2)
- field.validate(None)
- field.validate((1, 2))
- field.validate((1, 2, 3))
-
- self.assertRaises(TooShort, field.validate, ())
- self.assertRaises(TooShort, field.validate, (1,))
-
- def testValidateMaxValues(self):
- field = Tuple(title=u('Tuple field'), description=u(''),
- readonly=False, required=False, max_length=2)
- field.validate(None)
- field.validate(())
- field.validate((1, 2))
-
- self.assertRaises(TooLong, field.validate, (1, 2, 3, 4))
- self.assertRaises(TooLong, field.validate, (1, 2, 3))
-
- def testValidateMinValuesAndMaxValues(self):
- field = Tuple(title=u('Tuple field'), description=u(''),
- readonly=False, required=False,
- min_length=1, max_length=2)
- field.validate(None)
- field.validate((1, ))
- field.validate((1, 2))
-
- self.assertRaises(TooShort, field.validate, ())
- self.assertRaises(TooLong, field.validate, (1, 2, 3))
-
- def testValidateValueTypes(self):
- field = Tuple(title=u('Tuple field'), description=u(''),
- readonly=False, required=False,
- value_type=Int())
- field.validate(None)
- field.validate((5,))
- field.validate((2, 3))
-
- self.assertRaises(WrongContainedType, field.validate, ('',) )
- self.assertRaises(WrongContainedType, field.validate, (3.14159,) )
-
- def testCorrectValueType(self):
- # allow value_type of None (??? is this OK?)
- Tuple(value_type=None)
-
- # do not allow arbitrary value types
- self.assertRaises(ValueError, Tuple, value_type=object())
- self.assertRaises(ValueError, Tuple, value_type=Field)
-
- # however, allow anything that implements IField
- Tuple(value_type=Field())
- @implementer(IField)
- class FakeField(object):
- pass
- Tuple(value_type=FakeField())
-
- def testUnique(self):
- field = self._Field_Factory(title=u('test field'), description=u(''),
- readonly=False, required=True, unique=True)
- field.validate((1, 2))
- self.assertRaises(NotUnique, field.validate, (1, 2, 1))
-
- def testImplements(self):
- field = Tuple()
- self.assertTrue(ITuple.providedBy(field))
- self.assertTrue(ISequence.providedBy(field))
- self.assertTrue(ICollection.providedBy(field))
-
-def test_suite():
- suite = TestSuite()
- suite.addTest(makeSuite(TupleTest))
- return suite
-
-if __name__ == '__main__':
- main(defaultTest='test_suite')
Modified: zope.schema/trunk/src/zope/schema/tests/test_vocabulary.py
===================================================================
--- zope.schema/trunk/src/zope/schema/tests/test_vocabulary.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/tests/test_vocabulary.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -15,164 +15,143 @@
"""
import unittest
-try:
- from collections import OrderedDict
-except ImportError:
- from ordereddict import OrderedDict
-from zope.interface.verify import verifyObject
-from zope.interface.exceptions import DoesNotImplement
-from zope.interface import Interface, implementer
-from zope.interface.common.mapping import IEnumerableMapping
+class SimpleTermTests(unittest.TestCase):
-from zope.schema import interfaces
-from zope.schema import vocabulary
+ def _getTargetClass(self):
+ from zope.schema.vocabulary import SimpleTerm
+ return SimpleTerm
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
-class DummyRegistry(vocabulary.VocabularyRegistry):
- def get(self, object, name):
- v = SampleVocabulary()
- v.object = object
- v.name = name
- return v
+ 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'))
-class BaseTest(unittest.TestCase):
- # Clear the vocabulary and presentation registries on each side of
- # each test.
+ 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 setUp(self):
- vocabulary._clear()
+ 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 tearDown(self):
- vocabulary._clear()
-
-class RegistryTests(BaseTest):
- """Tests of the simple vocabulary and presentation registries."""
-
- def test_setVocabularyRegistry(self):
- r = DummyRegistry()
- vocabulary.setVocabularyRegistry(r)
- self.assertTrue(vocabulary.getVocabularyRegistry() is r)
-
- def test_getVocabularyRegistry(self):
- r = vocabulary.getVocabularyRegistry()
- self.assertTrue(interfaces.IVocabularyRegistry.providedBy(r))
-
- # TODO: still need to test the default implementation
-
-class SampleTerm(object):
- pass
-
- at implementer(interfaces.IVocabulary)
-class SampleVocabulary(object):
-
- def __iter__(self):
- return iter([self.getTerm(x) for x in range(0, 10)])
-
- def __contains__(self, value):
- return 0 <= value < 10
-
- def __len__(self):
- return 10
-
- def getTerm(self, value):
- if value in self:
- t = SampleTerm()
- t.value = value
- t.double = 2 * value
- return t
- raise LookupError("no such value: %r" % value)
-
-
class SimpleVocabularyTests(unittest.TestCase):
- list_vocab = vocabulary.SimpleVocabulary.fromValues([1, 2, 3])
- items_vocab = vocabulary.SimpleVocabulary.fromItems(
- [('one', 1), ('two', 2), ('three', 3), ('fore!', 4)])
+ def _getTargetClass(self):
+ from zope.schema.vocabulary import SimpleVocabulary
+ return SimpleVocabulary
- def test_simple_term(self):
- t = vocabulary.SimpleTerm(1)
- verifyObject(interfaces.ITokenizedTerm, t)
- self.assertEqual(t.value, 1)
- self.assertEqual(t.token, "1")
- t = vocabulary.SimpleTerm(1, "One")
- verifyObject(interfaces.ITokenizedTerm, t)
- self.assertEqual(t.value, 1)
- self.assertEqual(t.token, "One")
+ def _makeOne(self, *args, **kw):
+ return self._getTargetClass()(*args, **kw)
- def test_simple_term_title(self):
- t = vocabulary.SimpleTerm(1)
- verifyObject(interfaces.ITokenizedTerm, t)
- self.assertRaises(DoesNotImplement, verifyObject,
- interfaces.ITitledTokenizedTerm, t)
- self.assertTrue(t.title is None)
- t = vocabulary.SimpleTerm(1, title="Title")
- verifyObject(interfaces.ITokenizedTerm, t)
- verifyObject(interfaces.ITitledTokenizedTerm, t)
- self.assertEqual(t.title, "Title")
+ 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_order(self):
- value = 1
- for t in self.list_vocab:
- self.assertEqual(t.value, value)
- value += 1
+ def test_instance_conforms_to_IVocabularyTokenized(self):
+ from zope.interface.verify import verifyObject
+ from zope.schema.interfaces import IVocabularyTokenized
+ verifyObject(IVocabularyTokenized, self._makeOne(()))
- value = 1
- for t in self.items_vocab:
- self.assertEqual(t.value, value)
- value += 1
+ 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.assertTrue(vocabulary.getTerm(term.value) is term)
+ self.assertTrue(vocabulary.getTermByToken(term.token) is term)
- def test_implementation(self):
- self.assertTrue(verifyObject(interfaces.IVocabulary, self.list_vocab))
- self.assertTrue(
- verifyObject(interfaces.IVocabularyTokenized, self.list_vocab))
- self.assertTrue(verifyObject(interfaces.IVocabulary, self.items_vocab))
- self.assertTrue(
- verifyObject(interfaces.IVocabularyTokenized, self.items_vocab))
+ 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.assertTrue(value in vocabulary)
- def test_addt_interfaces(self):
+ def test_fromItems(self):
+ from zope.interface import Interface
+ from zope.schema.interfaces import ITokenizedTerm
class IStupid(Interface):
pass
- v = vocabulary.SimpleVocabulary.fromValues([1, 2, 3], IStupid)
- self.assertTrue(IStupid.providedBy(v))
+ 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.assertTrue(item[1] in vocabulary)
- def test_len(self):
- self.assertEqual(len(self.list_vocab), 3)
- self.assertEqual(len(self.items_vocab), 4)
+ 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_contains(self):
- for v in (self.list_vocab, self.items_vocab):
- self.assertTrue(1 in v and 2 in v and 3 in v)
- self.assertTrue(5 not in v)
+ def test_getTerm_miss(self):
+ vocabulary = self._makeOne(())
+ self.assertRaises(LookupError, vocabulary.getTerm, 'nonesuch')
- def test_iter_and_get_term(self):
- for v in (self.list_vocab, self.items_vocab):
- for term in v:
- self.assertTrue(v.getTerm(term.value) is term)
- self.assertTrue(v.getTermByToken(term.token) is term)
+ def test_getTermByToken_miss(self):
+ vocabulary = self._makeOne(())
+ self.assertRaises(LookupError, vocabulary.getTermByToken, 'nonesuch')
def test_nonunique_tokens(self):
- self.assertRaises(
- ValueError, vocabulary.SimpleVocabulary.fromValues,
- [2, '2'])
- self.assertRaises(
- ValueError, vocabulary.SimpleVocabulary.fromItems,
- [(1, 'one'), ('1', 'another one')])
- self.assertRaises(
- ValueError, vocabulary.SimpleVocabulary.fromItems,
- [(0, 'one'), (1, 'one')])
+ 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_token_message(self):
try:
- vocabulary.SimpleVocabulary.fromValues([2, '2'])
+ 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:
- vocabulary.SimpleVocabulary.fromItems([(0, 'one'), (1, 'one')])
+ self._getTargetClass().fromItems([(0, 'one'), (1, 'one')])
except ValueError as e:
self.assertEqual(str(e), "term values must be unique: 'one'")
@@ -183,7 +162,7 @@
self.token = repr(value)
self.nextvalue = value + 1
- class MyVocabulary(vocabulary.SimpleVocabulary):
+ class MyVocabulary(self._getTargetClass()):
def createTerm(cls, value):
return MyTerm(value)
createTerm = classmethod(createTerm)
@@ -193,63 +172,82 @@
self.assertEqual(term.value + 1, term.nextvalue)
+# Test _createTermTree via TreeVocabulary.fromDict
+
+
class TreeVocabularyTests(unittest.TestCase):
- region_tree = {
- ('regions', 'Regions'): {
- ('aut', 'Austria'): {
- ('tyr', 'Tyrol'): {
- ('auss', 'Ausserfern'): {},
- }
- },
- ('ger', 'Germany'): {
- ('bav', 'Bavaria'):{}
- },
+
+ 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'):{}
+ },
+ }
}
- }
- tree_vocab_2 = vocabulary.TreeVocabulary.fromDict(region_tree)
+ return self._getTargetClass().fromDict(region_tree)
- business_tree = {
- ('services', 'services', 'Services'): {
- ('reservations', 'reservations', 'Reservations'): {
- ('res_host', 'res_host', 'Res Host'): {},
- ('res_gui', 'res_gui', 'Res GUI'): {},
+ 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'): {},
+ },
},
- ('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'): {},
},
- },
- ('infrastructure', 'infrastructure', 'Infrastructure'): {
- ('communication_network', 'communication_network', 'Communication/Network'): {
- ('messaging', 'messaging', 'Messaging'): {},
- },
- ('data_transaction', 'data_transaction', 'Data/Transaction'): {
- ('database', 'database', 'Database'): {},
- },
- ('security', 'security', 'Security'): {},
- },
- }
- tree_vocab_3 = vocabulary.TreeVocabulary.fromDict(business_tree)
+ }
+ def tree_vocab_3(self):
+ return self._getTargetClass().fromDict(self.business_tree())
def test_implementation(self):
- for v in [self.tree_vocab_2, self.tree_vocab_3]:
+ 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(interfaces.IVocabulary, v))
- self.assertTrue(verifyObject(interfaces.IVocabularyTokenized, v))
- self.assertTrue(verifyObject(interfaces.ITreeVocabulary, v))
+ self.assertTrue(verifyObject(IVocabulary, v))
+ self.assertTrue(verifyObject(IVocabularyTokenized, v))
+ self.assertTrue(verifyObject(ITreeVocabulary, v))
- def test_addt_interfaces(self):
+ def test_additional_interfaces(self):
+ from zope.interface import Interface
class IStupid(Interface):
pass
- v = vocabulary.TreeVocabulary.fromDict({('one', '1'): {}}, IStupid)
+ 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 it's
- internal tree representation.
+ #The TreeVocabulary makes use of an OrderedDict to store it's
+ #internal tree representation.
+ #
+ #Check that they keys are indeed oredered.
+ from zope.schema._compat import OrderedDict
- Check that they keys are indeed oredered.
- """
-
d = { (1, 'new_york', 'New York'): {
(2, 'ny_albany', 'Albany'): {},
(3, 'ny_new_york', 'New York'): {},
@@ -263,165 +261,177 @@
(9, 'utah', 'Utah'): {},
}
dict_ = OrderedDict(sorted(d.items(), key=lambda t: t[0]))
- vocab = vocabulary.TreeVocabulary.fromDict(dict_)
+ vocab = self._getTargetClass().fromDict(dict_)
# Test keys
- self.assertEqual([k.token for k in vocab.keys()], ['1', '4', '7', '8', '9'])
+ 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],
+ ['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'])
+ 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):
- """ The TreeVocabulary creates three indexes for quick lookups,
- term_by_value, term_by_value and path_by_value.
- """
+ # 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 self.tree_vocab_2.term_by_value.keys()],
- ['Tyrol', 'Bavaria', 'Regions', 'Austria', 'Germany', 'Ausserfern'])
+ [k for k in sorted(tv2.term_by_value.keys())],
+ ['Ausserfern','Austria','Bavaria','Germany','Regions','Tyrol'])
self.assertEqual(
- [k for k in self.tree_vocab_2.term_by_token.keys()],
- ['bav', 'ger', 'auss', 'regions', 'aut', 'tyr'])
+ [k for k in sorted(tv2.term_by_token.keys())],
+ ['auss', 'aut', 'bav', 'ger', 'regions', 'tyr'])
self.assertEqual(
- [k for k in self.tree_vocab_2.path_by_value.keys()],
- ['Tyrol', 'Bavaria', 'Regions', 'Austria', 'Germany', 'Ausserfern'])
+ [k for k in sorted(tv2.path_by_value.keys())],
+ ['Ausserfern','Austria','Bavaria','Germany','Regions','Tyrol'])
self.assertEqual(
- [k for k in self.tree_vocab_2.path_by_value.values()],
- [
- ['Regions', 'Austria', 'Tyrol'],
- ['Regions', 'Germany', 'Bavaria'],
- ['Regions'],
- ['Regions', 'Austria'],
- ['Regions', 'Germany'],
- ['Regions', 'Austria', 'Tyrol', 'Ausserfern']
+ [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 self.tree_vocab_3.term_by_value.keys()],
- [ 'data_transaction',
- 'check_in',
- 'infrastructure',
- 'res_gui',
- 'database',
- 'reservations',
- 'dcs_host',
- 'communication_network',
- 'res_host',
- 'services',
- 'messaging',
- 'security'
+ [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 self.tree_vocab_3.term_by_token.keys()],
- [ 'data_transaction',
- 'check_in',
- 'infrastructure',
- 'res_gui',
- 'database',
- 'reservations',
- 'dcs_host',
- 'communication_network',
- 'res_host',
- 'services',
- 'messaging',
- 'security'
+ [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 self.tree_vocab_3.path_by_value.values()],
- [ ['infrastructure', 'data_transaction'],
- ['services', 'check_in'],
- ['infrastructure'],
- ['services', 'reservations', 'res_gui'],
- ['infrastructure', 'data_transaction', 'database'],
- ['services', 'reservations'],
- ['services', 'check_in', 'dcs_host'],
- ['infrastructure', 'communication_network'],
- ['services', 'reservations', 'res_host'],
- ['services'],
- ['infrastructure', 'communication_network', 'messaging'],
- ['infrastructure', 'security']
+ [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(
- self.tree_vocab_2.getTermPath('Bavaria'),
+ tv2.getTermPath('Bavaria'),
['Regions', 'Germany', 'Bavaria'])
self.assertEqual(
- self.tree_vocab_2.getTermPath('Austria'),
+ tv2.getTermPath('Austria'),
['Regions', 'Austria'])
self.assertEqual(
- self.tree_vocab_2.getTermPath('Ausserfern'),
+ tv2.getTermPath('Ausserfern'),
['Regions', 'Austria', 'Tyrol', 'Ausserfern'])
self.assertEqual(
- self.tree_vocab_2.getTermPath('Non-existent'),
+ tv2.getTermPath('Non-existent'),
[])
self.assertEqual(
- self.tree_vocab_3.getTermPath('database'),
+ 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)
+ # 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):
- self.assertTrue('Regions' in self.tree_vocab_2 and
- 'Austria' in self.tree_vocab_2 and
- 'Bavaria' in self.tree_vocab_2)
+ tv2 = self.tree_vocab_2()
+ self.assertTrue('Regions' in tv2 and
+ 'Austria' in tv2 and
+ 'Bavaria' in tv2)
- self.assertTrue('bav' not in self.tree_vocab_2)
- self.assertTrue('foo' not in self.tree_vocab_2)
+ self.assertTrue('bav' not in tv2)
+ self.assertTrue('foo' not in tv2)
+ self.assertTrue({} not in tv2) # not hashable
- self.assertTrue('database' in self.tree_vocab_3 and
- 'security' in self.tree_vocab_3 and
- 'services' in self.tree_vocab_3)
+ tv3 = self.tree_vocab_3()
+ self.assertTrue('database' in tv3 and
+ 'security' in tv3 and
+ 'services' in tv3)
- self.assertTrue('Services' not in self.tree_vocab_3)
- self.assertTrue('Database' not in self.tree_vocab_3)
+ 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 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()])
+ 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 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 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')
+ 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.
- """
+ # Since we do term and value lookups, all terms' values and tokens
+ # must be unique. This rule applies recursively.
self.assertRaises(
- ValueError, vocabulary.TreeVocabulary.fromDict,
+ ValueError, self._getTargetClass().fromDict,
{ ('one', '1'): {},
('two', '1'): {},
})
self.assertRaises(
- ValueError, vocabulary.TreeVocabulary.fromDict,
+ ValueError, self._getTargetClass().fromDict,
{ ('one', '1'): {},
('one', '2'): {},
})
# Even nested tokens must be unique.
self.assertRaises(
- ValueError, vocabulary.TreeVocabulary.fromDict,
+ ValueError, self._getTargetClass().fromDict,
{ ('new_york', 'New York'): {
('albany', 'Albany'): {},
('new_york', 'New York'): {},
@@ -429,27 +439,27 @@
})
# The same applies to nested values.
self.assertRaises(
- ValueError, vocabulary.TreeVocabulary.fromDict,
+ ValueError, self._getTargetClass().fromDict,
{ ('1', 'new_york'): {
('2', 'albany'): {},
('3', 'new_york'): {},
},
})
# The title attribute does however not have to be unique.
- vocabulary.TreeVocabulary.fromDict(
+ self._getTargetClass().fromDict(
{ ('1', 'new_york', 'New York'): {
('2', 'ny_albany', 'Albany'): {},
('3', 'ny_new_york', 'New York'): {},
},
})
- vocabulary.TreeVocabulary.fromDict({
+ self._getTargetClass().fromDict({
('one', '1', 'One'): {},
('two', '2', 'One'): {},
})
def test_nonunique_value_message(self):
try:
- vocabulary.TreeVocabulary.fromDict(
+ self._getTargetClass().fromDict(
{ ('one', '1'): {},
('two', '1'): {},
})
@@ -458,7 +468,7 @@
def test_nonunique_token_message(self):
try:
- vocabulary.TreeVocabulary.fromDict(
+ self._getTargetClass().fromDict(
{ ('one', '1'): {},
('one', '2'): {},
})
@@ -466,10 +476,10 @@
self.assertEqual(str(e), "Term tokens must be unique: 'one'")
def test_recursive_methods(self):
- """Test the _createTermTree and _getPathToTreeNode methods
- """
- tree = vocabulary._createTermTree({}, self.business_tree)
- vocab = vocabulary.TreeVocabulary.fromDict(self.business_tree)
+ #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")
@@ -484,7 +494,8 @@
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"])
+ self.assertEqual(term_path,
+ ["infrastructure", "data_transaction", "database"])
term_path = vocab._getPathToTreeNode(tree, "dcs_host")
vocab_path = vocab._getPathToTreeNode(vocab, "dcs_host")
@@ -496,12 +507,80 @@
self.assertEqual(term_path, vocab_path)
self.assertEqual(term_path, [])
-def test_suite():
- suite = unittest.makeSuite(RegistryTests)
- suite.addTest(unittest.makeSuite(SimpleVocabularyTests))
- suite.addTest(unittest.makeSuite(TreeVocabularyTests))
- return suite
-if __name__ == "__main__":
- unittest.main(defaultTest="test_suite")
+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):
+ return iter([self.getTerm(x) for x in range(0, 10)])
+
+ def __contains__(self, value):
+ return 0 <= value < 10
+
+ def __len__(self):
+ return 10
+
+ def getTerm(self, value):
+ if value in self:
+ t = SampleTerm()
+ t.value = value
+ t.double = 2 * value
+ return t
+ raise LookupError("no such value: %r" % value)
+
+ return SampleVocabulary()
+
+
+def _makeDummyRegistry():
+ from zope.schema.vocabulary import VocabularyRegistry
+
+ class DummyRegistry(VocabularyRegistry):
+ def get(self, object, name):
+ v = _makeSampleVocabulary()
+ v.object = object
+ v.name = name
+ return v
+ return DummyRegistry()
+
+
+def test_suite():
+ return unittest.TestSuite((
+ unittest.makeSuite(SimpleTermTests),
+ unittest.makeSuite(SimpleVocabularyTests),
+ unittest.makeSuite(TreeVocabularyTests),
+ unittest.makeSuite(RegistryTests),
+ ))
Deleted: zope.schema/trunk/src/zope/schema/validation.txt
===================================================================
--- zope.schema/trunk/src/zope/schema/validation.txt 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/validation.txt 2012-05-04 23:47:32 UTC (rev 125654)
@@ -1,166 +0,0 @@
-=================
-Schema Validation
-=================
-
-There are two helper methods to verify schemas and interfaces:
-
-getValidationErrors
- first validates via the zope.schema field validators. If that succeeds the
- invariants are checked.
-getSchemaValidationErrors
- *only* validateds via the zope.schema field validators. The invariants are
- *not* checked.
-
-
-Create an interface to validate against:
-
- >>> import zope.interface
- >>> import zope.schema
- >>> from six import print_
- >>> 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):
- ... print_("Checking if a > b")
- ... if obj.a <= obj.b:
- ... raise zope.interface.Invalid("%s<=%s" % (obj.a, obj.b))
- ...
-
-Create a silly model:
-
- >>> class TwoInts(object):
- ... pass
-
-Create an instance of TwoInts but do not set attributes. We get two errors:
-
- >>> ti = TwoInts()
- >>> r = zope.schema.getValidationErrors(ITwoInts, ti)
- >>> r.sort()
- >>> r
- [('a', SchemaNotFullyImplemented(...AttributeError...)),
- ('b', SchemaNotFullyImplemented(...AttributeError...))]
- >>> r[0][1].args[0].args
- ("'TwoInts' object has no attribute 'a'",)
- >>> r[1][1].args[0].args
- ("'TwoInts' object has no attribute 'b'",)
-
-The `getSchemaValidationErrors` function returns the same result:
-
- >>> r = zope.schema.getSchemaValidationErrors(ITwoInts, ti)
- >>> r.sort()
- >>> r
- [('a', SchemaNotFullyImplemented(...AttributeError...)),
- ('b', SchemaNotFullyImplemented(...AttributeError...))]
- >>> r[0][1].args[0].args
- ("'TwoInts' object has no attribute 'a'",)
- >>> 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
-vaildated if there are other schema errors.
-
-When we set a valid value for `a` we still get the same error for `b`:
-
- >>> ti.a = 11
- >>> errors = zope.schema.getValidationErrors(ITwoInts, ti)
- >>> errors.sort()
- >>> errors
- [('a', TooBig(11, 10)),
- ('b', SchemaNotFullyImplemented(...AttributeError...))]
- >>> errors[1][1].args[0].args
- ("'TwoInts' object has no attribute 'b'",)
-
- >>> errors[0][1].doc()
- u'Value is too big'
-
-
-After setting a valid value for `a` there is only the error for the missing `b`
-left:
-
- >>> 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:
-
- >>> ti.b = 10
- >>> errors = zope.schema.getValidationErrors(ITwoInts, ti)
- Checking if a > b
- >>> errors
- [(None, <zope.interface.exceptions.Invalid instance at 0x...>)]
-
-
-When using `getSchemaValidationErrors` we do not get an error any more:
-
- >>> zope.schema.getSchemaValidationErrors(ITwoInts, ti)
- []
-
-
-Set `b=5` so everything is fine:
-
- >>> ti.b = 5
- >>> zope.schema.getValidationErrors(ITwoInts, ti)
- Checking if a > b
- []
-
-
-Compare ValidationError
------------------------
-
-There was an issue with compare validation error with somthing else then an
-exceptions. Let's test if we can compare ValidationErrors with different things
-
- >>> from zope.schema._bootstrapinterfaces import ValidationError
- >>> v1 = ValidationError('one')
- >>> v2 = ValidationError('one')
- >>> v3 = ValidationError('another one')
-
-A ValidationError with the same arguments compares:
-
- >>> v1 == v2
- True
-
-but not with an error with different arguments:
-
- >>> v1 == v3
- False
-
-We can also compare validation erros 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'
-
- >>> 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:
-
- >>> from zope.schema._bootstrapinterfaces import RequiredMissing
- >>> r1 = RequiredMissing('one')
- >>> v1 == r1
- True
Modified: zope.schema/trunk/src/zope/schema/vocabulary.py
===================================================================
--- zope.schema/trunk/src/zope/schema/vocabulary.py 2012-05-04 23:45:00 UTC (rev 125653)
+++ zope.schema/trunk/src/zope/schema/vocabulary.py 2012-05-04 23:47:32 UTC (rev 125654)
@@ -13,17 +13,15 @@
##############################################################################
"""Vocabulary support for schema.
"""
-try:
- from collections import OrderedDict
-except ImportError:
- from ordereddict import OrderedDict
-from zope.interface.declarations import directlyProvides, implementer
-from zope.schema.interfaces import ValidationError
-from zope.schema.interfaces import IVocabularyRegistry
-from zope.schema.interfaces import IVocabulary, IVocabularyTokenized
+from zope.interface import directlyProvides
+from zope.interface import implementer
+from zope.schema.interfaces import ITitledTokenizedTerm
+from zope.schema.interfaces import ITokenizedTerm
from zope.schema.interfaces import ITreeVocabulary
-from zope.schema.interfaces import ITokenizedTerm, ITitledTokenizedTerm
+from zope.schema.interfaces import IVocabularyRegistry
+from zope.schema.interfaces import IVocabularyTokenized
+from zope.schema._compat import OrderedDict
# simple vocabularies performing enumerated-like tasks
_marker = object()
@@ -384,9 +382,9 @@
try:
from zope.testing.cleanup import addCleanUp
-except ImportError:
+except ImportError: #pragma NO COVER
# don't have that part of Zope
pass
-else:
+else: #pragma NO COVER
addCleanUp(_clear)
del addCleanUp
Copied: zope.schema/trunk/tox.ini (from rev 125653, zope.schema/branches/tseaver-test_cleanup/tox.ini)
===================================================================
--- zope.schema/trunk/tox.ini (rev 0)
+++ zope.schema/trunk/tox.ini 2012-05-04 23:47:32 UTC (rev 125654)
@@ -0,0 +1,35 @@
+[tox]
+envlist =
+# Jython support pending 2.7 support, due 2012-07-15 or so. See:
+# http://fwierzbicki.blogspot.com/2012/03/adconion-to-fund-jython-27.html
+# py26,py27,py32,jython,pypy,coverage
+ py26,py27,py32,pypy,coverage
+
+[testenv]
+deps =
+ zope.schema[test]
+commands =
+ python setup.py test -q
+
+[testenv:jython]
+commands =
+ jython setup.py test -q
+
+[testenv:coverage]
+basepython =
+ python2.6
+commands =
+# The installed version messes up nose's test discovery / coverage reporting
+# So, we uninstall that from the environment, and then install the editable
+# version, before running nosetests.
+ pip uninstall -y zope.schema
+ pip install -e .
+ nosetests --with-xunit --with-xcoverage
+deps =
+ zope.schema[test]
+ zope.interface>=3.6.0
+ zope.event
+ zope.testing
+ nose
+ coverage
+ nosexcover
More information about the checkins
mailing list