[Zope3-checkins] CVS: Zope3/src/zope/schema/tests - states.py:1.1.2.1 tabcomplete.py:1.1.2.1 test_states.py:1.1.2.1 test_tabcomplete.py:1.1.2.1 test_vocabulary.py:1.1.2.1
Fred L. Drake, Jr.
fred@zope.com
Fri, 2 May 2003 10:11:17 -0400
Update of /cvs-repository/Zope3/src/zope/schema/tests
In directory cvs.zope.org:/tmp/cvs-serv21481/tests
Added Files:
Tag: schema-vocabulary-branch
states.py tabcomplete.py test_states.py test_tabcomplete.py
test_vocabulary.py
Log Message:
Preliminary implementation of Vocabulary Fields, as described in:
http://dev.zope.org/Zope3/VocabularyFields
=== Added File Zope3/src/zope/schema/tests/states.py ===
##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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 import vocabulary
# This table is based on information from the United States Postal Service:
# http://www.usps.com/ncsc/lookups/abbreviations.html#states
_states = {
'AL': u'Alabama',
'AK': u'Alaska',
'AS': u'American Samoa',
'AZ': u'Arizona',
'AR': u'Arkansas',
'CA': u'California',
'CO': u'Colorado',
'CT': u'Connecticut',
'DE': u'Delaware',
'DC': u'District of Columbia',
'FM': u'Federated States of Micronesia',
'FL': u'Florida',
'GA': u'Georgia',
'GU': u'Guam',
'HI': u'Hawaii',
'ID': u'Idaho',
'IL': u'Illinois',
'IN': u'Indiana',
'IA': u'Iowa',
'KS': u'Kansas',
'KY': u'Kentucky',
'LA': u'Louisiana',
'ME': u'Maine',
'MH': u'Marshall Islands',
'MD': u'Maryland',
'MA': u'Massachusetts',
'MI': u'Michigan',
'MN': u'Minnesota',
'MS': u'Mississippi',
'MO': u'Missouri',
'MT': u'Montana',
'NE': u'Nebraska',
'NV': u'Nevada',
'NH': u'New Hampshire',
'NJ': u'New Jersey',
'NM': u'New Mexico',
'NY': u'New York',
'NC': u'North Carolina',
'ND': u'North Dakota',
'MP': u'Northern Mariana Islands',
'OH': u'Ohio',
'OK': u'Oklahoma',
'OR': u'Oregon',
'PW': u'Palau',
'PA': u'Pennsylvania',
'PR': u'Puerto Rico',
'RI': u'Rhode Island',
'SC': u'South Carolina',
'SD': u'South Dakota',
'TN': u'Tennessee',
'TX': u'Texas',
'UT': u'Utah',
'VT': u'Vermont',
'VI': u'Virgin Islands',
'VA': u'Virginia',
'WA': u'Washington',
'WV': u'West Virginia',
'WI': u'Wisconsin',
'WY': u'Wyoming',
}
class State:
__slots__ = 'value', 'title'
__implements__ = vocabulary.ITerm
def __init__(self, value, title):
self.value = value
self.title = title
for v,p in _states.iteritems():
_states[v] = State(v, p)
class IStateVocabulary(vocabulary.IVocabulary):
"""Vocabularies that support the states database conform to this."""
class StateVocabulary(object):
__slots__ = ()
__implements__ = IStateVocabulary
def __init__(self, object=None):
pass
def __contains__(self, value):
return value in _states
def getTerm(self, value):
return _states[value]
def __iter__(self):
return _states.itervalues()
def __len__(self):
return len(_states)
class StateSelectionField(vocabulary.VocabularyField):
__implements__ = vocabulary.VocabularyField.__implements__
vocabulary = StateVocabulary()
def __init__(self, **kw):
super(StateSelectionField, self).__init__(
vocabulary=StateSelectionField.vocabulary,
**kw)
self.vocabularyName = "states"
=== Added File Zope3/src/zope/schema/tests/tabcomplete.py ===
##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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.
#
##############################################################################
"""Example vocabulary for tab completion."""
from zope.schema.vocabulary import ITerm, ISubsetVocabulary, IVocabulary
class Term:
__implements__ = ITerm
def __init__(self, value):
self.value = value
class TermIterator:
def __init__(self, values):
self._next = iter(values).next
def __iter__(self):
return self
def next(self):
return Term(self._next())
class CompletionVocabulary(object):
__implements__ = IVocabulary
def __init__(self, values):
# In practice, something more dynamic could be used to
# get the list possible completions.
self._values = tuple(values)
def __contains__(self, value):
return value in self._values
def getTerm(self, value):
if value in self._values:
return Term(value)
raise LookupError(value)
def __iter__(self):
return TermIterator(self._values)
def __len__(self):
return len(self._values)
def queryForPrefix(self, prefix):
return SubsetCompletionVocabulary(self._match_prefix(prefix),
self)
def _match_prefix(self, prefix):
L = [v for v in self._values if v.startswith(prefix)]
if L:
return L
else:
raise LookupError("no entries matching prefix %r" % prefix)
class SubsetCompletionVocabulary(CompletionVocabulary):
__implements__ = IVocabulary, ISubsetVocabulary
def __init__(self, values, master):
super(SubsetCompletionVocabulary, self).__init__(values)
self._master = master
def getMasterVocabulary(self):
return self._master
def queryForPrefix(self, prefix):
# Never nest more than one level; cause the real
# master to always be returned by getMasterVocabulary()
return SubsetCompletionVocabulary(self._match_prefix(prefix),
self._master)
=== Added File Zope3/src/zope/schema/tests/test_states.py ===
##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Tests of the states example."""
import unittest
from zope.interface import Interface
from zope.schema import vocabulary
from zope.schema.tests import states
class IBirthInfo(Interface):
state1 = vocabulary.VocabularyField(
title=u'State of Birth',
description=u'The state in which you were born.',
vocabulary="states",
default="AL",
)
state2 = vocabulary.VocabularyField(
title=u'State of Birth',
description=u'The state in which you were born.',
vocabulary="states",
default="AL",
)
state3 = vocabulary.VocabularyField(
title=u'Favorite State',
description=u'The state you like the most.',
vocabulary=states.StateVocabulary(),
)
state4 = vocabulary.VocabularyField(
title=u"Name",
description=u"The name of your new state",
vocabulary="states",
)
class BirthInfo:
__implements__ = IBirthInfo
def __init__(self):
self.state = state
class StateSelectionTest(unittest.TestCase):
def setUp(self):
vocabulary._clear()
vr = vocabulary.getVocabularyRegistry()
vr.register("states", states.StateVocabulary)
def tearDown(self):
vocabulary._clear()
def test_default_presentation(self):
field = IBirthInfo.getDescriptionFor("state1")
bound = field.bind(object())
self.assertEqual(bound.vocabulary.getTerm("VA").title, "Virginia")
def test_contains(self):
vocab = states.StateVocabulary()
count = 0
L = list(vocab)
for term in L:
count += 1
self.assert_(term.value in vocab)
self.assertEqual(count, len(vocab))
# make sure we get the same values the second time around:
L = [term.value for term in L]
L.sort()
L2 = [term.value for term in vocab]
L2.sort()
self.assertEqual(L, L2)
def test_prebound_vocabulary(self):
field = IBirthInfo.getDescriptionFor("state3")
bound = field.bind(None)
self.assert_(bound.vocabularyName is None)
self.assert_("AL" in bound.vocabulary)
def test_suite():
return unittest.makeSuite(StateSelectionTest)
if __name__ == "__main__":
unittest.main(defaultTest="test_suite")
=== Added File Zope3/src/zope/schema/tests/test_tabcomplete.py ===
##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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 'tab completion' example vocabulary."""
import unittest
from zope.schema import vocabulary
from zope.schema.tests import tabcomplete
class TabCompletionTests(unittest.TestCase):
def setUp(self):
self.vocab = tabcomplete.CompletionVocabulary(['abc', 'def'])
def test_successful_query(self):
subset = self.vocab.queryForPrefix("a")
L = [term.value for term in subset]
self.assertEqual(L, ["abc"])
self.assert_(subset.getMasterVocabulary() is self.vocab)
subset = self.vocab.queryForPrefix("def")
L = [term.value for term in subset]
self.assertEqual(L, ["def"])
self.assert_(subset.getMasterVocabulary() is self.vocab)
def test_failed_query(self):
self.assertRaises(LookupError, self.vocab.queryForPrefix, "g")
def test_getTerm(self):
term = self.vocab.getTerm("abc")
self.assert_(vocabulary.ITerm.isImplementedBy(term))
self.assertEqual(term.value, "abc")
def test_suite():
return unittest.makeSuite(TabCompletionTests)
if __name__ == "__main__":
unittest.main(defaultTest="test_suite")
=== Added File Zope3/src/zope/schema/tests/test_vocabulary.py ===
##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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 VocabularyField and related support APIs."""
import unittest
from zope.schema.interfaces import ValidationError
from zope.schema import vocabulary
class Thing:
def __init__(self, object, name):
self.object = object
self.name = name
class DummyRegistry(vocabulary.VocabularyRegistry):
def get(self, object, name):
return Thing(object, name)
class BaseTest(unittest.TestCase):
# Clear the vocabulary and presentation registries on each side of
# each test.
def setUp(self):
vocabulary._clear()
def tearDown(self):
vocabulary._clear()
class RegistryTests(BaseTest):
"""Tests of the simple vocabulary and presentation registries."""
def test_setVocabularyRegistry(self):
r = DummyRegistry()
vocabulary.setVocabularyRegistry(r)
self.assert_(vocabulary.getVocabularyRegistry() is r)
def test_getVocabularyRegistry(self):
r = vocabulary.getVocabularyRegistry()
self.assert_(vocabulary.IVocabularyRegistry.isImplementedBy(r))
# XXX still need to test the default implementation
class SampleTerm:
pass
class SampleVocabulary:
__implements__ = vocabulary.IVocabulary
def __contains__(self, value):
return 0 <= value < 10
def __len__(self):
return 10
def getTerm(self, value):
if value in self:
t = SampleTerm()
t.value = value
t.double = 2 * value
return t
raise LookupError("no such value: %r" % value)
class VocabularyFieldTests(BaseTest):
"""Tests of the VocabularyField implementation."""
def test_preconstructed_vocabulary(self):
v = SampleVocabulary()
field = vocabulary.VocabularyField(vocabulary=v)
self.assert_(field.vocabulary is v)
self.assert_(field.vocabularyName is None)
bound = field.bind(None)
self.assert_(bound.vocabulary is v)
self.assert_(bound.vocabularyName is None)
self.assertRaises(ValidationError,
setattr, bound, "default", 42)
def test_constructed_vocabulary(self):
vocabulary.setVocabularyRegistry(DummyRegistry())
field = vocabulary.VocabularyField(vocabulary="vocab")
self.assert_(field.vocabulary is None)
self.assertEqual(field.vocabularyName, "vocab")
o = object()
bound = field.bind(o)
v = bound.vocabulary
self.assert_(isinstance(v, Thing))
self.assert_(v.object is o)
self.assertEqual(v.name, "vocab")
def test_suite():
suite = unittest.makeSuite(RegistryTests)
suite.addTest(unittest.makeSuite(VocabularyFieldTests))
return suite
if __name__ == "__main__":
unittest.main(defaultTest="test_suite")