[Zope3-checkins] CVS: Zope3/src/zope/app/schemagen/tests - __init__.py:1.1.2.1 setstate.py.txt:1.1.2.1 setstatemodule.py.txt:1.1.2.1 setstatemodule_no_history.py.txt:1.1.2.1 test_modulegen.py:1.1.2.1 test_schemaspec.py:1.1.2.1 test_typereg.py:1.1.2.1

Jim Fulton jim@zope.com
Mon, 23 Dec 2002 14:32:16 -0500


Update of /cvs-repository/Zope3/src/zope/app/schemagen/tests
In directory cvs.zope.org:/tmp/cvs-serv19908/zope/app/schemagen/tests

Added Files:
      Tag: NameGeddon-branch
	__init__.py setstate.py.txt setstatemodule.py.txt 
	setstatemodule_no_history.py.txt test_modulegen.py 
	test_schemaspec.py test_typereg.py 
Log Message:
Initial renaming before debugging

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


=== Added File Zope3/src/zope/app/schemagen/tests/setstate.py.txt ===
    def __setstate__(self, state):
        transformations = schemaspec.prepareSetstate(self, state, 6)
        if transformations is None:
            return
        dict = self.__dict__
        if 0 in transformations:
            schemaspec.AddField.update(dict, state, 'alpha')
        if 1 in transformations:
            schemaspec.RemoveField.update(dict, state, 'alpha')
        if 2 in transformations:
            schemaspec.AddField.update(dict, state, 'beta')
        if 3 in transformations:
            schemaspec.InsertField.update(dict, state, 'gamma', 0)
        if 4 in transformations:
            schemaspec.MoveField.update(dict, state, 'gamma', 2)
        if 5 in transformations:
            schemaspec.RenameField.update(dict, state, 'gamma', 'gamma2')


=== Added File Zope3/src/zope/app/schemagen/tests/setstatemodule.py.txt ===
from Interface import Interface
from Persistence import Persistent
from Zope.Schema.FieldProperty import FieldProperty

# field imports
from Zope.Schema import Text
from Zope.App.schemagen import schemaspec

class IFoo(Interface):
    """Autogenerated schema."""
    alpha = Text(title=u'alpha')
    
class FooClass(Persistent):
    """Autogenerated class for IFoo."""
    __implements__ = IFoo

    def __init__(self):
        self.__schema_version__ = 1
        
    alpha = FieldProperty(IFoo['alpha'])

    def __setstate__(self, state):
        transformations = schemaspec.prepareSetstate(self, state, 1)
        if transformations is None:
            return
        dict = self.__dict__
        if 0 in transformations:
            schemaspec.AddField.update(dict, state, 'alpha')



=== Added File Zope3/src/zope/app/schemagen/tests/setstatemodule_no_history.py.txt ===
from Interface import Interface
from Persistence import Persistent
from Zope.Schema.FieldProperty import FieldProperty

# field imports


class IFoo(Interface):
    """Autogenerated schema."""

    
class FooClass(Persistent):
    """Autogenerated class for IFoo."""
    __implements__ = IFoo

    def __init__(self):
        self.__schema_version__ = 0
        




=== Added File Zope3/src/zope/app/schemagen/tests/test_modulegen.py ===
##############################################################################
#
# Copyright (c) 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_modulegen.py,v 1.1.2.1 2002/12/23 19:32:14 jim Exp $
"""

from unittest import TestCase, makeSuite, TestSuite
from zope.interface import Interface
from zope.schema import Field, Text, Int, Float, getFieldsInOrder

from zope.app.schemagen.modulegen import generateModuleSource
    
class GenerateModuleSourceTestsBase(TestCase):

    fields = []

    def setUp(self):
        source = generateModuleSource('IFoo', self.fields, "Foo")
        self.source = source
        g = {}
        exec source in g
        del g['__builtins__'] # to ease inspection during debugging
        self.g = g
        
    def test_schema(self):
        IFoo = self.g['IFoo']
        self.assertEquals(self.fields, getFieldsInOrder(IFoo))

    def test_roundtrip(self):
        IFoo = self.g['IFoo']
        # not dealing with issues of schema inheritance,
        # so simply get all fields
        fields = getFieldsInOrder(IFoo) 
        new_source = generateModuleSource('IFoo', fields, 'Foo')
        self.assertEquals(self.source, new_source)
    
    def test_class(self):
        from zope.schema.fieldproperty import FieldProperty
        IFoo = self.g['IFoo']
        Foo = self.g['Foo']
        # we don't want a schema version attribute on the class, just
        # on the individual instances
        self.assertRaises(AttributeError, getattr, Foo, '__schema_version__')
        self.assertEquals(Foo.__implements__, IFoo)
        for field_name, field in self.fields:
            prop = getattr(Foo, field_name, None)
            self.assert_(prop is not None)
            self.assert_(type(prop) is FieldProperty)

    def test_instance(self):
        Foo = self.g['Foo']
        foo = Foo()
        self.assertEquals(foo.__schema_version__, 0)
        for field_name, field in self.fields:
            self.assertEquals(field.default, getattr(foo, field_name))

class GenerateModuleSourceTestsEmpty(GenerateModuleSourceTestsBase):
    fields = []

class GenerateModuleSourceTests1(GenerateModuleSourceTestsBase):
    fields = [('foo', Text(title=u"Foo")),
              ('bar', Int(title=u"Bar")),
              ('hoi', Float(title=u"Float")),
              ('dag', Int(title=u"Dag", default=42)),]

class ExtraImportsAndMethodsTests(TestCase):
    fields = [('foo', Text(title=u"Foo")),
              ('bar', Int(title=u"Bar")),
              ('hoi', Float(title=u"Float")),
              ('dag', Int(title=u"Dag", default=42)),]
    
    def test_extraMethods(self):
        extra_methods = """\
    def forGreatJustice(self):
        return 'zig!'
"""
        source = generateModuleSource('IFoo', self.fields, "Foo",
                                      extra_methods=extra_methods)
        g = {}
        exec source in g
        del g['__builtins__'] # to ease inspection during debugging
        foo = g['Foo']()
        self.assertEquals('zig!', foo.forGreatJustice())

    def test_extraImports(self):
        # we import ourselves, as then there's no dependencies
        from Zope.App.schemagen.tests import test_modulegen
        extra_imports = "from Zope.App.schemagen.tests import test_modulegen"
        source = generateModuleSource('IFoo', self.fields, "Foo",
                                      extra_imports=extra_imports)
        g = {}
        exec source in g
        del g['__builtins__'] # to ease inspection during debugging
        self.assert_(g['test_modulegen'] is test_modulegen)
        
def test_suite():
    return TestSuite(
        (makeSuite(GenerateModuleSourceTestsEmpty),
         makeSuite(GenerateModuleSourceTests1),
         makeSuite(ExtraImportsAndMethodsTests),
         ))



=== Added File Zope3/src/zope/app/schemagen/tests/test_schemaspec.py ===
##############################################################################
#
# Copyright (c) 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_schemaspec.py,v 1.1.2.1 2002/12/23 19:32:15 jim Exp $
"""

from unittest import TestCase, makeSuite, TestSuite
from zope.app.schemagen.schemaspec import SchemaSpec
from zope.schema import Text
import os

def openInTests(name, mode):
    return open(os.path.join(os.path.dirname(__file__), name), mode)

class SchemaSpecTests(TestCase):

    def setUp(self):
        self.s = SchemaSpec('IFoo')
        self.alpha = Text(title=u"alpha")
    
    def test_addField(self):
        s = self.s
        s.addField('alpha', self.alpha)
        self.assertEquals(
            [('alpha', self.alpha)],
            s.getFieldsInOrder())

    def test_removeField(self):
        s = self.s
        s.addField('alpha', self.alpha)
        s.removeField('alpha')
        self.assertEquals(
            [],
            s.getFieldsInOrder())

    def test_addFieldCollision(self):
        s = self.s
        s.addField('alpha', self.alpha)
        self.assertRaises(KeyError, s.addField, 'alpha', self.alpha)
        
    def test_removeFieldNotPresent(self):
        self.assertRaises(KeyError, self.s.removeField, 'alpha')

    def test_renameField(self):
        s = self.s
        s.addField('alpha', self.alpha)
        s.renameField('alpha', 'beta')
        self.assertEquals(
            [('beta', self.alpha)],
            s.getFieldsInOrder())

    def test_renameFieldCollision(self):
        s = self.s
        s.addField('alpha', self.alpha)
        s.addField('beta', Text(title=u"Beta"))
        self.assertRaises(KeyError, s.renameField, 'alpha', 'beta')
        
    def test_renameFieldNotPresent(self):
        self.assertRaises(KeyError, self.s.renameField, 'alpha', 'beta')

    def test_insertField(self):
        s = self.s
        s.addField('alpha', self.alpha)
        beta = Text(title=u"Beta")
        s.insertField('beta', beta, 0)
        self.assertEquals(
            [('beta', beta),
             ('alpha', self.alpha)],
            s.getFieldsInOrder())

    def test_insertFieldCollision(self):
        s = self.s
        s.addField('alpha', self.alpha)
        beta = Text(title=u"Beta")
        self.assertRaises(KeyError, s.insertField, 'alpha', beta, 0)

    def test_insertFieldCornerCases(self):
        s = self.s
        gamma = Text(title=u"Gamma")
        # it's still possible to insert at beginning
        s.insertField('gamma', gamma, 0)
        self.assertEquals(
            [('gamma', gamma)],
            s.getFieldsInOrder())
        # should be allowed to insert field at the end
        s.insertField('alpha', self.alpha, 1)
        self.assertEquals(
            [('gamma', gamma),
             ('alpha', self.alpha)],
            s.getFieldsInOrder())
        # should be allowed to insert field at the beginning still
        delta = Text(title=u"Delta")
        s.insertField('delta', delta, 0)
        self.assertEquals(
            [('delta', delta),
             ('gamma', gamma),
             ('alpha', self.alpha)],
            s.getFieldsInOrder())
        
    def test_insertFieldBeyondEnd(self):
        s = self.s
        s.addField('alpha', self.alpha)
        beta = Text(title=u"Beta")
        self.assertRaises(IndexError, s.insertField,
                          'beta', beta, 100)

    def test_insertFieldBeforeBeginning(self):
        s = self.s
        s.addField('alpha', self.alpha)
        beta = Text(title=u"Beta")
        self.assertRaises(IndexError, s.insertField,
                          'beta', beta, -1)

    def test_moveField(self):
        s = self.s
        s.addField('alpha', self.alpha)
        beta = Text(title=u'Beta')
        s.addField('beta', beta)
        gamma = Text(title=u'Gamma')
        s.addField('gamma', gamma)
        s.moveField('beta', 3)
        self.assertEquals(
            [('alpha', self.alpha),
             ('gamma', gamma),
             ('beta', beta)],
            s.getFieldsInOrder())

    def test_moveFieldBeyondEnd(self):
        s = self.s
        s.addField('alpha', self.alpha)
        beta = Text(title=u"Beta")
        s.addField('beta', beta)
        self.assertRaises(IndexError, s.moveField,
                          'beta', 100)

    def test_moveFieldBeforeBeginning(self):
        s = self.s
        s.addField('alpha', self.alpha)
        beta = Text(title=u"Beta")
        s.addField('beta', beta)
        self.assertRaises(IndexError, s.moveField,
                          'beta', -1)

    # XXX the following tests compare python source text
    # this is very dependent on whitespace issues, which we really
    # don't care about. Is there a better way? (compare some form of AST?)
    def test_history(self):
        s = self.s
        alpha = Text(title=u'Alpha')
        beta = Text(title=u'Beta')
        gamma = Text(title=u'Gamma')
        delta = Text(title=u'Delta')

        history = []
        self.assertEquals(0, s.getCurrentVersion())
        history.append(s.addField('alpha', alpha))
        self.assertEquals(1, s.getCurrentVersion())
        history.append(s.removeField('alpha'))
        self.assertEquals(2, s.getCurrentVersion())
        history.append(s.addField('beta', beta))
        self.assertEquals(3, s.getCurrentVersion())
        history.append(s.insertField('gamma', gamma, 0))
        self.assertEquals(4, s.getCurrentVersion())
        history.append(s.moveField('gamma', 2))
        self.assertEquals(5, s.getCurrentVersion())
        history.append(s.renameField('gamma', 'gamma2'))
        self.assertEquals(6, s.getCurrentVersion())

        # just to verify we know what happened
        self.assertEquals(
            [('beta', beta),
             ('gamma2', gamma)],
            s.getFieldsInOrder())
        # now compare history
        self.assertEquals(history, s.getHistory())

        # check whether generated source is as we expect
        f = openInTests('setstate.py.txt', 'r')
        source = f.read()
        f.close()
        self.assertEquals(source, s.generateSetstateSource())

    def test_generateModuleSource(self):
        s = self.s
        s.addField('alpha', self.alpha)
        
        f = openInTests('setstatemodule.py.txt', 'r')
        source = f.read()
        f.close()
        self.assertEquals(source, s.generateModuleSource())

    def test_generateModuleSource(self):
        s = self.s
        # no history, so expect no setstate
        f = openInTests('setstatemodule_no_history.py.txt', 'r')
        source = f.read()
        f.close()
        self.assertEquals(source.strip(), s.generateModuleSource().strip())

    def test_prepareSetstate(self):
        from zope.app.schemagen.schemaspec import prepareSetstate
        class DummySchemaClass(object):
            pass
        obj = DummySchemaClass()
        state = { '__schema_version__': 1, 'foo': 'baz' }
        version = 2
        d = prepareSetstate(obj, state, version)
        self.assertEquals({ 1: 1}, d)
        self.assertEquals(obj.foo, 'baz')
        self.assertEquals(obj.__schema_version__, 2)
        
class ModuleUsageTests(TestCase):

    def executeModule(self, s):
        source = s.generateModuleSource()
        g = {}
        exec source in g
        del g['__builtins__'] # to ease inspection during debugging
        return g
        
    def test_setstate(self):
        s = SchemaSpec('IFoo', 'Foo')
        s.addField('alpha', Text(title=u'Alpha'))
        s.addField('beta', Text(title=u'Beta', default=u"default"))
        g = self.executeModule(s)
        foo = g['Foo']()
        self.assertEquals(foo.__schema_version__, 2)
        self.assertEquals(foo.beta, u"default")
        
        foo.beta = u"Frog"
        # this is evil, but we do this for testing
        foo.__schema_version__ = 1
        # do the automatical upgrade according to schema
        foo.__setstate__(foo.__getstate__())
        self.assertEquals(foo.beta, u"default")
        self.assertEquals(foo.__schema_version__, 2)
        
def test_suite():
    return TestSuite(
        (makeSuite(SchemaSpecTests),
         makeSuite(ModuleUsageTests),
         ))


=== Added File Zope3/src/zope/app/schemagen/tests/test_typereg.py ===
##############################################################################
#
# Copyright (c) 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_typereg.py,v 1.1.2.1 2002/12/23 19:32:15 jim Exp $
"""

from unittest import TestCase, makeSuite, TestSuite
import datetime

from zope.app.schemagen.typereg import TypeRepresentationRegistry,\
     DefaultTypeRepresentation, DatetimeRepresentation,\
     DefaultFieldRepresentation

from Zope import Schema

from zope.schema.interfaces import IField
from zope.schema import Field, Text, Int

class DefaultTypeRepresentationTests(TestCase):
    def test_getTypes(self):
        c = DefaultTypeRepresentation
        self.assertEquals((), tuple(c.getTypes()))

    def h(self, obj):
        r = DefaultTypeRepresentation(obj)
        self.assertEquals(eval(r.text), obj)
    
    def h_builtin(self, obj):
        r = DefaultTypeRepresentation(obj)
        self.assertEquals(eval(r.text), obj)
        self.assertEquals([], r.importList)

    builtin_instances = [
        'foo',
        1,
        1.1,
        (),
        (1, "foo"),
        [],
        [5, 2],
        {},
        {'foo':'bar', 'baz':'hoi'},
        {'foo': (1, "foo")}
        ]
    
    def test_builtins(self):
        for builtin_instance in self.builtin_instances:
            self.h_builtin(builtin_instance)

    def test_recursive(self):
        # we cannot cope with recursive structures
        recursive = [1, 2]
        recursive.append(recursive)
        r = DefaultTypeRepresentation(recursive)
        self.assertRaises(SyntaxError, eval, r.text)

class DatetimeRepresentationTests(TestCase):

    datetime_instances = [
        (datetime.date(2002, 10, 30),
         [('datetime', 'date')]),
        (datetime.datetime(2002, 10, 30, 11, 44, 10),
         [('datetime', 'datetime')]),
        (datetime.time(10, 0, 1),
         [('datetime', 'time')]),
        ]
    
    def test_date(self):
        for datetime_instance, import_list in self.datetime_instances:
            r = DatetimeRepresentation(datetime_instance)
            self.assertEquals(datetime_instance, evalRepresentation(r))
            r_imports = r.importList
            r_imports.sort()
            import_list.sort()
            self.assertEquals(r_imports, import_list)

def evalRepresentation(r):
    import_dict = {}
    for import_name, import_from in r.importList:
        module = __import__(import_name, {}, {}, [import_from])
        import_dict[import_from] = getattr(module, import_from)
    return eval(r.text, import_dict)

class TypeRepresentationRegistryTests(TestCase):
    def setUp(self):
        self.tr = TypeRepresentationRegistry(DefaultTypeRepresentation)

    def test_default(self):
        self.assert_(isinstance(
            self.tr.represent(1), DefaultTypeRepresentation))
        
    def test_register(self):
        from zope.app.interfaces.schemagen import ITypeRepresentation
        class IntRepresentation:
            __implements__ = ITypeRepresentation
            def __init__(self, obj):
                pass
            def getTypes():
                return (int,)

            getTypes = staticmethod(getTypes)

            importList = []
            text = ''
            
        self.tr.register(IntRepresentation)
        self.assert_(isinstance(self.tr.represent(1), IntRepresentation))

        self.assert_(isinstance(self.tr.represent('foo'),
                                DefaultTypeRepresentation))

class IFieldSchema(IField):
    # the greek alphabet is not in alphabetical order, so we cannot
    # depend on ascii sort order, which is good as we shouldn't.
    alpha = Text(title=u"Alpha", default=u"")
    beta = Int(title=u"Beta", default=0)
    gamma = Text(title=u"Gamma", default=u"")
    delta = Int(title=u"Delta", default=0)

class MyField(Field):
    __implements__ = IFieldSchema

    def __init__(self, alpha=u'', beta=0, gamma=u'', delta=0, **kw):
        super(MyField, self).__init__(**kw)
        self.alpha = alpha
        self.beta = beta
        self.gamma = gamma
        self.delta = delta
        
class DefaultFieldRepresentationTests(TestCase):
    # XXX there is an issue with field classes which have the same name
    # multiple 'from x import y' statements will cause one name to be
    # shadowed by another. We can't test for this yet.

    schema_fields = [
        (Schema.Text(title=u"text"),
         [('Zope.Schema', 'Text')]),
        (Schema.Int(title=u"int"),
         [('Zope.Schema', 'Int')]),
        (Schema.TextLine(title=u"text"),
         [('Zope.Schema', 'TextLine')]),
        (Schema.Float(title=u"float"),
         [('Zope.Schema', 'Float')])
        ]
    
    def test_field(self):
        for field, import_list in self.schema_fields:
            r = DefaultFieldRepresentation(field)
            self.assertEquals(field, evalRepresentation(r))
            r_imports = r.importList
            r_imports.sort()
            import_list.sort()
            self.assertEquals(r_imports, import_list)

    def test_order(self):
        field = MyField(alpha=u'alpha', gamma=u'gamma', delta=23)
        r = DefaultFieldRepresentation(field)
        t = r.text
        a = t.find('alpha')
        g = t.find('gamma')
        d = t.find('delta')
        self.assertNotEquals(a, -1)
        self.assertNotEquals(g, -1)
        self.assertNotEquals(d, -1)
        self.assert_(a < g < d)
    
def test_suite():
    return TestSuite(
        (makeSuite(DefaultTypeRepresentationTests),
         makeSuite(DatetimeRepresentationTests),
         makeSuite(TypeRepresentationRegistryTests),
         makeSuite(DefaultFieldRepresentationTests),
        ))