zope.schema-3.7.1/ 000755 000765 000765 00000000000 11505354711 014526 5 ustar 00gotcha gotcha 000000 000000 zope.schema-3.7.1/.bzrignore 000644 000765 000765 00000000107 11505354675 016537 0 ustar 00gotcha gotcha 000000 000000 ./.installed.cfg
./bin
./eggs
./develop-eggs
./docs
./parts
*.egg-info
zope.schema-3.7.1/bootstrap.py 000644 000765 000765 00000007330 11505354675 017131 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Bootstrap a buildout-based project
Simply run this script in a directory containing a buildout.cfg.
The script accepts buildout command-line options, so you can
use the -c option to specify an alternate configuration file.
"""
import os, shutil, sys, tempfile, urllib2
from optparse import OptionParser
tmpeggs = tempfile.mkdtemp()
is_jython = sys.platform.startswith('java')
# parsing arguments
parser = OptionParser()
parser.add_option("-v", "--version", dest="version",
help="use a specific zc.buildout version")
parser.add_option("-d", "--distribute",
action="store_true", dest="distribute", default=False,
help="Use Disribute rather than Setuptools.")
parser.add_option("-c", None, action="store", dest="config_file",
help=("Specify the path to the buildout configuration "
"file to be used."))
options, args = parser.parse_args()
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args += ['-c', options.config_file]
if options.version is not None:
VERSION = '==%s' % options.version
else:
VERSION = ''
USE_DISTRIBUTE = options.distribute
args = args + ['bootstrap']
to_reload = False
try:
import pkg_resources
if not hasattr(pkg_resources, '_distribute'):
to_reload = True
raise ImportError
except ImportError:
ez = {}
if USE_DISTRIBUTE:
exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py'
).read() in ez
ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True)
else:
exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py'
).read() in ez
ez['use_setuptools'](to_dir=tmpeggs, download_delay=0)
if to_reload:
reload(pkg_resources)
else:
import pkg_resources
if sys.platform == 'win32':
def quote(c):
if ' ' in c:
return '"%s"' % c # work around spawn lamosity on windows
else:
return c
else:
def quote (c):
return c
cmd = 'from setuptools.command.easy_install import main; main()'
ws = pkg_resources.working_set
if USE_DISTRIBUTE:
requirement = 'distribute'
else:
requirement = 'setuptools'
if is_jython:
import subprocess
assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd',
quote(tmpeggs), 'zc.buildout' + VERSION],
env=dict(os.environ,
PYTHONPATH=
ws.find(pkg_resources.Requirement.parse(requirement)).location
),
).wait() == 0
else:
assert os.spawnle(
os.P_WAIT, sys.executable, quote (sys.executable),
'-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION,
dict(os.environ,
PYTHONPATH=
ws.find(pkg_resources.Requirement.parse(requirement)).location
),
) == 0
ws.add_entry(tmpeggs)
ws.require('zc.buildout' + VERSION)
import zc.buildout.buildout
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs)
zope.schema-3.7.1/buildout.cfg 000644 000765 000765 00000000354 11505354675 017051 0 ustar 00gotcha gotcha 000000 000000 [buildout]
develop = .
parts = test docs
[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 =
zope.schema-3.7.1/CHANGES.txt 000644 000765 000765 00000012241 11505354675 016350 0 ustar 00gotcha gotcha 000000 000000 =======
CHANGES
=======
3.7.1 (2010-12-25)
------------------
- The validation token, used in the validation of schema with Object
Field to avoid infinite recursion, has been renamed.
``__schema_being_validated`` became ``_v_schema_being_validated``,
a volatile attribute, to avoid persistency and therefore,
read/write conflicts.
- Don't allow "[\]^`" in DottedName.
https://bugs.launchpad.net/zope.schema/+bug/191236
3.7.0 (2010-09-12)
------------------
- Improve error messages when term tokens or values are duplicates.
- Fix the buildout so the tests run.
3.6.4 (2010-06-08)
------------------
- fix validation of schema with Object Field that specify Interface schema.
3.6.3 (2010-04-30)
------------------
- Prefer the standard libraries doctest module to the one from zope.testing.
3.6.2 (2010-04-30)
------------------
- Avoid maximum recursion when validating Object field that points to cycles
- Made the dependency on ``zope.i18nmessageid`` optional.
3.6.1 (2010-01-05)
------------------
- Allow "setup.py test" to run at least a subset of the tests runnable
via ``bin/test`` (227 for ``setup.py test`` vs. 258. for
``bin/test``)
- Make ``zope.schema._bootstrapfields.ValidatedProperty`` descriptor
work under Jython.
- Make "setup.py test" tests pass on Jython.
3.6.0 (2009-12-22)
------------------
- Prefer zope.testing.doctest over doctestunit.
- Extend validation error to hold the field name.
- Add FieldProperty class that uses Field.get and Field.set methods
instead of storing directly on the instance __dict__.
3.5.4 (2009-03-25)
------------------
- Don't fail trying to validate default value for Choice fields with
IContextSourceBinder object given as a source. See
https://bugs.launchpad.net/zope3/+bug/340416.
- Add an interface for ``DottedName`` field.
- Add ``vocabularyName`` attribute to the ``IChoice`` interface, change
"vocabulary" attribute description to be more sensible, making it
``zope.schema.Field`` instead of plain ``zope.interface.Attribute``.
- Make IBool interface of Bool more important than IFromUnicode so adapters
registered for IBool take precendence over adapters registered for
IFromUnicode.
3.5.3 (2009-03-10)
------------------
- Make Choice and Bool fields implement IFromUnicode interface, because
they do provide the ``fromUnicode`` method.
- Change package's mailing list address to zope-dev at zope.org, as
zope3-dev at zope.org is now retired.
- Fix package's documentation formatting. Change package's description.
- Add buildout part that builds Sphinx-generated documentation.
- Remove zpkg-related file.
3.5.2 (2009-02-04)
------------------
- Made validation tests compatible with Python 2.5 again (hopefully not
breaking Python 2.4)
- Added an __all__ package attribute to expose documentation.
3.5.1 (2009-01-31)
------------------
- Stop using the old old set type.
- Make tests compatible and silent with Python 2.4.
- Fix __cmp__ method in ValidationError. Show some side effects based on the
existing __cmp__ implementation. See validation.txt
- Make 'repr' of the ValidationError and its subclasses more sensible. This
may require you to adapt your doctests for the new style, but now it makes
much more sense for debugging for developers.
3.5.0a2 (2008-12-11)
--------------------
- Move zope.testing to "test" extras_require, as it is not needed
for zope.schema itself.
- Change the order of classes in SET_TYPES tuple, introduced in
previous release to one that was in 3.4 (SetType, set), because
third-party code could be dependent on that order. The one
example is z3c.form's converter.
3.5.0a1 (2008-10-10)
--------------------
- Added the doctests to the long description.
- Removed use of deprecated 'sets' module when running under Python 2.6.
- Removed spurious doctest failure when running under Python 2.6.
- Added support to bootstrap on Jython.
- Added helper methods for schema validation: ``getValidationErrors``
and ``getSchemaValidationErrors``.
- zope.schema now works on Python2.5
3.4.0 (2007-09-28)
------------------
Added BeforeObjectAssignedEvent that is triggered before the object
field sets a value.
3.3.0 (2007-03-15)
------------------
Corresponds to the version of the zope.schema package shipped as part of
the Zope 3.3.0 release.
3.2.1 (2006-03-26)
------------------
Corresponds to the version of the zope.schema package shipped as part of
the Zope 3.2.1 release.
Fixed missing import of 'VocabularyRegistryError'. See
http://www.zope.org/Collectors/Zope3-dev/544 .
3.2.0 (2006-01-05)
------------------
Corresponds to the version of the zope.schema package shipped as part of
the Zope 3.2.0 release.
Added "iterable" sources to replace vocabularies, which are now deprecated
and scheduled for removal in Zope 3.3.
3.1.0 (2005-10-03)
------------------
Corresponds to the version of the zope.schema package shipped as part of
the Zope 3.1.0 release.
Allowed 'Choice' fields to take either a 'vocabulary' or a 'source'
argument (sources are a simpler implementation).
Added 'TimeDelta' and 'ASCIILine' field types.
3.0.0 (2004-11-07)
------------------
Corresponds to the version of the zope.schema package shipped as part of
the Zope X3.0.0 release.
zope.schema-3.7.1/COPYRIGHT.txt 000644 000765 000765 00000000040 11505354675 016642 0 ustar 00gotcha gotcha 000000 000000 Zope Foundation and Contributors zope.schema-3.7.1/LICENSE.txt 000644 000765 000765 00000004026 11505354675 016364 0 ustar 00gotcha gotcha 000000 000000 Zope Public License (ZPL) Version 2.1
A copyright notice accompanies this license document that identifies the
copyright holders.
This license has been certified as open source. It has also been designated as
GPL compatible by the Free Software Foundation (FSF).
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions in source code must retain the accompanying copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the accompanying copyright
notice, this list of conditions, and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Names of the copyright holders must not be used to endorse or promote
products derived from this software without prior written permission from the
copyright holders.
4. The right to distribute this software or to use it for any purpose does not
give you the right to use Servicemarks (sm) or Trademarks (tm) of the
copyright
holders. Use of them is covered by separate agreement with the copyright
holders.
5. If any files are modified, you must cause the modified files to carry
prominent notices stating that you changed the files and the date of any
change.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zope.schema-3.7.1/PKG-INFO 000644 000765 000765 00000107471 11505354711 015635 0 ustar 00gotcha gotcha 000000 000000 Metadata-Version: 1.0
Name: zope.schema
Version: 3.7.1
Summary: zope.interface extension for defining data schemas
Home-page: http://pypi.python.org/pypi/zope.schema
Author: Zope Foundation and Contributors
Author-email: zope-dev@zope.org
License: ZPL 2.1
Description: ==============
Zope 3 Schemas
==============
Introduction
------------
*This package is intended to be independently reusable in any Python
project. It is maintained by the* `Zope Toolkit project `_.
Schemas extend the notion of interfaces to detailed descriptions of Attributes
(but not methods). Every schema is an interface and specifies the public
fields of an object. A *field* roughly corresponds to an attribute of a
python object. But a Field provides space for at least a title and a
description. It can also constrain its value and provide a validation method.
Besides you can optionally specify characteristics such as its value being
read-only or not required.
Zope 3 schemas were born when Jim Fulton and Martijn Faassen thought
about Formulator for Zope 3 and ``PropertySets`` while at the `Zope 3
sprint`_ at the Zope BBQ in Berlin. They realized that if you strip
all view logic from forms then you have something similar to interfaces. And
thus schemas were born.
.. _Zope 3 sprint: http://dev.zope.org/Zope3/ZopeBBQ2002Sprint
.. 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
>>> 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:
>>> class Bookmark(object):
... zope.interface.implements(IBookmark)
...
... 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 = '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', , 'url')
>>> url_bound.validate('foo.bar')
Traceback (most recent call last):
...
InvalidURI: foo.bar
Now that the data has been successfully validated, we can set it on the
object:
>>> 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@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.
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
======
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
>>> 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.
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`.
=======
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
>>> class MySource(object):
... interface.implements(ISource)
... 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.
>>> 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.
=================
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
>>> 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, )]
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
=======
CHANGES
=======
3.7.1 (2010-12-25)
------------------
- The validation token, used in the validation of schema with Object
Field to avoid infinite recursion, has been renamed.
``__schema_being_validated`` became ``_v_schema_being_validated``,
a volatile attribute, to avoid persistency and therefore,
read/write conflicts.
- Don't allow "[\]^`" in DottedName.
https://bugs.launchpad.net/zope.schema/+bug/191236
3.7.0 (2010-09-12)
------------------
- Improve error messages when term tokens or values are duplicates.
- Fix the buildout so the tests run.
3.6.4 (2010-06-08)
------------------
- fix validation of schema with Object Field that specify Interface schema.
3.6.3 (2010-04-30)
------------------
- Prefer the standard libraries doctest module to the one from zope.testing.
3.6.2 (2010-04-30)
------------------
- Avoid maximum recursion when validating Object field that points to cycles
- Made the dependency on ``zope.i18nmessageid`` optional.
3.6.1 (2010-01-05)
------------------
- Allow "setup.py test" to run at least a subset of the tests runnable
via ``bin/test`` (227 for ``setup.py test`` vs. 258. for
``bin/test``)
- Make ``zope.schema._bootstrapfields.ValidatedProperty`` descriptor
work under Jython.
- Make "setup.py test" tests pass on Jython.
3.6.0 (2009-12-22)
------------------
- Prefer zope.testing.doctest over doctestunit.
- Extend validation error to hold the field name.
- Add FieldProperty class that uses Field.get and Field.set methods
instead of storing directly on the instance __dict__.
3.5.4 (2009-03-25)
------------------
- Don't fail trying to validate default value for Choice fields with
IContextSourceBinder object given as a source. See
https://bugs.launchpad.net/zope3/+bug/340416.
- Add an interface for ``DottedName`` field.
- Add ``vocabularyName`` attribute to the ``IChoice`` interface, change
"vocabulary" attribute description to be more sensible, making it
``zope.schema.Field`` instead of plain ``zope.interface.Attribute``.
- Make IBool interface of Bool more important than IFromUnicode so adapters
registered for IBool take precendence over adapters registered for
IFromUnicode.
3.5.3 (2009-03-10)
------------------
- Make Choice and Bool fields implement IFromUnicode interface, because
they do provide the ``fromUnicode`` method.
- Change package's mailing list address to zope-dev at zope.org, as
zope3-dev at zope.org is now retired.
- Fix package's documentation formatting. Change package's description.
- Add buildout part that builds Sphinx-generated documentation.
- Remove zpkg-related file.
3.5.2 (2009-02-04)
------------------
- Made validation tests compatible with Python 2.5 again (hopefully not
breaking Python 2.4)
- Added an __all__ package attribute to expose documentation.
3.5.1 (2009-01-31)
------------------
- Stop using the old old set type.
- Make tests compatible and silent with Python 2.4.
- Fix __cmp__ method in ValidationError. Show some side effects based on the
existing __cmp__ implementation. See validation.txt
- Make 'repr' of the ValidationError and its subclasses more sensible. This
may require you to adapt your doctests for the new style, but now it makes
much more sense for debugging for developers.
3.5.0a2 (2008-12-11)
--------------------
- Move zope.testing to "test" extras_require, as it is not needed
for zope.schema itself.
- Change the order of classes in SET_TYPES tuple, introduced in
previous release to one that was in 3.4 (SetType, set), because
third-party code could be dependent on that order. The one
example is z3c.form's converter.
3.5.0a1 (2008-10-10)
--------------------
- Added the doctests to the long description.
- Removed use of deprecated 'sets' module when running under Python 2.6.
- Removed spurious doctest failure when running under Python 2.6.
- Added support to bootstrap on Jython.
- Added helper methods for schema validation: ``getValidationErrors``
and ``getSchemaValidationErrors``.
- zope.schema now works on Python2.5
3.4.0 (2007-09-28)
------------------
Added BeforeObjectAssignedEvent that is triggered before the object
field sets a value.
3.3.0 (2007-03-15)
------------------
Corresponds to the version of the zope.schema package shipped as part of
the Zope 3.3.0 release.
3.2.1 (2006-03-26)
------------------
Corresponds to the version of the zope.schema package shipped as part of
the Zope 3.2.1 release.
Fixed missing import of 'VocabularyRegistryError'. See
http://www.zope.org/Collectors/Zope3-dev/544 .
3.2.0 (2006-01-05)
------------------
Corresponds to the version of the zope.schema package shipped as part of
the Zope 3.2.0 release.
Added "iterable" sources to replace vocabularies, which are now deprecated
and scheduled for removal in Zope 3.3.
3.1.0 (2005-10-03)
------------------
Corresponds to the version of the zope.schema package shipped as part of
the Zope 3.1.0 release.
Allowed 'Choice' fields to take either a 'vocabulary' or a 'source'
argument (sources are a simpler implementation).
Added 'TimeDelta' and 'ASCIILine' field types.
3.0.0 (2004-11-07)
------------------
Corresponds to the version of the zope.schema package shipped as part of
the Zope X3.0.0 release.
Platform: UNKNOWN
zope.schema-3.7.1/README.txt 000644 000765 000765 00000001073 11505354675 016236 0 ustar 00gotcha gotcha 000000 000000 ***********
zope.schema
***********
Schemas extend the notion of interfaces to detailed descriptions of
Attributes (but not methods). Every schema is an interface and
specifies the public fields of an object. A *field* roughly
corresponds to an attribute of a Python object. But a Field provides
space for at least a title and a description. It can also constrain
its value and provide a validation method. Besides you can optionally
specify characteristics such as its value being read-only or not
required.
See 'src/zope/schema/README.txt' for more information.
zope.schema-3.7.1/setup.cfg 000644 000765 000765 00000000073 11505354711 016347 0 ustar 00gotcha gotcha 000000 000000 [egg_info]
tag_build =
tag_date = 0
tag_svn_revision = 0
zope.schema-3.7.1/setup.py 000644 000765 000765 00000007007 11505354675 016255 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
# This package is developed by the Zope Toolkit project, documented here:
# http://docs.zope.org/zopetoolkit
# When developing and releasing this package, please follow the documented
# Zope Toolkit policies as described by this documentation.
##############################################################################
"""Setup for zope.schema package
"""
import os
from setuptools import setup, find_packages
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
def _modname(path, base, name=''):
if path == base:
return name
dirname, basename = os.path.split(path)
return _modname(dirname, base, basename + '.' + name)
def alltests():
import logging
import pkg_resources
import unittest
class NullHandler(logging.Handler):
level = 50
def emit(self, record):
pass
logging.getLogger().addHandler(NullHandler())
suite = unittest.TestSuite()
base = pkg_resources.working_set.find(
pkg_resources.Requirement.parse('zope.schema')).location
for dirpath, dirnames, filenames in os.walk(base):
if os.path.basename(dirpath) == 'tests':
for filename in filenames:
if filename.endswith('.py') and filename.startswith('test'):
mod = __import__(
_modname(dirpath, base, os.path.splitext(filename)[0]),
{}, {}, ['*'])
suite.addTest(mod.test_suite())
elif 'tests.py' in filenames:
continue
mod = __import__(_modname(dirpath, base, 'tests'), {}, {}, ['*'])
suite.addTest(mod.test_suite())
return suite
setup(name='zope.schema',
version = '3.7.1',
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@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')),
packages=find_packages('src'),
package_dir = {'': 'src'},
namespace_packages=['zope',],
extras_require={'test': ['zope.testing'],
'docs': ['z3c.recipe.sphinxdoc']},
install_requires=['setuptools',
'zope.interface',
'zope.event',
],
include_package_data = True,
zip_safe = False,
test_suite='__main__.alltests',
tests_require='zope.testing',
)
zope.schema-3.7.1/src/ 000755 000765 000765 00000000000 11505354711 015315 5 ustar 00gotcha gotcha 000000 000000 zope.schema-3.7.1/src/zope/ 000755 000765 000765 00000000000 11505354711 016272 5 ustar 00gotcha gotcha 000000 000000 zope.schema-3.7.1/src/zope.schema.egg-info/ 000755 000765 000765 00000000000 11505354711 021223 5 ustar 00gotcha gotcha 000000 000000 zope.schema-3.7.1/src/zope.schema.egg-info/dependency_links.txt 000644 000765 000765 00000000001 11505354705 025274 0 ustar 00gotcha gotcha 000000 000000
zope.schema-3.7.1/src/zope.schema.egg-info/namespace_packages.txt 000644 000765 000765 00000000005 11505354705 025554 0 ustar 00gotcha gotcha 000000 000000 zope
zope.schema-3.7.1/src/zope.schema.egg-info/not-zip-safe 000644 000765 000765 00000000001 11505354676 023463 0 ustar 00gotcha gotcha 000000 000000
zope.schema-3.7.1/src/zope.schema.egg-info/PKG-INFO 000644 000765 000765 00000107471 11505354705 022335 0 ustar 00gotcha gotcha 000000 000000 Metadata-Version: 1.0
Name: zope.schema
Version: 3.7.1
Summary: zope.interface extension for defining data schemas
Home-page: http://pypi.python.org/pypi/zope.schema
Author: Zope Foundation and Contributors
Author-email: zope-dev@zope.org
License: ZPL 2.1
Description: ==============
Zope 3 Schemas
==============
Introduction
------------
*This package is intended to be independently reusable in any Python
project. It is maintained by the* `Zope Toolkit project `_.
Schemas extend the notion of interfaces to detailed descriptions of Attributes
(but not methods). Every schema is an interface and specifies the public
fields of an object. A *field* roughly corresponds to an attribute of a
python object. But a Field provides space for at least a title and a
description. It can also constrain its value and provide a validation method.
Besides you can optionally specify characteristics such as its value being
read-only or not required.
Zope 3 schemas were born when Jim Fulton and Martijn Faassen thought
about Formulator for Zope 3 and ``PropertySets`` while at the `Zope 3
sprint`_ at the Zope BBQ in Berlin. They realized that if you strip
all view logic from forms then you have something similar to interfaces. And
thus schemas were born.
.. _Zope 3 sprint: http://dev.zope.org/Zope3/ZopeBBQ2002Sprint
.. 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
>>> 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:
>>> class Bookmark(object):
... zope.interface.implements(IBookmark)
...
... 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 = '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', , 'url')
>>> url_bound.validate('foo.bar')
Traceback (most recent call last):
...
InvalidURI: foo.bar
Now that the data has been successfully validated, we can set it on the
object:
>>> 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@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.
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
======
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
>>> 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.
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`.
=======
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
>>> class MySource(object):
... interface.implements(ISource)
... 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.
>>> 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.
=================
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
>>> 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, )]
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
=======
CHANGES
=======
3.7.1 (2010-12-25)
------------------
- The validation token, used in the validation of schema with Object
Field to avoid infinite recursion, has been renamed.
``__schema_being_validated`` became ``_v_schema_being_validated``,
a volatile attribute, to avoid persistency and therefore,
read/write conflicts.
- Don't allow "[\]^`" in DottedName.
https://bugs.launchpad.net/zope.schema/+bug/191236
3.7.0 (2010-09-12)
------------------
- Improve error messages when term tokens or values are duplicates.
- Fix the buildout so the tests run.
3.6.4 (2010-06-08)
------------------
- fix validation of schema with Object Field that specify Interface schema.
3.6.3 (2010-04-30)
------------------
- Prefer the standard libraries doctest module to the one from zope.testing.
3.6.2 (2010-04-30)
------------------
- Avoid maximum recursion when validating Object field that points to cycles
- Made the dependency on ``zope.i18nmessageid`` optional.
3.6.1 (2010-01-05)
------------------
- Allow "setup.py test" to run at least a subset of the tests runnable
via ``bin/test`` (227 for ``setup.py test`` vs. 258. for
``bin/test``)
- Make ``zope.schema._bootstrapfields.ValidatedProperty`` descriptor
work under Jython.
- Make "setup.py test" tests pass on Jython.
3.6.0 (2009-12-22)
------------------
- Prefer zope.testing.doctest over doctestunit.
- Extend validation error to hold the field name.
- Add FieldProperty class that uses Field.get and Field.set methods
instead of storing directly on the instance __dict__.
3.5.4 (2009-03-25)
------------------
- Don't fail trying to validate default value for Choice fields with
IContextSourceBinder object given as a source. See
https://bugs.launchpad.net/zope3/+bug/340416.
- Add an interface for ``DottedName`` field.
- Add ``vocabularyName`` attribute to the ``IChoice`` interface, change
"vocabulary" attribute description to be more sensible, making it
``zope.schema.Field`` instead of plain ``zope.interface.Attribute``.
- Make IBool interface of Bool more important than IFromUnicode so adapters
registered for IBool take precendence over adapters registered for
IFromUnicode.
3.5.3 (2009-03-10)
------------------
- Make Choice and Bool fields implement IFromUnicode interface, because
they do provide the ``fromUnicode`` method.
- Change package's mailing list address to zope-dev at zope.org, as
zope3-dev at zope.org is now retired.
- Fix package's documentation formatting. Change package's description.
- Add buildout part that builds Sphinx-generated documentation.
- Remove zpkg-related file.
3.5.2 (2009-02-04)
------------------
- Made validation tests compatible with Python 2.5 again (hopefully not
breaking Python 2.4)
- Added an __all__ package attribute to expose documentation.
3.5.1 (2009-01-31)
------------------
- Stop using the old old set type.
- Make tests compatible and silent with Python 2.4.
- Fix __cmp__ method in ValidationError. Show some side effects based on the
existing __cmp__ implementation. See validation.txt
- Make 'repr' of the ValidationError and its subclasses more sensible. This
may require you to adapt your doctests for the new style, but now it makes
much more sense for debugging for developers.
3.5.0a2 (2008-12-11)
--------------------
- Move zope.testing to "test" extras_require, as it is not needed
for zope.schema itself.
- Change the order of classes in SET_TYPES tuple, introduced in
previous release to one that was in 3.4 (SetType, set), because
third-party code could be dependent on that order. The one
example is z3c.form's converter.
3.5.0a1 (2008-10-10)
--------------------
- Added the doctests to the long description.
- Removed use of deprecated 'sets' module when running under Python 2.6.
- Removed spurious doctest failure when running under Python 2.6.
- Added support to bootstrap on Jython.
- Added helper methods for schema validation: ``getValidationErrors``
and ``getSchemaValidationErrors``.
- zope.schema now works on Python2.5
3.4.0 (2007-09-28)
------------------
Added BeforeObjectAssignedEvent that is triggered before the object
field sets a value.
3.3.0 (2007-03-15)
------------------
Corresponds to the version of the zope.schema package shipped as part of
the Zope 3.3.0 release.
3.2.1 (2006-03-26)
------------------
Corresponds to the version of the zope.schema package shipped as part of
the Zope 3.2.1 release.
Fixed missing import of 'VocabularyRegistryError'. See
http://www.zope.org/Collectors/Zope3-dev/544 .
3.2.0 (2006-01-05)
------------------
Corresponds to the version of the zope.schema package shipped as part of
the Zope 3.2.0 release.
Added "iterable" sources to replace vocabularies, which are now deprecated
and scheduled for removal in Zope 3.3.
3.1.0 (2005-10-03)
------------------
Corresponds to the version of the zope.schema package shipped as part of
the Zope 3.1.0 release.
Allowed 'Choice' fields to take either a 'vocabulary' or a 'source'
argument (sources are a simpler implementation).
Added 'TimeDelta' and 'ASCIILine' field types.
3.0.0 (2004-11-07)
------------------
Corresponds to the version of the zope.schema package shipped as part of
the Zope X3.0.0 release.
Platform: UNKNOWN
zope.schema-3.7.1/src/zope.schema.egg-info/requires.txt 000644 000765 000765 00000000126 11505354705 023625 0 ustar 00gotcha gotcha 000000 000000 setuptools
zope.interface
zope.event
[test]
zope.testing
[docs]
z3c.recipe.sphinxdoc zope.schema-3.7.1/src/zope.schema.egg-info/SOURCES.txt 000644 000765 000765 00000003635 11505354706 023122 0 ustar 00gotcha gotcha 000000 000000 .bzrignore
CHANGES.txt
COPYRIGHT.txt
LICENSE.txt
README.txt
bootstrap.py
buildout.cfg
setup.py
src/zope/__init__.py
src/zope.schema.egg-info/PKG-INFO
src/zope.schema.egg-info/SOURCES.txt
src/zope.schema.egg-info/dependency_links.txt
src/zope.schema.egg-info/namespace_packages.txt
src/zope.schema.egg-info/not-zip-safe
src/zope.schema.egg-info/requires.txt
src/zope.schema.egg-info/top_level.txt
src/zope/schema/README.txt
src/zope/schema/__init__.py
src/zope/schema/_bootstrapfields.py
src/zope/schema/_bootstrapinterfaces.py
src/zope/schema/_field.py
src/zope/schema/_messageid.py
src/zope/schema/_schema.py
src/zope/schema/accessors.py
src/zope/schema/fieldproperty.py
src/zope/schema/fields.txt
src/zope/schema/index.txt
src/zope/schema/interfaces.py
src/zope/schema/sources.txt
src/zope/schema/validation.txt
src/zope/schema/vocabulary.py
src/zope/schema/tests/__init__.py
src/zope/schema/tests/states.py
src/zope/schema/tests/test_accessors.py
src/zope/schema/tests/test_boolfield.py
src/zope/schema/tests/test_choice.py
src/zope/schema/tests/test_containerfield.py
src/zope/schema/tests/test_date.py
src/zope/schema/tests/test_datetime.py
src/zope/schema/tests/test_decimalfield.py
src/zope/schema/tests/test_dictfield.py
src/zope/schema/tests/test_docs.py
src/zope/schema/tests/test_dotted_name.py
src/zope/schema/tests/test_equality.py
src/zope/schema/tests/test_field.py
src/zope/schema/tests/test_fieldproperty.py
src/zope/schema/tests/test_floatfield.py
src/zope/schema/tests/test_interfacefield.py
src/zope/schema/tests/test_intfield.py
src/zope/schema/tests/test_iterablefield.py
src/zope/schema/tests/test_listfield.py
src/zope/schema/tests/test_objectfield.py
src/zope/schema/tests/test_schema.py
src/zope/schema/tests/test_setfield.py
src/zope/schema/tests/test_states.py
src/zope/schema/tests/test_strfield.py
src/zope/schema/tests/test_timedelta.py
src/zope/schema/tests/test_tuplefield.py
src/zope/schema/tests/test_vocabulary.py zope.schema-3.7.1/src/zope.schema.egg-info/top_level.txt 000644 000765 000765 00000000005 11505354705 023753 0 ustar 00gotcha gotcha 000000 000000 zope
zope.schema-3.7.1/src/zope/__init__.py 000644 000765 000765 00000000070 11505354675 020411 0 ustar 00gotcha gotcha 000000 000000 __import__('pkg_resources').declare_namespace(__name__)
zope.schema-3.7.1/src/zope/schema/ 000755 000765 000765 00000000000 11505354711 017532 5 ustar 00gotcha gotcha 000000 000000 zope.schema-3.7.1/src/zope/schema/__init__.py 000644 000765 000765 00000003000 11505354675 021645 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Schema package constructor
"""
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
from zope.schema._field import InterfaceField
from zope.schema._schema import (
getFields, getFieldsInOrder, getFieldNames, getFieldNamesInOrder,
getValidationErrors, getSchemaValidationErrors)
from zope.schema.accessors import accessors
from zope.schema.interfaces import ValidationError
__all__ = tuple(name for name in globals() if not name.startswith('_'))
zope.schema-3.7.1/src/zope/schema/_bootstrapfields.py 000644 000765 000765 00000031120 11505354675 023455 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Bootstrapping fields
"""
__docformat__ = 'restructuredtext'
import sys
from zope.interface import Attribute, providedBy, implements
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._schema import getFields
class ValidatedProperty(object):
def __init__(self, name, check=None):
self._info = name, check
def __set__(self, inst, value):
name, check = self._info
if value != inst.missing_value:
if check is not None:
check(inst, value)
else:
inst.validate(value)
inst.__dict__[name] = value
if sys.platform.startswith('java'):
# apparently descriptors work differently on Jython
def __get__(self, inst, owner):
name, check = self._info
return inst.__dict__[name]
class Field(Attribute):
# Type restrictions, if any
_type = None
context = None
# If a field has no assigned value, it will be set to missing_value.
missing_value = None
# This is the default value for the missing_value argument to the
# Field constructor. A marker is helpful since we don't want to
# overwrite missing_value if it is set differently on a Field
# subclass and isn't specified via the constructor.
__missing_value_marker = object()
# Note that the "order" field has a dual existance:
# 1. The class variable Field.order is used as a source for the
# monotonically increasing values used to provide...
# 2. The instance variable self.order which provides a
# monotonically increasing value that tracks the creation order
# of Field (including Field subclass) instances.
order = 0
default = ValidatedProperty('default')
# These were declared as slots in zope.interface, we override them here to
# get rid of the dedcriptors so they don't break .bind()
__name__ = None
interface = None
_Element__tagged_values = None
def __init__(self, title=u'', description=u'', __name__='',
required=True, readonly=False, constraint=None, default=None,
missing_value=__missing_value_marker):
"""Pass in field values as keyword parameters.
Generally, you want to pass either a title and description, or
a doc string. If you pass no doc string, it will be computed
from the title and description. If you pass a doc string that
follows the Python coding style (title line separated from the
body by a blank line), the title and description will be
computed from the doc string. Unfortunately, the doc string
must be passed as a positional argument.
Here are some examples:
>>> f = Field()
>>> f.__doc__, f.title, f.description
('', u'', u'')
>>> f = Field(title=u'sample')
>>> f.__doc__, f.title, f.description
(u'sample', u'sample', u'')
>>> f = Field(title=u'sample', description=u'blah blah\\nblah')
>>> f.__doc__, f.title, f.description
(u'sample\\n\\nblah blah\\nblah', u'sample', u'blah blah\\nblah')
"""
__doc__ = ''
if title:
if description:
__doc__ = "%s\n\n%s" % (title, description)
else:
__doc__ = title
elif description:
__doc__ = description
super(Field, self).__init__(__name__, __doc__)
self.title = title
self.description = description
self.required = required
self.readonly = readonly
if constraint is not None:
self.constraint = constraint
self.default = default
# Keep track of the order of field definitions
Field.order += 1
self.order = Field.order
if missing_value is not self.__missing_value_marker:
self.missing_value = missing_value
def constraint(self, value):
return True
def bind(self, object):
clone = self.__class__.__new__(self.__class__)
clone.__dict__.update(self.__dict__)
clone.context = object
return clone
def validate(self, value):
if value == self.missing_value:
if self.required:
raise RequiredMissing(self.__name__)
else:
try:
self._validate(value)
except StopValidation:
pass
def __eq__(self, other):
# should be the same type
if type(self) != type(other):
return False
# should have the same properties
names = {} # used as set of property names, ignoring values
for interface in providedBy(self):
names.update(getFields(interface))
# order will be different always, don't compare it
if 'order' in names:
del names['order']
for name in names:
if getattr(self, name) != getattr(other, name):
return False
return True
def __ne__(self, other):
return not self.__eq__(other)
def _validate(self, value):
if self._type is not None and not isinstance(value, self._type):
raise WrongType(value, self._type, self.__name__)
if not self.constraint(value):
raise ConstraintNotSatisfied(value)
def get(self, object):
return getattr(object, self.__name__)
def query(self, object, default=None):
return getattr(object, self.__name__, default)
def set(self, object, value):
if self.readonly:
raise TypeError("Can't set values on read-only fields "
"(name=%s, class=%s.%s)"
% (self.__name__,
object.__class__.__module__,
object.__class__.__name__))
setattr(object, self.__name__, value)
class Container(Field):
def _validate(self, value):
super(Container, self)._validate(value)
if not hasattr(value, '__contains__'):
try:
iter(value)
except TypeError:
raise NotAContainer(value)
class Iterable(Container):
def _validate(self, value):
super(Iterable, self)._validate(value)
# See if we can get an iterator for it
try:
iter(value)
except TypeError:
raise NotAnIterator(value)
class Orderable(object):
"""Values of ordered fields can be sorted.
They can be restricted to a range of values.
Orderable is a mixin used in combination with Field.
"""
min = ValidatedProperty('min')
max = ValidatedProperty('max')
def __init__(self, min=None, max=None, default=None, **kw):
# Set min and max to None so that we can validate if
# one of the super methods invoke validation.
self.min = None
self.max = None
super(Orderable, self).__init__(**kw)
# Now really set min and max
self.min = min
self.max = max
# We've taken over setting default so it can be limited by min
# and max.
self.default = default
def _validate(self, value):
super(Orderable, self)._validate(value)
if self.min is not None and value < self.min:
raise TooSmall(value, self.min)
if self.max is not None and value > self.max:
raise TooBig(value, self.max)
class MinMaxLen(object):
"""Expresses constraints on the length of a field.
MinMaxLen is a mixin used in combination with Field.
"""
min_length = 0
max_length = None
def __init__(self, min_length=0, max_length=None, **kw):
self.min_length = min_length
self.max_length = max_length
super(MinMaxLen, self).__init__(**kw)
def _validate(self, value):
super(MinMaxLen, self)._validate(value)
if self.min_length is not None and len(value) < self.min_length:
raise TooShort(value, self.min_length)
if self.max_length is not None and len(value) > self.max_length:
raise TooLong(value, self.max_length)
class Text(MinMaxLen, Field):
"""A field containing text used for human discourse."""
_type = unicode
implements(IFromUnicode)
def __init__(self, *args, **kw):
super(Text, self).__init__(*args, **kw)
def fromUnicode(self, str):
"""
>>> t = Text(constraint=lambda v: 'x' in v)
>>> t.fromUnicode("foo x spam")
Traceback (most recent call last):
...
WrongType: ('foo x spam', , '')
>>> t.fromUnicode(u"foo x spam")
u'foo x spam'
>>> t.fromUnicode(u"foo spam")
Traceback (most recent call last):
...
ConstraintNotSatisfied: foo spam
"""
self.validate(str)
return str
class TextLine(Text):
"""A text field with no newlines."""
def constraint(self, value):
return '\n' not in value and '\r' not in value
class Password(TextLine):
"""A text field containing a text used as a password."""
UNCHANGED_PASSWORD = object()
def set(self, context, value):
"""Update the password.
We use a special marker value that a widget can use
to tell us that the password didn't change. This is
needed to support edit forms that don't display the
existing password and want to work together with
encryption.
"""
if value is self.UNCHANGED_PASSWORD:
return
super(Password, self).set(context, value)
def validate(self, value):
try:
existing = bool(self.get(self.context))
except AttributeError:
existing = False
if value is self.UNCHANGED_PASSWORD and existing:
# Allow the UNCHANGED_PASSWORD value, if a password is set already
return
return super(Password, self).validate(value)
class Bool(Field):
"""A field representing a Bool."""
_type = type(True)
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 set(self, object, value):
if isinstance(value, int):
value = bool(value)
Field.set(self, object, value)
def fromUnicode(self, str):
"""
>>> b = Bool()
>>> IFromUnicode.providedBy(b)
True
>>> b.fromUnicode('True')
True
>>> b.fromUnicode('')
False
>>> b.fromUnicode('true')
True
>>> b.fromUnicode('false') or b.fromUnicode('False')
False
"""
v = str == 'True' or str == 'true'
self.validate(v)
return v
class Int(Orderable, Field):
"""A field representing an Integer."""
_type = int, long
implements(IFromUnicode)
def __init__(self, *args, **kw):
super(Int, self).__init__(*args, **kw)
def fromUnicode(self, str):
"""
>>> f = Int()
>>> f.fromUnicode("125")
125
>>> f.fromUnicode("125.6") #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ValueError: invalid literal for int(): 125.6
"""
v = int(str)
self.validate(v)
return v
zope.schema-3.7.1/src/zope/schema/_bootstrapinterfaces.py 000644 000765 000765 00000004712 11505354675 024341 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Bootstrap schema interfaces and exceptions
"""
import zope.interface
from zope.schema._messageid import _
class StopValidation(Exception):
"""Raised if the validation is completed early.
Note that this exception should be always caught, since it is just
a way for the validator to save time.
"""
class ValidationError(zope.interface.Invalid):
"""Raised if the Validation process fails."""
def doc(self):
return self.__class__.__doc__
def __cmp__(self, other):
if not hasattr(other, 'args'):
return -1
return cmp(self.args, other.args)
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__,
', '.join(repr(arg) for arg in self.args))
class RequiredMissing(ValidationError):
__doc__ = _("""Required input is missing.""")
class WrongType(ValidationError):
__doc__ = _("""Object is of wrong type.""")
class TooBig(ValidationError):
__doc__ = _("""Value is too big""")
class TooSmall(ValidationError):
__doc__ = _("""Value is too small""")
class TooLong(ValidationError):
__doc__ = _("""Value is too long""")
class TooShort(ValidationError):
__doc__ = _("""Value is too short""")
class InvalidValue(ValidationError):
__doc__ = _("""Invalid value""")
class ConstraintNotSatisfied(ValidationError):
__doc__ = _("""Constraint not satisfied""")
class NotAContainer(ValidationError):
__doc__ = _("""Not a container""")
class NotAnIterator(ValidationError):
__doc__ = _("""Not an iterator""")
class IFromUnicode(zope.interface.Interface):
"""Parse a unicode string to a value
We will often adapt fields to this interface to support views and
other applications that need to conver raw data as unicode
values.
"""
def fromUnicode(str):
"""Convert a unicode string to a value.
"""
zope.schema-3.7.1/src/zope/schema/_field.py 000644 000765 000765 00000062717 11505354675 021354 0 ustar 00gotcha gotcha 000000 000000 # -*- coding: utf-8 -*-
##############################################################################
# Copyright (c) 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Schema Fields
"""
__docformat__ = 'restructuredtext'
import re
import decimal
from datetime import datetime, date, timedelta, time
from zope.event import notify
from zope.interface import classImplements, implements, Interface
from zope.interface.interfaces import IInterface, IMethod
from zope.schema.interfaces import IField
from zope.schema.interfaces import IMinMaxLen, IText, ITextLine
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 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 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 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
# Fix up bootstrap field types
Field.title = FieldProperty(IField['title'])
Field.description = FieldProperty(IField['description'])
Field.required = FieldProperty(IField['required'])
Field.readonly = FieldProperty(IField['readonly'])
# Default is already taken care of
classImplements(Field, IField)
MinMaxLen.min_length = FieldProperty(IMinMaxLen['min_length'])
MinMaxLen.max_length = FieldProperty(IMinMaxLen['max_length'])
classImplements(Text, IText)
classImplements(TextLine, ITextLine)
classImplements(Password, IPassword)
classImplements(Bool, IBool)
classImplements(Bool, IFromUnicode)
classImplements(Int, IInt)
class SourceText(Text):
__doc__ = ISourceText.__doc__
implements(ISourceText)
_type = unicode
class Bytes(MinMaxLen, Field):
__doc__ = IBytes.__doc__
implements(IBytes, IFromUnicode)
_type = str
def fromUnicode(self, u):
"""
>>> b = Bytes(constraint=lambda v: 'x' in v)
>>> b.fromUnicode(u" foo x.y.z bat")
' foo x.y.z bat'
>>> b.fromUnicode(u" foo y.z bat")
Traceback (most recent call last):
...
ConstraintNotSatisfied: foo y.z bat
"""
v = str(u)
self.validate(v)
return v
class ASCII(Bytes):
__doc__ = IASCII.__doc__
implements(IASCII)
def _validate(self, value):
"""
>>> ascii = ASCII()
Make sure we accept empty strings:
>>> empty = ''
>>> ascii._validate(empty)
and all kinds of alphanumeric strings:
>>> alphanumeric = "Bob\'s my 23rd uncle"
>>> ascii._validate(alphanumeric)
>>> umlauts = "Köhlerstraße"
>>> ascii._validate(umlauts)
Traceback (most recent call last):
...
InvalidValue
"""
super(ASCII, self)._validate(value)
if not value:
return
if not max(map(ord, value)) < 128:
raise InvalidValue
class BytesLine(Bytes):
"""A Text field with no newlines."""
implements(IBytesLine)
def constraint(self, value):
# TODO: we should probably use a more general definition of newlines
return '\n' not in value
class ASCIILine(ASCII):
__doc__ = IASCIILine.__doc__
implements(IASCIILine)
def constraint(self, value):
# TODO: we should probably use a more general definition of newlines
return '\n' not in value
class Float(Orderable, Field):
__doc__ = IFloat.__doc__
implements(IFloat, IFromUnicode)
_type = float
def __init__(self, *args, **kw):
super(Float, self).__init__(*args, **kw)
def fromUnicode(self, u):
"""
>>> f = Float()
>>> f.fromUnicode("1.25")
1.25
>>> f.fromUnicode("1.25.6") #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ValueError: invalid literal for float(): 1.25.6
"""
v = float(u)
self.validate(v)
return v
class Decimal(Orderable, Field):
__doc__ = IDecimal.__doc__
implements(IDecimal, IFromUnicode)
_type = decimal.Decimal
def __init__(self, *args, **kw):
super(Decimal, self).__init__(*args, **kw)
def fromUnicode(self, u):
"""
>>> f = Decimal()
>>> import decimal
>>> isinstance(f.fromUnicode("1.25"), decimal.Decimal)
True
>>> float(f.fromUnicode("1.25"))
1.25
>>> f.fromUnicode("1.25.6")
Traceback (most recent call last):
...
ValueError: invalid literal for Decimal(): 1.25.6
"""
try:
v = decimal.Decimal(u)
except decimal.InvalidOperation:
raise ValueError('invalid literal for Decimal(): %s' % u)
self.validate(v)
return v
class Datetime(Orderable, Field):
__doc__ = IDatetime.__doc__
implements(IDatetime)
_type = datetime
def __init__(self, *args, **kw):
super(Datetime, self).__init__(*args, **kw)
class Date(Orderable, Field):
__doc__ = IDate.__doc__
implements(IDate)
_type = date
def _validate(self, value):
super(Date, self)._validate(value)
if isinstance(value, datetime):
raise WrongType(value, self._type, self.__name__)
class Timedelta(Orderable, Field):
__doc__ = ITimedelta.__doc__
implements(ITimedelta)
_type = timedelta
class Time(Orderable, Field):
__doc__ = ITime.__doc__
implements(ITime)
_type = time
class Choice(Field):
"""Choice fields can have a value found in a constant or dynamic set of
values given by the field definition.
"""
implements(IChoice, IFromUnicode)
def __init__(self, values=None, vocabulary=None, source=None, **kw):
"""Initialize object."""
if vocabulary is not None:
assert (isinstance(vocabulary, basestring)
or IBaseVocabulary.providedBy(vocabulary))
assert source is None, (
"You cannot specify both source and vocabulary.")
elif source is not None:
vocabulary = source
assert not (values is None and vocabulary is None), (
"You must specify either values or vocabulary.")
assert values is None or vocabulary is None, (
"You cannot specify both values and vocabulary.")
self.vocabulary = None
self.vocabularyName = None
if values is not None:
self.vocabulary = SimpleVocabulary.fromValues(values)
elif isinstance(vocabulary, (unicode, str)):
self.vocabularyName = vocabulary
else:
assert (ISource.providedBy(vocabulary) or
IContextSourceBinder.providedBy(vocabulary))
self.vocabulary = vocabulary
# Before a default value is checked, it is validated. However, a
# named vocabulary is usually not complete when these fields are
# initialized. Therefore signal the validation method to ignore
# default value checks during initialization of a Choice tied to a
# registered vocabulary.
self._init_field = (bool(self.vocabularyName) or
IContextSourceBinder.providedBy(self.vocabulary))
super(Choice, self).__init__(**kw)
self._init_field = False
source = property(lambda self: self.vocabulary)
def bind(self, object):
"""See zope.schema._bootstrapinterfaces.IField."""
clone = super(Choice, self).bind(object)
# 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)
return clone
def fromUnicode(self, str):
"""
>>> from vocabulary import SimpleVocabulary
>>> t = Choice(
... vocabulary=SimpleVocabulary.fromValues([u'foo',u'bar']))
>>> IFromUnicode.providedBy(t)
True
>>> t.fromUnicode(u"baz")
Traceback (most recent call last):
...
ConstraintNotSatisfied: baz
>>> t.fromUnicode(u"foo")
u'foo'
"""
self.validate(str)
return str
def _validate(self, value):
# Pass all validations during initialization
if self._init_field:
return
super(Choice, self)._validate(value)
vocabulary = self.vocabulary
if vocabulary is None:
vr = getVocabularyRegistry()
try:
vocabulary = vr.get(None, self.vocabularyName)
except VocabularyRegistryError:
raise ValueError("Can't validate value without vocabulary")
if value not in vocabulary:
raise ConstraintNotSatisfied(value)
class InterfaceField(Field):
__doc__ = IInterfaceField.__doc__
implements(IInterfaceField)
def _validate(self, value):
super(InterfaceField, self)._validate(value)
if not IInterface.providedBy(value):
raise WrongType("An interface is required", value, self.__name__)
def _validate_sequence(value_type, value, errors=None):
"""Validates a sequence value.
Returns a list of validation errors generated during the validation. If
no errors are generated, returns an empty list.
value_type is a field. value is the sequence being validated. errors is
an optional list of errors that will be prepended to the return value.
To illustrate, we'll use a text value type. All values must be unicode.
>>> field = TextLine(required=True)
To validate a sequence of various values:
>>> errors = _validate_sequence(field, ('foo', u'bar', 1))
>>> errors
[WrongType('foo', , ''), WrongType(1, , '')]
The only valid value in the sequence is the second item. The others
generated errors.
We can use the optional errors argument to collect additional errors
for a new sequence:
>>> errors = _validate_sequence(field, (2, u'baz'), errors)
>>> errors
[WrongType('foo', , ''), WrongType(1, , ''), WrongType(2, , '')]
"""
if errors is None:
errors = []
if value_type is None:
return errors
for item in value:
try:
value_type.validate(item)
except ValidationError, error:
errors.append(error)
return errors
def _validate_uniqueness(value):
temp_values = []
for item in value:
if item in temp_values:
raise NotUnique(item)
temp_values.append(item)
class AbstractCollection(MinMaxLen, Iterable):
value_type = None
unique = False
def __init__(self, value_type=None, unique=False, **kw):
super(AbstractCollection, self).__init__(**kw)
# whine if value_type is not a field
if value_type is not None and not IField.providedBy(value_type):
raise ValueError("'value_type' must be field instance.")
self.value_type = value_type
self.unique = unique
def bind(self, object):
"""See zope.schema._bootstrapinterfaces.IField."""
clone = super(AbstractCollection, self).bind(object)
# binding value_type is necessary for choices with named vocabularies,
# and possibly also for other fields.
if clone.value_type is not None:
clone.value_type = clone.value_type.bind(object)
return clone
def _validate(self, value):
super(AbstractCollection, self)._validate(value)
errors = _validate_sequence(self.value_type, value)
if errors:
raise WrongContainedType(errors, self.__name__)
if self.unique:
_validate_uniqueness(value)
class Tuple(AbstractCollection):
"""A field representing a Tuple."""
implements(ITuple)
_type = tuple
class List(AbstractCollection):
"""A field representing a List."""
implements(IList)
_type = list
class Set(AbstractCollection):
"""A field representing a set."""
implements(ISet)
_type = set
def __init__(self, **kw):
if 'unique' in kw: # set members are always unique
raise TypeError(
"__init__() got an unexpected keyword argument 'unique'")
super(Set, self).__init__(unique=True, **kw)
class FrozenSet(AbstractCollection):
implements(IFrozenSet)
_type = frozenset
def __init__(self, **kw):
if 'unique' in kw: # set members are always unique
raise TypeError(
"__init__() got an unexpected keyword argument 'unique'")
super(FrozenSet, self).__init__(unique=True, **kw)
def _validate_fields(schema, value, errors=None):
if errors is None:
errors = []
# Interface can be used as schema property for Object fields that plan to
# hold values of any type.
# Because Interface does not include any Attribute, it is obviously not
# worth looping on its methods and filter them all out.
if schema is Interface:
return errors
# if `value` is part of a cyclic graph, we need to break the cycle to avoid
# infinite recursion.
#
# (use volatile attribute to avoid persistency/conflicts)
if hasattr(value, '_v_schema_being_validated'):
return errors
# Mark the value as being validated.
value._v_schema_being_validated = True
# (If we have gotten here, we know that `value` provides an interface
# other than zope.interface.Interface;
# iow, we can rely on the fact that it is an instance
# that supports attribute assignment.)
try:
for name in schema.names(all=True):
if not IMethod.providedBy(schema[name]):
try:
attribute = schema[name]
if IField.providedBy(attribute):
# validate attributes that are fields
attribute.validate(getattr(value, name))
except ValidationError, error:
errors.append(error)
except AttributeError, error:
# property for the given name is not implemented
errors.append(SchemaNotFullyImplemented(error))
finally:
delattr(value, '_v_schema_being_validated')
return errors
class Object(Field):
__doc__ = IObject.__doc__
implements(IObject)
def __init__(self, schema, **kw):
if not IInterface.providedBy(schema):
raise WrongType
self.schema = schema
super(Object, self).__init__(**kw)
def _validate(self, value):
super(Object, self)._validate(value)
# schema has to be provided by value
if not self.schema.providedBy(value):
raise SchemaNotProvided
# check the value against schema
errors = _validate_fields(self.schema, value)
if errors:
raise WrongContainedType(errors, self.__name__)
def set(self, object, value):
# Announce that we're going to assign the value to the object.
# Motivation: Widgets typically like to take care of policy-specific
# actions, like establishing location.
event = BeforeObjectAssignedEvent(value, self.__name__, object)
notify(event)
# The event subscribers are allowed to replace the object, thus we need
# to replace our previous value.
value = event.object
super(Object, self).set(object, value)
class BeforeObjectAssignedEvent(object):
"""An object is going to be assigned to an attribute on another object."""
implements(IBeforeObjectAssignedEvent)
def __init__(self, object, name, context):
self.object = object
self.name = name
self.context = context
class Dict(MinMaxLen, Iterable):
"""A field representing a Dict."""
implements(IDict)
_type = dict
key_type = None
value_type = None
def __init__(self, key_type=None, value_type=None, **kw):
super(Dict, self).__init__(**kw)
# whine if key_type or value_type is not a field
if key_type is not None and not IField.providedBy(key_type):
raise ValueError("'key_type' must be field instance.")
if value_type is not None and not IField.providedBy(value_type):
raise ValueError("'value_type' must be field instance.")
self.key_type = key_type
self.value_type = value_type
def _validate(self, value):
super(Dict, self)._validate(value)
errors = []
try:
if self.value_type:
errors = _validate_sequence(self.value_type, value.values(),
errors)
errors = _validate_sequence(self.key_type, value, errors)
if errors:
raise WrongContainedType(errors, self.__name__)
finally:
errors = None
def bind(self, object):
"""See zope.schema._bootstrapinterfaces.IField."""
clone = super(Dict, self).bind(object)
# binding value_type is necessary for choices with named vocabularies,
# and possibly also for other fields.
if clone.key_type is not None:
clone.key_type = clone.key_type.bind(object)
if clone.value_type is not None:
clone.value_type = clone.value_type.bind(object)
return clone
_isuri = re.compile(
# scheme
r"[a-zA-z0-9+.-]+:"
# non space (should be pickier)
r"\S*$").match
class URI(BytesLine):
"""URI schema field
"""
implements(IURI, IFromUnicode)
def _validate(self, value):
"""
>>> uri = URI(__name__='test')
>>> uri.validate("http://www.python.org/foo/bar")
>>> uri.validate("DAV:")
>>> uri.validate("www.python.org/foo/bar")
Traceback (most recent call last):
...
InvalidURI: www.python.org/foo/bar
"""
super(URI, self)._validate(value)
if _isuri(value):
return
raise InvalidURI(value)
def fromUnicode(self, value):
"""
>>> uri = URI(__name__='test')
>>> uri.fromUnicode("http://www.python.org/foo/bar")
'http://www.python.org/foo/bar'
>>> uri.fromUnicode(" http://www.python.org/foo/bar")
'http://www.python.org/foo/bar'
>>> uri.fromUnicode(" \\n http://www.python.org/foo/bar\\n")
'http://www.python.org/foo/bar'
>>> uri.fromUnicode("http://www.python.org/ foo/bar")
Traceback (most recent call last):
...
InvalidURI: http://www.python.org/ foo/bar
"""
v = str(value.strip())
self.validate(v)
return v
_isdotted = re.compile(
r"([a-zA-Z][a-zA-Z0-9_]*)"
r"([.][a-zA-Z][a-zA-Z0-9_]*)*"
# use the whole line
r"$").match
class Id(BytesLine):
"""Id field
Values of id fields must be either uris or dotted names.
"""
implements(IId, IFromUnicode)
def _validate(self, value):
"""
>>> id = Id(__name__='test')
>>> id.validate("http://www.python.org/foo/bar")
>>> id.validate("zope.app.content")
>>> id.validate("zope.app.content/a")
Traceback (most recent call last):
...
InvalidId: zope.app.content/a
>>> id.validate("http://zope.app.content x y")
Traceback (most recent call last):
...
InvalidId: http://zope.app.content x y
"""
super(Id, self)._validate(value)
if _isuri(value):
return
if _isdotted(value) and "." in value:
return
raise InvalidId(value)
def fromUnicode(self, value):
"""
>>> id = Id(__name__='test')
>>> id.fromUnicode("http://www.python.org/foo/bar")
'http://www.python.org/foo/bar'
>>> id.fromUnicode(u" http://www.python.org/foo/bar ")
'http://www.python.org/foo/bar'
>>> id.fromUnicode("http://www.python.org/ foo/bar")
Traceback (most recent call last):
...
InvalidId: http://www.python.org/ foo/bar
>>> id.fromUnicode(" \\n x.y.z \\n")
'x.y.z'
"""
v = str(value.strip())
self.validate(v)
return v
class DottedName(BytesLine):
"""Dotted name field.
Values of DottedName fields must be Python-style dotted names.
"""
implements(IDottedName)
def __init__(self, *args, **kw):
"""
>>> DottedName(min_dots=-1)
Traceback (most recent call last):
...
ValueError: min_dots cannot be less than zero
>>> DottedName(max_dots=-1)
Traceback (most recent call last):
...
ValueError: max_dots cannot be less than min_dots
>>> DottedName(max_dots=1, min_dots=2)
Traceback (most recent call last):
...
ValueError: max_dots cannot be less than min_dots
>>> dotted_name = DottedName(max_dots=1, min_dots=1)
>>> from zope.interface.verify import verifyObject
>>> verifyObject(IDottedName, dotted_name)
True
>>> dotted_name = DottedName(max_dots=1)
>>> dotted_name.min_dots
0
>>> dotted_name = DottedName(min_dots=1)
>>> dotted_name.max_dots
>>> dotted_name.min_dots
1
"""
self.min_dots = int(kw.pop("min_dots", 0))
if self.min_dots < 0:
raise ValueError("min_dots cannot be less than zero")
self.max_dots = kw.pop("max_dots", None)
if self.max_dots is not None:
self.max_dots = int(self.max_dots)
if self.max_dots < self.min_dots:
raise ValueError("max_dots cannot be less than min_dots")
super(DottedName, self).__init__(*args, **kw)
def _validate(self, value):
"""
>>> dotted_name = DottedName(__name__='test')
>>> dotted_name.validate("a.b.c")
>>> dotted_name.validate("a")
>>> dotted_name.validate(" a")
Traceback (most recent call last):
...
InvalidDottedName: a
>>> dotted_name = DottedName(__name__='test', min_dots=1)
>>> dotted_name.validate('a.b')
>>> dotted_name.validate('a.b.c.d')
>>> dotted_name.validate('a')
Traceback (most recent call last):
...
InvalidDottedName: ('too few dots; 1 required', 'a')
>>> dotted_name = DottedName(__name__='test', max_dots=0)
>>> dotted_name.validate('a')
>>> dotted_name.validate('a.b')
Traceback (most recent call last):
...
InvalidDottedName: ('too many dots; no more than 0 allowed', 'a.b')
>>> dotted_name = DottedName(__name__='test', max_dots=2)
>>> dotted_name.validate('a')
>>> dotted_name.validate('a.b')
>>> dotted_name.validate('a.b.c')
>>> dotted_name.validate('a.b.c.d')
Traceback (most recent call last):
...
InvalidDottedName: ('too many dots; no more than 2 allowed', 'a.b.c.d')
>>> dotted_name = DottedName(__name__='test', max_dots=1, min_dots=1)
>>> dotted_name.validate('a.b')
>>> dotted_name.validate('a')
Traceback (most recent call last):
...
InvalidDottedName: ('too few dots; 1 required', 'a')
>>> dotted_name.validate('a.b.c')
Traceback (most recent call last):
...
InvalidDottedName: ('too many dots; no more than 1 allowed', 'a.b.c')
"""
super(DottedName, self)._validate(value)
if not _isdotted(value):
raise InvalidDottedName(value)
dots = value.count(".")
if dots < self.min_dots:
raise InvalidDottedName("too few dots; %d required" % self.min_dots,
value)
if self.max_dots is not None and dots > self.max_dots:
raise InvalidDottedName("too many dots; no more than %d allowed" %
self.max_dots, value)
def fromUnicode(self, value):
v = str(value.strip())
self.validate(v)
return v
zope.schema-3.7.1/src/zope/schema/_messageid.py 000644 000765 000765 00000001412 11505354675 022213 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# Copyright (c) 2000 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
try:
from zope.i18nmessageid import MessageFactory
except ImportError:
_ = lambda x: unicode(x)
else:
_ = MessageFactory("zope")
zope.schema-3.7.1/src/zope/schema/_schema.py 000644 000765 000765 00000006004 11505354675 021514 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Schema convenience functions
"""
import zope.interface.verify
def getFieldNames(schema):
"""Return a list of all the Field names in a schema.
"""
from zope.schema.interfaces import IField
return [name for name in schema if IField.providedBy(schema[name])]
def getFields(schema):
"""Return a dictionary containing all the Fields in a schema.
"""
from zope.schema.interfaces import IField
fields = {}
for name in schema:
attr = schema[name]
if IField.providedBy(attr):
fields[name] = attr
return fields
def getFieldsInOrder(schema,
_fieldsorter=lambda x, y: cmp(x[1].order, y[1].order)):
"""Return a list of (name, value) tuples in native schema order.
"""
fields = getFields(schema).items()
fields.sort(_fieldsorter)
return fields
def getFieldNamesInOrder(schema):
"""Return a list of all the Field names in a schema in schema order.
"""
return [ name for name, field in getFieldsInOrder(schema) ]
def getValidationErrors(schema, object):
"""Return a list of all validation errors.
"""
errors = getSchemaValidationErrors(schema, object)
if errors:
return errors
# Only validate invariants if there were no previous errors. Previous
# errors could be missing attributes which would most likely make an
# invariant raise an AttributeError.
invariant_errors = []
try:
schema.validateInvariants(object, invariant_errors)
except zope.interface.exceptions.Invalid:
# Just collect errors
pass
errors = [(None, e) for e in invariant_errors]
return errors
def getSchemaValidationErrors(schema, object):
errors = []
for name in schema.names(all=True):
if zope.interface.interfaces.IMethod.providedBy(schema[name]):
continue
attribute = schema[name]
if not zope.schema.interfaces.IField.providedBy(attribute):
continue
try:
value = getattr(object, name)
except AttributeError, error:
# property for the given name is not implemented
errors.append((
name, zope.schema.interfaces.SchemaNotFullyImplemented(error)))
else:
try:
attribute.bind(object).validate(value)
except zope.schema.ValidationError, e:
errors.append((name, e))
return errors
zope.schema-3.7.1/src/zope/schema/accessors.py 000644 000765 000765 00000007003 11505354675 022102 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""\
Field accessors
===============
Accessors are used to model methods used to access data defined by fields.
Accessors are fields that work by decorating existing fields.
To define accessors in an interface, use the accessors function::
class IMyInterface(Interface):
getFoo, setFoo = accessors(Text(title=u'Foo', ...))
getBar, = accessors(TextLine(title=u'Foo', readonly=True, ...)
Normally a read accessor and a write accessor are defined. Only a
read accessor is defined for read-only fields.
Read accessors function as access method specifications and as field
specifications. Write accessors are solely method specifications.
"""
from zope.interface import providedBy, implementedBy
from zope.interface.interface import Method
class FieldReadAccessor(Method):
"""Field read accessor
"""
# A read field accessor is a method and a field.
# A read accessor is a decorator of a field, using the given
# fields properties to provide meta data.
def __provides__(self):
return providedBy(self.field) + implementedBy(FieldReadAccessor)
__provides__ = property(__provides__)
def __init__(self, field):
self.field = field
Method.__init__(self, '')
self.__doc__ = 'get %s' % field.__doc__
def getSignatureString(self):
return '()'
def getSignatureInfo(self):
return {'positional': (),
'required': (),
'optional': (),
'varargs': None,
'kwargs': None,
}
def get(self, object):
return getattr(object, self.__name__)()
def query(self, object, default=None):
try:
f = getattr(object, self.__name__)
except AttributeError:
return default
else:
return f()
def set(self, object, value):
if self.readonly:
raise TypeError("Can't set values on read-only fields")
getattr(object, self.writer.__name__)(value)
def __getattr__(self, name):
return getattr(self.field, name)
def bind(self, object):
clone = self.__class__.__new__(self.__class__)
clone.__dict__.update(self.__dict__)
clone.field = self.field.bind(object)
return clone
class FieldWriteAccessor(Method):
def __init__(self, field):
Method.__init__(self, '')
self.field = field
self.__doc__ = 'set %s' % field.__doc__
def getSignatureString(self):
return '(newvalue)'
def getSignatureInfo(self):
return {'positional': ('newvalue',),
'required': ('newvalue',),
'optional': (),
'varargs': None,
'kwargs': None,
}
def accessors(field):
reader = FieldReadAccessor(field)
yield reader
if not field.readonly:
writer = FieldWriteAccessor(field)
reader.writer = writer
yield writer
zope.schema-3.7.1/src/zope/schema/fieldproperty.py 000644 000765 000765 00000006502 11505354675 023010 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Computed attributes based on schema fields
"""
from copy import copy
_marker = object()
class FieldProperty(object):
"""Computed attributes based on schema fields
Field properties provide default values, data validation and error messages
based on data found in field meta-data.
Note that FieldProperties cannot be used with slots. They can only
be used for attributes stored in instance dictionaries.
"""
def __init__(self, field, name=None):
if name is None:
name = field.__name__
self.__field = field
self.__name = name
def __get__(self, inst, klass):
if inst is None:
return self
value = inst.__dict__.get(self.__name, _marker)
if value is _marker:
field = self.__field.bind(inst)
value = getattr(field, 'default', _marker)
if value is _marker:
raise AttributeError(self.__name)
return value
def __set__(self, inst, value):
field = self.__field.bind(inst)
field.validate(value)
if field.readonly and inst.__dict__.has_key(self.__name):
raise ValueError(self.__name, 'field is readonly')
inst.__dict__[self.__name] = value
def __getattr__(self, name):
return getattr(self.__field, name)
class FieldPropertyStoredThroughField(object):
def __init__(self, field, name=None):
if name is None:
name = field.__name__
self.field = copy(field)
self.field.__name__ = "__st_%s_st" % self.field.__name__
self.__name = name
def setValue(self, inst, field, value):
field.set(inst, value)
def getValue(self, inst, field):
return field.query(inst, _marker)
def queryValue(self, inst, field, default):
return field.query(inst, default)
def __getattr__(self, name):
return getattr(self.field, name)
def __get__(self, inst, klass):
if inst is None:
return self
field = self.field.bind(inst)
value = self.getValue(inst, field)
if value is _marker:
value = getattr(field, 'default', _marker)
if value is _marker:
raise AttributeError(self.__name)
return value
def __set__(self, inst, value):
field = self.field.bind(inst)
field.validate(value)
if field.readonly:
if self.queryValue(inst, field, _marker) is _marker:
field.readonly = False
self.setValue(inst, field, value)
field.readonly = True
return
else:
raise ValueError(self.__name, 'field is readonly')
self.setValue(inst, field, value)
zope.schema-3.7.1/src/zope/schema/fields.txt 000644 000765 000765 00000015642 11505354675 021562 0 ustar 00gotcha gotcha 000000 000000 ======
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
>>> 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.
Choices and Collections
-----------------------
Choices are a field type and can be used as a value_type for collections. Just
as a collection of an "Int" value_type constrains members to integers, so a
choice-based value type constrains members to choices within the Choice's
vocabulary. Typically in the Zope application server widgets are found not
only for the collection and the choice field but also for the vocabulary on
which the choice is based.
Using Choice and Collection Fields within a Widget Framework
------------------------------------------------------------
While fields support several use cases, including code documentation and data
description and even casting, a significant use case influencing their design is
to support form generation -- generating widgets for a field. Choice and
collection fields are expected to be used within widget frameworks. The
zope.app approach typically (but configurably) uses multiple dispatches to
find widgets on the basis of various aspects of the fields.
Widgets for all fields are found by looking up a browser view of the field
providing an input or display widget view. Typically there is only a single
"widget" registered for Choice fields. When it is looked up, it performs
another dispatch -- another lookup -- for a widget registered for both the field
and the vocabulary. This widget typically has enough information to render
without a third dispatch.
Collection fields may fire several dispatches. The first is the usual lookup
by field. A single "widget" should be registered for ICollection, which does
a second lookup by field and value_type constraint, if any, or, theoretically,
if value_type is None, renders some absolutely generic collection widget that
allows input of any value imaginable: a check-in of such a widget would be
unexpected. This second lookup may find a widget that knows how to render,
and stop. However, the value_type may be a choice, which will usually fire a
third dispatch: a search for a browser widget for the collection field, the
value_type field, and the vocabulary. Further lookups may even be configured
on the basis of uniqueness and other constraints.
This level of indirection may be unnecessary for some applications, and can be
disabled with simple ZCML changes within `zope.app`.
zope.schema-3.7.1/src/zope/schema/index.txt 000644 000765 000765 00000000403 11505354675 021410 0 ustar 00gotcha gotcha 000000 000000 Welcome to zope.schema's documentation!
=======================================
Contents:
.. toctree::
:maxdepth: 2
README
fields
sources
validation
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
zope.schema-3.7.1/src/zope/schema/interfaces.py 000644 000765 000765 00000047273 11505354675 022255 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Schema interfaces and exceptions
"""
__docformat__ = "reStructuredText"
from zope.interface import Interface, Attribute
from zope.schema._messageid import _
# Import from _bootstrapinterfaces only because other packages will expect
# to find these interfaces here.
from zope.schema._bootstrapfields import Field
from zope.schema._bootstrapfields import Container
from zope.schema._bootstrapfields import Iterable
from zope.schema._bootstrapfields import Text
from zope.schema._bootstrapfields import TextLine
from zope.schema._bootstrapfields import TextLine
from zope.schema._bootstrapfields import Bool
from zope.schema._bootstrapfields import Int
from zope.schema._bootstrapinterfaces import StopValidation
from zope.schema._bootstrapinterfaces import ValidationError
from zope.schema._bootstrapinterfaces import IFromUnicode
from zope.schema._bootstrapinterfaces import RequiredMissing
from zope.schema._bootstrapinterfaces import WrongType
from zope.schema._bootstrapinterfaces import ConstraintNotSatisfied
from zope.schema._bootstrapinterfaces import NotAContainer
from zope.schema._bootstrapinterfaces import NotAnIterator
from zope.schema._bootstrapinterfaces import TooSmall
from zope.schema._bootstrapinterfaces import TooBig
from zope.schema._bootstrapinterfaces import TooLong
from zope.schema._bootstrapinterfaces import TooShort
from zope.schema._bootstrapinterfaces import InvalidValue
class WrongContainedType(ValidationError):
__doc__ = _("""Wrong contained type""")
class NotUnique(ValidationError):
__doc__ = _("""One or more entries of sequence are not unique.""")
class SchemaNotFullyImplemented(ValidationError):
__doc__ = _("""Schema not fully implemented""")
class SchemaNotProvided(ValidationError):
__doc__ = _("""Schema not provided""")
class InvalidURI(ValidationError):
__doc__ = _("""The specified URI is not valid.""")
class InvalidId(ValidationError):
__doc__ = _("""The specified id is not valid.""")
class InvalidDottedName(ValidationError):
__doc__ = _("""The specified dotted name is not valid.""")
class Unbound(Exception):
__doc__ = _("""The field is not bound.""")
class IField(Interface):
"""Basic Schema Field Interface.
Fields are used for Interface specifications. They at least provide
a title, description and a default value. You can also
specify if they are required and/or readonly.
The Field Interface is also used for validation and specifying
constraints.
We want to make it possible for a IField to not only work
on its value but also on the object this value is bound to.
This enables a Field implementation to perform validation
against an object which also marks a certain place.
Note that many fields need information about the object
containing a field. For example, when validating a value to be
set as an object attribute, it may be necessary for the field to
introspect the object's state. This means that the field needs to
have access to the object when performing validation::
bound = field.bind(object)
bound.validate(value)
"""
def bind(object):
"""Return a copy of this field which is bound to context.
The copy of the Field will have the 'context' attribute set
to 'object'. This way a Field can implement more complex
checks involving the object's location/environment.
Many fields don't need to be bound. Only fields that condition
validation or properties on an object containing the field
need to be bound.
"""
title = TextLine(
title=_(u"Title"),
description=_(u"A short summary or label"),
default=u"",
required=False,
)
description = Text(
title=_(u"Description"),
description=_(u"A description of the field"),
default=u"",
required=False,
)
required = Bool(
title=_(u"Required"),
description=(
_(u"Tells whether a field requires its value to exist.")),
default=True)
readonly = Bool(
title=_(u"Read Only"),
description=_(u"If true, the field's value cannot be changed."),
required=False,
default=False)
default = Field(
title=_(u"Default Value"),
description=_(u"""The field default value may be None or a legal
field value""")
)
missing_value = Field(
title=_(u"Missing Value"),
description=_(u"""If input for this Field is missing, and that's ok,
then this is the value to use""")
)
order = Int(
title=_(u"Field Order"),
description=_(u"""
The order attribute can be used to determine the order in
which fields in a schema were defined. If one field is created
after another (in the same thread), its order will be
greater.
(Fields in separate threads could have the same order.)
"""),
required=True,
readonly=True,
)
def constraint(value):
u"""Check a customized constraint on the value.
You can implement this method with your Field to
require a certain constraint. This relaxes the need
to inherit/subclass a Field you to add a simple constraint.
Returns true if the given value is within the Field's constraint.
"""
def validate(value):
u"""Validate that the given value is a valid field value.
Returns nothing but raises an error if the value is invalid.
It checks everything specific to a Field and also checks
with the additional constraint.
"""
def get(object):
"""Get the value of the field for the given object."""
def query(object, default=None):
"""Query the value of the field for the given object.
Return the default if the value hasn't been set.
"""
def set(object, value):
"""Set the value of the field for the object
Raises a type error if the field is a read-only field.
"""
class IIterable(IField):
u"""Fields with a value that can be iterated over.
The value needs to support iteration; the implementation mechanism
is not constrained. (Either `__iter__()` or `__getitem__()` may be
used.)
"""
class IContainer(IField):
u"""Fields whose value allows an ``x in value`` check.
The value needs to support the `in` operator, but is not
constrained in how it does so (whether it defines `__contains__()`
or `__getitem__()` is immaterial).
"""
class IOrderable(IField):
u"""Field requiring its value to be orderable.
The set of value needs support a complete ordering; the
implementation mechanism is not constrained. Either `__cmp__()` or
'rich comparison' methods may be used.
"""
class ILen(IField):
u"""A Field requiring its value to have a length.
The value needs to have a conventional __len__ method.
"""
class IMinMax(IOrderable):
u"""Field requiring its value to be between min and max.
This implies that the value needs to support the IOrderable interface.
"""
min = Field(
title=_(u"Start of the range"),
required=False,
default=None
)
max = Field(
title=_(u"End of the range (including the value itself)"),
required=False,
default=None
)
class IMinMaxLen(ILen):
u"""Field requiring the length of its value to be within a range"""
min_length = Int(
title=_(u"Minimum length"),
description=_(u"""
Value after whitespace processing cannot have less than
`min_length` characters (if a string type) or elements (if
another sequence type). If `min_length` is ``None``, there is
no minimum.
"""),
required=False,
min=0, # needs to be a positive number
default=0)
max_length = Int(
title=_(u"Maximum length"),
description=_(u"""
Value after whitespace processing cannot have greater
or equal than `max_length` characters (if a string type) or
elements (if another sequence type). If `max_length` is
``None``, there is no maximum."""),
required=False,
min=0, # needs to be a positive number
default=None)
class IInterfaceField(IField):
u"""Fields with a value that is an interface (implementing
zope.interface.Interface)."""
class IBool(IField):
u"""Boolean Field."""
default = Bool(
title=_(u"Default Value"),
description=_(u"""The field default value may be None or a legal
field value""")
)
class IBytes(IMinMaxLen, IIterable, IField):
u"""Field containing a byte string (like the python str).
The value might be constrained to be with length limits.
"""
class IASCII(IBytes):
u"""Field containing a 7-bit ASCII string. No characters > DEL
(chr(127)) are allowed
The value might be constrained to be with length limits.
"""
class IBytesLine(IBytes):
u"""Field containing a byte string without newlines."""
class IASCIILine(IASCII):
u"""Field containing a 7-bit ASCII string without newlines."""
class IText(IMinMaxLen, IIterable, IField):
u"""Field containing a unicode string."""
class ISourceText(IText):
u"""Field for source text of object."""
class ITextLine(IText):
u"""Field containing a unicode string without newlines."""
class IPassword(ITextLine):
u"Field containing a unicode string without newlines that is a password."
class IInt(IMinMax, IField):
u"""Field containing an Integer Value."""
min = Int(
title=_(u"Start of the range"),
required=False,
default=None
)
max = Int(
title=_(u"End of the range (excluding the value itself)"),
required=False,
default=None
)
default = Int(
title=_(u"Default Value"),
description=_(u"""The field default value may be None or a legal
field value""")
)
class IFloat(IMinMax, IField):
u"""Field containing a Float."""
class IDecimal(IMinMax, IField):
u"""Field containing a Decimal."""
class IDatetime(IMinMax, IField):
u"""Field containing a DateTime."""
class IDate(IMinMax, IField):
u"""Field containing a date."""
class ITimedelta(IMinMax, IField):
u"""Field containing a timedelta."""
class ITime(IMinMax, IField):
u"""Field containing a time."""
def _is_field(value):
if not IField.providedBy(value):
return False
return True
def _fields(values):
for value in values:
if not _is_field(value):
return False
return True
class IURI(IBytesLine):
"""A field containing an absolute URI
"""
class IId(IBytesLine):
"""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(IBytesLine):
"""Dotted name field.
Values of DottedName fields must be Python-style dotted names.
"""
min_dots = Int(
title=_(u"Minimum number of dots"),
required=True,
min=0,
default=0
)
max_dots = Int(
title=_(u"Maximum number of dots (should not be less than min_dots)"),
required=False,
default=None
)
class IChoice(IField):
u"""Field whose value is contained in a predefined set
Only one, values or vocabulary, may be specified for a given choice.
"""
vocabulary = Field(
title=_(u"Vocabulary or source providing values"),
description=_(u"The ISource, IContextSourceBinder or IBaseVocabulary "
u"object that provides values for this field."),
required=False,
default=None
)
vocabularyName = TextLine(
title=_(u"Vocabulary name"),
description=_(u"Vocabulary name to lookup in the vocabulary registry"),
required=False,
default=None
)
# Collections:
# Abstract
class ICollection(IMinMaxLen, IIterable, IContainer):
u"""Abstract interface containing a collection value.
The Value must be iterable and may have a min_length/max_length.
"""
value_type = Field(
title = _("Value Type"),
description = _(u"Field value items must conform to the given type, "
u"expressed via a Field."))
unique = Bool(
title = _('Unique Members'),
description = _('Specifies whether the members of the collection '
'must be unique.'),
default=False)
class ISequence(ICollection):
u"""Abstract interface specifying that the value is ordered"""
class IUnorderedCollection(ICollection):
u"""Abstract interface specifying that the value cannot be ordered"""
class IAbstractSet(IUnorderedCollection):
u"""An unordered collection of unique values."""
unique = Attribute(u"This ICollection interface attribute must be True")
class IAbstractBag(IUnorderedCollection):
u"""An unordered collection of values, with no limitations on whether
members are unique"""
unique = Attribute(u"This ICollection interface attribute must be False")
# Concrete
class ITuple(ISequence):
u"""Field containing a value that implements the API of a conventional
Python tuple."""
class IList(ISequence):
u"""Field containing a value that implements the API of a conventional
Python list."""
class ISet(IAbstractSet):
u"""Field containing a value that implements the API of a Python2.4+ set.
"""
class IFrozenSet(IAbstractSet):
u"""Field containing a value that implements the API of a conventional
Python 2.4+ frozenset."""
# (end Collections)
class IObject(IField):
u"""Field containing an Object value."""
schema = Attribute("schema",
_(u"The Interface that defines the Fields comprising the Object."))
class IBeforeObjectAssignedEvent(Interface):
"""An object is going to be assigned to an attribute on another object.
Subscribers to this event can change the object on this event to change
what object is going to be assigned. This is useful, e.g. for wrapping
or replacing objects before they get assigned to conform to application
policy.
"""
object = Attribute("The object that is going to be assigned.")
name = Attribute("The name of the attribute under which the object "
"will be assigned.")
context = Attribute("The context object where the object will be "
"assigned to.")
class IDict(IMinMaxLen, IIterable, IContainer):
u"""Field containing a conventional dict.
The key_type and value_type fields allow specification
of restrictions for keys and values contained in the dict.
"""
key_type = Attribute("key_type",
_(u"""Field keys must conform to the given type, expressed
via a Field.
"""))
value_type = Attribute("value_type",
_(u"""Field values must conform to the given type, expressed
via a Field.
"""))
class ITerm(Interface):
"""Object representing a single value in a vocabulary."""
value = Attribute(
"value", "The value used to represent vocabulary term in a field.")
class ITokenizedTerm(ITerm):
"""Object representing a single value in a tokenized vocabulary.
"""
# TODO: There should be a more specialized field type for this.
token = Attribute(
"token",
"""Token which can be used to represent the value on a stream.
The value of this attribute must be a non-empty 7-bit string.
Control characters are not allowed.
""")
class ITitledTokenizedTerm(ITokenizedTerm):
"""A tokenized term that includes a title."""
title = TextLine(title=_(u"Title"))
class ISource(Interface):
"""A set of values from which to choose
Sources represent sets of values. They are used to specify the
source for choice fields.
Sources can be large (even infinite), in which case, they need to
be queried to find out what their values are.
"""
def __contains__(value):
"""Return whether the value is available in this source
"""
class ISourceQueriables(Interface):
"""A collection of objects for querying sources
"""
def getQueriables():
"""Return an iterable of objects that can be queried
The returned obects should be two-tuples with:
- A unicode id
The id must uniquely identify the queriable object within
the set of queriable objects. Furthermore, in subsequent
calls, the same id should be used for a given queriable
object.
- A queriable object
This is an object for which there is a view provided for
searching for items.
"""
class IContextSourceBinder(Interface):
def __call__(context):
"""Return a context-bound instance that implements ISource.
"""
class IBaseVocabulary(ISource):
"""Representation of a vocabulary.
At this most basic level, a vocabulary only need to support a test
for containment. This can be implemented either by __contains__()
or by sequence __getitem__() (the later only being useful for
vocabularies which are intrinsically ordered).
"""
def getTerm(value):
"""Return the ITerm object for the term 'value'.
If 'value' is not a valid term, this method raises LookupError.
"""
class IIterableSource(ISource):
"""Source which supports iteration over allowed values.
The objects iteration provides must be values from the source.
"""
def __iter__():
"""Return an iterator which provides the values from the source."""
def __len__():
"""Return the number of valid values, or sys.maxint."""
# BBB vocabularies are pending deprecation, hopefully in 3.3
class IIterableVocabulary(Interface):
"""Vocabulary which supports iteration over allowed values.
The objects iteration provides must conform to the ITerm
interface.
"""
def __iter__():
"""Return an iterator which provides the terms from the vocabulary."""
def __len__():
"""Return the number of valid terms, or sys.maxint."""
class IVocabulary(IIterableVocabulary, IBaseVocabulary):
"""Vocabulary which is iterable."""
class IVocabularyTokenized(IVocabulary):
"""Vocabulary that provides support for tokenized representation.
Terms returned from getTerm() and provided by iteration must
conform to ITokenizedTerm.
"""
def getTermByToken(token):
"""Return an ITokenizedTerm for the passed-in token.
If `token` is not represented in the vocabulary, `LookupError`
is raised.
"""
class IVocabularyRegistry(Interface):
"""Registry that provides IBaseVocabulary objects for specific fields.
"""
def get(object, name):
"""Return the vocabulary named 'name' for the content object
'object'.
When the vocabulary cannot be found, LookupError is raised.
"""
class IVocabularyFactory(Interface):
"""Can create vocabularies."""
def __call__(self, context):
"""The context provides a location that the vocabulary can make use
of."""
zope.schema-3.7.1/src/zope/schema/README.txt 000644 000765 000765 00000022557 11505354675 021254 0 ustar 00gotcha gotcha 000000 000000 ==============
Zope 3 Schemas
==============
Introduction
------------
*This package is intended to be independently reusable in any Python
project. It is maintained by the* `Zope Toolkit project `_.
Schemas extend the notion of interfaces to detailed descriptions of Attributes
(but not methods). Every schema is an interface and specifies the public
fields of an object. A *field* roughly corresponds to an attribute of a
python object. But a Field provides space for at least a title and a
description. It can also constrain its value and provide a validation method.
Besides you can optionally specify characteristics such as its value being
read-only or not required.
Zope 3 schemas were born when Jim Fulton and Martijn Faassen thought
about Formulator for Zope 3 and ``PropertySets`` while at the `Zope 3
sprint`_ at the Zope BBQ in Berlin. They realized that if you strip
all view logic from forms then you have something similar to interfaces. And
thus schemas were born.
.. _Zope 3 sprint: http://dev.zope.org/Zope3/ZopeBBQ2002Sprint
.. 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
>>> 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:
>>> class Bookmark(object):
... zope.interface.implements(IBookmark)
...
... 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 = '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', , 'url')
>>> url_bound.validate('foo.bar')
Traceback (most recent call last):
...
InvalidURI: foo.bar
Now that the data has been successfully validated, we can set it on the
object:
>>> 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@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.
Fields and Widgets
------------------
Widgets are components that display field values and, in the case of
writable fields, allow the user to edit those values.
Widgets:
- Display current field values, either in a read-only format, or in a
format that lets the user change the field value.
- Update their corresponding field values based on values provided by users.
- Manage the relationships between their representation of a field value
and the object's field value. For example, a widget responsible for
editing a number will likely represent that number internally as a string.
For this reason, widgets must be able to convert between the two value
formats. In the case of the number-editing widget, string values typed
by the user need to be converted to numbers such as int or float.
- Support the ability to assign a missing value to a field. For example,
a widget may present a ``None`` option for selection that, when selected,
indicates that the object should be updated with the field's ``missing``
value.
References
----------
- Use case list, http://dev.zope.org/Zope3/Zope3SchemasUseCases
- Documented interfaces, zope/schema/interfaces.py
- Jim Fulton's Programmers Tutorial; in CVS:
Docs/ZopeComponentArchitecture/PythonProgrammerTutorial/Chapter2
zope.schema-3.7.1/src/zope/schema/sources.txt 000644 000765 000765 00000005725 11505354675 022000 0 ustar 00gotcha gotcha 000000 000000 =======
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
>>> class MySource(object):
... interface.implements(ISource)
... 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.
>>> 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.
zope.schema-3.7.1/src/zope/schema/tests/ 000755 000765 000765 00000000000 11505354711 020674 5 ustar 00gotcha gotcha 000000 000000 zope.schema-3.7.1/src/zope/schema/validation.txt 000644 000765 000765 00000010262 11505354675 022437 0 ustar 00gotcha gotcha 000000 000000 =================
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
>>> 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, )]
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
zope.schema-3.7.1/src/zope/schema/vocabulary.py 000644 000765 000765 00000014774 11505354675 022301 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Vocabulary support for schema.
"""
from zope.interface.declarations import directlyProvides, implements
from zope.schema.interfaces import ValidationError
from zope.schema.interfaces import IVocabularyRegistry
from zope.schema.interfaces import IVocabulary, IVocabularyTokenized
from zope.schema.interfaces import ITokenizedTerm, ITitledTokenizedTerm
# simple vocabularies performing enumerated-like tasks
_marker = object()
class SimpleTerm(object):
"""Simple tokenized term used by SimpleVocabulary."""
implements(ITokenizedTerm)
def __init__(self, value, token=None, title=None):
"""Create a term for value and token. If token is omitted,
str(value) is used for the token. If title is provided,
term implements ITitledTokenizedTerm.
"""
self.value = value
if token is None:
token = value
self.token = str(token)
self.title = title
if title is not None:
directlyProvides(self, ITitledTokenizedTerm)
class SimpleVocabulary(object):
"""Vocabulary that works from a sequence of terms."""
implements(IVocabularyTokenized)
def __init__(self, terms, *interfaces):
"""Initialize the vocabulary given a list of terms.
The vocabulary keeps a reference to the list of terms passed
in; it should never be modified while the vocabulary is used.
One or more interfaces may also be provided so that alternate
widgets may be bound without subclassing.
"""
self.by_value = {}
self.by_token = {}
self._terms = terms
for term in self._terms:
if term.value in self.by_value:
raise ValueError(
'term values must be unique: %s' % repr(term.value))
if term.token in self.by_token:
raise ValueError(
'term tokens must be unique: %s' % repr(term.token))
self.by_value[term.value] = term
self.by_token[term.token] = term
if interfaces:
directlyProvides(self, *interfaces)
def fromItems(cls, items, *interfaces):
"""Construct a vocabulary from a list of (token, value) pairs.
The order of the items is preserved as the order of the terms
in the vocabulary. Terms are created by calling the class
method createTerm() with the pair (value, token).
One or more interfaces may also be provided so that alternate
widgets may be bound without subclassing.
"""
terms = [cls.createTerm(value, token) for (token, value) in items]
return cls(terms, *interfaces)
fromItems = classmethod(fromItems)
def fromValues(cls, values, *interfaces):
"""Construct a vocabulary from a simple list.
Values of the list become both the tokens and values of the
terms in the vocabulary. The order of the values is preserved
as the order of the terms in the vocabulary. Tokens are
created by calling the class method createTerm() with the
value as the only parameter.
One or more interfaces may also be provided so that alternate
widgets may be bound without subclassing.
"""
terms = [cls.createTerm(value) for value in values]
return cls(terms, *interfaces)
fromValues = classmethod(fromValues)
def createTerm(cls, *args):
"""Create a single term from data.
Subclasses may override this with a class method that creates
a term of the appropriate type from the arguments.
"""
return SimpleTerm(*args)
createTerm = classmethod(createTerm)
def __contains__(self, value):
"""See zope.schema.interfaces.IBaseVocabulary"""
try:
return value in self.by_value
except TypeError:
# sometimes values are not hashable
return False
def getTerm(self, value):
"""See zope.schema.interfaces.IBaseVocabulary"""
try:
return self.by_value[value]
except KeyError:
raise LookupError(value)
def getTermByToken(self, token):
"""See zope.schema.interfaces.IVocabularyTokenized"""
try:
return self.by_token[token]
except KeyError:
raise LookupError(token)
def __iter__(self):
"""See zope.schema.interfaces.IIterableVocabulary"""
return iter(self._terms)
def __len__(self):
"""See zope.schema.interfaces.IIterableVocabulary"""
return len(self.by_value)
# registry code
class VocabularyRegistryError(LookupError):
def __init__(self, name):
self.name = name
Exception.__init__(self, str(self))
def __str__(self):
return "unknown vocabulary: %r" % self.name
class VocabularyRegistry(object):
__slots__ = '_map',
implements(IVocabularyRegistry)
def __init__(self):
self._map = {}
def get(self, object, name):
"""See zope.schema.interfaces.IVocabularyRegistry"""
try:
vtype = self._map[name]
except KeyError:
raise VocabularyRegistryError(name)
return vtype(object)
def register(self, name, factory):
self._map[name] = factory
_vocabularies = None
def getVocabularyRegistry():
"""Return the vocabulary registry.
If the registry has not been created yet, an instance of
VocabularyRegistry will be installed and used.
"""
if _vocabularies is None:
setVocabularyRegistry(VocabularyRegistry())
return _vocabularies
def setVocabularyRegistry(registry):
"""Set the vocabulary registry."""
global _vocabularies
_vocabularies = registry
def _clear():
"""Remove the registries (for use by tests)."""
global _vocabularies
_vocabularies = None
try:
from zope.testing.cleanup import addCleanUp
except ImportError:
# don't have that part of Zope
pass
else:
addCleanUp(_clear)
del addCleanUp
zope.schema-3.7.1/src/zope/schema/tests/__init__.py 000644 000765 000765 00000000075 11505354675 023020 0 ustar 00gotcha gotcha 000000 000000 #
# This file is necessary to make this directory a package.
zope.schema-3.7.1/src/zope/schema/tests/states.py 000644 000765 000765 00000006522 11505354675 022567 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Sample vocabulary supporting state abbreviations.
"""
from zope.interface import implements
from zope.schema import interfaces
from zope.schema import Choice
# This table is based on information from the United States Postal Service:
# http://www.usps.com/ncsc/lookups/abbreviations.html#states
_states = {
'AL': u'Alabama',
'AK': u'Alaska',
'AS': u'American Samoa',
'AZ': u'Arizona',
'AR': u'Arkansas',
'CA': u'California',
'CO': u'Colorado',
'CT': u'Connecticut',
'DE': u'Delaware',
'DC': u'District of Columbia',
'FM': u'Federated States of Micronesia',
'FL': u'Florida',
'GA': u'Georgia',
'GU': u'Guam',
'HI': u'Hawaii',
'ID': u'Idaho',
'IL': u'Illinois',
'IN': u'Indiana',
'IA': u'Iowa',
'KS': u'Kansas',
'KY': u'Kentucky',
'LA': u'Louisiana',
'ME': u'Maine',
'MH': u'Marshall Islands',
'MD': u'Maryland',
'MA': u'Massachusetts',
'MI': u'Michigan',
'MN': u'Minnesota',
'MS': u'Mississippi',
'MO': u'Missouri',
'MT': u'Montana',
'NE': u'Nebraska',
'NV': u'Nevada',
'NH': u'New Hampshire',
'NJ': u'New Jersey',
'NM': u'New Mexico',
'NY': u'New York',
'NC': u'North Carolina',
'ND': u'North Dakota',
'MP': u'Northern Mariana Islands',
'OH': u'Ohio',
'OK': u'Oklahoma',
'OR': u'Oregon',
'PW': u'Palau',
'PA': u'Pennsylvania',
'PR': u'Puerto Rico',
'RI': u'Rhode Island',
'SC': u'South Carolina',
'SD': u'South Dakota',
'TN': u'Tennessee',
'TX': u'Texas',
'UT': u'Utah',
'VT': u'Vermont',
'VI': u'Virgin Islands',
'VA': u'Virginia',
'WA': u'Washington',
'WV': u'West Virginia',
'WI': u'Wisconsin',
'WY': u'Wyoming',
}
class State(object):
__slots__ = 'value', 'title'
implements(interfaces.ITerm)
def __init__(self, value, title):
self.value = value
self.title = title
for v,p in _states.iteritems():
_states[v] = State(v, p)
class IStateVocabulary(interfaces.IVocabulary):
"""Vocabularies that support the states database conform to this."""
class StateVocabulary(object):
__slots__ = ()
implements(IStateVocabulary)
def __init__(self, object=None):
pass
def __contains__(self, value):
return value in _states
def __iter__(self):
return _states.itervalues()
def __len__(self):
return len(_states)
def getTerm(self, value):
return _states[value]
class StateSelectionField(Choice):
vocabulary = StateVocabulary()
def __init__(self, **kw):
super(StateSelectionField, self).__init__(
vocabulary=StateSelectionField.vocabulary,
**kw)
self.vocabularyName = "states"
zope.schema-3.7.1/src/zope/schema/tests/test_accessors.py 000644 000765 000765 00000007735 11505354675 024317 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Test Interface accessor methods.
"""
import unittest
from zope.interface import Interface, implements
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):
field = Text(title=u"Foo thing")
class I(Interface):
getFoo, setFoo = accessors(field)
class Bad(object):
implements(I)
class Good(object):
implements(I)
def __init__(self):
self.set = 0
def getFoo(self):
return u"foo"
def setFoo(self, v):
self.set += 1
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'])
# test some field attrs
for attr in ('title', 'description', 'readonly'):
self.assertEqual(getattr(I['getFoo'], attr), getattr(field, attr))
self.assert_(IText.providedBy(I['getFoo']))
self.assert_(IMethod.providedBy(I['getFoo']))
self.assert_(IMethod.providedBy(I['setFoo']))
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)
self.assertRaises(Exception, verifyClass, I, Bad)
self.assertRaises(Exception, verifyObject, I, Bad())
self.assertEquals(I['getFoo'].query(Bad(), 42), 42)
self.assertRaises(AttributeError, I['getFoo'].get, Bad())
verifyClass(I, Good)
verifyObject(I, Good())
self.assertEquals(I['getFoo'].query(Good(), 42), u'foo')
self.assertEquals(I['getFoo'].get(Good()), u'foo')
instance = Good()
I['getFoo'].set(instance, u'whatever')
self.assertEquals(instance.set, 1)
def test_doc(self):
field = Text(title=u"Foo thing")
class I(Interface):
getFoo, setFoo = accessors(field)
def bar(): pass
x = Text()
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_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(Test))
return suite
if __name__ == '__main__':
unittest.main()
zope.schema-3.7.1/src/zope/schema/tests/test_boolfield.py 000644 000765 000765 00000004331 11505354675 024256 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# 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 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')
zope.schema-3.7.1/src/zope/schema/tests/test_choice.py 000644 000765 000765 00000010566 11505354675 023560 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# 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 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 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.assert_(field.vocabulary is v)
self.assert_(field.vocabularyName is None)
bound = field.bind(None)
self.assert_(bound.vocabulary is v)
self.assert_(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.assert_(field.vocabulary is None)
self.assertEqual(field.vocabularyName, "vocab")
o = object()
bound = field.bind(o)
self.assert_(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")
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(Vocabulary_ChoiceFieldTests))
suite.addTest(unittest.makeSuite(Value_ChoiceFieldTests))
return suite
if __name__ == "__main__":
unittest.main(defaultTest="test_suite")
zope.schema-3.7.1/src/zope/schema/tests/test_containerfield.py 000644 000765 000765 00000003530 11505354675 025305 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# 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 UserDict 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')
zope.schema-3.7.1/src/zope/schema/tests/test_date.py 000644 000765 000765 00000006520 11505354675 023236 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# 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 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')
zope.schema-3.7.1/src/zope/schema/tests/test_datetime.py 000644 000765 000765 00000006204 11505354675 024114 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# 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 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')
zope.schema-3.7.1/src/zope/schema/tests/test_decimalfield.py 000644 000765 000765 00000007246 11505354675 024731 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# 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 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')
zope.schema-3.7.1/src/zope/schema/tests/test_dictfield.py 000644 000765 000765 00000010524 11505354675 024247 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# 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 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')
zope.schema-3.7.1/src/zope/schema/tests/test_docs.py 000644 000765 000765 00000002522 11505354675 023247 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# 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
def test_suite():
checker = renormalizing.RENormalizing([
(re.compile(r"\[\(None, Invalid\('8<=10',\)\)\]"),
r"[(None, )]",)
])
return unittest.TestSuite((
doctest.DocFileSuite('../sources.txt', optionflags=doctest.ELLIPSIS),
doctest.DocFileSuite('../fields.txt'),
doctest.DocFileSuite('../README.txt'),
doctest.DocFileSuite(
'../validation.txt', checker=checker,
optionflags=doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS),
))
zope.schema-3.7.1/src/zope/schema/tests/test_dotted_name.py 000644 000765 000765 00000003577 11505354675 024615 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# 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 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 test_suite():
suite = makeSuite(DottedNameTest)
return suite
zope.schema-3.7.1/src/zope/schema/tests/test_equality.py 000644 000765 000765 00000002141 11505354675 024151 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Field equality tests
"""
from unittest import TestCase, TestSuite, makeSuite
from zope.schema import Text, Int
class FieldEqualityTests(TestCase):
equality = [
'Text(title=u"Foo", description=u"Bar")',
'Int(title=u"Foo", description=u"Bar")',
]
def test_equality(self):
for text in self.equality:
self.assertEquals(eval(text), eval(text))
def test_suite():
return TestSuite(
[makeSuite(FieldEqualityTests)])
zope.schema-3.7.1/src/zope/schema/tests/test_field.py 000644 000765 000765 00000011060 11505354675 023377 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# 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 zope.interface import Interface
from zope.schema import Field, Text, Int
from zope.schema.interfaces import ValidationError, RequiredMissing
from zope.schema.interfaces import ConstraintNotSatisfied
from zope.testing import renormalizing
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.assertEquals(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="")
def test__doc__(self):
field = Text(title=u"test fiield",
description=(
u"To make sure that\n"
u"doc strings are working correctly\n"
)
)
self.assertEqual(
field.__doc__,
u"test fiield\n\n"
u"To make sure that\n"
u"doc strings are working correctly\n"
)
def testOrdering(self):
from zope.interface import Interface
class S1(Interface):
a = Text()
b = Text()
self.failUnless(S1['a'].order < S1['b'].order)
class S2(Interface):
b = Text()
a = Text()
self.failUnless(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)
class FieldDefaultBehaviour(TestCase):
def test_required_defaults_to_true(self):
class MyField(Field):
pass
field = MyField(title=u'my')
self.assert_(field.required)
def test_suite():
checker = renormalizing.RENormalizing([
(re.compile(r" with base 10: '125.6'"),
r': 125.6')
])
return TestSuite((
makeSuite(FieldTest),
makeSuite(FieldDefaultBehaviour),
DocTestSuite("zope.schema._field"),
DocTestSuite("zope.schema._bootstrapfields",checker=checker),
))
zope.schema-3.7.1/src/zope/schema/tests/test_fieldproperty.py 000644 000765 000765 00000005747 11505354675 025223 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Field Properties tests
"""
from unittest import TestCase, TestSuite, main, makeSuite
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 I(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='xxxxxx')
date = Float(title=u'Date', readonly=True)
class C(object):
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()
self.assertEqual(c.title, u'say something')
self.assertEqual(c.weight, None)
self.assertEqual(c.code, 'xxxxxx')
self.assertRaises(ValidationError, setattr, c, 'title', 'foo')
self.assertRaises(ValidationError, setattr, c, 'weight', 'foo')
self.assertRaises(ValidationError, setattr, c, 'weight', -1.0)
self.assertRaises(ValidationError, setattr, c, 'weight', 2)
self.assertRaises(ValidationError, setattr, c, 'code', -1)
self.assertRaises(ValidationError, setattr, c, 'code', 'xxxx')
self.assertRaises(ValidationError, setattr, c, 'code', u'xxxxxx')
c.title = u'c is good'
c.weight = 10.0
c.code = 'abcdef'
self.assertEqual(c.title, u'c is good')
self.assertEqual(c.weight, 10)
self.assertEqual(c.code, 'abcdef')
def test_readonly(self):
c = self.klass()
# 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):
title = FieldPropertyStoredThroughField(I['title'])
weight = FieldPropertyStoredThroughField(I['weight'])
code = FieldPropertyStoredThroughField(I['code'])
date = FieldPropertyStoredThroughField(I['date'])
class TestStoredThroughField(Test):
klass = D
def test_suite():
return TestSuite((
makeSuite(Test),
makeSuite(TestStoredThroughField),
))
if __name__ == '__main__':
main(defaultTest='test_suite')
zope.schema-3.7.1/src/zope/schema/tests/test_floatfield.py 000644 000765 000765 00000006064 11505354675 024435 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# 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 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')
zope.schema-3.7.1/src/zope/schema/tests/test_interfacefield.py 000644 000765 000765 00000003166 11505354675 025270 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# 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 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')
zope.schema-3.7.1/src/zope/schema/tests/test_intfield.py 000644 000765 000765 00000005765 11505354675 024131 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# 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 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')
zope.schema-3.7.1/src/zope/schema/tests/test_iterablefield.py 000644 000765 000765 00000003732 11505354675 025116 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# 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 UserDict import UserDict, IterableUserDict
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')
zope.schema-3.7.1/src/zope/schema/tests/test_listfield.py 000644 000765 000765 00000010625 11505354675 024301 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# 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 zope.interface import implements
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())
class FakeField(object):
implements(IField)
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.failUnless(IList.providedBy(field))
self.failUnless(ISequence.providedBy(field))
self.failUnless(ICollection.providedBy(field))
def test_suite():
return makeSuite(ListTest)
if __name__ == '__main__':
main(defaultTest='test_suite')
zope.schema-3.7.1/src/zope/schema/tests/test_objectfield.py 000644 000765 000765 00000022442 11505354675 024574 0 ustar 00gotcha gotcha 000000 000000 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
import zope.event
from zope.interface import Attribute, Interface, implements
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=_(u"Foo"),
description=_(u"Foo description"),
default=u"",
required=True)
bar = TextLine(
title=_(u"Bar"),
description=_(u"Bar description"),
default=u"",
required=False)
attribute = Attribute("Test attribute, an attribute can't be validated.")
class TestClass(object):
implements(ITestSchema)
_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')
class FieldPropertyTestClass(object):
implements(ITestSchema)
foo = FieldProperty(ITestSchema['foo'])
bar = FieldProperty(ITestSchema['bar'])
attribute = FieldProperty(ITestSchema['attribute'])
class NotFullyImplementedTestClass(object):
implements(ITestSchema)
foo = FieldProperty(ITestSchema['foo'])
# bar = FieldProperty(ITestSchema['bar']): bar is not implemented
# attribute
class ISchemaWithObjectFieldAsInterface(Interface):
obj = Object(
schema=Interface,
title=_(u"Object"),
description=_(u"object description"),
required=False)
class ClassWithObjectFieldAsInterface(object):
implements(ISchemaWithObjectFieldAsInterface)
_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=_(u"Boss"),
description=_(u"Boss description"),
required=False,
)
members = List(
value_type=Object(schema=Interface),
title=_(u"Member List"),
description=_(u"Member list description"),
required=False,
)
class IPerson(Interface):
"""A schema that participate to a cycle"""
unit = Object(
schema=IUnit,
title=_(u"Unit"),
description=_(u"Unit description"),
required=False,
)
IUnit['boss'].schema = IPerson
IUnit['members'].value_type.schema = IPerson
class Unit(object):
implements(IUnit)
def __init__(self, person, person_list):
self.boss = person
self.members = person_list
class Person(object):
implements(IPerson)
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, e:
try:
return e[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.assertEquals(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.assert_(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.assertEquals(1, len(events))
event = events[0]
self.failUnless(IBeforeObjectAssignedEvent.providedBy(event))
self.assertEquals(data, event.object)
self.assertEquals('object_field', event.name)
self.assertEquals(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')
zope.schema-3.7.1/src/zope/schema/tests/test_schema.py 000644 000765 000765 00000007424 11505354675 023565 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Schema field tests
"""
from unittest import TestCase, main, makeSuite
from zope.interface import Interface
from zope.schema import Bytes
from zope.schema import getFields, getFieldsInOrder
from zope.schema import getFieldNames, getFieldNamesInOrder
class ISchemaTest(Interface):
title = Bytes(
title=u"Title",
description=u"Title",
default="",
required=True)
description = Bytes(
title=u"Description",
description=u"Description",
default="",
required=True)
spam = Bytes(
title=u"Spam",
description=u"Spam",
default="",
required=True)
class ISchemaTestSubclass(ISchemaTest):
foo = Bytes(
title=u'Foo',
description=u'Fooness',
default="",
required=False)
class SchemaTest(TestCase):
def test_getFieldNames(self):
names = getFieldNames(ISchemaTest)
self.assertEqual(len(names),3)
self.assert_('title' in names)
self.assert_('description' in names)
self.assert_('spam' in names)
def test_getFieldNamesAll(self):
names = getFieldNames(ISchemaTestSubclass)
self.assertEqual(len(names),4)
self.assert_('title' in names)
self.assert_('description' in names)
self.assert_('spam' in names)
self.assert_('foo' in names)
def test_getFields(self):
fields = getFields(ISchemaTest)
self.assert_(fields.has_key('title'))
self.assert_(fields.has_key('description'))
self.assert_(fields.has_key('spam'))
# test whether getName() has the right value
for key, value in fields.iteritems():
self.assertEquals(key, value.getName())
def test_getFieldsAll(self):
fields = getFields(ISchemaTestSubclass)
self.assert_(fields.has_key('title'))
self.assert_(fields.has_key('description'))
self.assert_(fields.has_key('spam'))
self.assert_(fields.has_key('foo'))
# test whether getName() has the right value
for key, value in fields.iteritems():
self.assertEquals(key, value.getName())
def test_getFieldsInOrder(self):
fields = getFieldsInOrder(ISchemaTest)
field_names = [name for name, field in fields]
self.assertEquals(field_names, ['title', 'description', 'spam'])
for key, value in fields:
self.assertEquals(key, value.getName())
def test_getFieldsInOrderAll(self):
fields = getFieldsInOrder(ISchemaTestSubclass)
field_names = [name for name, field in fields]
self.assertEquals(field_names, ['title', 'description', 'spam', 'foo'])
for key, value in fields:
self.assertEquals(key, value.getName())
def test_getFieldsNamesInOrder(self):
names = getFieldNamesInOrder(ISchemaTest)
self.assertEquals(names, ['title', 'description', 'spam'])
def test_getFieldsNamesInOrderAll(self):
names = getFieldNamesInOrder(ISchemaTestSubclass)
self.assertEquals(names, ['title', 'description', 'spam', 'foo'])
def test_suite():
return makeSuite(SchemaTest)
if __name__ == '__main__':
main(defaultTest='test_suite')
zope.schema-3.7.1/src/zope/schema/tests/test_setfield.py 000644 000765 000765 00000026061 11505354675 024122 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# 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 zope.interface import implements, 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())
class FakeField(object):
implements(IField)
Set(value_type=FakeField())
def testNoUniqueArgument(self):
self.assertRaises(TypeError, Set, unique=False)
self.assertRaises(TypeError, Set, unique=True)
self.failUnless(Set().unique)
def testImplements(self):
field = Set()
self.failUnless(ISet.providedBy(field))
self.failUnless(IUnorderedCollection.providedBy(field))
self.failUnless(IAbstractSet.providedBy(field))
self.failUnless(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())
class FakeField(object):
implements(IField)
FrozenSet(value_type=FakeField())
def testNoUniqueArgument(self):
self.assertRaises(TypeError, FrozenSet, unique=False)
self.assertRaises(TypeError, FrozenSet, unique=True)
self.failUnless(FrozenSet().unique)
def testImplements(self):
field = FrozenSet()
self.failUnless(IFrozenSet.providedBy(field))
self.failUnless(IAbstractSet.providedBy(field))
self.failUnless(IUnorderedCollection.providedBy(field))
self.failUnless(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')
zope.schema-3.7.1/src/zope/schema/tests/test_states.py 000644 000765 000765 00000006007 11505354675 023624 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Tests of the states example.
"""
import unittest
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 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)
def tearDown(self):
vocabulary._clear()
def test_default_presentation(self):
field = IBirthInfo.getDescriptionFor("state1")
bound = field.bind(object())
self.assert_(verifyObject(IVocabulary, bound.vocabulary))
self.assertEqual(bound.vocabulary.getTerm("VA").title, "Virginia")
def test_contains(self):
vocab = states.StateVocabulary()
self.assert_(verifyObject(IVocabulary, vocab))
count = 0
L = list(vocab)
for term in L:
count += 1
self.assert_(term.value in vocab)
self.assertEqual(count, len(vocab))
# make sure we get the same values the second time around:
L = [term.value for term in L]
L.sort()
L2 = [term.value for term in vocab]
L2.sort()
self.assertEqual(L, L2)
def test_prebound_vocabulary(self):
field = IBirthInfo.getDescriptionFor("state3")
bound = field.bind(None)
self.assert_(bound.vocabularyName is None)
self.assert_(verifyObject(IVocabulary, bound.vocabulary))
self.assert_("AL" in bound.vocabulary)
def test_suite():
return unittest.makeSuite(StateSelectionTest)
if __name__ == "__main__":
unittest.main(defaultTest="test_suite")
zope.schema-3.7.1/src/zope/schema/tests/test_strfield.py 000644 000765 000765 00000013341 11505354675 024134 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# 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 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
_convert = str
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 unicode(v, 'ascii')
def testBadStringType(self):
field = self._Field_Factory()
self.assertRaises(ValidationError, field.validate, '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.assertEquals(u'test', dummy.password)
# Using UNCHANGED_PASSWORD the field is not updated.
field.set(dummy, field.UNCHANGED_PASSWORD)
self.assertEquals(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')
zope.schema-3.7.1/src/zope/schema/tests/test_timedelta.py 000644 000765 000765 00000006460 11505354675 024274 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# 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 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')
zope.schema-3.7.1/src/zope/schema/tests/test_tuplefield.py 000644 000765 000765 00000011333 11505354675 024454 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# 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 zope.interface import implements
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())
class FakeField(object):
implements(IField)
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.failUnless(ITuple.providedBy(field))
self.failUnless(ISequence.providedBy(field))
self.failUnless(ICollection.providedBy(field))
def test_suite():
suite = TestSuite()
suite.addTest(makeSuite(TupleTest))
return suite
if __name__ == '__main__':
main(defaultTest='test_suite')
zope.schema-3.7.1/src/zope/schema/tests/test_vocabulary.py 000644 000765 000765 00000014601 11505354675 024467 0 ustar 00gotcha gotcha 000000 000000 ##############################################################################
#
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Test of the Vocabulary and related support APIs.
"""
import unittest
from zope.interface.verify import verifyObject
from zope.interface.exceptions import DoesNotImplement
from zope.interface import Interface, implements
from zope.schema import interfaces
from zope.schema import vocabulary
class DummyRegistry(vocabulary.VocabularyRegistry):
def get(self, object, name):
v = SampleVocabulary()
v.object = object
v.name = name
return v
class BaseTest(unittest.TestCase):
# Clear the vocabulary and presentation registries on each side of
# each test.
def setUp(self):
vocabulary._clear()
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.assert_(vocabulary.getVocabularyRegistry() is r)
def test_getVocabularyRegistry(self):
r = vocabulary.getVocabularyRegistry()
self.assert_(interfaces.IVocabularyRegistry.providedBy(r))
# TODO: still need to test the default implementation
class SampleTerm(object):
pass
class SampleVocabulary(object):
implements(interfaces.IVocabulary)
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 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 test_simple_term_title(self):
t = vocabulary.SimpleTerm(1)
verifyObject(interfaces.ITokenizedTerm, t)
self.failUnlessRaises(DoesNotImplement, verifyObject,
interfaces.ITitledTokenizedTerm, t)
self.failUnless(t.title is None)
t = vocabulary.SimpleTerm(1, title="Title")
verifyObject(interfaces.ITokenizedTerm, t)
verifyObject(interfaces.ITitledTokenizedTerm, t)
self.failUnlessEqual(t.title, "Title")
def test_order(self):
value = 1
for t in self.list_vocab:
self.assertEqual(t.value, value)
value += 1
value = 1
for t in self.items_vocab:
self.assertEqual(t.value, value)
value += 1
def test_implementation(self):
self.failUnless(verifyObject(interfaces.IVocabulary, self.list_vocab))
self.failUnless(
verifyObject(interfaces.IVocabularyTokenized, self.list_vocab))
self.failUnless(verifyObject(interfaces.IVocabulary, self.items_vocab))
self.failUnless(
verifyObject(interfaces.IVocabularyTokenized, self.items_vocab))
def test_addt_interfaces(self):
class IStupid(Interface):
pass
v = vocabulary.SimpleVocabulary.fromValues([1, 2, 3], IStupid)
self.failUnless(IStupid.providedBy(v))
def test_len(self):
self.assertEqual(len(self.list_vocab), 3)
self.assertEqual(len(self.items_vocab), 4)
def test_contains(self):
for v in (self.list_vocab, self.items_vocab):
self.assert_(1 in v and 2 in v and 3 in v)
self.assert_(5 not in v)
def test_iter_and_get_term(self):
for v in (self.list_vocab, self.items_vocab):
for term in v:
self.assert_(v.getTerm(term.value) is term)
self.assert_(v.getTermByToken(term.token) is term)
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')])
def test_nonunique_token_message(self):
try:
vocabulary.SimpleVocabulary.fromValues([2, '2'])
except ValueError, e:
self.assertEquals(str(e), "term tokens must be unique: '2'")
def test_nonunique_token_messages(self):
try:
vocabulary.SimpleVocabulary.fromItems([(0, 'one'), (1, 'one')])
except ValueError, e:
self.assertEquals(str(e), "term values must be unique: 'one'")
def test_overriding_createTerm(self):
class MyTerm(object):
def __init__(self, value):
self.value = value
self.token = repr(value)
self.nextvalue = value + 1
class MyVocabulary(vocabulary.SimpleVocabulary):
def createTerm(cls, value):
return MyTerm(value)
createTerm = classmethod(createTerm)
vocab = MyVocabulary.fromValues([1, 2, 3])
for term in vocab:
self.assertEqual(term.value + 1, term.nextvalue)
def test_suite():
suite = unittest.makeSuite(RegistryTests)
suite.addTest(unittest.makeSuite(SimpleVocabularyTests))
return suite
if __name__ == "__main__":
unittest.main(defaultTest="test_suite")