[Zope-Checkins] CVS: Zope3/lib/python/Zope/App/Formulator/tests - testField.py:1.1.2.1 testFieldRegistry.py:1.1.2.1 testIInstanceFactory.py:1.1.2.1 testPropertyFieldAdapter.py:1.1.2.1 testSimpleRegistry.py:1.1.2.1 testValidator.py:1.1.2.1 testValidatorRegistry.py:1.1.2.1

Stephan Richter srichter@cbu.edu
Fri, 1 Mar 2002 02:04:39 -0500


Update of /cvs-repository/Zope3/lib/python/Zope/App/Formulator/tests
In directory cvs.zope.org:/tmp/cvs-serv22190/tests

Added Files:
      Tag: srichter-OFS_Formulator-branch
	testField.py testFieldRegistry.py testIInstanceFactory.py 
	testPropertyFieldAdapter.py testSimpleRegistry.py 
	testValidator.py testValidatorRegistry.py 
Log Message:
Checkin for new Formualtor layout. Much has changed since the initial
checkin:


- Both classes and instances of fields can be used as factory when creating
  views.


- Field: This object is simply a meta-data container for a piece of 
  information; for content objects these are usually its properties.


  Note: It is planned to have a CompositeField for more complex inputs, 
        such as dates.


- FieldViews are virtual objects; they are basically realized Widgets (or 
  Widgets in context)


- Validator: An object that validates data. Note that this object is 
  totally input/protocol-agnostic. Therefore the old concept of some of the
  Zope 2 Formulator validators is not applicable anymore.


- Widget: This is a generic component that is concerned about the 
  presentation of a field in a particular protocol. A difference to the 
  Zope 2 Formulator version is that the widget is also responsible of
  converting possible input-specific representation to a standard one. This
  is not yet fully implemented though.


- Form: A protocol-specific object that is concerned with the overall 
  representation of a form and its action.


- There is a Validator and Field Registry, since Fields and Validators can
  also be used independent of Formulator's goals. Fields should really 
  become the standard way to provide meta-data for properties.


Todo: (too much)


- I need to write a proper metaConfigure.py.


- Make a CompositeField.


- Create XUL Widgets.


- Clean up files.


- Finishing the conversion to the Zope 3 Formulator model.


=== Added File Zope3/lib/python/Zope/App/Formulator/tests/testField.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
# 
##############################################################################
"""
This test suite tests all Field methods with exception tothe ones defined by
IInstanceFactory, since they have their own test suite.

$Id: testField.py,v 1.1.2.1 2002/03/01 07:04:37 srichter Exp $
"""

import unittest
from Zope.App.Formulator.Field import Field
from Zope.App.Formulator.Validators.StringValidator import StringValidator

class ContentObject:
    """Content Object stub that will provide the context fir the
       InstanceFactory"""
    pass



class Test( unittest.TestCase ):


    def _makeField(self):
        """Make a field to test the functions with."""

        context = ContentObject()
        some_field = Field(context=context,
                           id='some',
                           title='Something',
                           description='This is some field.',
                           required=1,
                           default='Empty',
                           validator=StringValidator())
        return some_field


    def testInitWithoutContext(self):
        """Test __init__ without passing a context."""
        some_field = Field(id='some',
                           title='Something',
                           description='This is some field.',
                           required=1,
                           default='Empty',
                           validator=None)

        self.assertEqual(some_field.context, None)
        self.assertEqual(some_field.id, 'some')
        self.assertEqual(some_field.title, 'Something')
        self.assertEqual(some_field.description, 'This is some field.')
        self.assertEqual(some_field.required, 1)
        self.assertEqual(some_field.default, 'Empty')
        self.assertEqual(some_field.validator, None)        


    def testInitWithContext(self):
        """Test __init__ with passing a context."""
        context = ContentObject()
        some_field = Field(context=context,
                           id='some',
                           title='Something',
                           description='This is some field.',
                           required=1,
                           default='Empty',
                           validator=None)

        self.assertEqual(some_field.context, context)
        self.assertEqual(some_field.id, 'some')
        self.assertEqual(some_field.title, 'Something')
        self.assertEqual(some_field.description, 'This is some field.')
        self.assertEqual(some_field.required, 1)
        self.assertEqual(some_field.default, 'Empty')
        self.assertEqual(some_field.validator, None)        


    def testGetValidator(self):
        """Test the getValidator method."""
        field = self._makeField()
        self.assertEqual(type(field.getValidator()), type(StringValidator()))        


    def testHasValue(self):
        """Test the hasValue method."""
        field = self._makeField()
        self.assertEqual(field.hasValue('id'), 1)
        self.assertEqual(field.hasValue('foo'), 0)


    def testGetValue(self):
        """Test the getValue method."""
        field = self._makeField()
        self.assertEqual(field.getValue('id'), 'some')
        self.assertEqual(field.getValue('foo'), None)
        self.assertEqual(field.getValue('foo', 'bar'), 'bar')


    def testIsRequired(self):
        """Test the isRequired method."""
        field = self._makeField()
        self.assertEqual(field.isRequired(), 1)


    def testGetErrorNames(self):
        """Test the getErrorNames method."""
        field = self._makeField()
        self.assertEqual(field.getErrorNames(), ['externalValidatorFailed',
                                                 'requiredNotFound', 'tooLong'])

    def testGetErrorMessage(self):
        """Test the getErrorMessage method."""
        field = self._makeField()
        self.assertEqual(field.getErrorMessage('tooLong'), field.validator.tooLong)
        self.assertEqual(field.getErrorMessage('foo'), None)
        


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


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



=== Added File Zope3/lib/python/Zope/App/Formulator/tests/testFieldRegistry.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
# 
##############################################################################
"""
I do not think it is necessary to do the entire SimpleRegistry tests again.
Instead we will test whether the module in itself works.

$Id: testFieldRegistry.py,v 1.1.2.1 2002/03/01 07:04:37 srichter Exp $
"""

import unittest
from Interface import Interface
from Zope.App.Formulator.FieldRegistry import registerField, getField, IField

class Field:
    """Field Stub."""

    __implements__ = IField



class Test( unittest.TestCase ):


    def testRegistry(self):

        field = Field()

        registerField('field', field)
        self.assertEqual(getField('field'), field)
        

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


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



=== Added File Zope3/lib/python/Zope/App/Formulator/tests/testIInstanceFactory.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
# 
##############################################################################
"""
This suite will test whether the IInstanceFactory will work correctly. In
order to save some dependencies, we will implement a stub for the test.

$Id: testIInstanceFactory.py,v 1.1.2.1 2002/03/01 07:04:37 srichter Exp $
"""

import unittest
from Zope.App.Formulator.IInstanceFactory import IInstanceFactory


class ContentObject:
    """Content Object stub that will provide the context fir the
       InstanceFactory"""
    pass


class Factory:
    """InstanceFactory stub."""

    __implements__ = IInstanceFactory


    context = None

    ############################################################
    # Implementation methods for interface
    # Zope.App.Formulator.IInstanceFactory.

    def __call__(self, context):
        '''See interface IInstanceFactory'''
        self.realize(context)


    def getContext(self):
        '''See interface IInstanceFactory'''
        return self.context


    def realize(self, context):
        '''See interface IInstanceFactory'''
        self.context = context
    #
    ############################################################



class Test(unittest.TestCase):


    def testRealize(self):
        context = ContentObject()
        factory = Factory()
        factory.realize(context)
        self.assertEqual(factory.context, context)


    def testCall(self):
        context = ContentObject()
        factory = Factory()
        factory(context)
        self.assertEqual(factory.context, context)


    def testGetContext(self):
        context = ContentObject()
        factory = Factory()
        factory.context = context
        self.assertEqual(factory.getContext(), context)

        

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


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



=== Added File Zope3/lib/python/Zope/App/Formulator/tests/testPropertyFieldAdapter.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
# 
##############################################################################
"""
This test suite tests the functionality of the PropertyFieldAdapter. This test
will actually depend on the Field class, but the required ContentObject is
implemented as a stub.

$Id: testPropertyFieldAdapter.py,v 1.1.2.1 2002/03/01 07:04:37 srichter Exp $
"""

import unittest
from Zope.App.Formulator.PropertyFieldAdapter import PropertyFieldAdapter
from Zope.App.Formulator.Fields.Generic.StringField import StringField

DataField = StringField(id='data',
                        title='Data of Content Object',
                        description='This field represents the data...',
                        default='')


class ContentObject:
    """Content Obejct stub."""

    data = ''

    def setData(self, data):
        """Set the data property."""
        self.data = data


    def getData(self):
        """Get the data property."""
        return self.data



class Test(unittest.TestCase):


    def testAdapterRegistry(self):
        """Test somehow whether the PropertyFieldAdapter was correclty
           registered"""

        # XXX I do not know how to do these tests yet.


    def testSetData(self):
        """Test setting the data in the ContentObejct."""

        content = ContentObject()
        field = DataField(content)
        adapter = PropertyFieldAdapter(field)

        adapter.setPropertyInContext('Some Data')
        self.assertEqual(content.data, 'Some Data')


    def testGetData(self):
        """Test getting the data from the ContentObejct."""

        content = ContentObject()
        content.data = 'Some Data'
        field = DataField(content)
        adapter = PropertyFieldAdapter(field)

        self.assertEqual(adapter.getPropertyInContext(), 'Some Data')
        


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


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



=== Added File Zope3/lib/python/Zope/App/Formulator/tests/testSimpleRegistry.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: testSimpleRegistry.py,v 1.1.2.1 2002/03/01 07:04:37 srichter Exp $
"""

import unittest
from Interface import Interface
from Zope.App.Formulator.SimpleRegistry import SimpleRegistry, \
     ZopeDuplicateRegistryEntryError, ZopeIllegalInterfaceError


class I1(Interface):
    pass


class I2(Interface):
    pass


class Object1:
    __implements__ = I1


class Object2:
    __implements__ = I2


class Test( unittest.TestCase ):


    def testRegister(self):

        registry = SimpleRegistry(I1)
        obj1 = Object1()

        self.assertEqual(registry.objects, {})
        
        registry.register('obj1', obj1)
        self.assertEqual(registry.objects, {'obj1': obj1})

        registry.register('obj2', obj1)
        self.assertEqual(registry.objects, {'obj1': obj1, 'obj2': obj1})


    def testIllegalInterfaceError(self):

        registry = SimpleRegistry(I1)
        obj2 = Object2()

        self.failUnlessRaises(ZopeIllegalInterfaceError,
                              registry.register, 'obj2', obj2)
        

    def testDuplicateEntry(self):

        registry = SimpleRegistry(I1)
        obj1 = Object1()
        registry.register('obj1', obj1)

        self.failUnlessRaises(ZopeDuplicateRegistryEntryError,
                              registry.register, 'obj1', obj1)
        

    def testGet(self):

        registry = SimpleRegistry(I1)
        obj1 = Object1()
        obj2 = Object1()
        registry.objects = {'obj1': obj1, 'obj2': obj2}

        self.assertEqual(registry.get('obj1'), obj1)
        self.assertEqual(registry.get('obj2'), obj2)

        # Requesting an object that does not exist
        self.assertEqual(registry.get('obj3'), None)
        


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


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



=== Added File Zope3/lib/python/Zope/App/Formulator/tests/testValidator.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
# 
##############################################################################
"""
This test suite tests all Validator methods with exception tothe ones defined
by IInstanceFactory, since they have their own test suite.

These tests are actually pretty boring, since almost nothing is implemented.
The action can be found in the Validators/ subdirectory/

$Id: testValidator.py,v 1.1.2.1 2002/03/01 07:04:37 srichter Exp $
"""

import unittest
from Zope.App.Formulator.Validator import Validator
from Zope.App.Formulator.Errors import ValidationError


class Field:
    """Field stub"""

    id = 'id'
    
    def getErrorMessage(self, name):
        return "Unknown error: %s" % name


def extValidator(self, value):
    """External Validator stub."""
    return value


class Test( unittest.TestCase ):

    def _makeValidator(self):
        """Make a validator to test the functions with."""
        some_validator = Validator()
        return some_validator


    def testInit(self):
        """Test __init__ without passing a context."""
        some_validator = Validator(externalValidator=extValidator)
        self.assertEqual(some_validator.externalValidator, extValidator)


    def testValidate(self):
        """Test the validate method."""
        validator = self._makeValidator()
        self.assertEqual(validator.validate(Field(), 'data'), None)        


    def testRaiseError(self):
        """Test the raiseError method."""
        validator = self._makeValidator()
        self.failUnlessRaises(ValidationError, validator.raiseError, 'Key', Field())


    def testGetMessage(self):
        """Test the getMessage method."""
        validator = self._makeValidator()
        self.assertEqual(validator.getMessage('externalValidatorFailed'),
                         validator.externalValidatorFailed)
        self.assertEqual(validator.getMessage('foo'), None)


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


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



=== Added File Zope3/lib/python/Zope/App/Formulator/tests/testValidatorRegistry.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
# 
##############################################################################
"""
I do not think it is necessary to do the entire SimpleRegistry tests again.
Instead we will test whether the module in itself works.

$Id: testValidatorRegistry.py,v 1.1.2.1 2002/03/01 07:04:37 srichter Exp $
"""

import unittest
from Interface import Interface
from Zope.App.Formulator.ValidatorRegistry import registerValidator, \
     getValidator, IValidator

class Validator:
    """Validator Stub."""

    __implements__ = IValidator



class Test( unittest.TestCase ):


    def testRegistry(self):

        validator = Validator()

        registerValidator('validator', validator)
        self.assertEqual(getValidator('validator'), validator)
        

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


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