mirror of
https://github.com/nottinghamtec/PyRIGS.git
synced 2026-01-19 14:32:16 +00:00
Added printing requirements
This commit is contained in:
49
zope/schema/tests/__init__.py
Normal file
49
zope/schema/tests/__init__.py
Normal file
@@ -0,0 +1,49 @@
|
||||
#
|
||||
# This file is necessary to make this directory a package.
|
||||
|
||||
import re
|
||||
|
||||
from zope.schema._compat import PY3
|
||||
from zope.testing import renormalizing
|
||||
|
||||
if PY3:
|
||||
py3_checker = renormalizing.RENormalizing([
|
||||
(re.compile(r"u'([^']*)'"),
|
||||
r"'\1'"),
|
||||
(re.compile(r"^b'([^']*)'"),
|
||||
r"'\1'"),
|
||||
(re.compile(r"([^'])b'([^']*)'"),
|
||||
r"\1'\2'"),
|
||||
(re.compile(r"<class 'bytes'>"),
|
||||
r"<type 'str'>"),
|
||||
(re.compile(r"<class 'str'>"),
|
||||
r"<type 'unicode'>"),
|
||||
(re.compile(r"zope.schema._bootstrapinterfaces.InvalidValue"),
|
||||
r"InvalidValue"),
|
||||
(re.compile(r"zope.schema.interfaces.InvalidId: '([^']*)'"),
|
||||
r"InvalidId: \1"),
|
||||
(re.compile(r"zope.schema.interfaces.InvalidId:"),
|
||||
r"InvalidId:"),
|
||||
(re.compile(r"zope.schema.interfaces.InvalidURI: '([^']*)'"),
|
||||
r"InvalidURI: \1"),
|
||||
(re.compile(r"zope.schema.interfaces.InvalidURI:"),
|
||||
r"InvalidURI:"),
|
||||
(re.compile(r"zope.schema.interfaces.InvalidDottedName: '([^']*)'"),
|
||||
r"InvalidDottedName: \1"),
|
||||
(re.compile(r"zope.schema.interfaces.InvalidDottedName:"),
|
||||
r"InvalidDottedName:"),
|
||||
(re.compile(
|
||||
r"zope.schema._bootstrapinterfaces.ConstraintNotSatisfied: '([^']*)'"
|
||||
),
|
||||
r"ConstraintNotSatisfied: \1"),
|
||||
(re.compile(
|
||||
r"zope.schema._bootstrapinterfaces.ConstraintNotSatisfied:"),
|
||||
r"ConstraintNotSatisfied:"),
|
||||
(re.compile(r"zope.schema._bootstrapinterfaces.WrongType:"),
|
||||
r"WrongType:"),
|
||||
])
|
||||
else:
|
||||
py3_checker = renormalizing.RENormalizing([
|
||||
(re.compile(r"([^'])b'([^']*)'"),
|
||||
r"\1'\2'"),
|
||||
])
|
||||
130
zope/schema/tests/states.py
Normal file
130
zope/schema/tests/states.py
Normal file
@@ -0,0 +1,130 @@
|
||||
##############################################################################
|
||||
#
|
||||
# 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.schema._compat import u
|
||||
from zope.interface import implementer
|
||||
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'),
|
||||
}
|
||||
|
||||
|
||||
@implementer(interfaces.ITerm)
|
||||
class State(object):
|
||||
__slots__ = 'value', 'title'
|
||||
|
||||
def __init__(self, value, title):
|
||||
self.value = value
|
||||
self.title = title
|
||||
|
||||
for v, p in _states.items():
|
||||
_states[v] = State(v, p)
|
||||
|
||||
|
||||
class IStateVocabulary(interfaces.IVocabulary):
|
||||
"""Vocabularies that support the states database conform to this."""
|
||||
|
||||
|
||||
@implementer(IStateVocabulary)
|
||||
class StateVocabulary(object):
|
||||
__slots__ = ()
|
||||
|
||||
def __init__(self, object=None):
|
||||
pass
|
||||
|
||||
def __contains__(self, value):
|
||||
return value in _states
|
||||
|
||||
def __iter__(self):
|
||||
return iter(_states.values())
|
||||
|
||||
def __len__(self):
|
||||
return len(_states)
|
||||
|
||||
def getTerm(self, value):
|
||||
return _states[value]
|
||||
|
||||
|
||||
class StateSelectionField(Choice):
|
||||
|
||||
vocabulary = StateVocabulary()
|
||||
|
||||
def __init__(self, **kw):
|
||||
super(StateSelectionField, self).__init__(
|
||||
vocabulary=StateSelectionField.vocabulary,
|
||||
**kw)
|
||||
self.vocabularyName = "states"
|
||||
822
zope/schema/tests/test__bootstrapfields.py
Normal file
822
zope/schema/tests/test__bootstrapfields.py
Normal file
@@ -0,0 +1,822 @@
|
||||
##############################################################################
|
||||
#
|
||||
# Copyright (c) 2012 Zope Foundation and Contributors.
|
||||
# All Rights Reserved.
|
||||
#
|
||||
# This software is subject to the provisions of the Zope Public License,
|
||||
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
|
||||
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
|
||||
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
|
||||
# FOR A PARTICULAR PURPOSE.
|
||||
#
|
||||
##############################################################################
|
||||
import unittest
|
||||
|
||||
|
||||
class ValidatedPropertyTests(unittest.TestCase):
|
||||
|
||||
def _getTargetClass(self):
|
||||
from zope.schema._bootstrapfields import ValidatedProperty
|
||||
return ValidatedProperty
|
||||
|
||||
def _makeOne(self, *args, **kw):
|
||||
return self._getTargetClass()(*args, **kw)
|
||||
|
||||
def test___set___not_missing_w_check(self):
|
||||
_checked = []
|
||||
|
||||
def _check(inst, value):
|
||||
_checked.append((inst, value))
|
||||
|
||||
class Test(DummyInst):
|
||||
_prop = None
|
||||
prop = self._makeOne('_prop', _check)
|
||||
inst = Test()
|
||||
inst.prop = 'PROP'
|
||||
self.assertEqual(inst._prop, 'PROP')
|
||||
self.assertEqual(_checked, [(inst, 'PROP')])
|
||||
|
||||
def test___set___not_missing_wo_check(self):
|
||||
class Test(DummyInst):
|
||||
_prop = None
|
||||
prop = self._makeOne('_prop')
|
||||
inst = Test(ValueError)
|
||||
|
||||
def _provoke(inst):
|
||||
inst.prop = 'PROP'
|
||||
self.assertRaises(ValueError, _provoke, inst)
|
||||
self.assertEqual(inst._prop, None)
|
||||
|
||||
def test___set___w_missing_wo_check(self):
|
||||
class Test(DummyInst):
|
||||
_prop = None
|
||||
prop = self._makeOne('_prop')
|
||||
inst = Test(ValueError)
|
||||
inst.prop = DummyInst.missing_value
|
||||
self.assertEqual(inst._prop, DummyInst.missing_value)
|
||||
|
||||
def test___get__(self):
|
||||
class Test(DummyInst):
|
||||
_prop = None
|
||||
prop = self._makeOne('_prop')
|
||||
inst = Test()
|
||||
inst._prop = 'PROP'
|
||||
self.assertEqual(inst.prop, 'PROP')
|
||||
|
||||
|
||||
class DefaultPropertyTests(unittest.TestCase):
|
||||
|
||||
def _getTargetClass(self):
|
||||
from zope.schema._bootstrapfields import DefaultProperty
|
||||
return DefaultProperty
|
||||
|
||||
def _makeOne(self, *args, **kw):
|
||||
return self._getTargetClass()(*args, **kw)
|
||||
|
||||
def test___get___wo_defaultFactory_miss(self):
|
||||
class Test(DummyInst):
|
||||
_prop = None
|
||||
prop = self._makeOne('_prop')
|
||||
inst = Test()
|
||||
inst.defaultFactory = None
|
||||
|
||||
def _provoke(inst):
|
||||
return inst.prop
|
||||
self.assertRaises(KeyError, _provoke, inst)
|
||||
|
||||
def test___get___wo_defaultFactory_hit(self):
|
||||
class Test(DummyInst):
|
||||
_prop = None
|
||||
prop = self._makeOne('_prop')
|
||||
inst = Test()
|
||||
inst.defaultFactory = None
|
||||
inst._prop = 'PROP'
|
||||
self.assertEqual(inst.prop, 'PROP')
|
||||
|
||||
def test__get___wo_defaultFactory_in_dict(self):
|
||||
class Test(DummyInst):
|
||||
_prop = None
|
||||
prop = self._makeOne('_prop')
|
||||
inst = Test()
|
||||
inst._prop = 'PROP'
|
||||
self.assertEqual(inst.prop, 'PROP')
|
||||
|
||||
def test___get___w_defaultFactory_not_ICAF_no_check(self):
|
||||
class Test(DummyInst):
|
||||
_prop = None
|
||||
prop = self._makeOne('_prop')
|
||||
inst = Test(ValueError)
|
||||
|
||||
def _factory():
|
||||
return 'PROP'
|
||||
inst.defaultFactory = _factory
|
||||
|
||||
def _provoke(inst):
|
||||
return inst.prop
|
||||
self.assertRaises(ValueError, _provoke, inst)
|
||||
|
||||
def test___get___w_defaultFactory_w_ICAF_w_check(self):
|
||||
from zope.interface import directlyProvides
|
||||
from zope.schema._bootstrapinterfaces \
|
||||
import IContextAwareDefaultFactory
|
||||
_checked = []
|
||||
|
||||
def _check(inst, value):
|
||||
_checked.append((inst, value))
|
||||
|
||||
class Test(DummyInst):
|
||||
_prop = None
|
||||
prop = self._makeOne('_prop', _check)
|
||||
inst = Test(ValueError)
|
||||
inst.context = object()
|
||||
_called_with = []
|
||||
|
||||
def _factory(context):
|
||||
_called_with.append(context)
|
||||
return 'PROP'
|
||||
directlyProvides(_factory, IContextAwareDefaultFactory)
|
||||
inst.defaultFactory = _factory
|
||||
self.assertEqual(inst.prop, 'PROP')
|
||||
self.assertEqual(_checked, [(inst, 'PROP')])
|
||||
self.assertEqual(_called_with, [inst.context])
|
||||
|
||||
|
||||
class FieldTests(unittest.TestCase):
|
||||
|
||||
def _getTargetClass(self):
|
||||
from zope.schema._bootstrapfields import Field
|
||||
return Field
|
||||
|
||||
def _makeOne(self, *args, **kw):
|
||||
return self._getTargetClass()(*args, **kw)
|
||||
|
||||
def test_ctor_defaults(self):
|
||||
from zope.schema._compat import u
|
||||
field = self._makeOne()
|
||||
self.assertEqual(field.__name__, u(''))
|
||||
self.assertEqual(field.__doc__, u(''))
|
||||
self.assertEqual(field.title, u(''))
|
||||
self.assertEqual(field.description, u(''))
|
||||
self.assertEqual(field.required, True)
|
||||
self.assertEqual(field.readonly, False)
|
||||
self.assertEqual(field.constraint(object()), True)
|
||||
self.assertEqual(field.default, None)
|
||||
self.assertEqual(field.defaultFactory, None)
|
||||
self.assertEqual(field.missing_value, None)
|
||||
self.assertEqual(field.context, None)
|
||||
|
||||
def test_ctor_w_title_wo_description(self):
|
||||
from zope.schema._compat import u
|
||||
field = self._makeOne(u('TITLE'))
|
||||
self.assertEqual(field.__name__, u(''))
|
||||
self.assertEqual(field.__doc__, u('TITLE'))
|
||||
self.assertEqual(field.title, u('TITLE'))
|
||||
self.assertEqual(field.description, u(''))
|
||||
|
||||
def test_ctor_wo_title_w_description(self):
|
||||
from zope.schema._compat import u
|
||||
field = self._makeOne(description=u('DESC'))
|
||||
self.assertEqual(field.__name__, u(''))
|
||||
self.assertEqual(field.__doc__, u('DESC'))
|
||||
self.assertEqual(field.title, u(''))
|
||||
self.assertEqual(field.description, u('DESC'))
|
||||
|
||||
def test_ctor_w_both_title_and_description(self):
|
||||
from zope.schema._compat import u
|
||||
field = self._makeOne(u('TITLE'), u('DESC'), u('NAME'))
|
||||
self.assertEqual(field.__name__, u('NAME'))
|
||||
self.assertEqual(field.__doc__, u('TITLE\n\nDESC'))
|
||||
self.assertEqual(field.title, u('TITLE'))
|
||||
self.assertEqual(field.description, u('DESC'))
|
||||
|
||||
def test_ctor_order_madness(self):
|
||||
klass = self._getTargetClass()
|
||||
order_before = klass.order
|
||||
field = self._makeOne()
|
||||
order_after = klass.order
|
||||
self.assertEqual(order_after, order_before + 1)
|
||||
self.assertEqual(field.order, order_after)
|
||||
|
||||
def test_explicit_required_readonly_missingValue(self):
|
||||
obj = object()
|
||||
field = self._makeOne(required=False, readonly=True, missing_value=obj)
|
||||
self.assertEqual(field.required, False)
|
||||
self.assertEqual(field.readonly, True)
|
||||
self.assertEqual(field.missing_value, obj)
|
||||
|
||||
def test_explicit_constraint_default(self):
|
||||
_called_with = []
|
||||
obj = object()
|
||||
|
||||
def _constraint(value):
|
||||
_called_with.append(value)
|
||||
return value is obj
|
||||
field = self._makeOne(
|
||||
required=False, readonly=True, constraint=_constraint, default=obj
|
||||
)
|
||||
self.assertEqual(field.required, False)
|
||||
self.assertEqual(field.readonly, True)
|
||||
self.assertEqual(_called_with, [obj])
|
||||
self.assertEqual(field.constraint(self), False)
|
||||
self.assertEqual(_called_with, [obj, self])
|
||||
self.assertEqual(field.default, obj)
|
||||
|
||||
def test_explicit_defaultFactory(self):
|
||||
_called_with = []
|
||||
obj = object()
|
||||
|
||||
def _constraint(value):
|
||||
_called_with.append(value)
|
||||
return value is obj
|
||||
|
||||
def _factory():
|
||||
return obj
|
||||
field = self._makeOne(
|
||||
required=False,
|
||||
readonly=True,
|
||||
constraint=_constraint,
|
||||
defaultFactory=_factory,
|
||||
)
|
||||
self.assertEqual(field.required, False)
|
||||
self.assertEqual(field.readonly, True)
|
||||
self.assertEqual(field.constraint(self), False)
|
||||
self.assertEqual(_called_with, [self])
|
||||
self.assertEqual(field.default, obj)
|
||||
self.assertEqual(_called_with, [self, obj])
|
||||
self.assertEqual(field.defaultFactory, _factory)
|
||||
|
||||
def test_explicit_defaultFactory_returning_missing_value(self):
|
||||
def _factory():
|
||||
return None
|
||||
field = self._makeOne(required=True,
|
||||
defaultFactory=_factory)
|
||||
self.assertEqual(field.default, None)
|
||||
|
||||
def test_bind(self):
|
||||
obj = object()
|
||||
field = self._makeOne()
|
||||
bound = field.bind(obj)
|
||||
self.assertEqual(bound.context, obj)
|
||||
expected = dict(field.__dict__)
|
||||
found = dict(bound.__dict__)
|
||||
found.pop('context')
|
||||
self.assertEqual(found, expected)
|
||||
self.assertEqual(bound.__class__, field.__class__)
|
||||
|
||||
def test_validate_missing_not_required(self):
|
||||
missing = object()
|
||||
|
||||
def _fail(value):
|
||||
return False
|
||||
field = self._makeOne(
|
||||
required=False, missing_value=missing, constraint=_fail,
|
||||
)
|
||||
self.assertEqual(field.validate(missing), None) # doesn't raise
|
||||
|
||||
def test_validate_missing_and_required(self):
|
||||
from zope.schema._bootstrapinterfaces import RequiredMissing
|
||||
missing = object()
|
||||
|
||||
def _fail(value):
|
||||
return False
|
||||
field = self._makeOne(
|
||||
required=True, missing_value=missing, constraint=_fail,
|
||||
)
|
||||
self.assertRaises(RequiredMissing, field.validate, missing)
|
||||
|
||||
def test_validate_wrong_type(self):
|
||||
from zope.schema._bootstrapinterfaces import WrongType
|
||||
|
||||
def _fail(value):
|
||||
return False
|
||||
field = self._makeOne(required=True, constraint=_fail)
|
||||
field._type = str
|
||||
self.assertRaises(WrongType, field.validate, 1)
|
||||
|
||||
def test_validate_constraint_fails(self):
|
||||
from zope.schema._bootstrapinterfaces import ConstraintNotSatisfied
|
||||
|
||||
def _fail(value):
|
||||
return False
|
||||
field = self._makeOne(required=True, constraint=_fail)
|
||||
field._type = int
|
||||
self.assertRaises(ConstraintNotSatisfied, field.validate, 1)
|
||||
|
||||
def test_validate_constraint_raises_StopValidation(self):
|
||||
from zope.schema._bootstrapinterfaces import StopValidation
|
||||
|
||||
def _fail(value):
|
||||
raise StopValidation
|
||||
field = self._makeOne(required=True, constraint=_fail)
|
||||
field._type = int
|
||||
field.validate(1) # doesn't raise
|
||||
|
||||
def test___eq___different_type(self):
|
||||
left = self._makeOne()
|
||||
|
||||
class Derived(self._getTargetClass()):
|
||||
pass
|
||||
right = Derived()
|
||||
self.assertEqual(left == right, False)
|
||||
self.assertEqual(left != right, True)
|
||||
|
||||
def test___eq___same_type_different_attrs(self):
|
||||
left = self._makeOne(required=True)
|
||||
right = self._makeOne(required=False)
|
||||
self.assertEqual(left == right, False)
|
||||
self.assertEqual(left != right, True)
|
||||
|
||||
def test___eq___same_type_same_attrs(self):
|
||||
left = self._makeOne()
|
||||
right = self._makeOne()
|
||||
self.assertEqual(left == right, True)
|
||||
self.assertEqual(left != right, False)
|
||||
|
||||
def test_get_miss(self):
|
||||
field = self._makeOne(__name__='nonesuch')
|
||||
inst = DummyInst()
|
||||
self.assertRaises(AttributeError, field.get, inst)
|
||||
|
||||
def test_get_hit(self):
|
||||
field = self._makeOne(__name__='extant')
|
||||
inst = DummyInst()
|
||||
inst.extant = 'EXTANT'
|
||||
self.assertEqual(field.get(inst), 'EXTANT')
|
||||
|
||||
def test_query_miss_no_default(self):
|
||||
field = self._makeOne(__name__='nonesuch')
|
||||
inst = DummyInst()
|
||||
self.assertEqual(field.query(inst), None)
|
||||
|
||||
def test_query_miss_w_default(self):
|
||||
field = self._makeOne(__name__='nonesuch')
|
||||
inst = DummyInst()
|
||||
self.assertEqual(field.query(inst, 'DEFAULT'), 'DEFAULT')
|
||||
|
||||
def test_query_hit(self):
|
||||
field = self._makeOne(__name__='extant')
|
||||
inst = DummyInst()
|
||||
inst.extant = 'EXTANT'
|
||||
self.assertEqual(field.query(inst), 'EXTANT')
|
||||
|
||||
def test_set_readonly(self):
|
||||
field = self._makeOne(__name__='lirame', readonly=True)
|
||||
inst = DummyInst()
|
||||
self.assertRaises(TypeError, field.set, inst, 'VALUE')
|
||||
|
||||
def test_set_hit(self):
|
||||
field = self._makeOne(__name__='extant')
|
||||
inst = DummyInst()
|
||||
inst.extant = 'BEFORE'
|
||||
field.set(inst, 'AFTER')
|
||||
self.assertEqual(inst.extant, 'AFTER')
|
||||
|
||||
|
||||
class ContainerTests(unittest.TestCase):
|
||||
|
||||
def _getTargetClass(self):
|
||||
from zope.schema._bootstrapfields import Container
|
||||
return Container
|
||||
|
||||
def _makeOne(self, *args, **kw):
|
||||
return self._getTargetClass()(*args, **kw)
|
||||
|
||||
def test_validate_not_required(self):
|
||||
field = self._makeOne(required=False)
|
||||
field.validate(None)
|
||||
|
||||
def test_validate_required(self):
|
||||
from zope.schema.interfaces import RequiredMissing
|
||||
field = self._makeOne()
|
||||
self.assertRaises(RequiredMissing, field.validate, None)
|
||||
|
||||
def test__validate_not_collection_not_iterable(self):
|
||||
from zope.schema._bootstrapinterfaces import NotAContainer
|
||||
cont = self._makeOne()
|
||||
self.assertRaises(NotAContainer, cont._validate, object())
|
||||
|
||||
def test__validate_collection_but_not_iterable(self):
|
||||
cont = self._makeOne()
|
||||
|
||||
class Dummy(object):
|
||||
def __contains__(self, item):
|
||||
return False
|
||||
cont._validate(Dummy()) # doesn't raise
|
||||
|
||||
def test__validate_not_collection_but_iterable(self):
|
||||
cont = self._makeOne()
|
||||
|
||||
class Dummy(object):
|
||||
def __iter__(self):
|
||||
return iter(())
|
||||
cont._validate(Dummy()) # doesn't raise
|
||||
|
||||
def test__validate_w_collections(self):
|
||||
cont = self._makeOne()
|
||||
cont._validate(()) # doesn't raise
|
||||
cont._validate([]) # doesn't raise
|
||||
cont._validate('') # doesn't raise
|
||||
cont._validate({}) # doesn't raise
|
||||
|
||||
|
||||
class IterableTests(ContainerTests):
|
||||
|
||||
def _getTargetClass(self):
|
||||
from zope.schema._bootstrapfields import Iterable
|
||||
return Iterable
|
||||
|
||||
def test__validate_collection_but_not_iterable(self):
|
||||
from zope.schema._bootstrapinterfaces import NotAnIterator
|
||||
itr = self._makeOne()
|
||||
|
||||
class Dummy(object):
|
||||
def __contains__(self, item):
|
||||
return False
|
||||
self.assertRaises(NotAnIterator, itr._validate, Dummy())
|
||||
|
||||
|
||||
class OrderableTests(unittest.TestCase):
|
||||
|
||||
def _getTargetClass(self):
|
||||
from zope.schema._bootstrapfields import Orderable
|
||||
return Orderable
|
||||
|
||||
def _makeOne(self, *args, **kw):
|
||||
# Orderable is a mixin for a type derived from Field
|
||||
from zope.schema._bootstrapfields import Field
|
||||
|
||||
class Mixed(self._getTargetClass(), Field):
|
||||
pass
|
||||
return Mixed(*args, **kw)
|
||||
|
||||
def test_ctor_defaults(self):
|
||||
ordb = self._makeOne()
|
||||
self.assertEqual(ordb.min, None)
|
||||
self.assertEqual(ordb.max, None)
|
||||
self.assertEqual(ordb.default, None)
|
||||
|
||||
def test_ctor_default_too_small(self):
|
||||
# This test exercises _validate, too
|
||||
from zope.schema._bootstrapinterfaces import TooSmall
|
||||
self.assertRaises(TooSmall, self._makeOne, min=0, default=-1)
|
||||
|
||||
def test_ctor_default_too_large(self):
|
||||
# This test exercises _validate, too
|
||||
from zope.schema._bootstrapinterfaces import TooBig
|
||||
self.assertRaises(TooBig, self._makeOne, max=10, default=11)
|
||||
|
||||
|
||||
class MinMaxLenTests(unittest.TestCase):
|
||||
|
||||
def _getTargetClass(self):
|
||||
from zope.schema._bootstrapfields import MinMaxLen
|
||||
return MinMaxLen
|
||||
|
||||
def _makeOne(self, *args, **kw):
|
||||
# MinMaxLen is a mixin for a type derived from Field
|
||||
from zope.schema._bootstrapfields import Field
|
||||
|
||||
class Mixed(self._getTargetClass(), Field):
|
||||
pass
|
||||
return Mixed(*args, **kw)
|
||||
|
||||
def test_ctor_defaults(self):
|
||||
mml = self._makeOne()
|
||||
self.assertEqual(mml.min_length, 0)
|
||||
self.assertEqual(mml.max_length, None)
|
||||
|
||||
def test_validate_too_short(self):
|
||||
from zope.schema._bootstrapinterfaces import TooShort
|
||||
mml = self._makeOne(min_length=1)
|
||||
self.assertRaises(TooShort, mml._validate, ())
|
||||
|
||||
def test_validate_too_long(self):
|
||||
from zope.schema._bootstrapinterfaces import TooLong
|
||||
mml = self._makeOne(max_length=2)
|
||||
self.assertRaises(TooLong, mml._validate, (0, 1, 2))
|
||||
|
||||
|
||||
class TextTests(unittest.TestCase):
|
||||
|
||||
def _getTargetClass(self):
|
||||
from zope.schema._bootstrapfields import Text
|
||||
return Text
|
||||
|
||||
def _makeOne(self, *args, **kw):
|
||||
return self._getTargetClass()(*args, **kw)
|
||||
|
||||
def test_ctor_defaults(self):
|
||||
from zope.schema._compat import text_type
|
||||
txt = self._makeOne()
|
||||
self.assertEqual(txt._type, text_type)
|
||||
|
||||
def test_validate_wrong_types(self):
|
||||
from zope.schema.interfaces import WrongType
|
||||
from zope.schema._compat import b
|
||||
field = self._makeOne()
|
||||
self.assertRaises(WrongType, field.validate, b(''))
|
||||
self.assertRaises(WrongType, field.validate, 1)
|
||||
self.assertRaises(WrongType, field.validate, 1.0)
|
||||
self.assertRaises(WrongType, field.validate, ())
|
||||
self.assertRaises(WrongType, field.validate, [])
|
||||
self.assertRaises(WrongType, field.validate, {})
|
||||
self.assertRaises(WrongType, field.validate, set())
|
||||
self.assertRaises(WrongType, field.validate, frozenset())
|
||||
self.assertRaises(WrongType, field.validate, object())
|
||||
|
||||
def test_validate_w_invalid_default(self):
|
||||
from zope.schema._compat import b
|
||||
from zope.schema.interfaces import ValidationError
|
||||
self.assertRaises(ValidationError, self._makeOne, default=b(''))
|
||||
|
||||
def test_validate_not_required(self):
|
||||
from zope.schema._compat import u
|
||||
field = self._makeOne(required=False)
|
||||
field.validate(u(''))
|
||||
field.validate(u('abc'))
|
||||
field.validate(u('abc\ndef'))
|
||||
field.validate(None)
|
||||
|
||||
def test_validate_required(self):
|
||||
from zope.schema.interfaces import RequiredMissing
|
||||
from zope.schema._compat import u
|
||||
field = self._makeOne()
|
||||
field.validate(u(''))
|
||||
field.validate(u('abc'))
|
||||
field.validate(u('abc\ndef'))
|
||||
self.assertRaises(RequiredMissing, field.validate, None)
|
||||
|
||||
def test_fromUnicode_miss(self):
|
||||
from zope.schema._bootstrapinterfaces import WrongType
|
||||
from zope.schema._compat import b
|
||||
deadbeef = b('DEADBEEF')
|
||||
txt = self._makeOne()
|
||||
self.assertRaises(WrongType, txt.fromUnicode, deadbeef)
|
||||
|
||||
def test_fromUnicode_hit(self):
|
||||
from zope.schema._compat import u
|
||||
deadbeef = u('DEADBEEF')
|
||||
txt = self._makeOne()
|
||||
self.assertEqual(txt.fromUnicode(deadbeef), deadbeef)
|
||||
|
||||
|
||||
class TextLineTests(unittest.TestCase):
|
||||
|
||||
def _getTargetClass(self):
|
||||
from zope.schema._field import TextLine
|
||||
return TextLine
|
||||
|
||||
def _makeOne(self, *args, **kw):
|
||||
return self._getTargetClass()(*args, **kw)
|
||||
|
||||
def test_class_conforms_to_ITextLine(self):
|
||||
from zope.interface.verify import verifyClass
|
||||
from zope.schema.interfaces import ITextLine
|
||||
verifyClass(ITextLine, self._getTargetClass())
|
||||
|
||||
def test_instance_conforms_to_ITextLine(self):
|
||||
from zope.interface.verify import verifyObject
|
||||
from zope.schema.interfaces import ITextLine
|
||||
verifyObject(ITextLine, self._makeOne())
|
||||
|
||||
def test_validate_wrong_types(self):
|
||||
from zope.schema.interfaces import WrongType
|
||||
from zope.schema._compat import b
|
||||
field = self._makeOne()
|
||||
self.assertRaises(WrongType, field.validate, b(''))
|
||||
self.assertRaises(WrongType, field.validate, 1)
|
||||
self.assertRaises(WrongType, field.validate, 1.0)
|
||||
self.assertRaises(WrongType, field.validate, ())
|
||||
self.assertRaises(WrongType, field.validate, [])
|
||||
self.assertRaises(WrongType, field.validate, {})
|
||||
self.assertRaises(WrongType, field.validate, set())
|
||||
self.assertRaises(WrongType, field.validate, frozenset())
|
||||
self.assertRaises(WrongType, field.validate, object())
|
||||
|
||||
def test_validate_not_required(self):
|
||||
from zope.schema._compat import u
|
||||
field = self._makeOne(required=False)
|
||||
field.validate(u(''))
|
||||
field.validate(u('abc'))
|
||||
field.validate(None)
|
||||
|
||||
def test_validate_required(self):
|
||||
from zope.schema.interfaces import RequiredMissing
|
||||
from zope.schema._compat import u
|
||||
field = self._makeOne()
|
||||
field.validate(u(''))
|
||||
field.validate(u('abc'))
|
||||
self.assertRaises(RequiredMissing, field.validate, None)
|
||||
|
||||
def test_constraint(self):
|
||||
from zope.schema._compat import u
|
||||
field = self._makeOne()
|
||||
self.assertEqual(field.constraint(u('')), True)
|
||||
self.assertEqual(field.constraint(u('abc')), True)
|
||||
self.assertEqual(field.constraint(u('abc\ndef')), False)
|
||||
|
||||
|
||||
class PasswordTests(unittest.TestCase):
|
||||
|
||||
def _getTargetClass(self):
|
||||
from zope.schema._bootstrapfields import Password
|
||||
return Password
|
||||
|
||||
def _makeOne(self, *args, **kw):
|
||||
return self._getTargetClass()(*args, **kw)
|
||||
|
||||
def test_set_unchanged(self):
|
||||
klass = self._getTargetClass()
|
||||
pw = self._makeOne()
|
||||
inst = DummyInst()
|
||||
before = dict(inst.__dict__)
|
||||
pw.set(inst, klass.UNCHANGED_PASSWORD) # doesn't raise, doesn't write
|
||||
after = dict(inst.__dict__)
|
||||
self.assertEqual(after, before)
|
||||
|
||||
def test_set_normal(self):
|
||||
pw = self._makeOne(__name__='password')
|
||||
inst = DummyInst()
|
||||
pw.set(inst, 'PASSWORD')
|
||||
self.assertEqual(inst.password, 'PASSWORD')
|
||||
|
||||
def test_validate_not_required(self):
|
||||
from zope.schema._compat import u
|
||||
field = self._makeOne(required=False)
|
||||
field.validate(u(''))
|
||||
field.validate(u('abc'))
|
||||
field.validate(None)
|
||||
|
||||
def test_validate_required(self):
|
||||
from zope.schema.interfaces import RequiredMissing
|
||||
from zope.schema._compat import u
|
||||
field = self._makeOne()
|
||||
field.validate(u(''))
|
||||
field.validate(u('abc'))
|
||||
self.assertRaises(RequiredMissing, field.validate, None)
|
||||
|
||||
def test_validate_unchanged_not_already_set(self):
|
||||
from zope.schema._bootstrapinterfaces import WrongType
|
||||
klass = self._getTargetClass()
|
||||
inst = DummyInst()
|
||||
pw = self._makeOne(__name__='password').bind(inst)
|
||||
self.assertRaises(WrongType,
|
||||
pw.validate, klass.UNCHANGED_PASSWORD)
|
||||
|
||||
def test_validate_unchanged_already_set(self):
|
||||
klass = self._getTargetClass()
|
||||
inst = DummyInst()
|
||||
inst.password = 'foobar'
|
||||
pw = self._makeOne(__name__='password').bind(inst)
|
||||
pw.validate(klass.UNCHANGED_PASSWORD) # doesn't raise
|
||||
|
||||
def test_constraint(self):
|
||||
from zope.schema._compat import u
|
||||
field = self._makeOne()
|
||||
self.assertEqual(field.constraint(u('')), True)
|
||||
self.assertEqual(field.constraint(u('abc')), True)
|
||||
self.assertEqual(field.constraint(u('abc\ndef')), False)
|
||||
|
||||
|
||||
class BoolTests(unittest.TestCase):
|
||||
|
||||
def _getTargetClass(self):
|
||||
from zope.schema._bootstrapfields import Bool
|
||||
return Bool
|
||||
|
||||
def _makeOne(self, *args, **kw):
|
||||
return self._getTargetClass()(*args, **kw)
|
||||
|
||||
def test_ctor_defaults(self):
|
||||
txt = self._makeOne()
|
||||
self.assertEqual(txt._type, bool)
|
||||
|
||||
def test__validate_w_int(self):
|
||||
boo = self._makeOne()
|
||||
boo._validate(0) # doesn't raise
|
||||
boo._validate(1) # doesn't raise
|
||||
|
||||
def test_set_w_int(self):
|
||||
boo = self._makeOne(__name__='boo')
|
||||
inst = DummyInst()
|
||||
boo.set(inst, 0)
|
||||
self.assertEqual(inst.boo, False)
|
||||
boo.set(inst, 1)
|
||||
self.assertEqual(inst.boo, True)
|
||||
|
||||
def test_fromUnicode_miss(self):
|
||||
from zope.schema._compat import u
|
||||
txt = self._makeOne()
|
||||
self.assertEqual(txt.fromUnicode(u('')), False)
|
||||
self.assertEqual(txt.fromUnicode(u('0')), False)
|
||||
self.assertEqual(txt.fromUnicode(u('1')), False)
|
||||
self.assertEqual(txt.fromUnicode(u('False')), False)
|
||||
self.assertEqual(txt.fromUnicode(u('false')), False)
|
||||
|
||||
def test_fromUnicode_hit(self):
|
||||
from zope.schema._compat import u
|
||||
txt = self._makeOne()
|
||||
self.assertEqual(txt.fromUnicode(u('True')), True)
|
||||
self.assertEqual(txt.fromUnicode(u('true')), True)
|
||||
|
||||
|
||||
class IntTests(unittest.TestCase):
|
||||
|
||||
def _getTargetClass(self):
|
||||
from zope.schema._bootstrapfields import Int
|
||||
return Int
|
||||
|
||||
def _makeOne(self, *args, **kw):
|
||||
return self._getTargetClass()(*args, **kw)
|
||||
|
||||
def test_ctor_defaults(self):
|
||||
from zope.schema._compat import integer_types
|
||||
txt = self._makeOne()
|
||||
self.assertEqual(txt._type, integer_types)
|
||||
|
||||
def test_validate_not_required(self):
|
||||
field = self._makeOne(required=False)
|
||||
field.validate(None)
|
||||
field.validate(10)
|
||||
field.validate(0)
|
||||
field.validate(-1)
|
||||
|
||||
def test_validate_required(self):
|
||||
from zope.schema.interfaces import RequiredMissing
|
||||
field = self._makeOne()
|
||||
field.validate(10)
|
||||
field.validate(0)
|
||||
field.validate(-1)
|
||||
self.assertRaises(RequiredMissing, field.validate, None)
|
||||
|
||||
def test_validate_min(self):
|
||||
from zope.schema.interfaces import TooSmall
|
||||
field = self._makeOne(min=10)
|
||||
field.validate(10)
|
||||
field.validate(20)
|
||||
self.assertRaises(TooSmall, field.validate, 9)
|
||||
self.assertRaises(TooSmall, field.validate, -10)
|
||||
|
||||
def test_validate_max(self):
|
||||
from zope.schema.interfaces import TooBig
|
||||
field = self._makeOne(max=10)
|
||||
field.validate(5)
|
||||
field.validate(9)
|
||||
field.validate(10)
|
||||
self.assertRaises(TooBig, field.validate, 11)
|
||||
self.assertRaises(TooBig, field.validate, 20)
|
||||
|
||||
def test_validate_min_and_max(self):
|
||||
from zope.schema.interfaces import TooBig
|
||||
from zope.schema.interfaces import TooSmall
|
||||
field = self._makeOne(min=0, max=10)
|
||||
field.validate(0)
|
||||
field.validate(5)
|
||||
field.validate(10)
|
||||
self.assertRaises(TooSmall, field.validate, -10)
|
||||
self.assertRaises(TooSmall, field.validate, -1)
|
||||
self.assertRaises(TooBig, field.validate, 11)
|
||||
self.assertRaises(TooBig, field.validate, 20)
|
||||
|
||||
def test_fromUnicode_miss(self):
|
||||
from zope.schema._compat import u
|
||||
txt = self._makeOne()
|
||||
self.assertRaises(ValueError, txt.fromUnicode, u(''))
|
||||
self.assertRaises(ValueError, txt.fromUnicode, u('False'))
|
||||
self.assertRaises(ValueError, txt.fromUnicode, u('True'))
|
||||
|
||||
def test_fromUnicode_hit(self):
|
||||
from zope.schema._compat import u
|
||||
txt = self._makeOne()
|
||||
self.assertEqual(txt.fromUnicode(u('0')), 0)
|
||||
self.assertEqual(txt.fromUnicode(u('1')), 1)
|
||||
self.assertEqual(txt.fromUnicode(u('-1')), -1)
|
||||
|
||||
|
||||
class DummyInst(object):
|
||||
missing_value = object()
|
||||
|
||||
def __init__(self, exc=None):
|
||||
self._exc = exc
|
||||
|
||||
def validate(self, value):
|
||||
if self._exc is not None:
|
||||
raise self._exc()
|
||||
|
||||
|
||||
def test_suite():
|
||||
return unittest.TestSuite((
|
||||
unittest.makeSuite(ValidatedPropertyTests),
|
||||
unittest.makeSuite(DefaultPropertyTests),
|
||||
unittest.makeSuite(FieldTests),
|
||||
unittest.makeSuite(ContainerTests),
|
||||
unittest.makeSuite(IterableTests),
|
||||
unittest.makeSuite(OrderableTests),
|
||||
unittest.makeSuite(MinMaxLenTests),
|
||||
unittest.makeSuite(TextTests),
|
||||
unittest.makeSuite(TextLineTests),
|
||||
unittest.makeSuite(PasswordTests),
|
||||
unittest.makeSuite(BoolTests),
|
||||
unittest.makeSuite(IntTests),
|
||||
))
|
||||
68
zope/schema/tests/test__bootstrapinterfaces.py
Normal file
68
zope/schema/tests/test__bootstrapinterfaces.py
Normal file
@@ -0,0 +1,68 @@
|
||||
##############################################################################
|
||||
#
|
||||
# Copyright (c) 2012 Zope Foundation and Contributors.
|
||||
# All Rights Reserved.
|
||||
#
|
||||
# This software is subject to the provisions of the Zope Public License,
|
||||
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
|
||||
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
|
||||
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
|
||||
# FOR A PARTICULAR PURPOSE.
|
||||
#
|
||||
##############################################################################
|
||||
import unittest
|
||||
|
||||
|
||||
def _skip_under_py3(testcase):
|
||||
from zope.schema._compat import PY3
|
||||
if not PY3:
|
||||
return testcase
|
||||
|
||||
|
||||
class ValidationErrorTests(unittest.TestCase):
|
||||
|
||||
def _getTargetClass(self):
|
||||
from zope.schema._bootstrapinterfaces import ValidationError
|
||||
return ValidationError
|
||||
|
||||
def _makeOne(self, *args, **kw):
|
||||
return self._getTargetClass()(*args, **kw)
|
||||
|
||||
def test_doc(self):
|
||||
class Derived(self._getTargetClass()):
|
||||
"""DERIVED"""
|
||||
inst = Derived()
|
||||
self.assertEqual(inst.doc(), 'DERIVED')
|
||||
|
||||
@_skip_under_py3
|
||||
def test___cmp___no_args(self):
|
||||
# Py3k??
|
||||
ve = self._makeOne()
|
||||
self.assertEqual(cmp(ve, object()), -1)
|
||||
|
||||
@_skip_under_py3
|
||||
def test___cmp___hit(self):
|
||||
# Py3k??
|
||||
left = self._makeOne('abc')
|
||||
right = self._makeOne('def')
|
||||
self.assertEqual(cmp(left, right), -1)
|
||||
self.assertEqual(cmp(left, left), 0)
|
||||
self.assertEqual(cmp(right, left), 1)
|
||||
|
||||
def test___eq___no_args(self):
|
||||
ve = self._makeOne()
|
||||
self.assertEqual(ve == object(), False)
|
||||
|
||||
def test___eq___w_args(self):
|
||||
left = self._makeOne('abc')
|
||||
right = self._makeOne('def')
|
||||
self.assertEqual(left == right, False)
|
||||
self.assertEqual(left == left, True)
|
||||
self.assertEqual(right == right, True)
|
||||
|
||||
|
||||
def test_suite():
|
||||
return unittest.TestSuite((
|
||||
unittest.makeSuite(ValidationErrorTests),
|
||||
))
|
||||
2122
zope/schema/tests/test__field.py
Normal file
2122
zope/schema/tests/test__field.py
Normal file
File diff suppressed because it is too large
Load Diff
315
zope/schema/tests/test_accessors.py
Normal file
315
zope/schema/tests/test_accessors.py
Normal file
@@ -0,0 +1,315 @@
|
||||
##############################################################################
|
||||
#
|
||||
# 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
|
||||
|
||||
|
||||
class FieldReadAccessorTests(unittest.TestCase):
|
||||
|
||||
def _getTargetClass(self):
|
||||
from zope.schema.accessors import FieldReadAccessor
|
||||
return FieldReadAccessor
|
||||
|
||||
def _makeOne(self, field=None):
|
||||
from zope.schema import Text
|
||||
if field is None:
|
||||
field = Text(__name__='testing')
|
||||
return self._getTargetClass()(field)
|
||||
|
||||
def test_ctor_not_created_inside_interface(self):
|
||||
from zope.schema import Text
|
||||
from zope.schema._compat import u
|
||||
field = Text(title=u('Hmm'))
|
||||
wrapped = self._makeOne(field)
|
||||
self.assertTrue(wrapped.field is field)
|
||||
self.assertEqual(wrapped.__name__, '') # __name__ set when in iface
|
||||
self.assertEqual(wrapped.__doc__, 'get Hmm')
|
||||
|
||||
def test_ctor_created_inside_interface(self):
|
||||
from zope.interface import Interface
|
||||
from zope.schema import Text
|
||||
from zope.schema._compat import u
|
||||
field = Text(title=u('Hmm'))
|
||||
|
||||
class IFoo(Interface):
|
||||
getter = self._makeOne(field)
|
||||
getter = IFoo['getter']
|
||||
self.assertEqual(getter.__name__, 'getter')
|
||||
self.assertEqual(getter.__doc__, 'get Hmm')
|
||||
|
||||
def test___provides___w_field_no_provides(self):
|
||||
from zope.interface import implementedBy
|
||||
from zope.interface import providedBy
|
||||
wrapped = self._makeOne(object())
|
||||
self.assertEqual(list(providedBy(wrapped)),
|
||||
list(implementedBy(self._getTargetClass())))
|
||||
|
||||
def test___provides___w_field_w_provides(self):
|
||||
from zope.interface import implementedBy
|
||||
from zope.interface import providedBy
|
||||
from zope.schema import Text
|
||||
field = Text()
|
||||
field_provides = list(providedBy(field))
|
||||
wrapped = self._makeOne(field)
|
||||
wrapped_provides = list(providedBy(wrapped))
|
||||
self.assertEqual(wrapped_provides[:len(field_provides)],
|
||||
list(providedBy(field)))
|
||||
for iface in list(implementedBy(self._getTargetClass())):
|
||||
self.assertTrue(iface in wrapped_provides)
|
||||
|
||||
def test_getSignatureString(self):
|
||||
wrapped = self._makeOne()
|
||||
self.assertEqual(wrapped.getSignatureString(), '()')
|
||||
|
||||
def test_getSignatureInfo(self):
|
||||
wrapped = self._makeOne()
|
||||
info = wrapped.getSignatureInfo()
|
||||
self.assertEqual(info['positional'], ())
|
||||
self.assertEqual(info['required'], ())
|
||||
self.assertEqual(info['optional'], ())
|
||||
self.assertEqual(info['varargs'], None)
|
||||
self.assertEqual(info['kwargs'], None)
|
||||
|
||||
def test_get_miss(self):
|
||||
from zope.interface import Interface
|
||||
|
||||
class IFoo(Interface):
|
||||
getter = self._makeOne()
|
||||
getter = IFoo['getter']
|
||||
|
||||
class Foo(object):
|
||||
pass
|
||||
self.assertRaises(AttributeError, getter.get, Foo())
|
||||
|
||||
def test_get_hit(self):
|
||||
from zope.interface import Interface
|
||||
|
||||
class IFoo(Interface):
|
||||
getter = self._makeOne()
|
||||
getter = IFoo['getter']
|
||||
|
||||
class Foo(object):
|
||||
def getter(self):
|
||||
return '123'
|
||||
self.assertEqual(getter.get(Foo()), '123')
|
||||
|
||||
def test_query_miss_implicit_default(self):
|
||||
from zope.interface import Interface
|
||||
|
||||
class IFoo(Interface):
|
||||
getter = self._makeOne()
|
||||
getter = IFoo['getter']
|
||||
|
||||
class Foo(object):
|
||||
pass
|
||||
self.assertEqual(getter.query(Foo()), None)
|
||||
|
||||
def test_query_miss_explicit_default(self):
|
||||
from zope.interface import Interface
|
||||
|
||||
class IFoo(Interface):
|
||||
getter = self._makeOne()
|
||||
getter = IFoo['getter']
|
||||
|
||||
class Foo(object):
|
||||
pass
|
||||
self.assertEqual(getter.query(Foo(), 234), 234)
|
||||
|
||||
def test_query_hit(self):
|
||||
from zope.interface import Interface
|
||||
|
||||
class IFoo(Interface):
|
||||
getter = self._makeOne()
|
||||
getter = IFoo['getter']
|
||||
|
||||
class Foo(object):
|
||||
def getter(self):
|
||||
return '123'
|
||||
|
||||
self.assertEqual(getter.query(Foo()), '123')
|
||||
|
||||
def test_set_readonly(self):
|
||||
from zope.interface import Interface
|
||||
from zope.schema import Text
|
||||
field = Text(readonly=True)
|
||||
|
||||
class IFoo(Interface):
|
||||
getter = self._makeOne(field)
|
||||
getter = IFoo['getter']
|
||||
|
||||
class Foo(object):
|
||||
def getter(self):
|
||||
return '123'
|
||||
self.assertRaises(TypeError, getter.set, Foo(), '456')
|
||||
|
||||
def test_set_no_writer(self):
|
||||
from zope.interface import Interface
|
||||
|
||||
class IFoo(Interface):
|
||||
getter = self._makeOne()
|
||||
getter = IFoo['getter']
|
||||
|
||||
class Foo(object):
|
||||
def getter(self):
|
||||
return '123'
|
||||
|
||||
self.assertRaises(AttributeError, getter.set, Foo(), '456')
|
||||
|
||||
def test_set_w_writer(self):
|
||||
from zope.interface import Interface
|
||||
|
||||
class IFoo(Interface):
|
||||
getter = self._makeOne()
|
||||
|
||||
getter = IFoo['getter']
|
||||
_called_with = []
|
||||
|
||||
class Writer(object):
|
||||
pass
|
||||
|
||||
writer = Writer()
|
||||
writer.__name__ = 'setMe'
|
||||
getter.writer = writer
|
||||
|
||||
class Foo(object):
|
||||
def setMe(self, value):
|
||||
_called_with.append(value)
|
||||
|
||||
getter.set(Foo(), '456')
|
||||
self.assertEqual(_called_with, ['456'])
|
||||
|
||||
def test_bind(self):
|
||||
from zope.interface import Interface
|
||||
|
||||
class IFoo(Interface):
|
||||
getter = self._makeOne()
|
||||
|
||||
getter = IFoo['getter']
|
||||
context = object()
|
||||
bound = getter.bind(context)
|
||||
self.assertEqual(bound.__name__, 'getter')
|
||||
self.assertTrue(isinstance(bound.field, getter.field.__class__))
|
||||
self.assertTrue(bound.field.context is context)
|
||||
|
||||
|
||||
class FieldWriteAccessorTests(unittest.TestCase):
|
||||
|
||||
def _getTargetClass(self):
|
||||
from zope.schema.accessors import FieldWriteAccessor
|
||||
return FieldWriteAccessor
|
||||
|
||||
def _makeOne(self, field=None):
|
||||
from zope.schema import Text
|
||||
if field is None:
|
||||
field = Text(__name__='testing')
|
||||
return self._getTargetClass()(field)
|
||||
|
||||
def test_ctor_not_created_inside_interface(self):
|
||||
from zope.schema import Text
|
||||
from zope.schema._compat import u
|
||||
field = Text(title=u('Hmm'))
|
||||
wrapped = self._makeOne(field)
|
||||
self.assertTrue(wrapped.field is field)
|
||||
self.assertEqual(wrapped.__name__, '') # __name__ set when in iface
|
||||
self.assertEqual(wrapped.__doc__, 'set Hmm')
|
||||
|
||||
def test_ctor_created_inside_interface(self):
|
||||
from zope.interface import Interface
|
||||
from zope.schema import Text
|
||||
from zope.schema._compat import u
|
||||
field = Text(title=u('Hmm'))
|
||||
|
||||
class IFoo(Interface):
|
||||
setter = self._makeOne(field)
|
||||
|
||||
setter = IFoo['setter']
|
||||
self.assertEqual(setter.__name__, 'setter')
|
||||
self.assertEqual(setter.__doc__, 'set Hmm')
|
||||
|
||||
def test_getSignatureString(self):
|
||||
wrapped = self._makeOne()
|
||||
self.assertEqual(wrapped.getSignatureString(), '(newvalue)')
|
||||
|
||||
def test_getSignatureInfo(self):
|
||||
wrapped = self._makeOne()
|
||||
info = wrapped.getSignatureInfo()
|
||||
self.assertEqual(info['positional'], ('newvalue',))
|
||||
self.assertEqual(info['required'], ('newvalue',))
|
||||
self.assertEqual(info['optional'], ())
|
||||
self.assertEqual(info['varargs'], None)
|
||||
self.assertEqual(info['kwargs'], None)
|
||||
|
||||
|
||||
class Test_accessors(unittest.TestCase):
|
||||
|
||||
def _callFUT(self, *args, **kw):
|
||||
from zope.schema.accessors import accessors
|
||||
return accessors(*args, **kw)
|
||||
|
||||
def test_w_only_read_accessor(self):
|
||||
from zope.interface import Interface
|
||||
from zope.schema import Text
|
||||
from zope.schema._compat import u
|
||||
field = Text(title=u('Hmm'), readonly=True)
|
||||
|
||||
class IFoo(Interface):
|
||||
getter, = self._callFUT(field)
|
||||
|
||||
getter = IFoo['getter']
|
||||
self.assertEqual(getter.__name__, 'getter')
|
||||
self.assertEqual(getter.__doc__, 'get Hmm')
|
||||
self.assertEqual(getter.getSignatureString(), '()')
|
||||
info = getter.getSignatureInfo()
|
||||
self.assertEqual(info['positional'], ())
|
||||
self.assertEqual(info['required'], ())
|
||||
self.assertEqual(info['optional'], ())
|
||||
self.assertEqual(info['varargs'], None)
|
||||
self.assertEqual(info['kwargs'], None)
|
||||
|
||||
def test_w_read_and_write_accessors(self):
|
||||
from zope.interface import Interface
|
||||
from zope.schema import Text
|
||||
from zope.schema._compat import u
|
||||
field = Text(title=u('Hmm'))
|
||||
|
||||
class IFoo(Interface):
|
||||
getter, setter = self._callFUT(field)
|
||||
|
||||
getter = IFoo['getter']
|
||||
self.assertEqual(getter.__name__, 'getter')
|
||||
self.assertEqual(getter.getSignatureString(), '()')
|
||||
info = getter.getSignatureInfo()
|
||||
self.assertEqual(info['positional'], ())
|
||||
self.assertEqual(info['required'], ())
|
||||
self.assertEqual(info['optional'], ())
|
||||
self.assertEqual(info['varargs'], None)
|
||||
self.assertEqual(info['kwargs'], None)
|
||||
setter = IFoo['setter']
|
||||
self.assertEqual(setter.__name__, 'setter')
|
||||
self.assertEqual(setter.getSignatureString(), '(newvalue)')
|
||||
info = setter.getSignatureInfo()
|
||||
self.assertEqual(info['positional'], ('newvalue',))
|
||||
self.assertEqual(info['required'], ('newvalue',))
|
||||
self.assertEqual(info['optional'], ())
|
||||
self.assertEqual(info['varargs'], None)
|
||||
self.assertEqual(info['kwargs'], None)
|
||||
|
||||
|
||||
def test_suite():
|
||||
return unittest.TestSuite((
|
||||
unittest.makeSuite(FieldReadAccessorTests),
|
||||
unittest.makeSuite(FieldWriteAccessorTests),
|
||||
unittest.makeSuite(Test_accessors),
|
||||
))
|
||||
41
zope/schema/tests/test_equality.py
Normal file
41
zope/schema/tests/test_equality.py
Normal file
@@ -0,0 +1,41 @@
|
||||
##############################################################################
|
||||
#
|
||||
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
|
||||
# All Rights Reserved.
|
||||
#
|
||||
# This software is subject to the provisions of the Zope Public License,
|
||||
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
|
||||
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
|
||||
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
|
||||
# FOR A PARTICULAR PURPOSE.
|
||||
#
|
||||
##############################################################################
|
||||
"""Field equality tests
|
||||
"""
|
||||
import unittest
|
||||
|
||||
|
||||
class FieldEqualityTests(unittest.TestCase):
|
||||
|
||||
def test_equality(self):
|
||||
|
||||
from zope.schema._compat import u
|
||||
from zope.schema import Int
|
||||
from zope.schema import Text
|
||||
|
||||
# pep 8 friendlyness
|
||||
u, Int, Text
|
||||
|
||||
equality = [
|
||||
'Text(title=u("Foo"), description=u("Bar"))',
|
||||
'Int(title=u("Foo"), description=u("Bar"))',
|
||||
]
|
||||
for text in equality:
|
||||
self.assertEqual(eval(text), eval(text))
|
||||
|
||||
|
||||
def test_suite():
|
||||
return unittest.TestSuite((
|
||||
unittest.makeSuite(FieldEqualityTests),
|
||||
))
|
||||
669
zope/schema/tests/test_fieldproperty.py
Normal file
669
zope/schema/tests/test_fieldproperty.py
Normal file
@@ -0,0 +1,669 @@
|
||||
##############################################################################
|
||||
#
|
||||
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
|
||||
# All Rights Reserved.
|
||||
#
|
||||
# This software is subject to the provisions of the Zope Public License,
|
||||
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
|
||||
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
|
||||
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
|
||||
# FOR A PARTICULAR PURPOSE.
|
||||
#
|
||||
##############################################################################
|
||||
"""Field Properties tests
|
||||
"""
|
||||
|
||||
import unittest
|
||||
|
||||
|
||||
class _Base(unittest.TestCase):
|
||||
|
||||
def _makeOne(self, field=None, name=None):
|
||||
from zope.schema import Text
|
||||
if field is None:
|
||||
field = Text(__name__='testing')
|
||||
if name is None:
|
||||
return self._getTargetClass()(field)
|
||||
return self._getTargetClass()(field, name)
|
||||
|
||||
|
||||
class _Integration(object):
|
||||
|
||||
def _makeImplementer(self):
|
||||
schema = _getSchema()
|
||||
|
||||
class _Implementer(object):
|
||||
title = self._makeOne(schema['title'])
|
||||
weight = self._makeOne(schema['weight'])
|
||||
code = self._makeOne(schema['code'])
|
||||
date = self._makeOne(schema['date'])
|
||||
|
||||
return _Implementer()
|
||||
|
||||
def test_basic(self):
|
||||
from zope.schema._compat import b
|
||||
from zope.schema._compat import u
|
||||
from zope.schema.interfaces import ValidationError
|
||||
c = self._makeImplementer()
|
||||
self.assertEqual(c.title, u('say something'))
|
||||
self.assertEqual(c.weight, None)
|
||||
self.assertEqual(c.code, b('xxxxxx'))
|
||||
self.assertRaises(ValidationError, setattr, c, 'title', b('foo'))
|
||||
self.assertRaises(ValidationError, setattr, c, 'weight', b('foo'))
|
||||
self.assertRaises(ValidationError, setattr, c, 'weight', -1.0)
|
||||
self.assertRaises(ValidationError, setattr, c, 'weight', 2)
|
||||
self.assertRaises(ValidationError, setattr, c, 'code', -1)
|
||||
self.assertRaises(ValidationError, setattr, c, 'code', b('xxxx'))
|
||||
self.assertRaises(ValidationError, setattr, c, 'code', u('xxxxxx'))
|
||||
|
||||
c.title = u('c is good')
|
||||
c.weight = 10.0
|
||||
c.code = b('abcdef')
|
||||
|
||||
self.assertEqual(c.title, u('c is good'))
|
||||
self.assertEqual(c.weight, 10)
|
||||
self.assertEqual(c.code, b('abcdef'))
|
||||
|
||||
def test_readonly(self):
|
||||
c = self._makeImplementer()
|
||||
# The date should be only settable once
|
||||
c.date = 0.0
|
||||
# Setting the value a second time should fail.
|
||||
self.assertRaises(ValueError, setattr, c, 'date', 1.0)
|
||||
|
||||
|
||||
class FieldPropertyTests(_Base, _Integration):
|
||||
|
||||
def _getTargetClass(self):
|
||||
from zope.schema.fieldproperty import FieldProperty
|
||||
return FieldProperty
|
||||
|
||||
def test_ctor_defaults(self):
|
||||
from zope.schema import Text
|
||||
field = Text(__name__='testing')
|
||||
cname = self._getTargetClass().__name__
|
||||
prop = self._makeOne(field)
|
||||
self.assertTrue(getattr(prop, '_%s__field' % cname) is field)
|
||||
self.assertEqual(getattr(prop, '_%s__name' % cname), 'testing')
|
||||
self.assertEqual(prop.__name__, 'testing')
|
||||
self.assertEqual(prop.description, field.description)
|
||||
self.assertEqual(prop.default, field.default)
|
||||
self.assertEqual(prop.readonly, field.readonly)
|
||||
self.assertEqual(prop.required, field.required)
|
||||
|
||||
def test_ctor_explicit(self):
|
||||
from zope.schema import Text
|
||||
from zope.schema._compat import u
|
||||
field = Text(
|
||||
__name__='testing',
|
||||
description=u('DESCRIPTION'),
|
||||
default=u('DEFAULT'),
|
||||
readonly=True,
|
||||
required=True,
|
||||
)
|
||||
cname = self._getTargetClass().__name__
|
||||
prop = self._makeOne(field, name='override')
|
||||
self.assertTrue(getattr(prop, '_%s__field' % cname) is field)
|
||||
self.assertEqual(getattr(prop, '_%s__name' % cname), 'override')
|
||||
self.assertEqual(prop.description, field.description)
|
||||
self.assertEqual(prop.default, field.default)
|
||||
self.assertEqual(prop.readonly, field.readonly)
|
||||
self.assertEqual(prop.required, field.required)
|
||||
|
||||
def test_query_value_with_default(self):
|
||||
from zope.schema import Text
|
||||
from zope.schema._compat import u
|
||||
field = Text(
|
||||
__name__='testing',
|
||||
description=u('DESCRIPTION'),
|
||||
default=u('DEFAULT'),
|
||||
readonly=True,
|
||||
required=True,
|
||||
)
|
||||
|
||||
prop = self._makeOne(field=field)
|
||||
|
||||
class Foo(object):
|
||||
testing = prop
|
||||
foo = Foo()
|
||||
self.assertEqual(prop.queryValue(foo, 'test'), u('DEFAULT'))
|
||||
foo.testing = u('NO')
|
||||
self.assertEqual(prop.queryValue(foo, 'test'), u('NO'))
|
||||
|
||||
def test_query_value_without_default(self):
|
||||
from zope.schema import Text
|
||||
from zope.schema._compat import u
|
||||
field = Text(
|
||||
__name__='testing',
|
||||
description=u('DESCRIPTION'),
|
||||
readonly=True,
|
||||
required=True,
|
||||
)
|
||||
|
||||
prop = self._makeOne(field=field)
|
||||
|
||||
class Foo(object):
|
||||
testing = prop
|
||||
foo = Foo()
|
||||
# field initialize its default to None if it hasn't any default
|
||||
# it should be zope.schema.NO_VALUE as 'None' has another semantic
|
||||
self.assertEqual(prop.queryValue(foo, 'test'), None)
|
||||
|
||||
def test___get___from_class(self):
|
||||
prop = self._makeOne()
|
||||
|
||||
class Foo(object):
|
||||
testing = prop
|
||||
|
||||
self.assertTrue(Foo.testing is prop)
|
||||
|
||||
def test___get___from_instance_pseudo_field_wo_default(self):
|
||||
class _Faux(object):
|
||||
def bind(self, other):
|
||||
return self
|
||||
prop = self._makeOne(_Faux(), 'nonesuch')
|
||||
|
||||
class Foo(object):
|
||||
testing = prop
|
||||
|
||||
foo = Foo()
|
||||
self.assertRaises(AttributeError, getattr, foo, 'testing')
|
||||
|
||||
def test___get___from_instance_miss_uses_field_default(self):
|
||||
prop = self._makeOne()
|
||||
|
||||
class Foo(object):
|
||||
testing = prop
|
||||
|
||||
foo = Foo()
|
||||
self.assertEqual(foo.testing, None)
|
||||
|
||||
def test___get___from_instance_hit(self):
|
||||
prop = self._makeOne(name='other')
|
||||
|
||||
class Foo(object):
|
||||
testing = prop
|
||||
|
||||
foo = Foo()
|
||||
foo.other = '123'
|
||||
self.assertEqual(foo.testing, '123')
|
||||
|
||||
def test___get___from_instance_hit_after_bind(self):
|
||||
class _Faux(object):
|
||||
default = '456'
|
||||
|
||||
def bind(self, other):
|
||||
return self
|
||||
|
||||
prop = self._makeOne(_Faux(), 'testing')
|
||||
|
||||
class Foo(object):
|
||||
testing = prop
|
||||
|
||||
foo = Foo()
|
||||
self.assertEqual(foo.testing, '456')
|
||||
|
||||
def test___set___not_readonly(self):
|
||||
class _Faux(object):
|
||||
readonly = False
|
||||
default = '456'
|
||||
|
||||
def bind(self, other):
|
||||
return self
|
||||
|
||||
faux = _Faux()
|
||||
_validated = []
|
||||
faux.validate = _validated.append
|
||||
prop = self._makeOne(faux, 'testing')
|
||||
|
||||
class Foo(object):
|
||||
testing = prop
|
||||
|
||||
foo = Foo()
|
||||
foo.testing = '123'
|
||||
self.assertEqual(foo.__dict__['testing'], '123')
|
||||
|
||||
def test___set___w_readonly_not_already_set(self):
|
||||
class _Faux(object):
|
||||
readonly = True
|
||||
default = '456'
|
||||
|
||||
def bind(self, other):
|
||||
return self
|
||||
|
||||
faux = _Faux()
|
||||
_validated = []
|
||||
faux.validate = _validated.append
|
||||
prop = self._makeOne(faux, 'testing')
|
||||
|
||||
class Foo(object):
|
||||
testing = prop
|
||||
|
||||
foo = Foo()
|
||||
foo.testing = '123'
|
||||
self.assertEqual(foo.__dict__['testing'], '123')
|
||||
self.assertEqual(_validated, ['123'])
|
||||
|
||||
def test___set___w_readonly_and_already_set(self):
|
||||
class _Faux(object):
|
||||
readonly = True
|
||||
default = '456'
|
||||
|
||||
def bind(self, other):
|
||||
return self
|
||||
|
||||
faux = _Faux()
|
||||
_validated = []
|
||||
faux.validate = _validated.append
|
||||
prop = self._makeOne(faux, 'testing')
|
||||
|
||||
class Foo(object):
|
||||
testing = prop
|
||||
|
||||
foo = Foo()
|
||||
foo.__dict__['testing'] = '789'
|
||||
self.assertRaises(ValueError, setattr, foo, 'testing', '123')
|
||||
self.assertEqual(_validated, ['123'])
|
||||
|
||||
def test_field_event(self):
|
||||
from zope.schema import Text
|
||||
from zope.schema._compat import u
|
||||
from zope.event import subscribers
|
||||
from zope.schema.fieldproperty import FieldUpdatedEvent
|
||||
log = []
|
||||
subscribers.append(log.append)
|
||||
self.assertEqual(log, [])
|
||||
field = Text(
|
||||
__name__='testing',
|
||||
description=u('DESCRIPTION'),
|
||||
default=u('DEFAULT'),
|
||||
readonly=True,
|
||||
required=True,
|
||||
)
|
||||
self.assertEqual(len(log), 6)
|
||||
event = log[0]
|
||||
self.assertTrue(isinstance(event, FieldUpdatedEvent))
|
||||
self.assertEqual(event.inst, field)
|
||||
self.assertEqual(event.old_value, 0)
|
||||
self.assertEqual(event.new_value, 0)
|
||||
self.assertEqual(
|
||||
[ev.field.__name__ for ev in log],
|
||||
['min_length', 'max_length', 'title', 'description', 'required', 'readonly'])
|
||||
|
||||
def test_field_event_update(self):
|
||||
from zope.schema import Text
|
||||
from zope.schema._compat import u
|
||||
from zope.event import subscribers
|
||||
from zope.schema.fieldproperty import FieldUpdatedEvent
|
||||
field = Text(
|
||||
__name__='testing',
|
||||
description=u('DESCRIPTION'),
|
||||
default=u('DEFAULT'),
|
||||
required=True,
|
||||
)
|
||||
prop = self._makeOne(field=field)
|
||||
|
||||
class Foo(object):
|
||||
testing = prop
|
||||
foo = Foo()
|
||||
|
||||
log = []
|
||||
subscribers.append(log.append)
|
||||
foo.testing = u('Bar')
|
||||
foo.testing = u('Foo')
|
||||
self.assertEqual(len(log), 2)
|
||||
event = log[1]
|
||||
self.assertTrue(isinstance(event, FieldUpdatedEvent))
|
||||
self.assertEqual(event.inst, foo)
|
||||
self.assertEqual(event.field, field)
|
||||
self.assertEqual(event.old_value, u('Bar'))
|
||||
self.assertEqual(event.new_value, u('Foo'))
|
||||
|
||||
|
||||
class FieldPropertyStoredThroughFieldTests(_Base, _Integration):
|
||||
|
||||
def _getTargetClass(self):
|
||||
from zope.schema.fieldproperty import FieldPropertyStoredThroughField
|
||||
return FieldPropertyStoredThroughField
|
||||
|
||||
def test_ctor_defaults(self):
|
||||
from zope.schema import Text
|
||||
field = Text(__name__='testing')
|
||||
cname = self._getTargetClass().__name__
|
||||
prop = self._makeOne(field)
|
||||
self.assertTrue(isinstance(prop.field, field.__class__))
|
||||
self.assertFalse(prop.field is field)
|
||||
self.assertEqual(prop.field.__name__, '__st_testing_st')
|
||||
self.assertEqual(prop.__name__, '__st_testing_st')
|
||||
self.assertEqual(getattr(prop, '_%s__name' % cname), 'testing')
|
||||
self.assertEqual(prop.description, field.description)
|
||||
self.assertEqual(prop.default, field.default)
|
||||
self.assertEqual(prop.readonly, field.readonly)
|
||||
self.assertEqual(prop.required, field.required)
|
||||
|
||||
def test_ctor_explicit(self):
|
||||
from zope.schema import Text
|
||||
from zope.schema._compat import u
|
||||
field = Text(
|
||||
__name__='testing',
|
||||
description=u('DESCRIPTION'),
|
||||
default=u('DEFAULT'),
|
||||
readonly=True,
|
||||
required=True,
|
||||
)
|
||||
cname = self._getTargetClass().__name__
|
||||
prop = self._makeOne(field, name='override')
|
||||
self.assertTrue(isinstance(prop.field, field.__class__))
|
||||
self.assertFalse(prop.field is field)
|
||||
self.assertEqual(prop.field.__name__, '__st_testing_st')
|
||||
self.assertEqual(prop.__name__, '__st_testing_st')
|
||||
self.assertEqual(getattr(prop, '_%s__name' % cname), 'override')
|
||||
self.assertEqual(prop.description, field.description)
|
||||
self.assertEqual(prop.default, field.default)
|
||||
self.assertEqual(prop.readonly, field.readonly)
|
||||
self.assertEqual(prop.required, field.required)
|
||||
|
||||
def test_setValue(self):
|
||||
from zope.schema import Text
|
||||
|
||||
class Foo(object):
|
||||
pass
|
||||
|
||||
foo = Foo()
|
||||
prop = self._makeOne()
|
||||
field = Text(__name__='testing')
|
||||
prop.setValue(foo, field, '123')
|
||||
self.assertEqual(foo.testing, '123')
|
||||
|
||||
def test_getValue_miss(self):
|
||||
from zope.schema import Text
|
||||
from zope.schema.fieldproperty import _marker
|
||||
|
||||
class Foo(object):
|
||||
pass
|
||||
|
||||
foo = Foo()
|
||||
prop = self._makeOne()
|
||||
field = Text(__name__='testing')
|
||||
value = prop.getValue(foo, field)
|
||||
self.assertTrue(value is _marker)
|
||||
|
||||
def test_getValue_hit(self):
|
||||
from zope.schema import Text
|
||||
|
||||
class Foo(object):
|
||||
pass
|
||||
|
||||
foo = Foo()
|
||||
foo.testing = '123'
|
||||
prop = self._makeOne()
|
||||
field = Text(__name__='testing')
|
||||
value = prop.getValue(foo, field)
|
||||
self.assertEqual(value, '123')
|
||||
|
||||
def test_queryValue_miss(self):
|
||||
from zope.schema import Text
|
||||
|
||||
class Foo(object):
|
||||
pass
|
||||
|
||||
foo = Foo()
|
||||
prop = self._makeOne()
|
||||
field = Text(__name__='testing')
|
||||
default = object()
|
||||
value = prop.queryValue(foo, field, default)
|
||||
self.assertTrue(value is default)
|
||||
|
||||
def test_queryValue_hit(self):
|
||||
from zope.schema import Text
|
||||
|
||||
class Foo(object):
|
||||
pass
|
||||
|
||||
foo = Foo()
|
||||
foo.testing = '123'
|
||||
prop = self._makeOne()
|
||||
field = Text(__name__='testing')
|
||||
default = object()
|
||||
value = prop.queryValue(foo, field, default)
|
||||
self.assertEqual(value, '123')
|
||||
|
||||
def test___get___from_class(self):
|
||||
prop = self._makeOne()
|
||||
|
||||
class Foo(object):
|
||||
testing = prop
|
||||
|
||||
self.assertTrue(Foo.testing is prop)
|
||||
|
||||
def test___get___from_instance_pseudo_field_wo_default(self):
|
||||
class _Faux(object):
|
||||
__name__ = 'Faux'
|
||||
|
||||
def bind(self, other):
|
||||
return self
|
||||
|
||||
def query(self, inst, default):
|
||||
return default
|
||||
|
||||
prop = self._makeOne(_Faux(), 'nonesuch')
|
||||
|
||||
class Foo(object):
|
||||
testing = prop
|
||||
|
||||
foo = Foo()
|
||||
self.assertRaises(AttributeError, getattr, foo, 'testing')
|
||||
|
||||
def test___get___from_instance_miss_uses_field_default(self):
|
||||
prop = self._makeOne()
|
||||
|
||||
class Foo(object):
|
||||
testing = prop
|
||||
|
||||
foo = Foo()
|
||||
self.assertEqual(foo.testing, None)
|
||||
|
||||
def test___get___from_instance_hit(self):
|
||||
from zope.schema import Text
|
||||
field = Text(__name__='testing')
|
||||
prop = self._makeOne(field, name='other')
|
||||
|
||||
class Foo(object):
|
||||
testing = prop
|
||||
|
||||
foo = Foo()
|
||||
foo.__dict__['__st_testing_st'] = '456'
|
||||
foo.other = '123'
|
||||
self.assertEqual(foo.testing, '456')
|
||||
|
||||
def test___set___not_readonly(self):
|
||||
class _Faux(object):
|
||||
__name__ = 'Faux'
|
||||
readonly = False
|
||||
default = '456'
|
||||
|
||||
def query(self, inst, default):
|
||||
return default
|
||||
|
||||
def bind(self, other):
|
||||
return self
|
||||
|
||||
def set(self, inst, value):
|
||||
setattr(inst, 'faux', value)
|
||||
|
||||
faux = _Faux()
|
||||
_validated = []
|
||||
faux.validate = _validated.append
|
||||
prop = self._makeOne(faux, 'testing')
|
||||
|
||||
class Foo(object):
|
||||
testing = prop
|
||||
|
||||
foo = Foo()
|
||||
foo.testing = '123'
|
||||
self.assertEqual(foo.__dict__['faux'], '123')
|
||||
self.assertEqual(_validated, ['123'])
|
||||
|
||||
def test___set___w_readonly_not_already_set(self):
|
||||
class _Faux(object):
|
||||
__name__ = 'Faux'
|
||||
readonly = True
|
||||
default = '456'
|
||||
|
||||
def bind(self, other):
|
||||
return self
|
||||
|
||||
def query(self, inst, default):
|
||||
return default
|
||||
|
||||
def set(self, inst, value):
|
||||
if self.readonly:
|
||||
raise ValueError
|
||||
setattr(inst, 'faux', value)
|
||||
|
||||
faux = _Faux()
|
||||
_validated = []
|
||||
faux.validate = _validated.append
|
||||
prop = self._makeOne(faux, 'testing')
|
||||
|
||||
class Foo(object):
|
||||
testing = prop
|
||||
|
||||
foo = Foo()
|
||||
foo.testing = '123'
|
||||
self.assertEqual(foo.__dict__['faux'], '123')
|
||||
self.assertEqual(_validated, ['123'])
|
||||
|
||||
def test___set___w_readonly_and_already_set(self):
|
||||
class _Faux(object):
|
||||
__name__ = 'Faux'
|
||||
readonly = True
|
||||
default = '456'
|
||||
|
||||
def bind(self, other):
|
||||
return self
|
||||
|
||||
def query(self, inst, default):
|
||||
return '789'
|
||||
|
||||
faux = _Faux()
|
||||
_validated = []
|
||||
faux.validate = _validated.append
|
||||
prop = self._makeOne(faux, 'testing')
|
||||
|
||||
class Foo(object):
|
||||
testing = prop
|
||||
|
||||
foo = Foo()
|
||||
foo.__dict__['testing'] = '789'
|
||||
self.assertRaises(ValueError, setattr, foo, 'testing', '123')
|
||||
|
||||
def test_field_event_update(self):
|
||||
from zope.schema import Text
|
||||
from zope.schema._compat import u
|
||||
from zope.event import subscribers
|
||||
from zope.schema.fieldproperty import FieldUpdatedEvent
|
||||
field = Text(
|
||||
__name__='testing',
|
||||
description=u('DESCRIPTION'),
|
||||
default=u('DEFAULT'),
|
||||
required=True,
|
||||
)
|
||||
prop = self._makeOne(field=field)
|
||||
|
||||
class Foo(object):
|
||||
testing = prop
|
||||
foo = Foo()
|
||||
|
||||
log = []
|
||||
subscribers.append(log.append)
|
||||
foo.testing = u('Bar')
|
||||
foo.testing = u('Foo')
|
||||
self.assertEqual(len(log), 2)
|
||||
event = log[1]
|
||||
self.assertTrue(isinstance(event, FieldUpdatedEvent))
|
||||
self.assertEqual(event.inst, foo)
|
||||
self.assertEqual(event.field, field)
|
||||
self.assertEqual(event.old_value, u('Bar'))
|
||||
self.assertEqual(event.new_value, u('Foo'))
|
||||
|
||||
def test_field_event(self):
|
||||
# fieldproperties are everywhere including in field themselfs
|
||||
# so event are triggered
|
||||
from zope.schema import Text
|
||||
from zope.schema._compat import u
|
||||
from zope.event import subscribers
|
||||
from zope.schema.fieldproperty import FieldUpdatedEvent
|
||||
log = []
|
||||
subscribers.append(log.append)
|
||||
self.assertEqual(log, [])
|
||||
field = Text(
|
||||
__name__='testing',
|
||||
description=u('DESCRIPTION'),
|
||||
default=u('DEFAULT'),
|
||||
readonly=True,
|
||||
required=True,
|
||||
)
|
||||
self.assertEqual(len(log), 6)
|
||||
# these are fieldproperties in the field
|
||||
self.assertEqual(
|
||||
[ev.field.__name__ for ev in log],
|
||||
['min_length', 'max_length', 'title', 'description', 'required', 'readonly'])
|
||||
event = log[0]
|
||||
self.assertTrue(isinstance(event, FieldUpdatedEvent))
|
||||
self.assertEqual(event.inst, field)
|
||||
self.assertEqual(event.old_value, 0)
|
||||
self.assertEqual(event.new_value, 0)
|
||||
|
||||
|
||||
def _getSchema():
|
||||
from zope.interface import Interface
|
||||
from zope.schema import Bytes
|
||||
from zope.schema import Float
|
||||
from zope.schema import Text
|
||||
from zope.schema._compat import b
|
||||
from zope.schema._compat import u
|
||||
|
||||
class Schema(Interface):
|
||||
title = Text(description=u("Short summary"),
|
||||
default=u('say something'))
|
||||
weight = Float(min=0.0)
|
||||
code = Bytes(min_length=6, max_length=6, default=b('xxxxxx'))
|
||||
date = Float(title=u('Date'), readonly=True)
|
||||
|
||||
return Schema
|
||||
|
||||
|
||||
class CreateFieldPropertiesTests(unittest.TestCase):
|
||||
"""Testing ..fieldproperty.createFieldProperties."""
|
||||
|
||||
def test_creates_fieldproperties_on_class(self):
|
||||
from zope.schema.fieldproperty import createFieldProperties
|
||||
from zope.schema.fieldproperty import FieldProperty
|
||||
schema = _getSchema()
|
||||
|
||||
class Dummy(object):
|
||||
createFieldProperties(schema)
|
||||
|
||||
self.assertTrue(isinstance(Dummy.title, FieldProperty))
|
||||
self.assertTrue(isinstance(Dummy.date, FieldProperty))
|
||||
self.assertTrue(Dummy.date._FieldProperty__field is schema['date'])
|
||||
|
||||
def test_fields_in_omit_are_not_created_on_class(self):
|
||||
from zope.schema.fieldproperty import createFieldProperties
|
||||
|
||||
class Dummy(object):
|
||||
createFieldProperties(_getSchema(), omit=['date', 'code'])
|
||||
|
||||
self.assertFalse(hasattr(Dummy, 'date'))
|
||||
self.assertFalse(hasattr(Dummy, 'code'))
|
||||
self.assertTrue(hasattr(Dummy, 'title'))
|
||||
|
||||
|
||||
def test_suite():
|
||||
return unittest.TestSuite((
|
||||
unittest.makeSuite(FieldPropertyTests),
|
||||
unittest.makeSuite(FieldPropertyStoredThroughFieldTests),
|
||||
unittest.makeSuite(CreateFieldPropertiesTests),
|
||||
))
|
||||
99
zope/schema/tests/test_interfaces.py
Normal file
99
zope/schema/tests/test_interfaces.py
Normal file
@@ -0,0 +1,99 @@
|
||||
import unittest
|
||||
|
||||
|
||||
class Test__is_field(unittest.TestCase):
|
||||
|
||||
def _callFUT(self, value):
|
||||
from zope.schema.interfaces import _is_field
|
||||
return _is_field(value)
|
||||
|
||||
def test_non_fields(self):
|
||||
from zope.schema._compat import b
|
||||
from zope.schema._compat import u
|
||||
self.assertEqual(self._callFUT(None), False)
|
||||
self.assertEqual(self._callFUT(0), False)
|
||||
self.assertEqual(self._callFUT(0.0), False)
|
||||
self.assertEqual(self._callFUT(True), False)
|
||||
self.assertEqual(self._callFUT(b('')), False)
|
||||
self.assertEqual(self._callFUT(u('')), False)
|
||||
self.assertEqual(self._callFUT(()), False)
|
||||
self.assertEqual(self._callFUT([]), False)
|
||||
self.assertEqual(self._callFUT({}), False)
|
||||
self.assertEqual(self._callFUT(set()), False)
|
||||
self.assertEqual(self._callFUT(frozenset()), False)
|
||||
self.assertEqual(self._callFUT(object()), False)
|
||||
|
||||
def test_w_normal_fields(self):
|
||||
from zope.schema import Text
|
||||
from zope.schema import Bytes
|
||||
from zope.schema import Int
|
||||
from zope.schema import Float
|
||||
from zope.schema import Decimal
|
||||
self.assertEqual(self._callFUT(Text()), True)
|
||||
self.assertEqual(self._callFUT(Bytes()), True)
|
||||
self.assertEqual(self._callFUT(Int()), True)
|
||||
self.assertEqual(self._callFUT(Float()), True)
|
||||
self.assertEqual(self._callFUT(Decimal()), True)
|
||||
|
||||
def test_w_explicitly_provided(self):
|
||||
from zope.interface import directlyProvides
|
||||
from zope.schema.interfaces import IField
|
||||
|
||||
class Foo(object):
|
||||
pass
|
||||
|
||||
foo = Foo()
|
||||
self.assertEqual(self._callFUT(foo), False)
|
||||
directlyProvides(foo, IField)
|
||||
self.assertEqual(self._callFUT(foo), True)
|
||||
|
||||
|
||||
class Test__fields(unittest.TestCase):
|
||||
|
||||
def _callFUT(self, values):
|
||||
from zope.schema.interfaces import _fields
|
||||
return _fields(values)
|
||||
|
||||
def test_empty_containers(self):
|
||||
self.assertEqual(self._callFUT(()), True)
|
||||
self.assertEqual(self._callFUT([]), True)
|
||||
|
||||
def test_w_non_fields(self):
|
||||
self.assertEqual(self._callFUT([None]), False)
|
||||
self.assertEqual(self._callFUT(['']), False)
|
||||
self.assertEqual(self._callFUT([object()]), False)
|
||||
|
||||
def test_w_fields(self):
|
||||
from zope.schema import Text
|
||||
from zope.schema import Bytes
|
||||
from zope.schema import Int
|
||||
from zope.schema import Float
|
||||
from zope.schema import Decimal
|
||||
self.assertEqual(self._callFUT([Text()]), True)
|
||||
self.assertEqual(self._callFUT([Bytes()]), True)
|
||||
self.assertEqual(self._callFUT([Int()]), True)
|
||||
self.assertEqual(self._callFUT([Float()]), True)
|
||||
self.assertEqual(self._callFUT([Decimal()]), True)
|
||||
self.assertEqual(
|
||||
self._callFUT([Text(), Bytes(), Int(), Float(), Decimal()]),
|
||||
True
|
||||
)
|
||||
|
||||
def test_w_mixed(self):
|
||||
from zope.schema import Text
|
||||
from zope.schema import Bytes
|
||||
from zope.schema import Int
|
||||
from zope.schema import Float
|
||||
from zope.schema import Decimal
|
||||
self.assertEqual(self._callFUT([Text(), 0]), False)
|
||||
self.assertEqual(
|
||||
self._callFUT([Text(), Bytes(), Int(), Float(), Decimal(), 0]),
|
||||
False
|
||||
)
|
||||
|
||||
|
||||
def test_suite():
|
||||
return unittest.TestSuite((
|
||||
unittest.makeSuite(Test__is_field),
|
||||
unittest.makeSuite(Test__fields),
|
||||
))
|
||||
276
zope/schema/tests/test_schema.py
Normal file
276
zope/schema/tests/test_schema.py
Normal file
@@ -0,0 +1,276 @@
|
||||
##############################################################################
|
||||
#
|
||||
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
|
||||
# All Rights Reserved.
|
||||
#
|
||||
# This software is subject to the provisions of the Zope Public License,
|
||||
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
|
||||
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
|
||||
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
|
||||
# FOR A PARTICULAR PURPOSE.
|
||||
#
|
||||
##############################################################################
|
||||
"""Schema field tests
|
||||
"""
|
||||
import unittest
|
||||
|
||||
|
||||
def _makeSchema():
|
||||
from zope.schema._compat import b
|
||||
from zope.schema._compat import u
|
||||
from zope.interface import Interface
|
||||
from zope.schema import Bytes
|
||||
|
||||
class ISchemaTest(Interface):
|
||||
title = Bytes(
|
||||
title=u("Title"),
|
||||
description=u("Title"),
|
||||
default=b(""),
|
||||
required=True)
|
||||
description = Bytes(
|
||||
title=u("Description"),
|
||||
description=u("Description"),
|
||||
default=b(""),
|
||||
required=True)
|
||||
spam = Bytes(
|
||||
title=u("Spam"),
|
||||
description=u("Spam"),
|
||||
default=b(""),
|
||||
required=True)
|
||||
return ISchemaTest
|
||||
|
||||
|
||||
def _makeDerivedSchema(base=None):
|
||||
from zope.schema._compat import b
|
||||
from zope.schema._compat import u
|
||||
from zope.schema import Bytes
|
||||
if base is None:
|
||||
base = _makeSchema()
|
||||
|
||||
class ISchemaTestSubclass(base):
|
||||
foo = Bytes(
|
||||
title=u('Foo'),
|
||||
description=u('Fooness'),
|
||||
default=b(""),
|
||||
required=False)
|
||||
return ISchemaTestSubclass
|
||||
|
||||
|
||||
class Test_getFields(unittest.TestCase):
|
||||
|
||||
def _callFUT(self, schema):
|
||||
from zope.schema import getFields
|
||||
return getFields(schema)
|
||||
|
||||
def test_simple(self):
|
||||
fields = self._callFUT(_makeSchema())
|
||||
|
||||
self.assertTrue('title' in fields)
|
||||
self.assertTrue('description' in fields)
|
||||
self.assertTrue('spam' in fields)
|
||||
|
||||
# test whether getName() has the right value
|
||||
for key, value in fields.items():
|
||||
self.assertEqual(key, value.getName())
|
||||
|
||||
def test_derived(self):
|
||||
fields = self._callFUT(_makeDerivedSchema())
|
||||
|
||||
self.assertTrue('title' in fields)
|
||||
self.assertTrue('description' in fields)
|
||||
self.assertTrue('spam' in fields)
|
||||
self.assertTrue('foo' in fields)
|
||||
|
||||
# test whether getName() has the right value
|
||||
for key, value in fields.items():
|
||||
self.assertEqual(key, value.getName())
|
||||
|
||||
|
||||
class Test_getFieldsInOrder(unittest.TestCase):
|
||||
|
||||
def _callFUT(self, schema):
|
||||
from zope.schema import getFieldsInOrder
|
||||
return getFieldsInOrder(schema)
|
||||
|
||||
def test_simple(self):
|
||||
fields = self._callFUT(_makeSchema())
|
||||
field_names = [name for name, field in fields]
|
||||
self.assertEqual(field_names, ['title', 'description', 'spam'])
|
||||
for key, value in fields:
|
||||
self.assertEqual(key, value.getName())
|
||||
|
||||
def test_derived(self):
|
||||
fields = self._callFUT(_makeDerivedSchema())
|
||||
field_names = [name for name, field in fields]
|
||||
self.assertEqual(field_names, ['title', 'description', 'spam', 'foo'])
|
||||
for key, value in fields:
|
||||
self.assertEqual(key, value.getName())
|
||||
|
||||
|
||||
class Test_getFieldNames(unittest.TestCase):
|
||||
|
||||
def _callFUT(self, schema):
|
||||
from zope.schema import getFieldNames
|
||||
return getFieldNames(schema)
|
||||
|
||||
def test_simple(self):
|
||||
names = self._callFUT(_makeSchema())
|
||||
self.assertEqual(len(names), 3)
|
||||
self.assertTrue('title' in names)
|
||||
self.assertTrue('description' in names)
|
||||
self.assertTrue('spam' in names)
|
||||
|
||||
def test_derived(self):
|
||||
names = self._callFUT(_makeDerivedSchema())
|
||||
self.assertEqual(len(names), 4)
|
||||
self.assertTrue('title' in names)
|
||||
self.assertTrue('description' in names)
|
||||
self.assertTrue('spam' in names)
|
||||
self.assertTrue('foo' in names)
|
||||
|
||||
|
||||
class Test_getFieldNamesInOrder(unittest.TestCase):
|
||||
|
||||
def _callFUT(self, schema):
|
||||
from zope.schema import getFieldNamesInOrder
|
||||
return getFieldNamesInOrder(schema)
|
||||
|
||||
def test_simple(self):
|
||||
names = self._callFUT(_makeSchema())
|
||||
self.assertEqual(names, ['title', 'description', 'spam'])
|
||||
|
||||
def test_derived(self):
|
||||
names = self._callFUT(_makeDerivedSchema())
|
||||
self.assertEqual(names, ['title', 'description', 'spam', 'foo'])
|
||||
|
||||
|
||||
class Test_getValidationErrors(unittest.TestCase):
|
||||
|
||||
def _callFUT(self, schema, object):
|
||||
from zope.schema import getValidationErrors
|
||||
return getValidationErrors(schema, object)
|
||||
|
||||
def test_schema(self):
|
||||
from zope.interface import Interface
|
||||
|
||||
class IEmpty(Interface):
|
||||
pass
|
||||
|
||||
errors = self._callFUT(IEmpty, object())
|
||||
self.assertEqual(len(errors), 0)
|
||||
|
||||
def test_schema_with_field_errors(self):
|
||||
from zope.interface import Interface
|
||||
from zope.schema import Text
|
||||
from zope.schema.interfaces import SchemaNotFullyImplemented
|
||||
|
||||
class IWithRequired(Interface):
|
||||
must = Text(required=True)
|
||||
|
||||
errors = self._callFUT(IWithRequired, object())
|
||||
self.assertEqual(len(errors), 1)
|
||||
self.assertEqual(errors[0][0], 'must')
|
||||
self.assertEqual(errors[0][1].__class__, SchemaNotFullyImplemented)
|
||||
|
||||
def test_schema_with_invariant_errors(self):
|
||||
from zope.interface import Interface
|
||||
from zope.interface import invariant
|
||||
from zope.interface.exceptions import Invalid
|
||||
|
||||
class IWithFailingInvariant(Interface):
|
||||
@invariant
|
||||
def _epic_fail(obj):
|
||||
raise Invalid('testing')
|
||||
|
||||
errors = self._callFUT(IWithFailingInvariant, object())
|
||||
self.assertEqual(len(errors), 1)
|
||||
self.assertEqual(errors[0][0], None)
|
||||
self.assertEqual(errors[0][1].__class__, Invalid)
|
||||
|
||||
def test_schema_with_invariant_ok(self):
|
||||
from zope.interface import Interface
|
||||
from zope.interface import invariant
|
||||
|
||||
class IWithPassingInvariant(Interface):
|
||||
@invariant
|
||||
def _hall_pass(obj):
|
||||
pass
|
||||
|
||||
errors = self._callFUT(IWithPassingInvariant, object())
|
||||
self.assertEqual(len(errors), 0)
|
||||
|
||||
|
||||
class Test_getSchemaValidationErrors(unittest.TestCase):
|
||||
|
||||
def _callFUT(self, schema, object):
|
||||
from zope.schema import getSchemaValidationErrors
|
||||
return getSchemaValidationErrors(schema, object)
|
||||
|
||||
def test_schema_wo_fields(self):
|
||||
from zope.interface import Interface
|
||||
from zope.interface import Attribute
|
||||
|
||||
class INoFields(Interface):
|
||||
def method():
|
||||
pass
|
||||
attr = Attribute('ignoreme')
|
||||
|
||||
errors = self._callFUT(INoFields, object())
|
||||
self.assertEqual(len(errors), 0)
|
||||
|
||||
def test_schema_with_fields_ok(self):
|
||||
from zope.interface import Interface
|
||||
from zope.schema import Text
|
||||
from zope.schema._compat import u
|
||||
|
||||
class IWithFields(Interface):
|
||||
foo = Text()
|
||||
bar = Text()
|
||||
|
||||
class Obj(object):
|
||||
foo = u('Foo')
|
||||
bar = u('Bar')
|
||||
|
||||
errors = self._callFUT(IWithFields, Obj())
|
||||
self.assertEqual(len(errors), 0)
|
||||
|
||||
def test_schema_with_missing_field(self):
|
||||
from zope.interface import Interface
|
||||
from zope.schema import Text
|
||||
from zope.schema.interfaces import SchemaNotFullyImplemented
|
||||
|
||||
class IWithRequired(Interface):
|
||||
must = Text(required=True)
|
||||
|
||||
errors = self._callFUT(IWithRequired, object())
|
||||
self.assertEqual(len(errors), 1)
|
||||
self.assertEqual(errors[0][0], 'must')
|
||||
self.assertEqual(errors[0][1].__class__, SchemaNotFullyImplemented)
|
||||
|
||||
def test_schema_with_invalid_field(self):
|
||||
from zope.interface import Interface
|
||||
from zope.schema import Int
|
||||
from zope.schema.interfaces import TooSmall
|
||||
|
||||
class IWithMinium(Interface):
|
||||
value = Int(required=True, min=0)
|
||||
|
||||
class Obj(object):
|
||||
value = -1
|
||||
|
||||
errors = self._callFUT(IWithMinium, Obj())
|
||||
self.assertEqual(len(errors), 1)
|
||||
self.assertEqual(errors[0][0], 'value')
|
||||
self.assertEqual(errors[0][1].__class__, TooSmall)
|
||||
|
||||
|
||||
def test_suite():
|
||||
return unittest.TestSuite((
|
||||
unittest.makeSuite(Test_getFields),
|
||||
unittest.makeSuite(Test_getFieldsInOrder),
|
||||
unittest.makeSuite(Test_getFieldNames),
|
||||
unittest.makeSuite(Test_getFieldNamesInOrder),
|
||||
unittest.makeSuite(Test_getValidationErrors),
|
||||
unittest.makeSuite(Test_getSchemaValidationErrors),
|
||||
))
|
||||
106
zope/schema/tests/test_states.py
Normal file
106
zope/schema/tests/test_states.py
Normal file
@@ -0,0 +1,106 @@
|
||||
##############################################################################
|
||||
#
|
||||
# Copyright (c) 2003 Zope Foundation and Contributors.
|
||||
# All Rights Reserved.
|
||||
#
|
||||
# This software is subject to the provisions of the Zope Public License,
|
||||
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
|
||||
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
|
||||
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
|
||||
# FOR A PARTICULAR PURPOSE.
|
||||
#
|
||||
##############################################################################
|
||||
"""Tests of the states example.
|
||||
"""
|
||||
import unittest
|
||||
|
||||
|
||||
class StateSelectionTest(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
from zope.schema.vocabulary import _clear
|
||||
from zope.schema.vocabulary import getVocabularyRegistry
|
||||
from zope.schema.tests.states import StateVocabulary
|
||||
_clear()
|
||||
vr = getVocabularyRegistry()
|
||||
vr.register("states", StateVocabulary)
|
||||
|
||||
def tearDown(self):
|
||||
from zope.schema.vocabulary import _clear
|
||||
_clear()
|
||||
|
||||
def _makeSchema(self):
|
||||
from zope.schema._compat import u
|
||||
from zope.interface import Interface
|
||||
from zope.schema import Choice
|
||||
from zope.schema.tests.states import StateVocabulary
|
||||
|
||||
class IBirthInfo(Interface):
|
||||
state1 = Choice(
|
||||
title=u('State of Birth'),
|
||||
description=u('The state in which you were born.'),
|
||||
vocabulary="states",
|
||||
default="AL",
|
||||
)
|
||||
state2 = Choice(
|
||||
title=u('State of Birth'),
|
||||
description=u('The state in which you were born.'),
|
||||
vocabulary="states",
|
||||
default="AL",
|
||||
)
|
||||
state3 = Choice(
|
||||
title=u('Favorite State'),
|
||||
description=u('The state you like the most.'),
|
||||
vocabulary=StateVocabulary(),
|
||||
)
|
||||
state4 = Choice(
|
||||
title=u("Name"),
|
||||
description=u("The name of your new state"),
|
||||
vocabulary="states",
|
||||
)
|
||||
return IBirthInfo
|
||||
|
||||
def test_default_presentation(self):
|
||||
from zope.interface.verify import verifyObject
|
||||
from zope.schema.interfaces import IVocabulary
|
||||
schema = self._makeSchema()
|
||||
field = schema.getDescriptionFor("state1")
|
||||
bound = field.bind(object())
|
||||
self.assertTrue(verifyObject(IVocabulary, bound.vocabulary))
|
||||
self.assertEqual(bound.vocabulary.getTerm("VA").title, "Virginia")
|
||||
|
||||
def test_contains(self):
|
||||
from zope.interface.verify import verifyObject
|
||||
from zope.schema.interfaces import IVocabulary
|
||||
from zope.schema.tests.states import StateVocabulary
|
||||
vocab = StateVocabulary()
|
||||
self.assertTrue(verifyObject(IVocabulary, vocab))
|
||||
count = 0
|
||||
L = list(vocab)
|
||||
for term in L:
|
||||
count += 1
|
||||
self.assertTrue(term.value in vocab)
|
||||
self.assertEqual(count, len(vocab))
|
||||
# make sure we get the same values the second time around:
|
||||
L = [term.value for term in L]
|
||||
L.sort()
|
||||
L2 = [term.value for term in vocab]
|
||||
L2.sort()
|
||||
self.assertEqual(L, L2)
|
||||
|
||||
def test_prebound_vocabulary(self):
|
||||
from zope.interface.verify import verifyObject
|
||||
from zope.schema.interfaces import IVocabulary
|
||||
schema = self._makeSchema()
|
||||
field = schema.getDescriptionFor("state3")
|
||||
bound = field.bind(None)
|
||||
self.assertTrue(bound.vocabularyName is None)
|
||||
self.assertTrue(verifyObject(IVocabulary, bound.vocabulary))
|
||||
self.assertTrue("AL" in bound.vocabulary)
|
||||
|
||||
|
||||
def test_suite():
|
||||
return unittest.TestSuite((
|
||||
unittest.makeSuite(StateSelectionTest),
|
||||
))
|
||||
642
zope/schema/tests/test_vocabulary.py
Normal file
642
zope/schema/tests/test_vocabulary.py
Normal file
@@ -0,0 +1,642 @@
|
||||
##############################################################################
|
||||
#
|
||||
# Copyright (c) 2003 Zope Foundation and Contributors.
|
||||
# All Rights Reserved.
|
||||
#
|
||||
# This software is subject to the provisions of the Zope Public License,
|
||||
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
|
||||
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
|
||||
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
|
||||
# FOR A PARTICULAR PURPOSE.
|
||||
#
|
||||
##############################################################################
|
||||
"""Test of the Vocabulary and related support APIs.
|
||||
"""
|
||||
import unittest
|
||||
|
||||
|
||||
class SimpleTermTests(unittest.TestCase):
|
||||
|
||||
def _getTargetClass(self):
|
||||
from zope.schema.vocabulary import SimpleTerm
|
||||
return SimpleTerm
|
||||
|
||||
def _makeOne(self, *args, **kw):
|
||||
return self._getTargetClass()(*args, **kw)
|
||||
|
||||
def test_class_conforms_to_ITokenizedTerm(self):
|
||||
from zope.interface.verify import verifyClass
|
||||
from zope.schema.interfaces import ITokenizedTerm
|
||||
verifyClass(ITokenizedTerm, self._getTargetClass())
|
||||
|
||||
def test_instance_conforms_to_ITokenizedTerm(self):
|
||||
from zope.interface.verify import verifyObject
|
||||
from zope.schema.interfaces import ITokenizedTerm
|
||||
verifyObject(ITokenizedTerm, self._makeOne('VALUE'))
|
||||
|
||||
def test_ctor_defaults(self):
|
||||
from zope.schema.interfaces import ITitledTokenizedTerm
|
||||
term = self._makeOne('VALUE')
|
||||
self.assertEqual(term.value, 'VALUE')
|
||||
self.assertEqual(term.token, 'VALUE')
|
||||
self.assertEqual(term.title, None)
|
||||
self.assertFalse(ITitledTokenizedTerm.providedBy(term))
|
||||
|
||||
def test_ctor_explicit(self):
|
||||
from zope.schema.interfaces import ITitledTokenizedTerm
|
||||
term = self._makeOne('TERM', 'TOKEN', 'TITLE')
|
||||
self.assertEqual(term.value, 'TERM')
|
||||
self.assertEqual(term.token, 'TOKEN')
|
||||
self.assertEqual(term.title, 'TITLE')
|
||||
self.assertTrue(ITitledTokenizedTerm.providedBy(term))
|
||||
|
||||
def test_bytes_value(self):
|
||||
from zope.schema.interfaces import ITitledTokenizedTerm
|
||||
term = self._makeOne(b'term')
|
||||
self.assertEqual(term.value, b'term')
|
||||
self.assertEqual(term.token, 'term')
|
||||
self.assertFalse(ITitledTokenizedTerm.providedBy(term))
|
||||
|
||||
|
||||
class SimpleVocabularyTests(unittest.TestCase):
|
||||
|
||||
def _getTargetClass(self):
|
||||
from zope.schema.vocabulary import SimpleVocabulary
|
||||
return SimpleVocabulary
|
||||
|
||||
def _makeOne(self, *args, **kw):
|
||||
return self._getTargetClass()(*args, **kw)
|
||||
|
||||
def test_class_conforms_to_IVocabularyTokenized(self):
|
||||
from zope.interface.verify import verifyClass
|
||||
from zope.schema.interfaces import IVocabularyTokenized
|
||||
verifyClass(IVocabularyTokenized, self._getTargetClass())
|
||||
|
||||
def test_instance_conforms_to_IVocabularyTokenized(self):
|
||||
from zope.interface.verify import verifyObject
|
||||
from zope.schema.interfaces import IVocabularyTokenized
|
||||
verifyObject(IVocabularyTokenized, self._makeOne(()))
|
||||
|
||||
def test_ctor_additional_interfaces(self):
|
||||
from zope.interface import Interface
|
||||
from zope.schema.vocabulary import SimpleTerm
|
||||
|
||||
class IStupid(Interface):
|
||||
pass
|
||||
|
||||
VALUES = [1, 4, 2, 9]
|
||||
vocabulary = self._makeOne([SimpleTerm(x) for x in VALUES], IStupid)
|
||||
self.assertTrue(IStupid.providedBy(vocabulary))
|
||||
self.assertEqual(len(vocabulary), len(VALUES))
|
||||
for value, term in zip(VALUES, vocabulary):
|
||||
self.assertEqual(term.value, value)
|
||||
for value in VALUES:
|
||||
self.assertTrue(value in vocabulary)
|
||||
self.assertFalse('ABC' in vocabulary)
|
||||
for term in vocabulary:
|
||||
self.assertTrue(vocabulary.getTerm(term.value) is term)
|
||||
self.assertTrue(vocabulary.getTermByToken(term.token) is term)
|
||||
|
||||
def test_fromValues(self):
|
||||
from zope.interface import Interface
|
||||
from zope.schema.interfaces import ITokenizedTerm
|
||||
|
||||
class IStupid(Interface):
|
||||
pass
|
||||
|
||||
VALUES = [1, 4, 2, 9]
|
||||
vocabulary = self._getTargetClass().fromValues(VALUES)
|
||||
self.assertEqual(len(vocabulary), len(VALUES))
|
||||
for value, term in zip(VALUES, vocabulary):
|
||||
self.assertTrue(ITokenizedTerm.providedBy(term))
|
||||
self.assertEqual(term.value, value)
|
||||
for value in VALUES:
|
||||
self.assertTrue(value in vocabulary)
|
||||
|
||||
def test_fromItems(self):
|
||||
from zope.interface import Interface
|
||||
from zope.schema.interfaces import ITokenizedTerm
|
||||
|
||||
class IStupid(Interface):
|
||||
pass
|
||||
|
||||
ITEMS = [('one', 1), ('two', 2), ('three', 3), ('fore!', 4)]
|
||||
vocabulary = self._getTargetClass().fromItems(ITEMS)
|
||||
self.assertEqual(len(vocabulary), len(ITEMS))
|
||||
for item, term in zip(ITEMS, vocabulary):
|
||||
self.assertTrue(ITokenizedTerm.providedBy(term))
|
||||
self.assertEqual(term.token, item[0])
|
||||
self.assertEqual(term.value, item[1])
|
||||
for item in ITEMS:
|
||||
self.assertTrue(item[1] in vocabulary)
|
||||
|
||||
def test_createTerm(self):
|
||||
from zope.schema.vocabulary import SimpleTerm
|
||||
VALUES = [1, 4, 2, 9]
|
||||
for value in VALUES:
|
||||
term = self._getTargetClass().createTerm(value)
|
||||
self.assertTrue(isinstance(term, SimpleTerm))
|
||||
self.assertEqual(term.value, value)
|
||||
self.assertEqual(term.token, str(value))
|
||||
|
||||
def test_getTerm_miss(self):
|
||||
vocabulary = self._makeOne(())
|
||||
self.assertRaises(LookupError, vocabulary.getTerm, 'nonesuch')
|
||||
|
||||
def test_getTermByToken_miss(self):
|
||||
vocabulary = self._makeOne(())
|
||||
self.assertRaises(LookupError, vocabulary.getTermByToken, 'nonesuch')
|
||||
|
||||
def test_nonunique_tokens(self):
|
||||
klass = self._getTargetClass()
|
||||
self.assertRaises(ValueError, klass.fromValues, [2, '2'])
|
||||
self.assertRaises(
|
||||
ValueError,
|
||||
klass.fromItems,
|
||||
[(1, 'one'), ('1', 'another one')]
|
||||
)
|
||||
self.assertRaises(
|
||||
ValueError,
|
||||
klass.fromItems,
|
||||
[(0, 'one'), (1, 'one')]
|
||||
)
|
||||
|
||||
def test_nonunique_tokens_swallow(self):
|
||||
klass = self._getTargetClass()
|
||||
items = [(0, 'one'), (1, 'one')]
|
||||
terms = [klass.createTerm(value, token) for (token, value) in items]
|
||||
vocab = self._getTargetClass()(terms, swallow_duplicates=True)
|
||||
self.assertEqual(vocab.getTerm('one').token, '1')
|
||||
|
||||
def test_nonunique_token_message(self):
|
||||
try:
|
||||
self._getTargetClass().fromValues([2, '2'])
|
||||
except ValueError as e:
|
||||
self.assertEqual(str(e), "term tokens must be unique: '2'")
|
||||
|
||||
def test_nonunique_token_messages(self):
|
||||
try:
|
||||
self._getTargetClass().fromItems([(0, 'one'), (1, 'one')])
|
||||
except ValueError as e:
|
||||
self.assertEqual(str(e), "term values must be unique: 'one'")
|
||||
|
||||
def test_overriding_createTerm(self):
|
||||
class MyTerm(object):
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
self.token = repr(value)
|
||||
self.nextvalue = value + 1
|
||||
|
||||
class MyVocabulary(self._getTargetClass()):
|
||||
def createTerm(cls, value):
|
||||
return MyTerm(value)
|
||||
createTerm = classmethod(createTerm)
|
||||
|
||||
vocab = MyVocabulary.fromValues([1, 2, 3])
|
||||
for term in vocab:
|
||||
self.assertEqual(term.value + 1, term.nextvalue)
|
||||
|
||||
|
||||
# Test _createTermTree via TreeVocabulary.fromDict
|
||||
|
||||
|
||||
class TreeVocabularyTests(unittest.TestCase):
|
||||
|
||||
def _getTargetClass(self):
|
||||
from zope.schema.vocabulary import TreeVocabulary
|
||||
return TreeVocabulary
|
||||
|
||||
def tree_vocab_2(self):
|
||||
region_tree = {
|
||||
('regions', 'Regions'): {
|
||||
('aut', 'Austria'): {
|
||||
('tyr', 'Tyrol'): {
|
||||
('auss', 'Ausserfern'): {},
|
||||
}
|
||||
},
|
||||
('ger', 'Germany'): {
|
||||
('bav', 'Bavaria'): {}
|
||||
},
|
||||
}
|
||||
}
|
||||
return self._getTargetClass().fromDict(region_tree)
|
||||
|
||||
def business_tree(self):
|
||||
return {
|
||||
('services', 'services', 'Services'): {
|
||||
('reservations', 'reservations', 'Reservations'): {
|
||||
('res_host', 'res_host', 'Res Host'): {},
|
||||
('res_gui', 'res_gui', 'Res GUI'): {},
|
||||
},
|
||||
('check_in', 'check_in', 'Check-in'): {
|
||||
('dcs_host', 'dcs_host', 'DCS Host'): {},
|
||||
},
|
||||
},
|
||||
('infrastructure', 'infrastructure', 'Infrastructure'): {
|
||||
('communication_network', 'communication_network',
|
||||
'Communication/Network'): {
|
||||
('messaging', 'messaging', 'Messaging'): {},
|
||||
},
|
||||
('data_transaction', 'data_transaction',
|
||||
'Data/Transaction'): {
|
||||
('database', 'database', 'Database'): {},
|
||||
},
|
||||
('security', 'security', 'Security'): {},
|
||||
},
|
||||
}
|
||||
|
||||
def tree_vocab_3(self):
|
||||
return self._getTargetClass().fromDict(self.business_tree())
|
||||
|
||||
def test_implementation(self):
|
||||
from zope.interface.verify import verifyObject
|
||||
from zope.interface.common.mapping import IEnumerableMapping
|
||||
from zope.schema.interfaces import ITreeVocabulary
|
||||
from zope.schema.interfaces import IVocabulary
|
||||
from zope.schema.interfaces import IVocabularyTokenized
|
||||
for v in [self.tree_vocab_2(), self.tree_vocab_3()]:
|
||||
self.assertTrue(verifyObject(IEnumerableMapping, v))
|
||||
self.assertTrue(verifyObject(IVocabulary, v))
|
||||
self.assertTrue(verifyObject(IVocabularyTokenized, v))
|
||||
self.assertTrue(verifyObject(ITreeVocabulary, v))
|
||||
|
||||
def test_additional_interfaces(self):
|
||||
from zope.interface import Interface
|
||||
|
||||
class IStupid(Interface):
|
||||
pass
|
||||
|
||||
v = self._getTargetClass().fromDict({('one', '1'): {}}, IStupid)
|
||||
self.assertTrue(IStupid.providedBy(v))
|
||||
|
||||
def test_ordering(self):
|
||||
#The TreeVocabulary makes use of an OrderedDict to store it's
|
||||
#internal tree representation.
|
||||
#
|
||||
#Check that they keys are indeed oredered.
|
||||
from zope.schema._compat import OrderedDict
|
||||
|
||||
d = {
|
||||
(1, 'new_york', 'New York'): {
|
||||
(2, 'ny_albany', 'Albany'): {},
|
||||
(3, 'ny_new_york', 'New York'): {},
|
||||
},
|
||||
(4, 'california', 'California'): {
|
||||
(5, 'ca_los_angeles', 'Los Angeles'): {},
|
||||
(6, 'ca_san_francisco', 'San Francisco'): {},
|
||||
},
|
||||
(7, 'texas', 'Texas'): {},
|
||||
(8, 'florida', 'Florida'): {},
|
||||
(9, 'utah', 'Utah'): {},
|
||||
}
|
||||
dict_ = OrderedDict(sorted(d.items(), key=lambda t: t[0]))
|
||||
vocab = self._getTargetClass().fromDict(dict_)
|
||||
# Test keys
|
||||
self.assertEqual(
|
||||
[k.token for k in vocab.keys()],
|
||||
['1', '4', '7', '8', '9']
|
||||
)
|
||||
# Test __iter__
|
||||
self.assertEqual(
|
||||
[k.token for k in vocab],
|
||||
['1', '4', '7', '8', '9']
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
[k.token for k in vocab[[k for k in vocab.keys()][0]].keys()],
|
||||
['2', '3']
|
||||
)
|
||||
self.assertEqual(
|
||||
[k.token for k in vocab[[k for k in vocab.keys()][1]].keys()],
|
||||
['5', '6']
|
||||
)
|
||||
|
||||
def test_indexes(self):
|
||||
# TreeVocabulary creates three indexes for quick lookups,
|
||||
# term_by_value, term_by_value and path_by_value.
|
||||
tv2 = self.tree_vocab_2()
|
||||
self.assertEqual(
|
||||
[k for k in sorted(tv2.term_by_value.keys())],
|
||||
['Ausserfern', 'Austria', 'Bavaria', 'Germany', 'Regions', 'Tyrol']
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
[k for k in sorted(tv2.term_by_token.keys())],
|
||||
['auss', 'aut', 'bav', 'ger', 'regions', 'tyr']
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
[k for k in sorted(tv2.path_by_value.keys())],
|
||||
['Ausserfern', 'Austria', 'Bavaria', 'Germany', 'Regions', 'Tyrol']
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
[k for k in sorted(tv2.path_by_value.values())],
|
||||
[
|
||||
['Regions'],
|
||||
['Regions', 'Austria'],
|
||||
['Regions', 'Austria', 'Tyrol'],
|
||||
['Regions', 'Austria', 'Tyrol', 'Ausserfern'],
|
||||
['Regions', 'Germany'],
|
||||
['Regions', 'Germany', 'Bavaria'],
|
||||
]
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
[k for k in sorted(self.tree_vocab_3().term_by_value.keys())],
|
||||
[
|
||||
'check_in',
|
||||
'communication_network',
|
||||
'data_transaction',
|
||||
'database',
|
||||
'dcs_host',
|
||||
'infrastructure',
|
||||
'messaging',
|
||||
'res_gui',
|
||||
'res_host',
|
||||
'reservations',
|
||||
'security',
|
||||
'services',
|
||||
]
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
[k for k in sorted(self.tree_vocab_3().term_by_token.keys())],
|
||||
[
|
||||
'check_in',
|
||||
'communication_network',
|
||||
'data_transaction',
|
||||
'database',
|
||||
'dcs_host',
|
||||
'infrastructure',
|
||||
'messaging',
|
||||
'res_gui',
|
||||
'res_host',
|
||||
'reservations',
|
||||
'security',
|
||||
'services',
|
||||
]
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
[k for k in sorted(self.tree_vocab_3().path_by_value.values())],
|
||||
[
|
||||
['infrastructure'],
|
||||
['infrastructure', 'communication_network'],
|
||||
['infrastructure', 'communication_network', 'messaging'],
|
||||
['infrastructure', 'data_transaction'],
|
||||
['infrastructure', 'data_transaction', 'database'],
|
||||
['infrastructure', 'security'],
|
||||
['services'],
|
||||
['services', 'check_in'],
|
||||
['services', 'check_in', 'dcs_host'],
|
||||
['services', 'reservations'],
|
||||
['services', 'reservations', 'res_gui'],
|
||||
['services', 'reservations', 'res_host'],
|
||||
]
|
||||
)
|
||||
|
||||
def test_termpath(self):
|
||||
tv2 = self.tree_vocab_2()
|
||||
tv3 = self.tree_vocab_3()
|
||||
self.assertEqual(
|
||||
tv2.getTermPath('Bavaria'),
|
||||
['Regions', 'Germany', 'Bavaria']
|
||||
)
|
||||
self.assertEqual(
|
||||
tv2.getTermPath('Austria'),
|
||||
['Regions', 'Austria']
|
||||
)
|
||||
self.assertEqual(
|
||||
tv2.getTermPath('Ausserfern'),
|
||||
['Regions', 'Austria', 'Tyrol', 'Ausserfern']
|
||||
)
|
||||
self.assertEqual(
|
||||
tv2.getTermPath('Non-existent'),
|
||||
[]
|
||||
)
|
||||
self.assertEqual(
|
||||
tv3.getTermPath('database'),
|
||||
["infrastructure", "data_transaction", "database"]
|
||||
)
|
||||
|
||||
def test_len(self):
|
||||
# len returns the number of all nodes in the dict
|
||||
self.assertEqual(len(self.tree_vocab_2()), 1)
|
||||
self.assertEqual(len(self.tree_vocab_3()), 2)
|
||||
|
||||
def test_contains(self):
|
||||
tv2 = self.tree_vocab_2()
|
||||
self.assertTrue('Regions' in tv2 and
|
||||
'Austria' in tv2 and
|
||||
'Bavaria' in tv2)
|
||||
|
||||
self.assertTrue('bav' not in tv2)
|
||||
self.assertTrue('foo' not in tv2)
|
||||
self.assertTrue({} not in tv2) # not hashable
|
||||
|
||||
tv3 = self.tree_vocab_3()
|
||||
self.assertTrue('database' in tv3 and
|
||||
'security' in tv3 and
|
||||
'services' in tv3)
|
||||
|
||||
self.assertTrue('Services' not in tv3)
|
||||
self.assertTrue('Database' not in tv3)
|
||||
self.assertTrue({} not in tv3) # not hashable
|
||||
|
||||
def test_values_and_items(self):
|
||||
for v in (self.tree_vocab_2(), self.tree_vocab_3()):
|
||||
for term in v:
|
||||
self.assertEqual([i for i in v.values()],
|
||||
[i for i in v._terms.values()])
|
||||
self.assertEqual([i for i in v.items()],
|
||||
[i for i in v._terms.items()])
|
||||
|
||||
def test_get(self):
|
||||
for v in [self.tree_vocab_2(), self.tree_vocab_3()]:
|
||||
for key, value in v.items():
|
||||
self.assertEqual(v.get(key), value)
|
||||
self.assertEqual(v[key], value)
|
||||
|
||||
def test_get_term(self):
|
||||
for v in (self.tree_vocab_2(), self.tree_vocab_3()):
|
||||
for term in v:
|
||||
self.assertTrue(v.getTerm(term.value) is term)
|
||||
self.assertTrue(v.getTermByToken(term.token) is term)
|
||||
self.assertRaises(LookupError, v.getTerm, 'non-present-value')
|
||||
self.assertRaises(LookupError,
|
||||
v.getTermByToken, 'non-present-token')
|
||||
|
||||
def test_nonunique_values_and_tokens(self):
|
||||
# Since we do term and value lookups, all terms' values and tokens
|
||||
# must be unique. This rule applies recursively.
|
||||
self.assertRaises(
|
||||
ValueError, self._getTargetClass().fromDict,
|
||||
{
|
||||
('one', '1'): {},
|
||||
('two', '1'): {},
|
||||
})
|
||||
self.assertRaises(
|
||||
ValueError, self._getTargetClass().fromDict,
|
||||
{
|
||||
('one', '1'): {},
|
||||
('one', '2'): {},
|
||||
})
|
||||
# Even nested tokens must be unique.
|
||||
self.assertRaises(
|
||||
ValueError, self._getTargetClass().fromDict,
|
||||
{
|
||||
('new_york', 'New York'): {
|
||||
('albany', 'Albany'): {},
|
||||
('new_york', 'New York'): {},
|
||||
},
|
||||
})
|
||||
# The same applies to nested values.
|
||||
self.assertRaises(
|
||||
ValueError, self._getTargetClass().fromDict,
|
||||
{
|
||||
('1', 'new_york'): {
|
||||
('2', 'albany'): {},
|
||||
('3', 'new_york'): {},
|
||||
},
|
||||
})
|
||||
# The title attribute does however not have to be unique.
|
||||
self._getTargetClass().fromDict({
|
||||
('1', 'new_york', 'New York'): {
|
||||
('2', 'ny_albany', 'Albany'): {},
|
||||
('3', 'ny_new_york', 'New York'): {},
|
||||
},
|
||||
})
|
||||
self._getTargetClass().fromDict({
|
||||
('one', '1', 'One'): {},
|
||||
('two', '2', 'One'): {},
|
||||
})
|
||||
|
||||
def test_nonunique_value_message(self):
|
||||
try:
|
||||
self._getTargetClass().fromDict({
|
||||
('one', '1'): {},
|
||||
('two', '1'): {},
|
||||
})
|
||||
except ValueError as e:
|
||||
self.assertEqual(str(e), "Term values must be unique: '1'")
|
||||
|
||||
def test_nonunique_token_message(self):
|
||||
try:
|
||||
self._getTargetClass().fromDict({
|
||||
('one', '1'): {},
|
||||
('one', '2'): {},
|
||||
})
|
||||
except ValueError as e:
|
||||
self.assertEqual(str(e), "Term tokens must be unique: 'one'")
|
||||
|
||||
def test_recursive_methods(self):
|
||||
#Test the _createTermTree and _getPathToTreeNode methods
|
||||
from zope.schema.vocabulary import _createTermTree
|
||||
tree = _createTermTree({}, self.business_tree())
|
||||
vocab = self._getTargetClass().fromDict(self.business_tree())
|
||||
|
||||
term_path = vocab._getPathToTreeNode(tree, "infrastructure")
|
||||
vocab_path = vocab._getPathToTreeNode(vocab, "infrastructure")
|
||||
self.assertEqual(term_path, vocab_path)
|
||||
self.assertEqual(term_path, ["infrastructure"])
|
||||
|
||||
term_path = vocab._getPathToTreeNode(tree, "security")
|
||||
vocab_path = vocab._getPathToTreeNode(vocab, "security")
|
||||
self.assertEqual(term_path, vocab_path)
|
||||
self.assertEqual(term_path, ["infrastructure", "security"])
|
||||
|
||||
term_path = vocab._getPathToTreeNode(tree, "database")
|
||||
vocab_path = vocab._getPathToTreeNode(vocab, "database")
|
||||
self.assertEqual(term_path, vocab_path)
|
||||
self.assertEqual(term_path,
|
||||
["infrastructure", "data_transaction", "database"])
|
||||
|
||||
term_path = vocab._getPathToTreeNode(tree, "dcs_host")
|
||||
vocab_path = vocab._getPathToTreeNode(vocab, "dcs_host")
|
||||
self.assertEqual(term_path, vocab_path)
|
||||
self.assertEqual(term_path, ["services", "check_in", "dcs_host"])
|
||||
|
||||
term_path = vocab._getPathToTreeNode(tree, "dummy")
|
||||
vocab_path = vocab._getPathToTreeNode(vocab, "dummy")
|
||||
self.assertEqual(term_path, vocab_path)
|
||||
self.assertEqual(term_path, [])
|
||||
|
||||
|
||||
class RegistryTests(unittest.TestCase):
|
||||
#Tests of the simple vocabulary and presentation registries.
|
||||
|
||||
def setUp(self):
|
||||
from zope.schema.vocabulary import _clear
|
||||
_clear()
|
||||
|
||||
def tearDown(self):
|
||||
from zope.schema.vocabulary import _clear
|
||||
_clear()
|
||||
|
||||
def test_setVocabularyRegistry(self):
|
||||
from zope.schema.vocabulary import setVocabularyRegistry
|
||||
from zope.schema.vocabulary import getVocabularyRegistry
|
||||
r = _makeDummyRegistry()
|
||||
setVocabularyRegistry(r)
|
||||
self.assertTrue(getVocabularyRegistry() is r)
|
||||
|
||||
def test_getVocabularyRegistry(self):
|
||||
from zope.schema.interfaces import IVocabularyRegistry
|
||||
from zope.schema.vocabulary import getVocabularyRegistry
|
||||
r = getVocabularyRegistry()
|
||||
self.assertTrue(IVocabularyRegistry.providedBy(r))
|
||||
|
||||
# TODO: still need to test the default implementation
|
||||
|
||||
|
||||
def _makeSampleVocabulary():
|
||||
from zope.interface import implementer
|
||||
from zope.schema.interfaces import IVocabulary
|
||||
|
||||
class SampleTerm(object):
|
||||
pass
|
||||
|
||||
@implementer(IVocabulary)
|
||||
class SampleVocabulary(object):
|
||||
|
||||
def __iter__(self):
|
||||
return iter([self.getTerm(x) for x in range(0, 10)])
|
||||
|
||||
def __contains__(self, value):
|
||||
return 0 <= value < 10
|
||||
|
||||
def __len__(self):
|
||||
return 10
|
||||
|
||||
def getTerm(self, value):
|
||||
if value in self:
|
||||
t = SampleTerm()
|
||||
t.value = value
|
||||
t.double = 2 * value
|
||||
return t
|
||||
raise LookupError("no such value: %r" % value)
|
||||
|
||||
return SampleVocabulary()
|
||||
|
||||
|
||||
def _makeDummyRegistry():
|
||||
from zope.schema.vocabulary import VocabularyRegistry
|
||||
|
||||
class DummyRegistry(VocabularyRegistry):
|
||||
def get(self, object, name):
|
||||
v = _makeSampleVocabulary()
|
||||
v.object = object
|
||||
v.name = name
|
||||
return v
|
||||
return DummyRegistry()
|
||||
|
||||
|
||||
def test_suite():
|
||||
return unittest.TestSuite((
|
||||
unittest.makeSuite(SimpleTermTests),
|
||||
unittest.makeSuite(SimpleVocabularyTests),
|
||||
unittest.makeSuite(TreeVocabularyTests),
|
||||
unittest.makeSuite(RegistryTests),
|
||||
))
|
||||
Reference in New Issue
Block a user