[Zope3-checkins] CVS: Zope3/src/zope/app/form/browser/tests -
registerWidgets.zcml:1.1 test_choicesequencetest.py:1.1
test_choicewidget.py:1.1 test_itemswidget.py:1.1
test_registrations.py:1.1 test_selectwidget.py:1.1
test_vocabularyquery.py:1.1
Stephan Richter
srichter at cosmos.phy.tufts.edu
Sat Apr 24 19:19:08 EDT 2004
Update of /cvs-repository/Zope3/src/zope/app/form/browser/tests
In directory cvs.zope.org:/tmp/cvs-serv29914/src/zope/app/form/browser/tests
Added Files:
registerWidgets.zcml test_choicesequencetest.py
test_choicewidget.py test_itemswidget.py test_registrations.py
test_selectwidget.py test_vocabularyquery.py
Log Message:
Test new widgets.
=== Added File Zope3/src/zope/app/form/browser/tests/registerWidgets.zcml ===
<configure
xmlns="http://namespaces.zope.org/zope"
i18n_domain="zope">
<include package="zope.app.component" file="meta.zcml" />
<include package="zope.app.form.browser" file="configure.zcml" />
</configure>
=== Added File Zope3/src/zope/app/form/browser/tests/test_choicesequencetest.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 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 the ChoiceSequence display and edit widget (function).
$Id: test_choicesequencetest.py,v 1.1 2004/04/24 23:19:07 srichter Exp $
"""
import unittest
from zope.publisher.interfaces.browser import IBrowserRequest
from zope.publisher.browser import TestRequest
from zope.schema.interfaces import IChoiceSequence, IIterableVocabulary
from zope.schema import Choice, Sequence
from zope.app import zapi
from zope.app.tests.placelesssetup import PlacelessSetup
from zope.app.form.interfaces import IInputWidget, IDisplayWidget
from zope.app.form.browser import ChoiceSequenceDisplayWidget
from zope.app.form.browser import ChoiceSequenceEditWidget
from zope.app.form.browser import ItemsMultiDisplayWidget, SelectWidget
def provideMultiView(for_, factory, providing, name='', layer="default"):
s = zapi.getService(None, zapi.servicenames.Presentation)
return s.provideAdapter(IBrowserRequest, factory, name, for_,
providing, layer)
class ChoiceSequenceWidgetTest(PlacelessSetup, unittest.TestCase):
def test_ChoiceSequenceDisplayWidget(self):
provideMultiView((IChoiceSequence, IIterableVocabulary),
ItemsMultiDisplayWidget, IDisplayWidget)
field = Sequence(value_type=Choice(values=[1, 2, 3]))
bound = field.bind(object())
widget = ChoiceSequenceDisplayWidget(bound, TestRequest())
self.assert_(isinstance(widget, ItemsMultiDisplayWidget))
self.assertEqual(widget.context, bound)
self.assertEqual(widget.vocabulary, bound.value_type.vocabulary)
def test_ChoiceSequenceEditWidget(self):
provideMultiView((IChoiceSequence, IIterableVocabulary),
SelectWidget, IInputWidget)
field = Sequence(value_type=Choice(values=[1, 2, 3]))
bound = field.bind(object())
widget = ChoiceSequenceEditWidget(bound, TestRequest())
self.assert_(isinstance(widget, SelectWidget))
self.assertEqual(widget.context, bound)
self.assertEqual(widget.vocabulary, bound.value_type.vocabulary)
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(ChoiceSequenceWidgetTest),
))
if __name__=='__main__':
unittest.main(defaultTest='test_suite')
=== Added File Zope3/src/zope/app/form/browser/tests/test_choicewidget.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 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 the Choice display and edit widget (function).
$Id: test_choicewidget.py,v 1.1 2004/04/24 23:19:07 srichter Exp $
"""
import unittest
from zope.publisher.interfaces.browser import IBrowserRequest
from zope.publisher.browser import TestRequest
from zope.schema.interfaces import IChoice, IIterableVocabulary
from zope.schema import Choice
from zope.app import zapi
from zope.app.tests.placelesssetup import PlacelessSetup
from zope.app.form.interfaces import IInputWidget, IDisplayWidget
from zope.app.form.browser import ChoiceDisplayWidget, ChoiceEditWidget
from zope.app.form.browser import ItemDisplayWidget, DropdownWidget
def provideMultiView(for_, factory, providing, name='', layer="default"):
s = zapi.getService(None, zapi.servicenames.Presentation)
return s.provideAdapter(IBrowserRequest, factory, name, for_,
providing, layer)
class ChoiceWidgetTest(PlacelessSetup, unittest.TestCase):
def test_ChoiceDisplayWidget(self):
provideMultiView((IChoice, IIterableVocabulary),
ItemDisplayWidget, IDisplayWidget)
field = Choice(values=[1, 2, 3])
bound = field.bind(object())
widget = ChoiceDisplayWidget(bound, TestRequest())
self.assert_(isinstance(widget, ItemDisplayWidget))
self.assertEqual(widget.context, bound)
self.assertEqual(widget.vocabulary, bound.vocabulary)
def test_ChoiceEditWidget(self):
provideMultiView((IChoice, IIterableVocabulary),
DropdownWidget, IInputWidget)
field = Choice(values=[1, 2, 3])
bound = field.bind(object())
widget = ChoiceEditWidget(bound, TestRequest())
self.assert_(isinstance(widget, DropdownWidget))
self.assertEqual(widget.context, bound)
self.assertEqual(widget.vocabulary, bound.vocabulary)
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(ChoiceWidgetTest),
))
if __name__=='__main__':
unittest.main(defaultTest='test_suite')
=== Added File Zope3/src/zope/app/form/browser/tests/test_itemswidget.py ===
##############################################################################
#
# Copyright (c) 2004 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.
#
##############################################################################
"""Select Widget Tests
$Id: test_itemswidget.py,v 1.1 2004/04/24 23:19:07 srichter Exp $
"""
import unittest
from zope.interface import Interface, implements
from zope.schema import Choice, Sequence
from zope.publisher.browser import TestRequest
from zope.app.form.interfaces import WidgetInputError
from zope.app.form.browser.itemswidgets import ItemsWidgetBase
from zope.app.form.browser.itemswidgets import ItemDisplayWidget
from zope.app.form.browser.itemswidgets import ItemsMultiDisplayWidget
from zope.app.form.browser.itemswidgets import ListDisplayWidget
from zope.app.form.browser.itemswidgets import SetDisplayWidget
from zope.app.form.browser.itemswidgets import ItemsEditWidgetBase
from zope.app.form.browser.itemswidgets import SelectWidget, DropdownWidget
from zope.app.form.browser.itemswidgets import RadioWidget
from zope.app.form.browser.itemswidgets import ItemsMultiEditWidgetBase
from zope.app.form.browser.itemswidgets import MultiSelectWidget
from zope.app.form.browser.itemswidgets import MultiCheckBoxWidget
from zope.app.form.browser.tests.support import VerifyResults
from zope.app.tests.placelesssetup import PlacelessSetup
class ICollector(Interface):
choice = Choice(
title=u"Number",
description=u"The Number",
values=['one', 'two', 'three'],
required=True)
numbers = Sequence(
title=u"Numbers",
description=u"The Numbers",
value_type=choice,
required=False)
class Collector(object):
implements(ICollector)
def __init__(self, numbers=None):
self.numbers = numbers or []
class ItemsWidgetBaseTest(VerifyResults, PlacelessSetup, unittest.TestCase):
_widget = ItemsWidgetBase
_field = ICollector.get('choice')
_vocabulary = _field.vocabulary
def _makeWidget(self, form=None, nums=None):
request = TestRequest(form=form or {})
collector = Collector(nums)
bound = self._field.bind(collector)
return self._widget(bound, self._vocabulary, request)
def test_setPrefix(self):
widget = self._makeWidget()
name = self._field.getName()
# Default prefix
self.assertEqual(widget._prefix, 'field.')
self.assertEqual(widget.name, 'field.%s' %name)
self.assertEqual(widget.empty_marker_name,
'field.%s-empty-marker' %name)
# Declaring custom prefix
widget.setPrefix('foo')
self.assertEqual(widget._prefix, 'foo.')
self.assertEqual(widget.name, 'foo.%s' %name)
self.assertEqual(widget.empty_marker_name,
'foo.%s-empty-marker' %name)
def test_convertTokensToValues(self):
widget = self._makeWidget()
self.assertEqual(widget.convertTokensToValues(['one', 'two']),
['one', 'two'])
class ItemDisplayWidgetTest(ItemsWidgetBaseTest):
_widget = ItemDisplayWidget
def test_setVocabulary(self):
widget = self._makeWidget()
self.assert_(widget.vocabulary is not None)
self.assertEqual(widget.vocabulary, self._field.vocabulary)
def test__call__(self):
widget = self._makeWidget()
self.assertEqual(widget(), '')
widget = self._makeWidget(form={'field.choice': 'one'})
self.assertEqual(widget(), 'one')
class ItemsMultiDisplayWidgetTest(ItemsWidgetBaseTest):
_widget = ItemsMultiDisplayWidget
_field = ICollector.get('numbers')
_vocabulary = _field.value_type.vocabulary
_tag = 'ol'
def test__call__(self):
widget = self._makeWidget()
self.assertEqual(widget(), '')
widget = self._makeWidget(form={'field.numbers': ['one', 'two']})
self.assertEqual(
widget(),
'<%s class="textType" '
'id="field.numbers" '
'name="field.numbers" '
'type="text" >'
'<li>one</li>\n<li>two</li>'
'</%s>' %(self._tag, self._tag))
def test_renderItems(self):
widget = self._makeWidget()
self.assertEqual(
widget.renderItems(['one', 'two']),
[u'<li>one</li>', u'<li>two</li>'])
self.assertRaises(LookupError, widget.renderItems, 'one')
self.assertRaises(TypeError, widget.renderItems, 1)
class ListDisplayWidgetTest(ItemsMultiDisplayWidgetTest):
_widget = ListDisplayWidget
_tag = 'ol'
class SetDisplayWidgetTest(ItemsMultiDisplayWidgetTest):
_widget = SetDisplayWidget
_tag = 'ul'
class ItemsEditWidgetBaseTest(ItemsWidgetBaseTest):
_widget = ItemsEditWidgetBase
def test_div(self):
widget = self._makeWidget()
self.assertEqual(widget._div('', ''), '')
self.assertEqual(widget._div('foo', ''), '')
self.assertEqual(widget._div('', 'bar'), '<div>\nbar\n</div>')
self.assertEqual(widget._div('foo', 'bar'),
'<div class="foo">\nbar\n</div>')
self.assertEqual(widget._div('foo', 'bar', style='blah'),
'<div class="foo" style="blah">\nbar\n</div>')
def test_renderItem(self):
widget = self._makeWidget()
self.assertEqual(widget.renderItem('', 'Foo', 'foo', '', None),
'<option value="foo">Foo</option>')
self.assertEqual(widget.renderItem('', 'Foo', 'foo', '', 'klass'),
'<option class="klass" value="foo">Foo</option>')
def test_renderSelectedItem(self):
widget = self._makeWidget()
self.verifyResult(
widget.renderSelectedItem('', 'Foo', 'foo', '', None),
['<option', 'value="foo"', 'selected="selected"', '>Foo</option>'])
self.verifyResult(
widget.renderSelectedItem('', 'Foo', 'foo', '', 'klass'),
['<option', 'class="klass"', 'value="foo"', 'selected="selected"',
'>Foo</option>'])
def test_renderItemsWithValues(self):
widget = self._makeWidget()
self.assertEqual(
widget.renderItemsWithValues(['one', 'two']),
[u'<option selected="selected" value="one">one</option>',
u'<option selected="selected" value="two">two</option>',
u'<option value="three">three</option>'])
self.assertEqual(
widget.renderItemsWithValues([]),
[u'<option value="one">one</option>',
u'<option value="two">two</option>',
u'<option value="three">three</option>'])
def test_error(self):
widget = self._makeWidget(form={'field.choice': 'ten'})
widget.setPrefix('field.')
widget._showData()
self.assert_(isinstance(widget._error, WidgetInputError))
class SelectWidgetTest(ItemsEditWidgetBaseTest):
_widget = SelectWidget
_size = 5
def test__call__(self):
widget = self._makeWidget(form={'field.choice': 'one'})
widget.setPrefix('field.')
widget.context.required = False
self.assertEqual(
widget(),
'<div id="field.choice">\n'
'<div class="value">\n'
'<select name="field.choice" size="%i" >\n'
'<option value="">(no value)</option>\n'
'<option selected="selected" value="one">one</option>\n'
'<option value="two">two</option>\n'
'<option value="three">three</option>\n'
'</select>\n</div>\n'
'<input name="field.choice-empty-marker" '
'type="hidden" value="1" />\n</div>' %self._size)
def test_renderValue(self):
widget = self._makeWidget()
widget.setPrefix('field.')
self.assertEqual(
widget.renderValue('one'),
'<select name="field.choice" size="%i" >\n'
'<option selected="selected" value="one">one</option>\n'
'<option value="two">two</option>\n'
'<option value="three">three</option>\n'
'</select>' %self._size)
def test_renderItems(self):
widget = self._makeWidget()
widget.setPrefix('field.')
self.assertEqual(
widget.renderItems('one'),
[u'<option selected="selected" value="one">one</option>',
u'<option value="two">two</option>',
u'<option value="three">three</option>'])
self.assertEqual(
widget.renderItems('two'),
[u'<option value="one">one</option>',
u'<option selected="selected" value="two">two</option>',
u'<option value="three">three</option>'])
self.assertEqual(
widget.renderItems(None),
[u'<option value="one">one</option>',
u'<option value="two">two</option>',
u'<option value="three">three</option>'])
def test_renderItems_notRequired(self):
widget = self._makeWidget()
widget.setPrefix('field.')
widget.context.required = False
self.assertEqual(
widget.renderItems([]),
[u'<option value="">(no value)</option>',
u'<option value="one">one</option>',
u'<option value="two">two</option>',
u'<option value="three">three</option>'])
def test_renderItems_firstItem(self):
widget = self._makeWidget()
widget.setPrefix('field.')
widget.firstItem = True
self.assertEqual(
widget.renderItems(None),
[u'<option selected="selected" value="one">one</option>',
u'<option value="two">two</option>',
u'<option value="three">three</option>'])
class DropdownWidgetTest(SelectWidgetTest):
_widget = DropdownWidget
_size = 1
class RadioWidgetTest(ItemsEditWidgetBaseTest):
_widget = RadioWidget
def test_renderItem(self):
widget = self._makeWidget()
self.verifyResult(
widget.renderItem('', 'Foo', 'foo', 'bar', None),
['<input', 'type="radio"', 'name="bar"', 'value="foo"',
'class="radioType"', '> Foo'])
self.verifyResult(
widget.renderItem('bar', 'Foo', 'foo', 'bar', 'klass'),
['<input', 'type="radio"', 'name="bar"', 'value="foo"',
'class="klass radioType"', '> Foo'])
def test_renderSelectedItem(self):
widget = self._makeWidget()
self.verifyResult(
widget.renderSelectedItem('', 'Foo', 'foo', 'bar', 'klass'),
['<input', 'type="radio"', 'name="bar"', 'value="foo"',
'checked="checked"', '> Foo'])
self.verifyResult(
widget.renderSelectedItem('', 'Foo', 'foo', 'bar', 'klass'),
['<input', 'type="radio"', 'name="bar"', 'value="foo"',
'class="klass radioType"', 'checked="checked"', '> Foo'])
def test_renderItemsWithValues(self):
widget = self._makeWidget()
items = widget.renderItemsWithValues(['one'])
values = ['one', 'two', 'three']
for item in items:
index = items.index(item)
self.verifyResult(
item,
['<input', 'class="radioType"', 'name="field.choice"',
'id="field.choice.%i' %index, 'type="radio"',
'value="%s"' %values[index], ' %s' %values[index]])
self.verifyResult(items[0], ['checked="checked"'])
def test_renderItems(self):
widget = self._makeWidget()
items = widget.renderItems('one')
values = ['one', 'two', 'three']
for item in items:
index = items.index(item)
self.verifyResult(
item,
['<input', 'class="radioType"', 'name="field.choice"',
'id="field.choice.%i' %index, 'type="radio"',
'value="%s"' %values[index], ' %s' %values[index]])
self.verifyResult(items[0], ['checked="checked"'])
def test_renderItems_notRequired(self):
widget = self._makeWidget()
widget.context.required = False
items = widget.renderItems([])
values = ['(no value)', 'one', 'two', 'three']
for item in items:
index = items.index(item)
self.verifyResult(
item,
['<input', 'class="radioType"', 'name="field.choice"',
'type="radio"', ' %s' %values[index]])
def test_renderItems_firstItem(self):
widget = self._makeWidget()
widget.firstItem = True
items = widget.renderItems(None)
values = ['one', 'two', 'three']
for item in items:
index = items.index(item)
self.verifyResult(
item,
['<input', 'class="radioType"', 'name="field.choice"',
'id="field.choice.%i"' %index, 'type="radio"',
' %s' %values[index]])
self.verifyResult(items[0], ['checked="checked"'])
def test_renderValue(self):
widget = self._makeWidget()
self.verifyResult(widget.renderValue(None), ['<br /><input'])
widget.orientation='horizontal'
self.verifyResult(widget.renderValue(None), [' <input'])
class ItemsMultiEditWidgetBaseTest(ItemsEditWidgetBaseTest):
_widget = ItemsMultiEditWidgetBase
_field = ICollector.get('numbers')
_vocabulary = _field.value_type.vocabulary
def test_renderValue(self):
widget = self._makeWidget()
self.verifyResult(
widget.renderValue(['one', 'two']),
['<select', 'multiple="multiple"', 'name="field.numbers:list"',
'size="5"', '><option', 'selected="selected"', 'value="one"',
'>one</option>\n', 'value="two"', '>two</option>\n',
'value="three"', '>three</option>', '</select>'])
def test_error(self):
widget = self._makeWidget(form={'field.numbers': ['ten']})
widget.setPrefix('field.')
widget._showData()
self.assert_(isinstance(widget._error, WidgetInputError))
class MultiSelectWidgetTest(ItemsMultiEditWidgetBaseTest):
_widget = MultiSelectWidget
class MultiCheckBoxWidgetTest(ItemsMultiEditWidgetBaseTest):
_widget = MultiCheckBoxWidget
def test_renderItem(self):
widget = self._makeWidget()
self.verifyResult(
widget.renderItem('', 'Foo', 'foo', 'bar', None),
['<input', 'type="checkbox"', 'name="bar"', 'value="foo"',
'class="checkboxType"', '> Foo'])
self.verifyResult(
widget.renderItem('bar', 'Foo', 'foo', 'bar', 'klass'),
['<input', 'type="checkbox"', 'name="bar"', 'value="foo"',
'class="klass checkboxType"', '> Foo'])
def test_renderSelectedItem(self):
widget = self._makeWidget()
self.verifyResult(
widget.renderSelectedItem('', 'Foo', 'foo', 'bar', 'klass'),
['<input', 'type="checkbox"', 'name="bar"', 'value="foo"',
'checked="checked"', '> Foo'])
self.verifyResult(
widget.renderSelectedItem('', 'Foo', 'foo', 'bar', 'klass'),
['<input', 'type="checkbox"', 'name="bar"', 'value="foo"',
'class="klass checkboxType"', 'checked="checked"', '> Foo'])
def test_renderValue(self):
widget = self._makeWidget()
self.verifyResult(widget.renderValue(None), ['<br /><input'])
widget.orientation='horizontal'
self.verifyResult(widget.renderValue(None), [' <input'])
def test_renderItemsWithValues(self):
widget = self._makeWidget()
items = widget.renderItemsWithValues(['one'])
for item in items:
index = items.index(item)
self.verifyResult(
item,
['<input', 'class="checkboxType',
'id="field.numbers.%i"' %index, 'type="checkbox"', '/> '])
self.verifyResult(items[0],
['checked="checked"', '/> one'])
def test_suite():
suite = unittest.makeSuite(ItemDisplayWidgetTest)
suite.addTest(unittest.makeSuite(ItemsMultiDisplayWidgetTest))
suite.addTest(unittest.makeSuite(ListDisplayWidgetTest))
suite.addTest(unittest.makeSuite(SetDisplayWidgetTest))
suite.addTest(unittest.makeSuite(ItemsEditWidgetBaseTest))
suite.addTest(unittest.makeSuite(SelectWidgetTest))
suite.addTest(unittest.makeSuite(DropdownWidgetTest))
suite.addTest(unittest.makeSuite(RadioWidgetTest))
suite.addTest(unittest.makeSuite(ItemsMultiEditWidgetBaseTest))
suite.addTest(unittest.makeSuite(MultiSelectWidgetTest))
suite.addTest(unittest.makeSuite(MultiCheckBoxWidgetTest))
return suite
if __name__ == '__main__':
unittest.main(defaultTest="test_suite")
=== Added File Zope3/src/zope/app/form/browser/tests/test_registrations.py ===
##############################################################################
#
# Copyright (c) 2004 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 widget registrations.
$Id: test_registrations.py,v 1.1 2004/04/24 23:19:07 srichter Exp $
"""
import unittest
from zope.configuration import xmlconfig
from zope.interface import implements
from zope.publisher.browser import TestRequest
from zope.testing.doctestunit import DocTestSuite
from zope.app import zapi
from zope.app.tests import setup
# import all widgets (in this case, importing * is ok, since we
# absolutely know what we're importing)
from zope.app.form.browser import *
from zope.app.form.interfaces import IDisplayWidget, IInputWidget
import zope.app.form.browser
import zope.schema as fields
from zope.schema import interfaces
from zope.schema import vocabulary
class ISampleObject(interfaces.IField):
pass
class SampleObject:
implements(ISampleObject)
class ISampleVocabulary(
interfaces.IVocabularyTokenized, interfaces.IVocabulary):
pass
class SampleVocabularyQuery:
implements(interfaces.IIterableVocabularyQuery)
def __init__(self, vocabulary):
self.vocabulary = vocabulary
class SampleVocabulary(vocabulary.SimpleVocabulary):
implements(ISampleVocabulary)
def getQuery(self):
return SampleVocabularyQuery(self)
request = TestRequest()
sample = SampleObject()
vocab = SampleVocabulary([])
def setUp():
setup.placelessSetUp()
context = xmlconfig.file("tests/registerWidgets.zcml",
zope.app.form.browser)
class Tests:
"""Documents and tests widgets registration for specific field types.
Standard Widgets
------------------------------------------------------------------------
The relationships between field types and standard widgets are listed
below.
IField, IDisplayWidget -> DisplayWidget
>>> field = fields.Field()
>>> widget = zapi.getViewProviding(field, IDisplayWidget, request)
>>> isinstance(widget, DisplayWidget)
True
ITextLine, IInputWidget -> TextWidget
>>> field = fields.TextLine()
>>> widget = zapi.getViewProviding(field, IInputWidget, request)
>>> isinstance(widget, TextWidget)
True
IText, IInputWidget -> TextAreaWidget
>>> field = fields.Text()
>>> widget = zapi.getViewProviding(field, IInputWidget, request)
>>> isinstance(widget, TextAreaWidget)
True
ISourceText, IInputWidget -> TextAreaWidget
>>> field = fields.SourceText()
>>> widget = zapi.getViewProviding(field, IInputWidget, request)
>>> isinstance(widget, TextAreaWidget)
True
IBytesLine, IInputWidget -> BytesWidget
>>> field = fields.BytesLine()
>>> widget = zapi.getViewProviding(field, IInputWidget, request)
>>> isinstance(widget, BytesWidget)
True
IBytes, IInputWidget -> FileWidget
>>> field = fields.Bytes()
>>> widget = zapi.getViewProviding(field, IInputWidget, request)
>>> isinstance(widget, FileWidget)
True
IASCII, IInputWidget -> BytesAreaWidget
>>> field = fields.ASCII()
>>> widget = zapi.getViewProviding(field, IInputWidget, request)
>>> isinstance(widget, BytesAreaWidget)
True
IInt, IInputWidget -> IntWidget
>>> field = fields.Int()
>>> widget = zapi.getViewProviding(field, IInputWidget, request)
>>> isinstance(widget, IntWidget)
True
IFloat, IInputWidget -> FloatWidget
>>> field = fields.Float()
>>> widget = zapi.getViewProviding(field, IInputWidget, request)
>>> isinstance(widget, FloatWidget)
True
IDatetime, IInputWidget -> DatetimeWidget
>>> field = fields.Datetime()
>>> widget = zapi.getViewProviding(field, IInputWidget, request)
>>> isinstance(widget, DatetimeWidget)
True
IDate, IInputWidget -> DateWidget
>>> field = fields.Date()
>>> widget = zapi.getViewProviding(field, IInputWidget, request)
>>> isinstance(widget, DateWidget)
True
IBool, IInputWidget -> CheckBoxWidget
>>> field = fields.Bool()
>>> widget = zapi.getViewProviding(field, IInputWidget, request)
>>> isinstance(widget, CheckBoxWidget)
True
ITuple, IInputWidget -> TupleSequenceWidget
>>> field = fields.Tuple()
>>> widget = zapi.getViewProviding(field, IInputWidget, request)
>>> isinstance(widget, TupleSequenceWidget)
True
IList, IInputWidget -> ListSequenceWidget
>>> field = fields.List()
>>> widget = zapi.getViewProviding(field, IInputWidget, request)
>>> isinstance(widget, ListSequenceWidget)
True
IPassword, IInputWidget -> PasswordWidget
>>> field = fields.Password()
>>> widget = zapi.getViewProviding(field, IInputWidget, request)
>>> isinstance(widget, PasswordWidget)
True
IChoice, IDisplayWidget -> ItemDisplayWidget
>>> field = fields.Choice(vocabulary=vocab)
>>> field = field.bind(sample)
>>> widget = zapi.getViewProviding(field, IDisplayWidget, request)
>>> isinstance(widget, ItemDisplayWidget)
True
IChoice, IInputWidget -> DropdownWidget
>>> field = fields.Choice(vocabulary=vocab)
>>> field = field.bind(sample)
>>> widget = zapi.getViewProviding(field, IInputWidget, request)
>>> isinstance(widget, DropdownWidget)
True
IChoiceSequence, IDisplayWidget -> ItemsMultiDisplayWidget
>>> field = fields.Sequence(value_type=fields.Choice(vocabulary=vocab))
>>> field = field.bind(sample)
>>> widget = zapi.getViewProviding(field, IDisplayWidget, request)
>>> isinstance(widget, ItemsMultiDisplayWidget)
True
IChoiceSequence, IInputWidget -> MultiSelectWidget
>>> field = fields.Sequence(value_type=fields.Choice(vocabulary=vocab))
>>> field = field.bind(sample)
>>> widget = zapi.getViewProviding(field, IInputWidget, request)
>>> isinstance(widget, MultiSelectWidget)
True
"""
def test_suite():
return DocTestSuite(setUp=setUp, tearDown=setup.placelessTearDown)
if __name__=='__main__':
unittest.main(defaultTest='test_suite')
=== Added File Zope3/src/zope/app/form/browser/tests/test_selectwidget.py ===
##############################################################################
#
# Copyright (c) 2004 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.
#
##############################################################################
"""Select Widget Tests
$Id: test_selectwidget.py,v 1.1 2004/04/24 23:19:07 srichter Exp $
"""
import unittest
from zope.schema import Choice, Sequence
from zope.app.form.browser import SelectWidget
choice = Choice(
title=u"Number",
description=u"The Number",
values=[1, 2, 3])
sequence = Sequence(
title=u"Numbers",
description=u"The Numbers",
value_type=choice)
class SelectWidgetTest(unittest.TestCase):
def _makeWidget(self, form):
request = TestRequest(form=form)
return SelectWidget(sequence, request)
def test_suite():
return unittest.makeSuite(SelectWidgetTest)
if __name__ == '__main__':
unittest.main(defaultTest="test_suite")
=== Added File Zope3/src/zope/app/form/browser/tests/test_vocabularyquery.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 vocabulary queries.
$Id: test_vocabularyquery.py,v 1.1 2004/04/24 23:19:07 srichter Exp $
"""
import unittest
from zope.interface import implements
from zope.publisher.browser import TestRequest
from zope.publisher.browser import IBrowserRequest
from zope.schema import vocabulary, Choice, Sequence
from zope.schema.interfaces import IVocabularyQuery, IChoice, IChoiceSequence
from zope.app import zapi
from zope.app.tests import ztapi
from zope.app.tests.placelesssetup import PlacelessSetup
from zope.app.form.browser import DropdownWidget, MultiSelectWidget
from zope.app.form.browser.interfaces import IVocabularyQueryView
from zope.app.form.browser.vocabularyquery import VocabularyQueryViewBase
from zope.app.form.browser.tests import support
def provideMultiView(for_, factory, providing, name='', layer="default"):
s = zapi.getService(None, zapi.servicenames.Presentation)
return s.provideAdapter(IBrowserRequest, factory, name, for_,
providing, layer)
_marker = object()
class SampleContent:
"""Stub content object used by makeField()."""
def __init__(self, value):
self.f = value
class SampleQueryVocabulary(vocabulary.SimpleVocabulary):
"""Vocabulary that offer simple query support."""
def getQuery(self):
return SampleVocabularyQuery(self)
class ISampleVocabularyQuery(IVocabularyQuery):
"""Specialized query type."""
class SampleVocabularyQuery:
"""Vocabulary query object which query views can be registered for."""
implements(ISampleVocabularyQuery)
def __init__(self, vocabulary):
self.vocabulary = vocabulary
class SampleQueryViewSingle(VocabularyQueryViewBase):
"""Single-selection vocabulary query view."""
implements(IVocabularyQueryView)
label = "single"
def _getResults(self):
return self.request.form.get(self.name)
def _renderQueryInput(self):
return "this-is-query-input"
def _renderQueryResults(self, results, value):
return "query-results-go-here"
class SampleQueryViewMulti(SampleQueryViewSingle):
"""Multi-selection vocabulary query view."""
label = "multi"
class QuerySupportTestBase(PlacelessSetup,
support.VerifyResults,
unittest.TestCase):
"""Base class defining tests that can be used for both single- and
multi-select query support.
Derived classes must specialize to support specific selection
mechanics.
"""
_marker = object()
defaultFieldValue = None
_sampleVocabulary = SampleQueryVocabulary.fromValues(
["splat", "foobar", "frob"])
_widgetFactory = None
def setUp(self):
super(QuerySupportTestBase, self).setUp()
self.registerViews()
def _makeWidget(self, form={}):
vocab = self._sampleVocabulary
bound = self.makeField(vocabulary=vocab)
widget = self._widgetFactory(bound, vocab, TestRequest(form=form))
return widget
def test_get_query_helper(self):
widget = self._makeWidget()
self.assert_(
isinstance(widget.queryview.context, SampleVocabularyQuery))
self.assert_(widget.queryview.widget is widget)
self.assertEqual(widget.queryview.name, widget.name + "-query")
self.assertEqual(widget.queryview.label, self.queryViewLabel)
def test_query_input_section(self):
widget = self._makeWidget()
widget.setRenderedValue(self.defaultFieldValue)
checks = [
"this-is-query-input",
]
self.verifyResult(widget.queryview.renderInput(), checks)
self.verifyResult(widget(), checks + ['class="queryinput"'])
def test_query_output_section_without_results(self):
widget = self._makeWidget()
widget.setRenderedValue(self.defaultFieldValue)
checks = [
"query-results-go-here",
]
self.verifyResultMissing(widget.queryview.renderResults([]), checks)
self.verifyResultMissing(widget(), checks + ['class="queryresults"'])
def test_query_output_section_with_results(self):
widget = self._makeWidget({'field.f-query': 'foo'})
widget.setRenderedValue(self.defaultFieldValue)
checks = [
"query-results-go-here",
]
self.verifyResult(widget.queryview.renderResults([]), checks)
self.verifyResult(widget(), checks + ['class="queryresults"'])
class SingleSelectionQuerySupportTests(QuerySupportTestBase):
"""Query support tests for single-selection widgets."""
defaultFieldValue = "splat"
fieldClass = Choice
queryViewLabel = "single"
_widgetFactory = DropdownWidget
def makeField(self, vocabulary=None, value=_marker, required=False):
"""Create and return a bound vocabulary field."""
if vocabulary is None:
vocabulary = self._sampleVocabulary
field = Choice(vocabulary=vocabulary, __name__="f",
required=required)
if value is self._marker:
value = self.defaultFieldValue
content = SampleContent(value)
return field.bind(content)
def registerViews(self):
provideMultiView((ISampleVocabularyQuery, IChoice),
SampleQueryViewSingle, IVocabularyQueryView)
class MultiSelectionQuerySupportTests(QuerySupportTestBase):
"""Query support tests for multi-selection widgets."""
defaultFieldValue = ["splat"]
fieldClass = Sequence
queryViewLabel = "multi"
_widgetFactory = MultiSelectWidget
def makeField(self, vocabulary=None, value=[], required=False):
"""Create and return a bound vocabulary field."""
if vocabulary is None:
vocabulary = self._sampleVocabulary
field = Sequence(__name__="f",
value_type=Choice(vocabulary=vocabulary,
required=required))
if value is self._marker:
value = self.defaultFieldValue
content = SampleContent(value)
return field.bind(content)
def registerViews(self):
provideMultiView((ISampleVocabularyQuery, IChoiceSequence),
SampleQueryViewMulti, IVocabularyQueryView)
def test_suite():
suite = unittest.makeSuite(SingleSelectionQuerySupportTests)
suite.addTest(unittest.makeSuite(MultiSelectionQuerySupportTests))
return suite
if __name__ == '__main__':
unittest.main(defaultTest="test_suite")
More information about the Zope3-Checkins
mailing list