[Zope3-checkins] CVS: Zope3/src/zope/app/form/browser/tests - __init__.py:1.1 support.py:1.1 test_add.py:1.1 test_browserwidget.py:1.1 test_checkboxwidget.py:1.1 test_configure.py:1.1 test_datetimewidget.py:1.1 test_datewidget.py:1.1 test_directives.py:1.1 test_editview.py:1.1 test_editwizardview.py:1.1 test_filewidget.py:1.1 test_floatwidget.py:1.1 test_intwidget.py:1.1 test_listwidget.py:1.1 test_multicheckboxwidget.py:1.1 test_multilistwidget.py:1.1 test_objectwidget.py:1.1 test_passwordwidget.py:1.1 test_radiowidget.py:1.1 test_sequencewidget.py:1.1 test_setprefix.py:1.1 test_textareawidget.py:1.1 test_textwidget.py:1.1 test_vocabularywidget.py:1.1 testconfigure.zcml:1.1 testeditform.pt:1.1 testlabeltranslation.mo:1.1 testlabeltranslation.po:1.1

Stephan Richter srichter at cosmos.phy.tufts.edu
Sat Mar 13 20:11:40 EST 2004


Update of /cvs-repository/Zope3/src/zope/app/form/browser/tests
In directory cvs.zope.org:/tmp/cvs-serv23846/src/zope/app/form/browser/tests

Added Files:
	__init__.py support.py test_add.py test_browserwidget.py 
	test_checkboxwidget.py test_configure.py 
	test_datetimewidget.py test_datewidget.py test_directives.py 
	test_editview.py test_editwizardview.py test_filewidget.py 
	test_floatwidget.py test_intwidget.py test_listwidget.py 
	test_multicheckboxwidget.py test_multilistwidget.py 
	test_objectwidget.py test_passwordwidget.py 
	test_radiowidget.py test_sequencewidget.py test_setprefix.py 
	test_textareawidget.py test_textwidget.py 
	test_vocabularywidget.py testconfigure.zcml testeditform.pt 
	testlabeltranslation.mo testlabeltranslation.po 
Log Message:
Moved zope.app.browser.form to zope.app.form.browser


=== Added File Zope3/src/zope/app/form/browser/tests/__init__.py ===
#
# This file is necessary to make this directory a package.


=== Added File Zope3/src/zope/app/form/browser/tests/support.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.
#
##############################################################################

"""General test support."""


class VerifyResults:
    """Mix-in for test classes with helpers for checking string data."""

    def verifyResult(self, result, check_list, inorder=False):
        start = 0
        for check in check_list:
            pos = result.find(check, start)
            self.assert_(pos >= 0,
                         "%r not found in %r" % (check, result[start:]))
            if inorder:
                start = pos + len(check)

    def verifyResultMissing(self, result, check_list):
        for check in check_list:
            self.assert_(result.find(check) < 0,
                         "%r unexpectedly found in %r" % (check, result))


=== Added File Zope3/src/zope/app/form/browser/tests/test_add.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.
#
##############################################################################
"""

$Id: test_add.py,v 1.1 2004/03/14 01:11:36 srichter Exp $
"""

import unittest

from zope.app.tests import ztapi
from zope.interface import Interface, implements
from zope.publisher.interfaces.browser import IBrowserRequest
from zope.publisher.browser import TestRequest
from zope.schema import TextLine, accessors
from zope.component import getView

from zope.app.form.browser.add import AddViewFactory, AddView
from zope.app.form.browser.metaconfigure import AddFormDirective
from zope.app.container.interfaces import IAdding
from zope.app.form.widget import CustomWidgetFactory
from zope.app.form.browser.widget import TextWidget as Text
from zope.app.tests.placelesssetup import PlacelessSetup
from zope.app.form.browser.submit import Update
# Foo needs to be imported as globals() are checked
from zope.app.form.browser.tests.test_editview import IFoo, IBar, Foo
from zope.app.form.browser.tests.test_editview import FooBarAdapter

class Context:

    def action(self, discriminator, callable, args=(), kw={}):
        self.last_action = (discriminator, callable, args, kw)

class I(Interface):

    name = TextLine()
    first = TextLine()
    last = TextLine()
    email = TextLine()
    address = TextLine()
    getfoo, setfoo = accessors(TextLine())
    extra1 = TextLine()
    extra2 = TextLine(required=False)

class C:

    implements(I)

    def __init__(self, *args, **kw):
        self.args = args
        self.kw = kw

    def getfoo(self): return self._foo
    def setfoo(self, v): self._foo = v

class V:
    name_widget = CustomWidgetFactory(Text)
    first_widget = CustomWidgetFactory(Text)
    last_widget = CustomWidgetFactory(Text)
    email_widget = CustomWidgetFactory(Text)
    address_widget = CustomWidgetFactory(Text)
    getfoo_widget = CustomWidgetFactory(Text)
    extra1_widget = CustomWidgetFactory(Text)
    extra2_widget = CustomWidgetFactory(Text)

class FooV:
    bar_widget = CustomWidgetFactory(Text)


class SampleData:

    name = u"foo"
    first = u"bar"
    last = u"baz"
    email = u"baz at dot.com"
    address = u"aa"
    getfoo = u"foo"
    extra1 = u"extra1"
    extra2 = u"extra2"

class Test(PlacelessSetup, unittest.TestCase):

    def setUp(self):
        self._context = Context()
        super(Test, self).setUp()
        ztapi.provideAdapter(IFoo, IBar, FooBarAdapter)

    def _invoke_add(self, schema=I, name="addthis", permission="zope.Public",
                    label="Add this", content_factory=C, class_=V,
                    arguments=['first', 'last'], keyword_arguments=['email'],
                    set_before_add=['getfoo'], set_after_add=['extra1'],
                    fields=None):
        """ Call the 'add' factory to process arguments into 'args'."""
        AddFormDirective(self._context,
                         schema=schema,
                         name=name,
                         permission=permission,
                         label=label,
                         content_factory=content_factory,
                         class_=class_,
                         arguments=arguments,
                         keyword_arguments=keyword_arguments,
                         set_before_add=set_before_add,
                         set_after_add=set_after_add,
                         fields=fields
                         )()

    def test_add_no_fields(self):
        _context = self._context
        self._invoke_add()
        result1 = _context.last_action
        self._invoke_add(
            fields="name first last email address getfoo extra1 extra2".split(),
            )
        result2 = _context.last_action

        self.assertEqual(result1, result2)

    def test_add_error_handling(self):
        # cannot use a field in arguments if it is not mentioned in fields
        self.assertRaises(ValueError, self._invoke_add, fields="first email getfoo extra1".split())
        # cannot use a field in keyword_arguments if it is not mentioned in fields
        self.assertRaises(ValueError, self._invoke_add, fields="first last getfoo extra1".split())
        # cannot use a field in set_before_add if it is not mentioned in fields
        self.assertRaises(ValueError, self._invoke_add, fields="first last email extra1".split())
        # cannot use a field in set_after_add if it is not mentioned in fields
        self.assertRaises(ValueError, self._invoke_add, fields="first last email getfoo".split())
        # cannot use an optional field in arguments
        self.assertRaises(ValueError, self._invoke_add, arguments=["extra2"])

    def test_add(self, args=None):
        self._invoke_add()
        (descriminator, callable, args, kw) = self._context.last_action

        self.assertEqual(descriminator,
                         ('view', IAdding, "addthis", IBrowserRequest,
                          "default"))
        self.assertEqual(callable, AddViewFactory)

        (name, schema, label, permission, layer, template,
         default_template, bases, for_, fields, content_factory,
         arguments, keyword_arguments, set_before_add,
         set_after_add)  = args

        self.assertEqual(name, 'addthis')
        self.assertEqual(schema, I)
        self.assertEqual(label, 'Add this')
        self.assertEqual(permission, 'zope.Public')
        self.assertEqual(layer, 'default')
        self.assertEqual(template, 'add.pt')
        self.assertEqual(default_template, 'add.pt')
        self.assertEqual(bases, (V, AddView, ))
        self.assertEqual(for_, IAdding)
        self.assertEqual(" ".join(fields),
                         "name first last email address getfoo extra1 extra2")
        self.assertEqual(content_factory, C)
        self.assertEqual(" ".join(arguments),
                         "first last")
        self.assertEqual(" ".join(keyword_arguments),
                         "email")
        self.assertEqual(" ".join(set_before_add),
                         "getfoo")
        self.assertEqual(" ".join(set_after_add),
                         "extra1 name address extra2")

        return args

    def test_create(self):

        class Adding:

            implements(IAdding)

            def __init__(self, test):
                self.test = test

            def add(self, ob):
                self.ob = ob
                self.test.assertEqual(
                    ob.__dict__,
                    {'args': ("bar", "baz"),
                     'kw': {'email': 'baz at dot.com'},
                     '_foo': 'foo',
                    })
                return ob
            def nextURL(self):
                return "."

        adding = Adding(self)
        self._invoke_add()
        (descriminator, callable, args, kw) = self._context.last_action
        factory = AddViewFactory(*args)
        request = TestRequest()
        view = getView(adding, 'addthis', request)
        content = view.create('a',0,abc='def')

        self.failUnless(isinstance(content, C))
        self.assertEqual(content.args, ('a', 0))
        self.assertEqual(content.kw, {'abc':'def'})

    def test_createAndAdd(self):

        class Adding:

            implements(IAdding)

            def __init__(self, test):
                self.test = test

            def add(self, ob):
                self.ob = ob
                self.test.assertEqual(
                    ob.__dict__,
                    {'args': ("bar", "baz"),
                     'kw': {'email': 'baz at dot.com'},
                     '_foo': 'foo',
                    })
                return ob
            def nextURL(self):
                return "."

        adding = Adding(self)
        self._invoke_add()
        (descriminator, callable, args, kw) = self._context.last_action
        factory = AddViewFactory(*args)
        request = TestRequest()
        view = getView(adding, 'addthis', request)

        view.createAndAdd(SampleData.__dict__)

        self.assertEqual(adding.ob.extra1, "extra1")
        self.assertEqual(adding.ob.extra2, "extra2")
        self.assertEqual(adding.ob.name, "foo")
        self.assertEqual(adding.ob.address, "aa")

    def test_createAndAdd_w_adapter(self):

        class Adding:

            implements(IAdding)

            def __init__(self, test):
                self.test = test

            def add(self, ob):
                self.ob = ob
                self.test.assertEqual(ob.__dict__, {'foo': 'bar'})
                return ob
            def nextURL(self):
                return "."

        adding = Adding(self)
        self._invoke_add(
            schema=IBar, name="addthis", permission="zope.Public",
            label="Add this", content_factory=Foo, class_=FooV,
            arguments=None, keyword_arguments=None,
            set_before_add=["bar"], set_after_add=None,
            fields=None
            )
        (descriminator, callable, args, kw) = self._context.last_action
        factory = AddViewFactory(*args)
        request = TestRequest()
        view = getView(adding, 'addthis', request)

        view.createAndAdd({'bar': 'bar'})

    def test_hooks(self):

        class Adding:
            implements(IAdding)

        adding = Adding()
        self._invoke_add()
        (descriminator, callable, args, kw) = self._context.last_action
        factory = AddViewFactory(*args)
        request = TestRequest()

        request.form.update(dict([
            ("field.%s" % k, v)
            for (k, v) in dict(SampleData.__dict__).items()
            ]))
        request.form[Update] = ''
        view = getView(adding, 'addthis', request)

        # Add hooks to V

        l=[None]

        def add(aself, ob):
            l[0] = ob
            self.assertEqual(
                ob.__dict__,
                {'args': ("bar", "baz"),
                 'kw': {'email': 'baz at dot.com'},
                 '_foo': 'foo',
                 })
            return ob

        V.add = add

        V.nextURL = lambda self: 'next'

        try:
            self.assertEqual(view.update(), '')

            self.assertEqual(view.errors, ())

            self.assertEqual(l[0].extra1, "extra1")
            self.assertEqual(l[0].extra2, "extra2")
            self.assertEqual(l[0].name, "foo")
            self.assertEqual(l[0].address, "aa")

            self.assertEqual(request.response.getHeader("Location"), "next")

            # Verify that calling update again doesn't do anything.
            l[0] = None
            self.assertEqual(view.update(), '')
            self.assertEqual(l[0], None)

        finally:
            # Uninstall hooks
            del V.add
            del V.nextURL


def test_suite():
    return unittest.makeSuite(Test)

if __name__=='__main__':
    unittest.main(defaultTest='test_suite')


=== Added File Zope3/src/zope/app/form/browser/tests/test_browserwidget.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.
#
##############################################################################
"""

$Id: test_browserwidget.py,v 1.1 2004/03/14 01:11:36 srichter Exp $
"""
import os
import unittest
from zope.testing.doctestunit import DocTestSuite
from zope.interface import Interface, implements

from zope.app.tests import ztapi
from zope.app.form.browser.widget import BrowserWidget
from zope.app.form.interfaces import ConversionError
from zope.app.form.interfaces import WidgetInputError, MissingInputError
from zope.app.tests.placelesssetup import PlacelessSetup
from zope.i18n.interfaces import ITranslationDomain
from zope.i18n.gettextmessagecatalog import GettextMessageCatalog
from zope.i18n.translationdomain import TranslationDomain
from zope.publisher.browser import TestRequest
from zope.schema import Text
from zope.app.form.browser.tests import support
import zope.app.form.browser.tests

class BrowserWidgetTest(PlacelessSetup,
                        support.VerifyResults,
                        unittest.TestCase):
    _FieldFactory = Text
    _WidgetFactory = BrowserWidget

    def setUpContent(self, desc=u''):
        class ITestContent(Interface):
            foo = self._FieldFactory(
                    title = u"Foo Title",
                    description = desc,
                    )
        class TestObject:
            implements(ITestContent)

        self.content = TestObject()
        field = ITestContent['foo']
        request = TestRequest(HTTP_ACCEPT_LANGUAGE='pl')
        request.form['field.foo'] = u'Foo Value'
        self._widget = self._WidgetFactory(field, request)

    def setUp(self):
        super(BrowserWidgetTest, self).setUp()
        self.setUpContent()

    def test_required(self):
        self._widget.context.required = False
        self.failIf(self._widget.required)
        self._widget.context.required = True
        self.failUnless(self._widget.required)

    def test_hasInput(self):
        self.failUnless(self._widget.hasInput())
        del self._widget.request.form['field.foo']
        self.failIf(self._widget.hasInput())

    def testProperties(self):
        self.assertEqual(self._widget.tag, 'input')
        self.assertEqual(self._widget.type, 'text')
        self.assertEqual(self._widget.cssClass, '')
        self.assertEqual(self._widget.extra, '')

    def testRender(self):
        value = 'Foo Value'
        check_list = ('type="text"', 'id="field.foo"', 'name="field.foo"',
                      'value="Foo Value"')
        self._widget.setRenderedValue(value)
        self.verifyResult(self._widget(), check_list)
        check_list = ('type="hidden"',) + check_list[1:]
        self.verifyResult(self._widget.hidden(), check_list)
        check_list = ('type="hidden"', 'style="color: red"') + check_list[1:]
        self._widget.extra = 'style="color: red"'
        self.verifyResult(self._widget.hidden(), check_list)

    def testLabel(self):
        label = ' '.join(self._widget.label().strip().split())
        self.assertEqual(label, '<label for="field.foo">Foo Title</label>')

        self.setUpContent(desc=u"Foo Description")
        label = ' '.join(self._widget.label().strip().split())
        self.assertEqual(label,
                         '<label for="field.foo" title="Foo Description">'
                         'Foo Title</label>'
                         )

    def testDescription(self):
        self.setUpContent(desc=u'Foo Description')
        description = ' '.join(self._widget.description.strip().split())
        self.assertEqual(description, u'Foo Description')

    def testTranslatedLabel(self):
        path = os.path.dirname(zope.app.form.browser.tests.__file__)
        catalog = GettextMessageCatalog(
            'pl', 'zope', os.path.join(path, 'testlabeltranslation.mo'))
        domain = TranslationDomain('zope')
        domain.addCatalog(catalog)
        ztapi.provideUtility(ITranslationDomain, domain, 'zope')
        label = ' '.join(self._widget.label().strip().split())
        self.assertEqual(label, '<label for="field.foo">oofay itletay</label>')

    def testRowRequired(self):
        self._widget.request.form.clear()
        self._widget.context.required = True
        label = ''.join(self._widget.label().strip().split())
        value = ''.join(self._widget().strip().split())
        row = ''.join(self._widget.row().strip().split())
        self.assertEqual(row, '<divclass="labelrequired">%s</div>'
                              '<divclass="field">%s</div>' % (label, value))

    def testRowNonRequired(self):
        self._widget.request.form.clear()
        self._widget.context.required = False
        label = ''.join(self._widget.label().strip().split())
        value = ''.join(self._widget().strip().split())
        row = ''.join(self._widget.row().strip().split())
        self.assertEqual(row, '<divclass="label">%s</div>'
                              '<divclass="field">%s</div>' % (label, value))

class TestWidget(BrowserWidget):

    def _convert(self, v):
        if v == u'barf!':
            raise ConversionError('ralph')
        return v or None

class Test(BrowserWidgetTest):

    _WidgetFactory = TestWidget

    def test_showData(self):

        class W(BrowserWidget):
            def _convert(self, v):
                return u'X' + (v or '')

            def _unconvert(self, v):
                return v and v[1:] or ''

        field = Text(__name__ = 'foo', title = u"Foo Title")
        request = TestRequest()

        w = W(field, request)
        self.assertEqual(w._showData(), '')
        request.form['field.foo'] = 'val'
        self.assertEqual(w._showData(), 'val')

        w.setRenderedValue('Xfoo')
        self.assertEqual(w._showData(), 'foo')

    def test_hasValidInput(self):
        self.assertEqual(self._widget.getInputValue(), u'Foo Value')

        self._widget.request.form['field.foo'] = (1, 2)
        self.failIf(self._widget.hasValidInput())

        self._widget.request.form['field.foo'] = u'barf!'
        self.failIf(self._widget.hasValidInput())

        del self._widget.request.form['field.foo']        
        self._widget.context.required = True
        self.failIf(self._widget.hasValidInput())

        self._widget.context.required = False
        self._widget.request.form['field.foo'] = u''
        self.failUnless(self._widget.hasValidInput())

    def test_getInputValue(self):
        self.assertEqual(self._widget.getInputValue(), u'Foo Value')

        self._widget.request.form['field.foo'] = (1, 2)
        self.assertRaises(WidgetInputError, self._widget.getInputValue)

        self._widget.request.form['field.foo'] = u'barf!'
        self.assertRaises(ConversionError, self._widget.getInputValue)

        del self._widget.request.form['field.foo']        
        self._widget.context.required = True
        self.assertRaises(MissingInputError, self._widget.getInputValue)

        self._widget.context.required = False
        self._widget.request.form['field.foo'] = u''
        self.assertEqual(self._widget.getInputValue(), None)

    def test_applyChanges(self):
        self.assertEqual(self._widget.applyChanges(self.content), True)

    def test_hasInput(self):
        self.failUnless(self._widget.hasInput())
        del self._widget.request.form['field.foo']
        self.failIf(self._widget.hasInput())
        self._widget.request.form['field.foo'] = u'foo'
        self.failUnless(self._widget.hasInput())
        # widget has input, even if input is an empty string
        self._widget.request.form['field.foo'] = u''
        self.failUnless(self._widget.hasInput())

    def test_showData_w_default(self):
        field = Text(__name__ = 'foo', title = u"Foo Title", default=u"def")
        request = TestRequest()
        widget = self._WidgetFactory(field, request)
        self.assertEqual(widget._showData(), u'def')


def test_suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(Test))
    suite.addTest(DocTestSuite("zope.app.form.browser.widget"))
    return suite

if __name__ == '__main__':
    unittest.main(defaultTest='test_suite')


=== Added File Zope3/src/zope/app/form/browser/tests/test_checkboxwidget.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.
#
##############################################################################
"""
$Id: test_checkboxwidget.py,v 1.1 2004/03/14 01:11:37 srichter Exp $
"""
import unittest, doctest

from zope.app.form.interfaces import IInputWidget
from zope.app.form.browser.widget import CheckBoxWidget
from zope.publisher.browser import TestRequest
from zope.schema import Bool
from zope.interface.verify import verifyClass

from zope.app.form.browser.tests.test_browserwidget import BrowserWidgetTest


class CheckBoxWidgetTest(BrowserWidgetTest):
    """Documents and tests thec checkbox widget.
        
        >>> verifyClass(IInputWidget, CheckBoxWidget)
        True
        
    The rest of the this doctest was moved from widget.py to this test module
    to keep widget.py free of detailed tests. XXX the tests below should be
    more narrative to highlight the 'story' being told.

    >>> field = Bool(__name__='foo', title=u'on')
    >>> request = TestRequest(form={'field.foo.used': u'on',
    ...                             'field.foo': u'on'})
    >>> widget = CheckBoxWidget(field, request)
    >>> widget.hasInput()
    True
    >>> widget.getInputValue()
    True

    >>> def normalize(s):
    ...   return '\\n  '.join(s.split())

    >>> print normalize( widget() )
    <input
      class="hiddenType"
      id="field.foo.used"
      name="field.foo.used"
      type="hidden"
      value=""
      />
      <input
      class="checkboxType"
      checked="checked"
      id="field.foo"
      name="field.foo"
      type="checkbox"
      />

    >>> print normalize( widget.hidden() )
    <input
      class="hiddenType"
      id="field.foo"
      name="field.foo"
      type="hidden"
      value="on"
      />

    Calling setRenderedValue will change what gets output:

    >>> widget.setRenderedValue(False)
    >>> print normalize( widget() )
    <input
      class="hiddenType"
      id="field.foo.used"
      name="field.foo.used"
      type="hidden"
      value=""
      />
      <input
      class="checkboxType"
      id="field.foo"
      name="field.foo"
      type="checkbox"
      />

    When a checkbox is not 'checked', it's value is not
    sent in the request, so we consider it 'False', which
    means that 'required' for a boolean field doesn't make
    much sense in the end.

    >>> field = Bool(__name__='foo', title=u'on', required=True)
    >>> request = TestRequest(form={'field.foo.used': u''})
    >>> widget = CheckBoxWidget(field, request)
    >>> widget.hasInput()
    True
    >>> widget.validate()
    >>> widget.getInputValue()
    False
    """

    _FieldFactory = Bool
    _WidgetFactory = CheckBoxWidget

    def testProperties(self):
        self.assertEqual(self._widget.tag, 'input')
        self.assertEqual(self._widget.type, 'checkbox')
        self.assertEqual(self._widget.cssClass, '')
        self.assertEqual(self._widget.extra, '')
        self.assertEqual(self._widget.default, 0)

    def testRender(self):
        value = 1
        self._widget.setRenderedValue(value)
        check_list = ('type="checkbox"', 'id="field.foo"',
                      'name="field.foo"', 'checked="checked"')
        self.verifyResult(self._widget(), check_list)
        value = 0
        self._widget.setRenderedValue(value)
        check_list = check_list[:-1]
        self.verifyResult(self._widget(), check_list)
        check_list = ('type="hidden"',) + check_list[1:-1]
        self.verifyResult(self._widget.hidden(), check_list)
        check_list = ('style="color: red"',) + check_list
        self._widget.extra = 'style="color: red"'
        self.verifyResult(self._widget.hidden(), check_list)

    def test_getInputValue(self):
        self._widget.request.form['field.foo'] = 'on'
        self.assertEqual(self._widget.getInputValue(), True)
        self._widget.request.form['field.foo'] = 'positive'
        self.assertEqual(self._widget.getInputValue(), False)
        del self._widget.request.form['field.foo']
        self.assertEqual(self._widget.getInputValue(), False)


def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(CheckBoxWidgetTest),
        doctest.DocTestSuite(),
        ))

if __name__=='__main__':
    unittest.main(defaultTest='test_suite')


=== Added File Zope3/src/zope/app/form/browser/tests/test_configure.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 that the package's configure.zcml can be loaded.

$Id: test_configure.py,v 1.1 2004/03/14 01:11:37 srichter Exp $
"""
import unittest

from zope.app.tests.placelesssetup import PlacelessSetup
from zope.configuration import xmlconfig


class TestBrowserFormZCML(PlacelessSetup, unittest.TestCase):

    def test_load_zcml(self):
        # XXX Not much of a test.
        xmlconfig.string(
            """<configure xmlns='http://namespaces.zope.org/zope'>
                 <include package='zope.app.component' file='meta.zcml' />
                 <include package='zope.app.event' file='meta.zcml' />
                 <include package='zope.app.publisher.browser'
                          file='meta.zcml' />
            
                 <include package='zope.app.form.browser' />
               </configure>"""
            )


def test_suite():
    return unittest.makeSuite(TestBrowserFormZCML)

if __name__ == '__main__':
    unittest.main(defaultTest="test_suite")


=== Added File Zope3/src/zope/app/form/browser/tests/test_datetimewidget.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.
#
##############################################################################
"""
$Id: test_datetimewidget.py,v 1.1 2004/03/14 01:11:37 srichter Exp $
"""
import unittest, doctest
from zope.app.datetimeutils import parseDatetimetz
from zope.app.form.browser.tests.test_browserwidget import BrowserWidgetTest
from zope.app.form.interfaces import IInputWidget
from zope.app.form.browser.widget import DatetimeWidget
from zope.app.form.interfaces import ConversionError, WidgetInputError
from zope.interface.verify import verifyClass

from zope.schema import Datetime


class DatetimeWidgetTest(BrowserWidgetTest):
    """Documents and tests the datetime widget.
        
        >>> verifyClass(IInputWidget, DatetimeWidget)
        True
    """

    _FieldFactory = Datetime
    _WidgetFactory = DatetimeWidget

    def test_hasInput(self):
        del self._widget.request.form['field.foo']
        self.failIf(self._widget.hasInput())
        # widget has input, even if input is an empty string
        self._widget.request.form['field.foo'] = u''
        self.failUnless(self._widget.hasInput())
        self._widget.request.form['field.foo'] = u'2003/03/26 12:00:00'
        self.failUnless(self._widget.hasInput())

    def test_getInputValue(self):
        TEST_DATE= u'2003/03/26 12:00:00'
        self._widget.request.form['field.foo'] = u''
        self.assertRaises(WidgetInputError, self._widget.getInputValue)
        self._widget.request.form['field.foo'] = TEST_DATE
        self.assertEquals(self._widget.getInputValue(), parseDatetimetz(TEST_DATE))
        self._widget.request.form['field.foo'] = u'abc'
        self.assertRaises(ConversionError, self._widget.getInputValue)


def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(DatetimeWidgetTest),
        doctest.DocTestSuite(),
        ))

if __name__=='__main__':
    unittest.main(defaultTest='test_suite')



=== Added File Zope3/src/zope/app/form/browser/tests/test_datewidget.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.
#
##############################################################################
"""
$Id: test_datewidget.py,v 1.1 2004/03/14 01:11:37 srichter Exp $
"""
import unittest, doctest
from zope.app.datetimeutils import parseDatetimetz
from zope.app.form.browser.tests.test_browserwidget import BrowserWidgetTest
from zope.app.form.interfaces import IInputWidget
from zope.app.form.browser.widget import DateWidget
from zope.app.form.interfaces import ConversionError, WidgetInputError
from zope.schema import Date
from zope.interface.verify import verifyClass

class DateWidgetTest(BrowserWidgetTest):
    """Documents and tests the date widget.

        >>> verifyClass(IInputWidget, DateWidget)
        True
    """

    _FieldFactory = Date
    _WidgetFactory = DateWidget

    def test_hasInput(self):
        del self._widget.request.form['field.foo']
        self.failIf(self._widget.hasInput())
        self._widget.request.form['field.foo'] = u''
        self.failUnless(self._widget.hasInput())
        self._widget.request.form['field.foo'] = u'2003/03/26'
        self.failUnless(self._widget.hasInput())

    def test_getInputValue(self):
        TEST_DATE= u'2003/03/26'
        self._widget.request.form['field.foo'] = u''
        self.assertRaises(WidgetInputError, self._widget.getInputValue)
        self._widget.request.form['field.foo'] = TEST_DATE
        self.assertEquals(
            self._widget.getInputValue(), 
            parseDatetimetz(TEST_DATE).date())
        self._widget.request.form['field.foo'] = u'abc'
        self.assertRaises(ConversionError, self._widget.getInputValue)


def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(DateWidgetTest),
        doctest.DocTestSuite(),
        ))

if __name__=='__main__':
    unittest.main(defaultTest='test_suite')



=== Added File Zope3/src/zope/app/form/browser/tests/test_directives.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.
#
##############################################################################
"""Form Directives Tests

$Id: test_directives.py,v 1.1 2004/03/14 01:11:37 srichter Exp $
"""
import os
import unittest
from cStringIO import StringIO

from zope.app import zapi
from zope.interface import Interface, implements

from zope.configuration.xmlconfig import xmlconfig, XMLConfig
from zope.component import getDefaultViewName, getResource
from zope.app.tests.placelesssetup import PlacelessSetup
from zope.security.proxy import ProxyFactory

from zope.component.exceptions import ComponentLookupError

from zope.publisher.browser import TestRequest

import zope.app.publisher.browser

from zope.schema import TextLine

tests_path = os.path.join(
    os.path.split(zope.app.publisher.browser.__file__)[0],
    'tests')

template = """<configure
   xmlns='http://namespaces.zope.org/zope'
   xmlns:browser='http://namespaces.zope.org/browser'
   i18n_domain='zope'>
   %s
   </configure>"""


request = TestRequest()

class Schema(Interface):

    text = TextLine(
        title=u'Text',
        description=u'Nice text',
        required=False)

class IC(Schema): pass

class Ob:
    implements(IC)

ob = Ob()


class Test(PlacelessSetup, unittest.TestCase):

    def setUp(self):
        super(Test, self).setUp()
        XMLConfig('meta.zcml', zope.app.component)()
        XMLConfig('meta.zcml', zope.app.form.browser)()
        XMLConfig('meta.zcml', zope.app.publisher.browser)()

        from zope.app.tests import ztapi
        from zope.app.traversing.adapters import DefaultTraversable
        from zope.app.traversing.interfaces import ITraversable

        ztapi.provideAdapter(None, ITraversable, DefaultTraversable)

        ps =  zapi.getService(None, zapi.servicenames.Presentation)
        ps.defineUsage("objectview")
        ps.defineUsage("overridden")
        
    def testEditForm(self):
        self.assertEqual(zapi.queryView(ob, 'test', request),
                         None)
        xmlconfig(StringIO(template % ("""
          <view
              type="zope.publisher.interfaces.browser.IBrowserRequest"
              for="zope.schema.interfaces.ITextLine"
              provides="zope.app.form.interfaces.IInputWidget"
              factory="zope.app.form.browser.widget.TextWidget"
              permission="zope.Public"
              />

          <browser:editform
              for="zope.app.form.browser.tests.test_directives.IC"
              schema="zope.app.form.browser.tests.test_directives.Schema"
              name="edit.html"
              label="Edit a ZPT page"
              fields="text"
              permission="zope.Public" />
            """)))

        v = zapi.queryView(ob, 'edit.html', request)
        # expect component lookup as standard macros are not configured
        self.assertRaises(ComponentLookupError, v)


    def testEditFormWithMenu(self):
        self.assertEqual(zapi.queryView(ob, 'test', request),
                         None)
        xmlconfig(StringIO(template % ("""
          <browser:menu id="test_menu" title="Test menu" usage="objectview"/>
          <view
              type="zope.publisher.interfaces.browser.IBrowserRequest"
              for="zope.schema.interfaces.ITextLine"
              provides="zope.app.form.interfaces.IInputWidget"
              factory="zope.app.form.browser.widget.TextWidget"
              permission="zope.Public"
              />
          <browser:editform
              for="zope.app.form.browser.tests.test_directives.IC"
              schema="zope.app.form.browser.tests.test_directives.Schema"
              name="edit.html"
              label="Edit a ZPT page"
              fields="text"
              permission="zope.Public"
              menu="test_menu"
              title="Test View"
              />
            """)))

        v = zapi.queryView(ob, 'edit.html', request)
        self.assertEqual(v.usage, 'objectview')
        # expect component lookup as standard macros are not configured
        self.assertRaises(ComponentLookupError, v)

    def testEditFormWithUsage(self):
        self.assertEqual(zapi.queryView(ob, 'test', request),
                         None)
        xmlconfig(StringIO(template % ("""
          <view
              type="zope.publisher.interfaces.browser.IBrowserRequest"
              for="zope.schema.interfaces.ITextLine"
              provides="zope.app.form.interfaces.IInputWidget"
              factory="zope.app.form.browser.widget.TextWidget"
              permission="zope.Public"
              />
          <browser:editform
              for="zope.app.form.browser.tests.test_directives.IC"
              schema="zope.app.form.browser.tests.test_directives.Schema"
              name="edit.html"
              label="Edit a ZPT page"
              fields="text"
              permission="zope.Public"
              usage="objectview"
              />
            """)))

        v = zapi.queryView(ob, 'edit.html', request)
        self.assertEqual(v.usage, 'objectview')
        # expect component lookup as standard macros are not configured
        self.assertRaises(ComponentLookupError, v)


    def testEditFormWithMenuAndUsage(self):
        self.assertEqual(zapi.queryView(ob, 'test', request),
                         None)
        xmlconfig(StringIO(template % ("""
          <browser:menu id="test_menu" title="Test menu" usage="overridden"/>
          <view
              type="zope.publisher.interfaces.browser.IBrowserRequest"
              for="zope.schema.interfaces.ITextLine"
              provides="zope.app.form.interfaces.IInputWidget"
              factory="zope.app.form.browser.widget.TextWidget"
              permission="zope.Public"
              />
          <browser:editform
              for="zope.app.form.browser.tests.test_directives.IC"
              schema="zope.app.form.browser.tests.test_directives.Schema"
              name="edit.html"
              label="Edit a ZPT page"
              fields="text"
              permission="zope.Public"
              menu="test_menu"
              title="Test View"
              usage="objectview"        
              />
            """)))

        v = zapi.queryView(ob, 'edit.html', request)
        self.assertEqual(v.usage, 'objectview')
        # expect component lookup as standard macros are not configured
        self.assertRaises(ComponentLookupError, v)

# XXX Tests for AddFormDirective are missing

def test_suite():
    loader=unittest.TestLoader()
    return loader.loadTestsFromTestCase(Test)

if __name__=='__main__':
    unittest.TextTestRunner().run(test_suite())


=== Added File Zope3/src/zope/app/form/browser/tests/test_editview.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.
#
##############################################################################
"""$Id: test_editview.py,v 1.1 2004/03/14 01:11:37 srichter Exp $
"""
import unittest

from zope.interface import Interface, implements
from zope.publisher.browser import TestRequest
from zope.schema import TextLine, accessors
from zope.schema.interfaces import ITextLine
from zope.component.exceptions import ComponentLookupError

from zope.app.tests import ztapi
from zope.app.tests.placelesssetup import PlacelessSetup
from zope.app.event.tests.placelesssetup import getEvents

from zope.app.form.browser.editview import EditView
from zope.app.form.browser.widget import TextWidget
from zope.app.form.browser.submit import Update
from zope.component.exceptions import ComponentLookupError
from zope.app.form.interfaces import IInputWidget

class I(Interface):
    foo = TextLine(title=u"Foo")
    bar = TextLine(title=u"Bar")
    a   = TextLine(title=u"A")
    b   = TextLine(title=u"B", min_length=0, required=False)
    getbaz, setbaz = accessors(TextLine(title=u"Baz"))

class EV(EditView):
    schema = I
    object_factories = []

class C:
    implements(I)
    foo = u"c foo"
    bar = u"c bar"
    a   = u"c a"
    b   = u"c b"

    _baz = u"c baz"
    def getbaz(self): return self._baz
    def setbaz(self, v): self._baz = v


class IFoo(Interface):
    foo = TextLine(title=u"Foo")

class IBar(Interface):
    bar = TextLine(title=u"Bar")

class Foo:
    implements(IFoo)

    foo = u'Foo foo'
    
class ConformFoo(object):
    implements(IFoo)

    foo = u'Foo foo'

    def __conform__(self, interface):
        # fake proxied adapter (attention only read proxy)
        from zope.security.checker import InterfaceChecker
        from zope.security.checker import ProxyFactory
        
        if interface is IBar:
            checker = InterfaceChecker(IBar)
            return ProxyFactory(OtherFooBarAdapter(self), checker)

            
class FooBarAdapter(object):
    implements(IBar)
    __used_for__ = IFoo

    def __init__(self, context):
        self.context = context

    def getbar(self): return self.context.foo
    def setbar(self, v): self.context.foo = v

    bar = property(getbar, setbar)
    
class OtherFooBarAdapter(FooBarAdapter):
    pass

class BarV(EditView):
    schema = IBar
    object_factories = []

class Test(PlacelessSetup, unittest.TestCase):

    def setUp(self):
        super(Test, self).setUp()
        ztapi.browserViewProviding(ITextLine, TextWidget, IInputWidget)
        ztapi.provideAdapter(IFoo, IBar, FooBarAdapter)

    def test_setPrefix_and_widgets(self):
        v = EV(C(), TestRequest())
        v.setPrefix("test")
        self.assertEqual(
            [w.name for w in v.widgets()],
            ['test.foo', 'test.bar', 'test.a', 'test.b', 'test.getbaz']
            )

    def test_fail_wo_adapter(self):
        c = Foo()
        request = TestRequest()
        self.assertRaises(ComponentLookupError, EV, c, request)

    def test_update_no_update(self):
        c = C()
        request = TestRequest()
        v = EV(c, request)
        self.assertEqual(v.update(), '')
        self.assertEqual(c.foo, u'c foo')
        self.assertEqual(c.bar, u'c bar')
        self.assertEqual(c.a  , u'c a')
        self.assertEqual(c.b  , u'c b')
        self.assertEqual(c.getbaz(), u'c baz')
        request.form['field.foo'] = u'r foo'
        request.form['field.bar'] = u'r bar'
        request.form['field.a']   = u'r a'
        request.form['field.b']   = u'r b'
        request.form['field.getbaz'] = u'r baz'
        self.assertEqual(v.update(), '')
        self.assertEqual(c.foo, u'c foo')
        self.assertEqual(c.bar, u'c bar')
        self.assertEqual(c.a  , u'c a')
        self.assertEqual(c.b  , u'c b')
        self.assertEqual(c.getbaz(), u'c baz')
        self.failIf(getEvents())

    def test_update(self):
        c = C()
        request = TestRequest()
        v = EV(c, request)
        request.form[Update] = ''
        request.form['field.foo'] = u'r foo'
        request.form['field.bar'] = u'r bar'
        request.form['field.getbaz'] = u'r baz'
        request.form['field.a'] = u'c a'

        message = v.update()
        self.failUnless(message.startswith('Updated '), message)
        self.assertEqual(c.foo, u'r foo')
        self.assertEqual(c.bar, u'r bar')
        self.assertEqual(c.a  , u'c a')
        self.assertEqual(c.b  , u'c b') # missing from form - unchanged
        self.assertEqual(c.getbaz(), u'r baz')

        # Verify that calling update multiple times has no effect

        c.__dict__.clear()
        self.assertEqual(v.update(), message)
        self.assertEqual(c.foo, u'c foo')
        self.assertEqual(c.bar, u'c bar')
        self.assertEqual(c.a  , u'c a')
        self.assertEqual(c.b  , u'c b')
        self.assertEqual(c.getbaz(), u'c baz')

    def test_update_via_adapter(self):
        f = Foo()
        request = TestRequest()
        v = BarV(f, request)
        # check adapter
        self.assertEqual(f.foo, u'Foo foo')
        a = IBar(f)
        self.assertEqual(a.bar, u'Foo foo')
        # update
        request.form[Update] = ''
        request.form['field.bar'] = u'r bar'
        message = v.update()
        self.failUnless(message.startswith('Updated '), message)
        self.assertEqual(a.bar, u'r bar')
        # wrong update
        self.failIf(getEvents())

    def test_setUpWidget_via_conform_adapter(self):
        
        f = ConformFoo()
        request = TestRequest()
        v = BarV(f, request)
        
def test_suite():
    return unittest.makeSuite(Test)

if __name__=='__main__':
    unittest.main(defaultTest='test_suite')


=== Added File Zope3/src/zope/app/form/browser/tests/test_editwizardview.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.
#
##############################################################################
"""$Id: test_editwizardview.py,v 1.1 2004/03/14 01:11:37 srichter Exp $
"""
import unittest

from zope.interface import Interface, implements
from zope.publisher.browser import TestRequest
from zope.schema import TextLine, accessors
from zope.schema.interfaces import ITextLine
from zope.security.checker import InterfaceChecker, ProxyFactory

from zope.app.tests import ztapi
from zope.app.tests.placelesssetup import PlacelessSetup

from zope.app.form.browser.editwizard import EditWizardView
from zope.app.form.browser.widget import TextWidget

from zope.app.form.interfaces import IInputWidget


class I(Interface):
    foo = TextLine(title=u"Foo")
    bar = TextLine(title=u"Bar")
    a   = TextLine(title=u"A")
    b   = TextLine(title=u"B", min_length=0, required=False)
    getbaz, setbaz = accessors(TextLine(title=u"Baz"))

class EV(EditWizardView):
    schema = I
    object_factories = []
    use_session = None

class C:
    implements(I)
    foo = u"c foo"
    bar = u"c bar"
    a   = u"c a"
    b   = u"c b"

    _baz = u"c baz"
    def getbaz(self): return self._baz
    def setbaz(self, v): self._baz = v


class IFoo(Interface):
    foo = TextLine(title=u"Foo")

class IBar(Interface):
    bar = TextLine(title=u"Bar")

class Foo:
    implements(IFoo)

    foo = u'Foo foo'
    
class ConformFoo(object):
    implements(IFoo)

    foo = u'Foo foo'

    def __conform__(self, interface):
        # fake proxied adapter (attention only read proxy)        
        if interface is IBar:
            checker = InterfaceChecker(IBar)
            return ProxyFactory(OtherFooBarAdapter(self), checker)

            
class FooBarAdapter(object):
    implements(IBar)
    __used_for__ = IFoo

    def __init__(self, context):
        self.context = context

    def getbar(self): return self.context.foo
    def setbar(self, v): self.context.foo = v

    bar = property(getbar, setbar)
    
class OtherFooBarAdapter(FooBarAdapter):
    pass

class BarV(EditWizardView):
    schema = IBar
    object_factories = []
    use_session = None

class Test(PlacelessSetup, unittest.TestCase):

    def setUp(self):
        super(Test, self).setUp()
        ztapi.browserViewProviding(ITextLine, TextWidget, IInputWidget)
        ztapi.provideAdapter(IFoo, IBar, FooBarAdapter)

    def test_setUpWidget(self):
        c = C()
        request = TestRequest()
        v = EV(c, request)

    def test_setUpWidget_via_adapter(self):
        f = Foo()
        request = TestRequest()
        v = BarV(f, request)

    def test_setUpWidget_via_conform_adapter(self):        
        f = ConformFoo()
        request = TestRequest()
        v = BarV(f, request)
        
def test_suite():
    return unittest.makeSuite(Test)

if __name__=='__main__':
    unittest.main(defaultTest='test_suite')


=== Added File Zope3/src/zope/app/form/browser/tests/test_filewidget.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.
#
##############################################################################
"""
$Id: test_filewidget.py,v 1.1 2004/03/14 01:11:37 srichter Exp $
"""
import unittest, doctest

from StringIO import StringIO
from zope.app.form.interfaces import IInputWidget
from zope.app.form.browser.widget import FileWidget

from zope.app.form.browser.tests.test_browserwidget import BrowserWidgetTest

from zope.interface.verify import verifyClass

class FileWidgetTest(BrowserWidgetTest):
    """Documents and tests the file widget.
    
        >>> verifyClass(IInputWidget, FileWidget)
        True
    """

    _WidgetFactory = FileWidget

    def setUp(self):
        BrowserWidgetTest.setUp(self)

        file = StringIO('Foo Value')
        file.filename = 'test.txt'
        self._widget.request.form['field.foo'] = file

    def testProperties(self):
        self.assertEqual(self._widget.tag, 'input')
        self.assertEqual(self._widget.type, 'file')
        self.assertEqual(self._widget.cssClass, '')
        self.assertEqual(self._widget.extra, '')
        self.assertEqual(self._widget.default, '')
        self.assertEqual(self._widget.displayWidth, 20)
        self.assertEqual(self._widget.displayMaxWidth, '')

    def testRender(self):
        value = 'Foo Value'
        self._widget.setRenderedValue(value)
        check_list = ('type="file"', 'id="field.foo"', 'name="field.foo"',
                      'size="20"')

        self.verifyResult(self._widget(), check_list)
        check_list = ('type="hidden"',) + check_list[1:-1]
        self.verifyResult(self._widget.hidden(), check_list)
        check_list = ('style="color: red"',) + check_list
        self._widget.extra = 'style="color: red"'
        self.verifyResult(self._widget.hidden(), check_list)



def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(FileWidgetTest),
        doctest.DocTestSuite(),
        ))

if __name__=='__main__':
    unittest.main(defaultTest='test_suite')


=== Added File Zope3/src/zope/app/form/browser/tests/test_floatwidget.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.
#
##############################################################################
"""
$Id: test_floatwidget.py,v 1.1 2004/03/14 01:11:37 srichter Exp $
"""
import unittest, doctest
from zope.app.form.browser.tests.test_browserwidget import BrowserWidgetTest
from zope.app.form.interfaces import IInputWidget
from zope.app.form.browser.widget import FloatWidget
from zope.app.form.interfaces import ConversionError, WidgetInputError
from zope.interface.verify import verifyClass

from zope.schema import Float


class FloatWidgetTest(BrowserWidgetTest):
    """Documents and tests the float widget.
        
        >>> verifyClass(IInputWidget, FloatWidget)
        True
    """

    _FieldFactory = Float
    _WidgetFactory = FloatWidget

    def test_hasInput(self):
        del self._widget.request.form['field.foo']
        self.failIf(self._widget.hasInput())
        # widget has input, even if input is an empty string
        self._widget.request.form['field.foo'] = u''
        self.failUnless(self._widget.hasInput())
        self._widget.request.form['field.foo'] = u'123'
        self.failUnless(self._widget.hasInput())

    def test_getInputValue(self):
        self._widget.request.form['field.foo'] = u''
        self.assertRaises(WidgetInputError, self._widget.getInputValue)
        self._widget.request.form['field.foo'] = u'123.45'
        self.assertEquals(self._widget.getInputValue(), 123.45)
        self._widget.request.form['field.foo'] = u'abc'
        self.assertRaises(ConversionError, self._widget.getInputValue)


def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(FloatWidgetTest),
        doctest.DocTestSuite(),
        ))

if __name__=='__main__':
    unittest.main(defaultTest='test_suite')


=== Added File Zope3/src/zope/app/form/browser/tests/test_intwidget.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.
#
##############################################################################
"""
$Id: test_intwidget.py,v 1.1 2004/03/14 01:11:37 srichter Exp $
"""
import unittest, doctest
from unittest import main, makeSuite
from zope.app.form.browser.tests.test_browserwidget import BrowserWidgetTest
from zope.app.form.interfaces import IInputWidget
from zope.app.form.browser.widget import IntWidget
from zope.app.form.interfaces import ConversionError, WidgetInputError
from zope.interface.verify import verifyClass

from zope.schema import Int


class IntWidgetTest(BrowserWidgetTest):
    """Documents and tests the int widget.
        
        >>> verifyClass(IInputWidget, IntWidget)
        True
    """

    _FieldFactory = Int
    _WidgetFactory = IntWidget

    def test_hasInput(self):
        del self._widget.request.form['field.foo']
        self.failIf(self._widget.hasInput())
        # widget has input, even if input is an empty string
        self._widget.request.form['field.foo'] = u''
        self.failUnless(self._widget.hasInput())
        self._widget.request.form['field.foo'] = u'123'
        self.failUnless(self._widget.hasInput())

    def test_getInputValue(self):
        self._widget.request.form['field.foo'] = u''
        self.assertRaises(WidgetInputError, self._widget.getInputValue)
        self._widget.request.form['field.foo'] = u'123'
        self.assertEquals(self._widget.getInputValue(), 123)
        self._widget.request.form['field.foo'] = u'abc'
        self.assertRaises(ConversionError, self._widget.getInputValue)


def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(IntWidgetTest),
        doctest.DocTestSuite(),
        ))

if __name__=='__main__':
    unittest.main(defaultTest='test_suite')


=== Added File Zope3/src/zope/app/form/browser/tests/test_listwidget.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.
#
##############################################################################
"""
$Id: test_listwidget.py,v 1.1 2004/03/14 01:11:37 srichter Exp $
"""
import unittest, doctest

from zope.app.form.interfaces import IInputWidget
from zope.app.form.browser.widget import ListWidget
from zope.app.form.browser.tests.test_browserwidget import BrowserWidgetTest
from zope.interface.verify import verifyClass

class ListWidgetTest(BrowserWidgetTest):
    """Documents and tests the list widget.
        
        >>> verifyClass(IInputWidget, ListWidget)
        True
    """

    def setUp(self):
        BrowserWidgetTest.setUp(self)
        self._widget.context.allowed_values = (u'foo', u'bar')

    _WidgetFactory = ListWidget

    def testProperties(self):
        self.assertEqual(self._widget.cssClass, "")
        self.assertEqual(self._widget.extra, '')
        self.assertEqual(self._widget.firstItem, 0)
        self.assertEqual(self._widget.size, 5)


    def testRenderItem(self):
        check_list = ('option', 'value="foo"', 'Foo')
        self.verifyResult(
            self._widget.renderItem(0, 'Foo', 'foo', 'field.bar', None),
            check_list)
        check_list += ('selected="selected"',)
        self.verifyResult(
            self._widget.renderSelectedItem(
                0, 'Foo', 'foo', 'field.bar', None),
            check_list)


    def testRenderItems(self):
        check_list = ('option', 'value="foo"', 'bar',
                      'value="foo"', 'foo', 'selected="selected"')
        self.verifyResult('\n'.join(self._widget.renderItems('foo')),
                          check_list)


    def testRender(self):
        value = 'foo'
        check_list = ('select', 'id="field.foo"', 'name="field.foo"',
                      'size="5"', 'option', 'value="foo"', '>foo<',
                      'value="foo"', '>bar<', 'selected="selected"')
        self._widget.setRenderedValue(value)
        self.verifyResult(self._widget(), check_list)

        check_list = ('type="hidden"', 'id="field.foo"', 'name="field.foo"',
                      'value="foo"')
        self.verifyResult(self._widget.hidden(), check_list)
        check_list = ('style="color: red"',) + check_list
        self._widget.extra = 'style="color: red"'
        self.verifyResult(self._widget.hidden(), check_list)



def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(ListWidgetTest),
        doctest.DocTestSuite(),
        ))

if __name__=='__main__':
    unittest.main(defaultTest='test_suite')


=== Added File Zope3/src/zope/app/form/browser/tests/test_multicheckboxwidget.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.
#
##############################################################################
"""
$Id: test_multicheckboxwidget.py,v 1.1 2004/03/14 01:11:37 srichter Exp $
"""
import unittest, doctest

from zope.app.form.interfaces import IInputWidget
from zope.app.form.browser.widget import MultiCheckBoxWidget
from zope.app.form.browser.tests.test_browserwidget import BrowserWidgetTest
from zope.interface.verify import verifyClass

class MultiCheckBoxWidgetTest(BrowserWidgetTest):
    """Documents and tests the multi checkbox widget.
        
        >>> verifyClass(IInputWidget, MultiCheckBoxWidget)
        True
    """

    _WidgetFactory = MultiCheckBoxWidget

    def setUp(self):
        BrowserWidgetTest.setUp(self)
        self._widget.context.allowed_values = (u'foo', u'bar')

    def testProperties(self):
        self.assertEqual(self._widget.cssClass, "")
        self.assertEqual(self._widget.extra, '')
        self.assertEqual(self._widget.orientation, 'vertical')


    def testRenderItem(self):
        check_list = ('type="checkbox"', 'id="field.bar"',
                      'name="field.bar"', 'value="foo"', 'Foo')
        self.verifyResult(
            self._widget.renderItem(0, 'Foo', 'foo', 'field.bar', None),
            check_list)
        check_list += ('checked="checked"',)
        self.verifyResult(
            self._widget.renderSelectedItem(
                0, 'Foo', 'foo', 'field.bar', None),
            check_list)


    def testRenderItems(self):
        check_list = ('type="checkbox"', 'id="field.foo"',
                      'name="field.foo"', 'value="bar"', 'bar',
                      'value="foo"', 'foo', 'checked="checked"')
        self.verifyResult('\n'.join(self._widget.renderItems('bar')),
                          check_list)


    def testRender(self):
        value = 'bar'
        self._widget.setRenderedValue(value)
        check_list = ('type="checkbox"', 'id="field.foo"',
                      'name="field.foo"', 'value="bar"', 'bar',
                      'value="foo"', 'foo', 'checked="checked"')
        self.verifyResult(self._widget(), check_list)

        check_list = ('type="hidden"', 'id="field.foo"', 'name="field.foo"',
                      'value="bar"')
        self.verifyResult(self._widget.hidden(), check_list)
        check_list = ('style="color: red"',) + check_list
        self._widget.extra = 'style="color: red"'
        self.verifyResult(self._widget.hidden(), check_list)


def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(MultiCheckBoxWidgetTest),
        doctest.DocTestSuite(),
        ))

if __name__=='__main__':
    unittest.main(defaultTest='test_suite')


=== Added File Zope3/src/zope/app/form/browser/tests/test_multilistwidget.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.
#
##############################################################################
"""
$Id: test_multilistwidget.py,v 1.1 2004/03/14 01:11:37 srichter Exp $
"""
import unittest, doctest

from zope.app.form.interfaces import IInputWidget
from zope.app.form.browser.widget import MultiListWidget
from zope.app.form.browser.tests.test_browserwidget import BrowserWidgetTest
from zope.interface.verify import verifyClass

class MultiListWidgetTest(BrowserWidgetTest):
    """Documents and tests the multi-list widget.
        
        >>> verifyClass(IInputWidget, MultiListWidget)
        True
    """

    _WidgetFactory = MultiListWidget

    def setUp(self):
        BrowserWidgetTest.setUp(self)
        self._widget.context.allowed_values = (u'foo', u'bar')

    def testProperties(self):
        self.assertEqual(self._widget.cssClass, "")
        self.assertEqual(self._widget.extra, '')
        self.assertEqual(self._widget.size, 5)


    def testRenderItem(self):
        check_list = ('option', 'value="foo"', 'Foo')
        self.verifyResult(
            self._widget.renderItem(0, 'Foo', 'foo', 'field.bar', None),
            check_list)
        check_list += ('selected="selected"',)
        self.verifyResult(
            self._widget.renderSelectedItem(
                0, 'Foo', 'foo', 'field.bar', None),
            check_list)

    def testRenderItems(self):
        check_list = ('option', 'value="foo"', 'bar',
                      'value="foo"', 'foo', 'selected="selected"')
        self.verifyResult('\n'.join(self._widget.renderItems('foo')),
                          check_list)


    def testRender(self):
        value = 'foo'
        self._widget.setRenderedValue(value)
        check_list = ('select', 'id="field.foo"', 'name="field.foo"',
                      'size="5"', 'option', 'value="foo"', '>foo<',
                      'value="foo"', '>bar<', 'selected="selected"',
                      'multiple="multiple"')
        self.verifyResult(self._widget(), check_list)

        check_list = ('type="hidden"', 'id="field.foo"', 'name="field.foo"',
                      'value="foo"')
        self.verifyResult(self._widget.hidden(), check_list)
        check_list = ('style="color: red"',) + check_list
        self._widget.extra = 'style="color: red"'
        self.verifyResult(self._widget.hidden(), check_list)



def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(MultiListWidgetTest),
        doctest.DocTestSuite(),
        ))

if __name__=='__main__':
    unittest.main(defaultTest='test_suite')


=== Added File Zope3/src/zope/app/form/browser/tests/test_objectwidget.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.
#
##############################################################################
"""
$Id: test_objectwidget.py,v 1.1 2004/03/14 01:11:37 srichter Exp $
"""

import unittest, doctest

from zope.app.tests import ztapi
from zope.interface import Interface, implements
from zope.schema.interfaces import ITextLine
from zope.publisher.browser import TestRequest
from zope.schema import Object, TextLine
from zope.app.form.interfaces import IInputWidget
from zope.app.form.browser.widget import TextWidget, ObjectWidget
from zope.interface.verify import verifyClass

from zope.app.form.browser.tests.test_browserwidget import BrowserWidgetTest

class ITestContact(Interface):
    name = TextLine()
    email = TextLine()
class TestContact:
    implements(ITestContact)

class ObjectWidgetTest(BrowserWidgetTest):
    """Documents and tests the object widget.
        
        >>> verifyClass(IInputWidget, ObjectWidget)
        True
    """

    _FieldFactory = Object
    def _WidgetFactory(self, context, request, **kw):
        kw.update({'factory': TestContact})
        return ObjectWidget(context, request, **kw)

    def setUpContent(self, desc=u''):
        ztapi.browserViewProviding(ITextLine, TextWidget, IInputWidget)

        class ITestContent(Interface):
            foo = self._FieldFactory(
                    ITestContact, 
                    title = u"Foo Title",
                    description = desc
                    )
        class TestObject:
            implements(ITestContent)

        self.content = TestObject()
        self.field = ITestContent['foo']
        self.request = TestRequest(HTTP_ACCEPT_LANGUAGE='pl')
        self.request.form['field.foo'] = u'Foo Value'
        self._widget = self._WidgetFactory(self.field, self.request)

    def test_hasInput(self):
        # doesn't work with subfields
        pass

    def testRender(self):
        # doesn't work with subfields
        pass

    def setUp(self):
        BrowserWidgetTest.setUp(self)
        self.field = Object(ITestContact, __name__=u'foo')
        ztapi.browserViewProviding(ITextLine, TextWidget, IInputWidget)

    def test_applyChanges(self):
        self.request.form['field.foo.name'] = u'Foo Name'
        self.request.form['field.foo.email'] = u'foo at foo.test'
        widget = self._WidgetFactory(self.field, self.request)

        self.assertEqual(widget.applyChanges(self.content), True)
        self.assertEqual(hasattr(self.content, 'foo'), True)
        self.assertEqual(isinstance(self.content.foo, TestContact), True)
        self.assertEqual(self.content.foo.name, u'Foo Name')
        self.assertEqual(self.content.foo.email, u'foo at foo.test')

    def test_applyChangesNoChange(self):
        self.content.foo = TestContact()
        self.content.foo.name = u'Foo Name'
        self.content.foo.email = u'foo at foo.test'

        self.request.form['field.foo.name'] = u'Foo Name'
        self.request.form['field.foo.email'] = u'foo at foo.test'
        widget = self._WidgetFactory(self.field, self.request)
        widget.setRenderedValue(self.content.foo)

        self.assertEqual(widget.applyChanges(self.content), False)
        self.assertEqual(hasattr(self.content, 'foo'), True)
        self.assertEqual(isinstance(self.content.foo, TestContact), True)
        self.assertEqual(self.content.foo.name, u'Foo Name')
        self.assertEqual(self.content.foo.email, u'foo at foo.test')

    def test_new(self):
        request = TestRequest()
        widget = ObjectWidget(self.field, request, TestContact)
        self.assertEquals(int(widget.hasInput()), 0)
        check_list = (
            'input', 'name="field.foo.name"',
            'input', 'name="field.foo.email"'
        )
        self.verifyResult(widget(), check_list)

    def test_edit(self):
        request = TestRequest(form={
            'field.foo.name': u'fred',
            'field.foo.email': u'fred at fred.com'
            })
        widget = ObjectWidget(self.field, request, TestContact)
        self.assertEquals(int(widget.hasInput()), 1)
        o = widget.getInputValue()
        self.assertEquals(hasattr(o, 'name'), 1)
        self.assertEquals(o.name, u'fred')
        self.assertEquals(o.email, u'fred at fred.com')
        check_list = (
            'input', 'name="field.foo.name"', 'value="fred"',
            'input', 'name="field.foo.email"', 'value="fred at fred.com"',
        )
        self.verifyResult(widget(), check_list)

def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(ObjectWidgetTest),
        doctest.DocTestSuite(),
        ))

if __name__=='__main__':
    unittest.main(defaultTest='test_suite')

# vim: set filetype=python ts=4 sw=4 et si




=== Added File Zope3/src/zope/app/form/browser/tests/test_passwordwidget.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.
#
##############################################################################
"""
$Id: test_passwordwidget.py,v 1.1 2004/03/14 01:11:37 srichter Exp $
"""
import unittest, doctest

from zope.app.form.interfaces import IInputWidget
from zope.app.form.browser.widget import PasswordWidget
from zope.app.form.browser.tests.test_browserwidget import BrowserWidgetTest
from zope.interface.verify import verifyClass

class PasswordWidgetTest(BrowserWidgetTest):
    """Documents and tests the password widget.

        >>> verifyClass(IInputWidget, PasswordWidget)
        True
    """

    _WidgetFactory = PasswordWidget

    def testProperties(self):
        self.assertEqual(self._widget.tag, 'input')
        self.assertEqual(self._widget.type, 'password')
        self.assertEqual(self._widget.cssClass, '')
        self.assertEqual(self._widget.extra, '')
        self.assertEqual(self._widget.default, '')
        self.assertEqual(self._widget.displayWidth, 20)
        self.assertEqual(self._widget.displayMaxWidth, '')

    def testRender(self):
        value = 'Foo Value'
        self._widget.setRenderedValue(value)
        check_list = ('type="password"', 'id="field.foo"',
                      'name="field.foo"', 'value=""', 'size="20"')
        self.verifyResult(self._widget(), check_list)

    def testHidden(self):
        self.assertRaises(NotImplementedError, self._widget.hidden)

def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(PasswordWidgetTest),
        doctest.DocTestSuite(),
        ))

if __name__=='__main__':
    unittest.main(defaultTest='test_suite')


=== Added File Zope3/src/zope/app/form/browser/tests/test_radiowidget.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.
#
##############################################################################
"""
$Id: test_radiowidget.py,v 1.1 2004/03/14 01:11:37 srichter Exp $
"""
import os
import unittest, doctest
from zope.interface.verify import verifyClass

from zope.i18n.interfaces import ITranslationDomain
from zope.i18n.gettextmessagecatalog import GettextMessageCatalog
from zope.i18n.translationdomain import TranslationDomain

from zope.app.tests import ztapi
from zope.app.form.interfaces import IInputWidget
from zope.app.form.browser.widget import RadioWidget
from zope.app.form.browser.tests.test_browserwidget import BrowserWidgetTest
import zope.app.form.browser.tests

class RadioWidgetTest(BrowserWidgetTest):
    """Documents and tests the radio widget.
        
        >>> verifyClass(IInputWidget, RadioWidget)
        True
    """

    _WidgetFactory = RadioWidget

    def setUp(self):
        BrowserWidgetTest.setUp(self)
        self._widget.context.allowed_values = (u'foo', u'bar')

    def testProperties(self):
        self.assertEqual(self._widget.cssClass, "")
        self.assertEqual(self._widget.extra, '')
        self.assertEqual(self._widget.firstItem, 0)
        self.assertEqual(self._widget.orientation, 'vertical')


    def testRenderItem(self):
        check_list = ('type="radio"', 'id="field.bar.0"',
                      'name="field.bar"', 'value="foo"', 'Foo')
        self.verifyResult(
            self._widget.renderItem(0, 'Foo', 'foo', 'field.bar', None),
            check_list)
        check_list += ('checked="checked"',)
        self.verifyResult(
            self._widget.renderSelectedItem(
                0, 'Foo', 'foo', 'field.bar', None),
            check_list)


    def testRenderItems(self):
        check_list = ('type="radio"', 'id="field.foo.0"', 'name="field.foo"',
                      'value="bar"', 'bar', 'value="foo"', 'foo',
                      'checked="checked"')
        self.verifyResult('\n'.join(self._widget.renderItems('bar')),
                          check_list)


    def testRender(self):
        value = 'bar'
        self._widget.setRenderedValue(value)
        check_list = ('type="radio"', 'id="field.foo.0"',
                      'name="field.foo"', 'value="bar"', 'bar',
                      'value="foo"', 'foo', 'checked="checked"')
        self.verifyResult(self._widget(), check_list)

        check_list = ('type="hidden"', 'id="field.foo"',
                      'name="field.foo"', 'value="bar"')
        self.verifyResult(self._widget.hidden(), check_list)
        check_list = ('style="color: red"',) + check_list
        self._widget.extra = 'style="color: red"'
        self.verifyResult(self._widget.hidden(), check_list)

    def testLabel(self):
        label = ' '.join(self._widget.label().strip().split())
        self.assertEqual(label, 'Foo Title')

    def testTranslatedLabel(self):
        path = os.path.dirname(zope.app.form.browser.tests.__file__)
        catalog = GettextMessageCatalog(
            'pl', 'zope', os.path.join(path, 'testlabeltranslation.mo'))
        domain = TranslationDomain('zope')
        domain.addCatalog(catalog)
        ztapi.provideUtility(ITranslationDomain, domain, 'zope')
        label = ' '.join(self._widget.label().strip().split())
        self.assertEqual(label, 'oofay itletay')

    def testRowRequired(self):
        self._widget.request.form.clear()
        self._widget.context.required = True
        label = ''.join(self._widget.label().strip().split())
        value = ''.join(self._widget().strip().split())
        row = ''.join(self._widget.row().strip().split())
        id = 'field.foo'
        self.assertEqual(row, '<divclass="labelrequired">'
                              '<labelfor="%s">%s</label>'
                              '</div>'
                              '<divclass="field"id="%s">'
                              '%s'
                              '</div>' % (id, label, id, value))

    def testRowNonRequired(self):
        self._widget.request.form.clear()
        self._widget.context.required = False
        label = ''.join(self._widget.label().strip().split())
        value = ''.join(self._widget().strip().split())
        row = ''.join(self._widget.row().strip().split())
        id = 'field.foo'
        self.assertEqual(row, '<divclass="label">'
                              '<labelfor="%s">%s</label>'
                              '</div>'
                              '<divclass="field"id="%s">'
                              '%s'
                              '</div>' % (id, label, id, value))

def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(RadioWidgetTest),
        doctest.DocTestSuite(),
        ))

if __name__=='__main__':
    unittest.main(defaultTest='test_suite')


=== Added File Zope3/src/zope/app/form/browser/tests/test_sequencewidget.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.
#
##############################################################################
"""
$Id: test_sequencewidget.py,v 1.1 2004/03/14 01:11:37 srichter Exp $
"""

import unittest, doctest

from zope.app.tests import ztapi
from zope.app.form.browser.widget import TextWidget
from zope.schema.interfaces import ITextLine, ValidationError
from zope.publisher.browser import TestRequest
from zope.schema import Tuple, List, TextLine
from zope.app.form.interfaces import IInputWidget
from zope.app.form.browser.widget import TupleSequenceWidget
from zope.app.form.browser.widget import ListSequenceWidget
from zope.interface.verify import verifyClass

from zope.app.form.browser.tests.test_browserwidget import BrowserWidgetTest

class SequenceWidgetTest(BrowserWidgetTest):
    """Documents and tests the tuple and list (sequence) widgets.
    
        >>> verifyClass(IInputWidget, TupleSequenceWidget)
        True
        >>> verifyClass(IInputWidget, ListSequenceWidget)
        True
    """

    def _FieldFactory(self, **kw):
        kw.update({
            '__name__': u'foo', 
            'value_type': TextLine(__name__=u'bar')})
        return Tuple(**kw)
    _WidgetFactory = TupleSequenceWidget

    def testRender(self):
        pass

    def setUp(self):
        BrowserWidgetTest.setUp(self)
        self.field = Tuple(
            __name__=u'foo',
            value_type=TextLine(__name__=u'bar'))
        ztapi.browserViewProviding(ITextLine, TextWidget, IInputWidget)

    def test_haveNoData(self):
        self.failIf(self._widget.hasInput())

    def test_hasInput(self):
        self._widget.request.form['field.foo.0.bar'] = u'hi, mum'
        self.failUnless(self._widget.hasInput())

    def test_list(self):
        self.field = List(
            __name__=u'foo',
            value_type=TextLine(__name__=u'bar'))
        request = TestRequest()
        widget = ListSequenceWidget(self.field, request)
        self.failIf(widget.hasInput())
        self.assertEquals(widget.getInputValue(), [])

        request = TestRequest(form={'field.foo.add': u'Add bar'})
        widget = ListSequenceWidget(self.field, request)
        self.assert_(widget.hasInput())
        self.assertRaises(ValidationError, widget.getInputValue)

        request = TestRequest(form={'field.foo.0.bar': u'Hello world!'})
        widget = ListSequenceWidget(self.field, request)
        self.assert_(widget.hasInput())
        self.assertEquals(widget.getInputValue(), [u'Hello world!'])

    def test_new(self):
        request = TestRequest()
        widget = TupleSequenceWidget(self.field, request)
        self.failIf(widget.hasInput())
        self.assertEquals(widget.getInputValue(), ())
        check_list = ('input', 'name="field.foo.add"')
        self.verifyResult(widget(), check_list)

    def test_add(self):
        request = TestRequest(form={'field.foo.add': u'Add bar'})
        widget = TupleSequenceWidget(self.field, request)
        self.assert_(widget.hasInput())
        self.assertRaises(ValidationError, widget.getInputValue)
        check_list = (
            'checkbox', 'field.foo.remove_0', 'input', 'field.foo.0.bar',
            'submit', 'submit', 'field.foo.add'
        )
        self.verifyResult(widget(), check_list, inorder=True)

    def test_request(self):
        request = TestRequest(form={'field.foo.0.bar': u'Hello world!'})
        widget = TupleSequenceWidget(self.field, request)
        self.assert_(widget.hasInput())
        self.assertEquals(widget.getInputValue(), (u'Hello world!',))

    def test_existing(self):
        request = TestRequest()
        widget = TupleSequenceWidget(self.field, request)
        widget.setRenderedValue((u'existing',))
        self.assert_(widget.hasInput())
        self.assertEquals(widget.getInputValue(), (u'existing',))
        check_list = (
            'checkbox', 'field.foo.remove_0', 'input', 'field.foo.0.bar',
                'existing',
            'submit', 'submit', 'field.foo.add'
        )
        self.verifyResult(widget(), check_list, inorder=True)
        widget.setRenderedValue((u'existing', u'second'))
        self.assert_(widget.hasInput())
        self.assertEquals(widget.getInputValue(), (u'existing', u'second'))
        check_list = (
            'checkbox', 'field.foo.remove_0', 'input', 'field.foo.0.bar',
                'existing',
            'checkbox', 'field.foo.remove_1', 'input', 'field.foo.1.bar',
                'second',
            'submit', 'submit', 'field.foo.add'
        )
        self.verifyResult(widget(), check_list, inorder=True)

    def test_remove(self):
        request = TestRequest(form={'field.foo.remove_0': u'Hello world!',
            'field.foo.0.bar': u'existing', 'field.foo.1.bar': u'second'})
        widget = TupleSequenceWidget(self.field, request)
        widget.setRenderedValue((u'existing', u'second'))
        self.assertEquals(widget.getInputValue(), (u'second',))
        check_list = (
            'checkbox', 'field.foo.remove_0', 'input', 'field.foo.0.bar',
                'second',
            'submit', 'submit', 'field.foo.add'
        )
        self.verifyResult(widget(), check_list, inorder=True)

    def test_min(self):
        request = TestRequest()
        self.field.min_length = 2
        widget = TupleSequenceWidget(self.field, request)
        widget.setRenderedValue((u'existing',))
        self.assertEquals(widget.getInputValue(), (u'existing',))
        check_list = (
            'input', 'field.foo.0.bar', 'existing',
            'input', 'field.foo.1.bar', 'value=""',
            'submit', 'field.foo.add'
        )
        s = widget()
        self.verifyResult(s, check_list, inorder=True)
        self.assertEquals(s.find('checkbox'), -1)

    def test_max(self):
        request = TestRequest()
        self.field.max_length = 1
        widget = TupleSequenceWidget(self.field, request)
        widget.setRenderedValue((u'existing',))
        self.assertEquals(widget.getInputValue(), (u'existing',))
        s = widget()
        self.assertEquals(s.find('field.foo.add'), -1)

    def test_anonymousfield(self):
        self.field = Tuple(__name__=u'foo', value_type=TextLine())
        request = TestRequest()
        widget = TupleSequenceWidget(self.field, request)
        widget.setRenderedValue((u'existing',))
        s = widget()
        check_list = (
            'input', '"field.foo.0."', 'existing',
            'submit', 'submit', 'field.foo.add'
        )
        s = widget()
        self.verifyResult(s, check_list, inorder=True)

def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(SequenceWidgetTest),
        doctest.DocTestSuite(),
        ))

if __name__=='__main__':
    unittest.main(defaultTest='test_suite')
# vim: set filetype=python ts=4 sw=4 et si



=== Added File Zope3/src/zope/app/form/browser/tests/test_setprefix.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.
#
##############################################################################
"""
$Id: test_setprefix.py,v 1.1 2004/03/14 01:11:37 srichter Exp $
"""
import unittest

from zope.app.form.browser.widget import TextWidget
from zope.publisher.browser import TestRequest
from zope.schema import Text

class Test(unittest.TestCase):

    def setUp(self):
        field = Text(__name__ = 'foo')
        request = TestRequest()
        request.form['spam.foo'] = u'Foo Value'
        self._widget = TextWidget(field, request)
        self._widget.setPrefix('spam')

    def testGetData(self):
        self.assertEqual(self._widget.getInputValue(), u'Foo Value')

    def testRender(self):
        value = 'Foo Value 2'
        check_list = ('type="text"', 'id="spam.foo"', 'name="spam.foo"',
                      'value="Foo Value 2"', 'size="20"')
        self._widget.setRenderedValue(value)
        self._verifyResult(self._widget(), check_list)
        check_list = ('type="hidden"',) + check_list[1:-1]
        self._verifyResult(self._widget.hidden(), check_list)
        check_list = ('style="color: red"',) + check_list
        self._widget.extra = 'style="color: red"'
        self._verifyResult(self._widget.hidden(), check_list)

    def _verifyResult(self, result, check_list):
        for check in check_list:
            self.assertNotEqual(-1, result.find(check),
                                '"'+check+'" not found in "'+result+'"')



def test_suite():
    return unittest.makeSuite(Test)

if __name__=='__main__':
    unittest.main(defaultTest='test_suite')


=== Added File Zope3/src/zope/app/form/browser/tests/test_textareawidget.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.
#
##############################################################################
"""
$Id: test_textareawidget.py,v 1.1 2004/03/14 01:11:37 srichter Exp $
"""
import unittest, doctest

from zope.app.form.interfaces import IInputWidget
from zope.app.form.browser.widget import TextAreaWidget
from zope.app.form.browser.tests.test_browserwidget import BrowserWidgetTest
from zope.interface.verify import verifyClass

class TextAreaWidgetTest(BrowserWidgetTest):
    """Documents and tests the text area widget.

        >>> verifyClass(IInputWidget, TextAreaWidget)
        True
    """

    _WidgetFactory = TextAreaWidget

    def testProperties(self):
        self.assertEqual(self._widget.tag, 'input')
        self.assertEqual(self._widget.type, 'text')
        self.assertEqual(self._widget.cssClass, '')
        self.assertEqual(self._widget.extra, '')
        self.assertEqual(self._widget.width, 60)
        self.assertEqual(self._widget.height, 15)

    def testRender(self):
        value = "Foo Value"
        self._widget.setRenderedValue(value)
        check_list = ('rows="15"', 'cols="60"', 'id="field.foo"',
                      'name="field.foo"', 'textarea')
        self.verifyResult(self._widget(), check_list)
        check_list = ('style="color: red"',) + check_list
        self._widget.extra = 'style="color: red"'
        self.verifyResult(self._widget(), check_list)
        check_list = ('type="hidden"', 'id="field.foo"', 'name="field.foo"',
                      'value="Foo Value"')
        self.verifyResult(self._widget.hidden(), check_list)


def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(TextAreaWidgetTest),
        doctest.DocTestSuite(),
        ))

if __name__=='__main__':
    unittest.main(defaultTest='test_suite')


=== Added File Zope3/src/zope/app/form/browser/tests/test_textwidget.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.
#
##############################################################################
"""
$Id: test_textwidget.py,v 1.1 2004/03/14 01:11:37 srichter Exp $
"""
import unittest, doctest

from zope.interface.verify import verifyClass
from zope.schema import TextLine

from zope.app.form.interfaces import IInputWidget
from zope.app.form.browser.widget import TextWidget
from zope.app.form.browser.tests.test_browserwidget import BrowserWidgetTest

class TextWidgetTest(BrowserWidgetTest):
    """Documents and tests the text widget.

        >>> verifyClass(IInputWidget, TextWidget)
        True
    """

    _WidgetFactory = TextWidget

    def testProperties(self):
        self.assertEqual(self._widget.tag, 'input')
        self.assertEqual(self._widget.type, 'text')
        self.assertEqual(self._widget.cssClass, '')
        self.assertEqual(self._widget.extra, '')
        self.assertEqual(self._widget.default, '')
        self.assertEqual(self._widget.displayWidth, 20)
        self.assertEqual(self._widget.displayMaxWidth, '')

    def testRender(self):
        value = 'Foo Value'
        self._widget.setRenderedValue(value)
        check_list = ('type="text"', 'id="field.foo"', 'name="field.foo"',
                      'value="Foo Value"', 'size="20"')
        self.verifyResult(self._widget(), check_list)
        check_list = ('type="hidden"',) + check_list[1:-1]
        self.verifyResult(self._widget.hidden(), check_list)
        check_list = ('style="color: red"',) + check_list
        self._widget.extra = 'style="color: red"'
        self.verifyResult(self._widget.hidden(), check_list)

def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(TextWidgetTest),
        doctest.DocTestSuite(),
        ))

if __name__=='__main__':
    unittest.main(defaultTest='test_suite')


=== Added File Zope3/src/zope/app/form/browser/tests/test_vocabularywidget.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 field widget machinery.

$Id: test_vocabularywidget.py,v 1.1 2004/03/14 01:11:37 srichter Exp $
"""

import unittest

from zope.app.tests import ztapi
from zope.app.form.browser import vocabularywidget
from zope.app.form.browser.tests import support
from zope.app.form.browser.interfaces import IBrowserWidget
from zope.app.form.browser.interfaces import IVocabularyQueryView
from zope.app.tests.placelesssetup import PlacelessSetup
from zope.component import getView
from zope.interface.declarations import implements
from zope.publisher.browser import TestRequest

from zope.schema.interfaces import IVocabulary, IVocabularyQuery
from zope.schema.interfaces import IVocabularyField, IVocabularyListField
from zope.schema.interfaces import IIterableVocabularyQuery
from zope.schema.interfaces import IVocabularyTokenized
from zope.schema import vocabulary


class ISampleVocabulary(IVocabularyTokenized, IVocabulary):
    """Specialized interface so we can hook views onto a vocabulary."""


class SampleVocabulary(vocabulary.SimpleVocabulary):
    """Vocabulary used to test vocabulary-based specialization of widgets."""
    implements(ISampleVocabulary)


class SampleDisplayWidget(vocabularywidget.VocabularyWidgetBase):
    """Widget used to test that vocabulary-based specialization works.

    This is not intended to be a useful widget.
    """
    implements(IBrowserWidget)

    def __call__(self):
        return "foo"


class SampleContent:
    """Stub content object used by makeField()."""


class QueryVocabulary(vocabulary.SimpleVocabulary):
    """Vocabulary that offer simple query support."""

    def getQuery(self):
        return MyVocabularyQuery(self)


class IMyVocabularyQuery(IVocabularyQuery):
    """Specialized query type."""


class MyVocabularyQuery:
    """Vocabulary query object which query views can be registered for."""

    implements(IMyVocabularyQuery)

    def __init__(self, vocabulary):
        self.vocabulary = vocabulary


class MyQueryViewSingle(vocabularywidget.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 MyQueryViewMulti(MyQueryViewSingle):
    """Multi-selection vocabulary query view."""

    label = "multi"


class VocabularyWidgetTestBase(PlacelessSetup,
                               support.VerifyResults,
                               unittest.TestCase):
    """Base class for all the vocabulary widget tests.

    This class provides version helper methods.
    """

    def setUp(self):
        super(VocabularyWidgetTestBase, self).setUp()
        self.registerViews()

    # makeField() uses the following class variables:
    _marker = object()
    # defaultFieldValue -- default value for the field on the content object
    # fieldClass -- class for the vocabulary field (VocabularyField or
    #               VocabularyMultiField)

    def makeField(self, vocabulary=None, value=_marker, required=False):
        """Create and return a bound vocabulary field."""
        if vocabulary is None:
            vocabulary = self.sampleVocabulary
        field = self.fieldClass(vocabulary=vocabulary, __name__="f",
                                required=required)
        content = SampleContent()
        if value is self._marker:
            value = self.defaultFieldValue
        content.f = value
        return field.bind(content)

    def makeRequest(self, querystring=None):
        """Create and return a request.

        If querystring is not None, it is passed as the QUERY_STRING.
        """
        if querystring is None:
            return TestRequest()
        else:
            tr = TestRequest(QUERY_STRING=querystring)
            tr.processInputs()
            return tr


class SingleSelectionViews:
    """Mixin that registers single-selection views."""

    def registerViews(self):
        # This is equivalent to the default configuration for
        # vocabulary field view registration from configure.zcml.
        # Single-selection views only.
        ztapi.browserView(
            IVocabularyField,
            "display",
            vocabularywidget.VocabularyFieldDisplayWidget)
        ztapi.browserView(
            IVocabularyField,
            "edit",
            vocabularywidget.VocabularyFieldEditWidget)
        # Register the "basic" widgets:
        ztapi.browserView(
            IVocabularyTokenized,
            "field-display-widget",
            vocabularywidget.VocabularyDisplayWidget)
        ztapi.browserView(
            IVocabularyTokenized,
            "field-edit-widget",
            # XXX indirect through a derived class to allow
            # testing of multiple concrete widgets
            self.singleSelectionEditWidget)
        ztapi.browserView(
            IIterableVocabularyQuery,
            "widget-query-helper",
            vocabularywidget.IterableVocabularyQueryView)
        # The following widget registration supports the specific
        # sample vocabulary we're using, used to demonstrate how to
        # override widget selection based on vocabulary:
        ztapi.browserView(ISampleVocabulary,
                    "field-display-widget",
                                        SampleDisplayWidget)


class MultiSelectionViews:

    def registerViews(self):
        # This is equivalent to the default configuration for
        # vocabulary field view registration from configure.zcml.
        # Multi-selection views only.
        ztapi.browserView(
            IVocabularyListField,
            "display",
            vocabularywidget.VocabularyListFieldDisplayWidget)
        ztapi.browserView(
            IVocabularyListField,
            "edit",
            vocabularywidget.VocabularyListFieldEditWidget)
        # Bind widgets to the vocabulary fields:
        ztapi.browserView(
            IVocabularyTokenized,
            "field-display-list-widget",
            vocabularywidget.VocabularyListDisplayWidget)
        ztapi.browserView(
            IVocabularyTokenized,
            "field-edit-list-widget",
            vocabularywidget.VocabularyMultiEditWidget)
        ztapi.browserView(
            IIterableVocabularyQuery,
            "widget-query-list-helper",
            vocabularywidget.IterableVocabularyQueryMultiView)
        # The following widget registration supports the specific
        # sample vocabulary we're using, used to demonstrate how to
        # override widget selection based on vocabulary:
        ztapi.browserView(ISampleVocabulary,
                    "field-display-list-widget",
                                        SampleDisplayWidget)


class SelectionTestBase(VocabularyWidgetTestBase):
    """Base class for the general widget tests (without query support)."""

    def test_vocabulary_specialization(self):
        bound = self.makeField(SampleVocabulary.fromValues(["frobnication"]))
        w = getView(bound, "display", self.makeRequest())
        self.assertEqual(w(), "foo")


class SingleSelectionTestsBase(SingleSelectionViews, SelectionTestBase):
    """Test cases for basic single-selection widgets."""

    defaultFieldValue = "splat"
    fieldClass = vocabulary.VocabularyField

    sampleVocabulary = vocabulary.SimpleVocabulary.fromValues(
        ["splat", "foobar"])

    def test_display(self):
        bound = self.makeField()
        w = getView(bound, "display", self.makeRequest())
        w.setRenderedValue(bound.context.f)
        self.assertEqual(w(), "splat")

    def test_display_with_form_value(self):
        bound = self.makeField()
        request = self.makeRequest('field.f=foobar')
        w = getView(bound, "display", request)
        self.assert_(w.hasInput())
        self.assertEqual(w(), "foobar")

    def setup_edit(self, bound):
        w = getView(bound, "edit", self.makeRequest())
        w.setRenderedValue(bound.context.f)
        self.assert_(not w.hasInput())
        return w

    def test_edit(self, extraChecks=[]):
        w = self.setup_edit(self.makeField())
        self.assertEqual(w.getInputValue(), None)
        self.verifyResult(w(), [
            'selected="selected"',
            'id="field.f"',
            'name="field.f"',
            'value="splat"',
            '>splat<',
            'value="foobar"',
            '>foobar<',
            ] + extraChecks)
        s0, s1, s2 = w.renderItems("foobar")
        self.verifyResult(s0, [
            "value=''",
            "no value",
            ])
        self.verifyResult(s1, [
            'value="splat"',
            '>splat<',
            ])
        self.assert_(s1.find('selected') < 0)
        self.verifyResult(s2, [
            'selected="selected"',
            'value="foobar"',
            '>foobar<',
            ])

    def test_edit_required(self, extraChecks=[]):
        w = self.setup_edit(self.makeField(required=True))
        self.verifyResult(w(), [
            'selected="selected"',
            'id="field.f"',
            'name="field.f"',
            'value="splat"',
            '>splat<',
            'value="foobar"',
            '>foobar<',
            ] + extraChecks)
        s1, s2 = w.renderItems("foobar")
        self.verifyResult(s1, [
            'value="splat"',
            '>splat<',
            ])
        self.assert_(s1.find('selected') < 0)
        self.verifyResult(s2, [
            'selected="selected"',
            'value="foobar"',
            '>foobar<',
            ])

    def test_edit_with_form_value(self):
        bound = self.makeField()
        request = self.makeRequest('field.f=foobar')
        w = getView(bound, "edit", request)
        self.assert_(w.hasInput())
        self.assertEqual(w.getInputValue(), "foobar")
        self.assert_(isinstance(w, vocabularywidget.VocabularyEditWidget))

    def test_edit_with_modified_empty_value(self):
        # This tests that emptying a value via the form when there's a
        # non-empty value for the field on the content object will
        # report hasInput() properly.
        bound = self.makeField()
        bound.context.f = "splat"
        w = getView(bound, "edit", self.makeRequest(
            'field.f-empty-marker='))
        self.assert_(w.hasInput())
        self.assertEqual(w.getInputValue(), None) # XXX might be []...

class SingleSelectionTests(SingleSelectionTestsBase):
    """Test single-selection with the selection-box widget."""

    singleSelectionEditWidget = vocabularywidget.SelectListWidget


class RadioSelectionTests(SingleSelectionTests):
    
    singleSelectionEditWidget = vocabularywidget.RadioWidget

    # override three tests

    def test_edit_with_form_value(self):
        bound = self.makeField()
        request = self.makeRequest('field.f=foobar')
        w = getView(bound, "edit", request)
        self.assert_(w.hasInput())
        self.assertEqual(w.getInputValue(), "foobar")
        self.assert_(isinstance(w, vocabularywidget.RadioWidget))

    def test_edit(self, extraChecks=[]):
        w = self.setup_edit(self.makeField())
        self.assertEqual(w.getInputValue(), None)
        self.verifyResult(w(), [
            'checked="checked"',
            'id="field.f"',
            'name="field.f"',
            'value="splat"',
            '&nbsp;splat',
            'value="foobar"',
            '&nbsp;foobar',
            ] + extraChecks)
        s0, s1, s2 = w.renderItems("foobar")
        self.verifyResult(s0, [
            'value=""',
            "no value",
            ])
        self.verifyResult(s1, [
            'value="splat"',
            '&nbsp;splat',
            ])
        self.assert_(s1.find('selected') < 0)
        self.verifyResult(s2, [
            'checked="checked"',
            'value="foobar"',
            '&nbsp;foobar',
            ])

    def test_edit_required(self, extraChecks=[]):
        w = self.setup_edit(self.makeField(required=True))
        self.verifyResult(w(), [
            'checked="checked"',
            'id="field.f"',
            'name="field.f"',
            'value="splat"',
            '&nbsp;splat',
            'value="foobar"',
            '&nbsp;foobar',
            ] + extraChecks)
        s1, s2 = w.renderItems("foobar")
        self.verifyResult(s1, [
            'value="splat"',
            '&nbsp;splat',
            ])
        self.assert_(s1.find('selected') < 0)
        self.verifyResult(s2, [
            'checked="checked"',
            'value="foobar"',
            '&nbsp;foobar',
            ])

class DropdownSelectionTests(SingleSelectionTestsBase):
    """Test single-selection with the dropdown-list widget."""

    singleSelectionEditWidget = vocabularywidget.DropdownListWidget

    def test_edit(self):
        SingleSelectionTestsBase.test_edit(self, extraChecks=['size="1"'])

    def test_edit_required(self):
        SingleSelectionTestsBase.test_edit_required(
            self, extraChecks=['size="1"'])


class MultiSelectionTests(MultiSelectionViews, SelectionTestBase):
    """Test cases for basic multi-selection widgets."""

    defaultFieldValue = ["splat"]
    fieldClass = vocabulary.VocabularyListField
    sampleVocabulary = vocabulary.SimpleVocabulary.fromValues(
        ["splat", "foobar", "frob"])

    def test_display_without_value(self):
        bound = self.makeField()
        del bound.context.f
        w = getView(bound, "display", self.makeRequest())
        self.assert_(not w.hasInput())
        self.assertEqual(w(), "")

    def test_display_with_value(self):
        bound = self.makeField(value=["foobar", "frob"])
        w = getView(bound, "display", self.makeRequest())
        w.setRenderedValue(bound.context.f)
        self.assert_(not w.hasInput())
        self.verifyResult(w(), [
            '<ol',
            'id="field.f"',
            'name="field.f"',
            '</ol>',
            ])
        w.cssClass = 'test'
        items = w.renderItems(['foobar'])
        self.assertEqual(len(items), 1)
        self.verifyResult(items[0], [
            '<li',
            'class="test-item"',
            '>foobar<',
            '</li>',
            ])

    def test_display_with_form_data(self):
        bound = self.makeField(value=["foobar", "frob"])
        request = self.makeRequest('field.f:list=splat')
        w = getView(bound, "display", request)
        self.assert_(w.hasInput())
        s = w()
        self.verifyResult(s, [
            '<ol',
            'id="field.f"',
            'name="field.f"',
            '<li',
            '>splat<',
            '</li>',
            '</ol>',
            ])
        self.assert_(s.find("foobar") < 0)
        self.assert_(s.find("frob") < 0)

    def test_edit(self):
        bound = self.makeField()
        w = getView(bound, "edit", self.makeRequest())
        self.assert_(not w.hasInput())
        self.verifyResult(w(), [
            'id="field.f"',
            'name="field.f:list"',
            'value="splat"',
            '>splat<',
            'value="foobar"',
            '>foobar<',
            'value="frob"',
            '>frob<',
            ])
        s1, s2, s3 = w.renderItems(w._missing)
        self.verifyResult(s1, [
            'value="splat"',
            '>splat<',
            ])
        self.assert_(s1.find('selected') < 0)
        self.verifyResult(s2, [
            'value="foobar"',
            '>foobar<',
            ])
        self.assert_(s2.find('selected') < 0)
        self.verifyResult(s3, [
            'value="frob"',
            '>frob<',
            ])
        self.assert_(s3.find('selected') < 0)

    def test_edit_with_form_value(self):
        bound = self.makeField()
        request = self.makeRequest('field.f:list=foobar&field.f:list=splat')
        w = getView(bound, "edit", request)
        self.assert_(w.hasInput())
        L = w.getInputValue()
        L.sort()
        self.assertEqual(L, ["foobar", "splat"])


class QuerySupportTestBase(VocabularyWidgetTestBase):
    """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.
    """

    sampleVocabulary = QueryVocabulary.fromValues(
        ["splat", "foobar", "frob"])

    def test_get_query_helper(self):
        bound = self.makeField()
        request = self.makeRequest()
        w = getView(bound, "edit", request)
        self.assert_(isinstance(w.query, MyVocabularyQuery))
        self.assert_(w.queryview.widget is w)
        self.assertEqual(w.queryview.name, w.name + "-query")
        self.assertEqual(w.queryview.label, self.queryViewLabel)

    def test_query_input_section(self):
        bound = self.makeField()
        w = getView(bound, "edit", self.makeRequest())
        w.setRenderedValue(bound.context.f)
        checks = [
            "this-is-query-input",
            ]
        self.verifyResult(w.queryview.renderInput(), checks)
        self.verifyResult(w(), checks + ['class="queryinput"'])

    def test_query_output_section_without_results(self):
        bound = self.makeField()
        w = getView(bound, "edit", self.makeRequest())
        w.setRenderedValue(bound.context.f)
        checks = [
            "query-results-go-here",
            ]
        self.verifyResultMissing(w.queryview.renderResults([]), checks)
        self.verifyResultMissing(w(), checks + ['class="queryresults"'])

    def test_query_output_section_with_results(self):
        bound = self.makeField()
        w = getView(bound, "edit", self.makeRequest("field.f-query=foo"))
        w.setRenderedValue(bound.context.f)
        checks = [
            "query-results-go-here",
            ]
        self.verifyResult(w.queryview.renderResults([]), checks)
        self.verifyResult(w(), checks + ['class="queryresults"'])


class SingleSelectionQuerySupportTests(SingleSelectionViews,
                                       QuerySupportTestBase):
    """Query support tests for single-selection widgets."""

    defaultFieldValue = "splat"
    fieldClass = vocabulary.VocabularyField
    queryViewLabel = "single"
    singleSelectionEditWidget = vocabularywidget.VocabularyEditWidget

    def registerViews(self):
        SingleSelectionViews.registerViews(self)
        ztapi.browserView(IMyVocabularyQuery,
                          "widget-query-helper",
                          MyQueryViewSingle)


class MultiSelectionQuerySupportTests(MultiSelectionViews,
                                      QuerySupportTestBase):
    """Query support tests for multi-selection widgets."""

    defaultFieldValue = ["splat"]
    fieldClass = vocabulary.VocabularyListField
    queryViewLabel = "multi"

    def registerViews(self):
        MultiSelectionViews.registerViews(self)
        ztapi.browserView(IMyVocabularyQuery,
                          "widget-query-list-helper",
                          MyQueryViewMulti)


def test_suite():
    suite = unittest.makeSuite(SingleSelectionTests)
    suite.addTest(unittest.makeSuite(RadioSelectionTests))
    suite.addTest(unittest.makeSuite(DropdownSelectionTests))
    suite.addTest(unittest.makeSuite(MultiSelectionTests))
    suite.addTest(unittest.makeSuite(SingleSelectionQuerySupportTests))
    suite.addTest(unittest.makeSuite(MultiSelectionQuerySupportTests))
    return suite

if __name__ == '__main__':
    unittest.main(defaultTest="test_suite")


=== Added File Zope3/src/zope/app/form/browser/tests/testconfigure.zcml ===
<configure
   xmlns='http://namespaces.zope.org/zope'
   xmlns:browser='http://namespaces.zope.org/browser'
   i18n_domain='zope'
   >

  <!-- Test view for folders -->
  <browser:pages
      permission="zope.View" 
      for="zope.app.folder.interfaces.IFolder"
      class=".SchemaTestObject.EditFactory">
      <browser:page name="testSchemaFormView.html" attribute="form" />
      <browser:page name="testSchemaFormAction.html" attribute="action" />
  </browser:pages>

</configure>


=== Added File Zope3/src/zope/app/form/browser/tests/testeditform.pt ===
<html>
  <head>
    <title>Simple Edit Form</title>
  </head>

  <body>

    <h1>This is a Schema produced form</h1>

    <div tal:condition="python: options.has_key('errors') and 
                                options['errors']">
      <span style="font-weight: bold">Errors:</span>
      <div tal:repeat="error options/errors | nothing">
        <span tal:replace="python: error[0].title" />: 
        <span tal:replace="python: error[1].error_name" />
      </div>
    </div>
    <br />
    <form action="testSchemaFormAction.html" method="post">
      <input type="hidden" name="nextURL" value=""
          tal:attributes="value request/URL" />   
      <table>

        <tal:block repeat="field view/getFields">
          <tr>
            <th tal:content="field/title">Title:</th>
            <td tal:content="structure python: view.renderField(field)">
              <input size="20" />
            </td>            
          </tr>
        </tal:block>

      </table>
 
      <input type="submit" name="save" value="Save" />

    </form>
  </body>

</html>


=== Added File Zope3/src/zope/app/form/browser/tests/testlabeltranslation.mo ===
  <Binary-ish file>

=== Added File Zope3/src/zope/app/form/browser/tests/testlabeltranslation.po ===
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL at ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"POT-Creation-Date: 2003-03-25 15:01-0500\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL at ADDRESS>\n"
"Language-Team: LANGUAGE <LL at li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=us-ascii\n"
"Content-Transfer-Encoding: 8bit\n"

#: test_browserwidget.py:34
msgid "Foo Title"
msgstr "oofay itletay"




More information about the Zope3-Checkins mailing list