[Zope3-checkins] CVS: Zope3/src/zope/app/sqlscript/tests - __init__.py:1.1.2.1 test_arguments.py:1.1.2.1 test_sqlscript.py:1.1.2.1 testdt_sqlgroup.py:1.1.2.1 testdt_sqltest.py:1.1.2.1 testdt_sqlvar.py:1.1.2.1

Philipp von Weitershausen philikon at philikon.de
Fri Feb 20 14:42:43 EST 2004


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

Added Files:
      Tag: philikon-movecontent-branch
	__init__.py test_arguments.py test_sqlscript.py 
	testdt_sqlgroup.py testdt_sqltest.py testdt_sqlvar.py 
Log Message:
SQLScript moved to zope.app 


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


=== Added File Zope3/src/zope/app/sqlscript/tests/test_arguments.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
#
##############################################################################
"""DT_SQLVar Tests

$Id: test_arguments.py,v 1.1.2.1 2004/02/20 19:42:41 philikon Exp $
"""

import unittest

from zope.app.sqlscript.sqlscript import Arguments, \
     parseArguments, InvalidParameter

class TestDT_SQLVar(unittest.TestCase):

    def _compareArgumentObjects(self, result, args):
        self.assertEqual(args.items(), result.items())

    def testSimpleParseArgument(self):
        args = parseArguments('arg1')
        result = Arguments({'arg1': {}})
        self._compareArgumentObjects(result, args)

    def testParseArgumentWithType(self):
        args = parseArguments('arg1:int')
        result = Arguments({'arg1': {'type': 'int'}})
        self._compareArgumentObjects(result, args)

    def testParseArgumentWithDefault(self):
        args1 = parseArguments('arg1=value')
        result1 = Arguments({'arg1': {'default': 'value'}})
        self._compareArgumentObjects(result1, args1)

        args2 = parseArguments('arg1="value"')
        result2 = Arguments({'arg1': {'default': 'value'}})
        self._compareArgumentObjects(result2, args2)

    def testParseArgumentWithTypeAndDefault(self):
        args1 = parseArguments('arg1:string=value')
        result1 = Arguments({'arg1': {'default': 'value', 'type': 'string'}})
        self._compareArgumentObjects(result1, args1)

        args2 = parseArguments('arg1:string="value"')
        result2 = Arguments({'arg1': {'default': 'value', 'type': 'string'}})
        self._compareArgumentObjects(result2, args2)

    def testParseMultipleArguments(self):
        args1 = parseArguments('arg1:string=value arg2')
        result1 = Arguments({'arg1': {'default': 'value', 'type': 'string'},
                             'arg2': {}})
        self._compareArgumentObjects(result1, args1)

        args2 = parseArguments('arg1:string=value\narg2')
        result2 = Arguments({'arg1': {'default': 'value', 'type': 'string'},
                             'arg2': {}})
        self._compareArgumentObjects(result2, args2)

    def testParseErrors(self):
        self.assertRaises(InvalidParameter, parseArguments, 'arg1:""')
        self.assertRaises(InvalidParameter, parseArguments, 'arg1 = value')
        self.assertRaises(InvalidParameter, parseArguments, 'arg1="value\' ')
        self.assertRaises(InvalidParameter, parseArguments, 'arg1:=value')


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

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


=== Added File Zope3/src/zope/app/sqlscript/tests/test_sqlscript.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.
#
##############################################################################
"""DT_SQLVar Tests

$Id: test_sqlscript.py,v 1.1.2.1 2004/02/20 19:42:41 philikon Exp $
"""
import unittest
from zope.interface import implements, classImplements
from zope.component import getService
from zope.component.service import serviceManager as sm

from zope.app.tests import ztapi
from zope.app.interfaces.rdb import IConnectionService, IZopeDatabaseAdapter
from zope.app.interfaces.rdb import IZopeConnection
from zope.app.interfaces.rdb import IZopeCursor
from zope.app.services.servicenames import Adapters
from zope.app.component import nextservice
from zope.app.tests.placelesssetup import PlacelessSetup

from zope.app.interfaces.annotation import IAnnotatable
from zope.app.interfaces.annotation import IAnnotations
from zope.app.interfaces.annotation import IAttributeAnnotatable
from zope.app.attributeannotations import AttributeAnnotations

from zope.app.interfaces.cache import ICacheable, ICachingService
from zope.app.cache.annotationcacheable import AnnotationCacheable
from zope.app.interfaces.traversing import IPhysicallyLocatable
from zope.app.interfaces.services.service import ISimpleService

from zope.app.sqlscript.sqlscript import SQLScript, Arguments
from zope.app.sqlscript.interfaces import ISQLScript


# Make spme fixes, so that we overcome some of the natural ZODB properties
def getNextServiceManager(context):
    return sm

class CursorStub:

    implements(IZopeCursor)

    description = (('name', 'string'), ('counter', 'int'))
    count = 0

    def execute(self, operation, parameters=None):
        CursorStub.count += 1
        self.result = {"SELECT name, counter FROM Table WHERE id = 1":
                       (('stephan', CursorStub.count),),
                       "SELECT name, counter FROM Table WHERE id = 2":
                       (('marius', CursorStub.count),),
                       "SELECT name, counter FROM Table WHERE id = 3":
                       (('erik', CursorStub.count),)
                      }[operation]

    def fetchall(self):
        return self.result



class ConnectionStub:
    implements(IZopeConnection)

    def cursor(self):
        return CursorStub()


class ConnectionUtilityStub:
    implements(IZopeDatabaseAdapter)

    def __init__(self):
        self.connection = ConnectionStub()
        
    def __call__(self):
        return  self.connection
        
class ConnectionServiceStub:
    implements(IConnectionService, ISimpleService)

    def getConnection(self, name):
        return ConnectionStub()


class CacheStub:

    def __init__(self):
        self.cache = {}

    def set(self, data, obj, key=None):
        if key:
            keywords = key.items()
            keywords.sort()
            keywords = tuple(keywords)
        self.cache[obj, keywords] = data

    def query(self, obj, key=None, default=None):
        if key:
            keywords = key.items()
            keywords.sort()
            keywords = tuple(keywords)
        return self.cache.get((obj, keywords), default)


class CachingServiceStub:

    implements(ICachingService, ISimpleService)

    def __init__(self):
        self.caches = {}

    def getCache(self, name):
        return self.caches[name]

class LocatableStub:

    implements(IPhysicallyLocatable)

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

    def getRoot(self):
        return None

    def getPath(self):
        return str(id(self.obj))


class SQLScriptTest(PlacelessSetup, unittest.TestCase):

    def setUp(self):
        super(SQLScriptTest, self).setUp()
        classImplements(SQLScript, IAttributeAnnotatable)
        self.connectionUtilityStub = ConnectionUtilityStub()
        ztapi.provideUtility(IZopeDatabaseAdapter, self.connectionUtilityStub,
                             'my_connection')
        
        self.caching_service = CachingServiceStub()
        sm.defineService('Caching', ICachingService)
        sm.provideService('Caching', self.caching_service)
        ztapi.provideAdapter(
            IAttributeAnnotatable, IAnnotations,
            AttributeAnnotations)
        ztapi.provideAdapter(
            ISQLScript, IPhysicallyLocatable,
            LocatableStub)
        ztapi.provideAdapter(
            IAnnotatable, ICacheable,
            AnnotationCacheable)

    def tearDown(self):
        pass
        
        #nextservice.getNextServiceManager = self._old_getNextServiceManager

    def _getScript(self):
        return SQLScript("my_connection",
                         "SELECT name, counter FROM Table WHERE"
                         " <dtml-sqltest id type=int>",
                         'id')

    def testGetArguments(self):
        assert isinstance(arguments, StringTypes), \
               '"arguments" argument of setArguments() must be a string'
        self._arg_string = arguments
        self.arguments = parseArguments(arguments)

    def testGetArguments(self):
        result = Arguments({'id': {}})
        args = self._getScript().getArguments()
        self.assertEqual(args, result)

    def testGetArgumentsString(self):
        self.assertEqual('id', self._getScript().getArgumentsString())

    def testSetSource(self):
        script = self._getScript()
        script.setSource('SELECT * FROM Table')
        self.assertEqual('SELECT * FROM Table', script.getSource())

    def testGetSource(self):
        expected = ("SELECT name, counter FROM Table"
                    " WHERE <dtml-sqltest id type=int>")
        self.assertEqual(expected,
                         self._getScript().getSource())

    def testConnectionName(self):
        script = self._getScript()
        self.assertEqual('my_connection', script.connectionName)
        script.connectionName = 'test_conn'
        self.assertEqual('test_conn', script.connectionName)

    def testgetConnection(self):
        script = self._getScript()
        name = script.connectionName
        conns = script.getConnection()
        self.assertEqual(conns, self.connectionUtilityStub.connection)

    def testSQLScript(self):
        result = self._getScript()(id=1)
        self.assertEqual(result.columns, ('name','counter'))
        self.assertEqual(result[0].name, 'stephan')

    def testSQLScriptCaching(self):
        script = self._getScript()
        CursorStub.count = 0
        # no caching: check that the counter grows
        result = script(id=1)
        self.assertEqual(result[0].counter, 1)
        result = script(id=1)
        self.assertEqual(result[0].counter, 2)
        # caching: and check that the counter stays still
        AnnotationCacheable(script).setCacheId('dumbcache')
        self.caching_service.caches['dumbcache'] = CacheStub()
        result = script(id=1)
        self.assertEqual(result[0].counter, 3)
        result = script(id=1)
        self.assertEqual(result[0].counter, 3)
        result = script(id=2)
        self.assertEqual(result[0].counter, 4)


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

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


=== Added File Zope3/src/zope/app/sqlscript/tests/testdt_sqlgroup.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
#
##############################################################################
"""DT_SQLVar Tests

$Id: testdt_sqlgroup.py,v 1.1.2.1 2004/02/20 19:42:41 philikon Exp $
"""

import unittest
from zope.app.sqlscript.dtml import SQLDTML

class TestDT_SQLGroup(unittest.TestCase):

    doc_class = SQLDTML


    def testSimpleUse(self):
        html = self.doc_class("""
          <dtml-sqlgroup>
            <dtml-sqlvar column type=nb>
          </dtml-sqlgroup>""")
        result = "'name'"

        self.assertEqual(html(column='name').strip(), result)


    def testComplexUse(self):
        html = self.doc_class("""
          <dtml-sqlgroup required>
            <dtml-sqlgroup>
              <dtml-sqltest name column=nick_name type=nb multiple optional>
            <dtml-or>
              <dtml-sqltest name column=first_name type=nb multiple optional>
            </dtml-sqlgroup>
          <dtml-and>
            <dtml-sqltest home_town type=nb optional>
          <dtml-and>
            <dtml-if minimum_age>
               age >= <dtml-sqlvar minimum_age type=int>
            </dtml-if>
          <dtml-and>
            <dtml-if maximum_age>
               age <= <dtml-sqlvar maximum_age type=int>
            </dtml-if>
          </dtml-sqlgroup>
        """)

        result = """
((nick_name = 'stephan'
 or first_name = 'stephan'
)
 and home_town = 'berlin'
 and age >= 16
 and age <= 21
)"""
        self.assertEqual(html(name="stephan", home_town="berlin",
                              minimum_age=16, maximum_age="21").strip(),
                         result.strip())



def test_suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(TestDT_SQLGroup))
    return suite

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


=== Added File Zope3/src/zope/app/sqlscript/tests/testdt_sqltest.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
#
##############################################################################
"""DT_SQLVar Tests

$Id: testdt_sqltest.py,v 1.1.2.1 2004/02/20 19:42:41 philikon Exp $
"""

import unittest
from zope.app.sqlscript.dtml import SQLDTML, comparison_operators

class TestDT_SQLTest(unittest.TestCase):

    doc_class = SQLDTML


    def testSimpleUse(self):
        html = self.doc_class("<dtml-sqltest column type=nb>")
        result = "column = 'name'"

        self.assertEqual(html(column='name'), result)


    def testIntType(self):
        html = self.doc_class("<dtml-sqltest column type=int>")
        result = "column = 3"

        self.assertEqual(html(column=3), result)
        self.assertEqual(html(column='3'), result)
        self.assertEqual(html(column=3.1), result)


    def testFloatType(self):
        html = self.doc_class("<dtml-sqltest column type=float>")
        result = "column = 3.1"

        self.assertEqual(html(column=3), "column = 3.0")
        self.assertEqual(html(column='3'), "column = 3")
        self.assertEqual(html(column='3.1'), result)
        self.assertEqual(html(column=3.1), result)
        self.assertEqual(html(column=0.0), "column = 0.0")

    def testStringTypeAndEscaping(self):
        html = self.doc_class("<dtml-sqltest column type=nb>")

        self.assertEqual(html(column='name'), "column = 'name'")
        self.assertEqual(html(column='Let\'s do it'),
                         "column = 'Let''s do it'")
        # Acid test :)
        self.assertEqual(html(column="\'\'"), "column = ''''''")


    def testOperators(self):
        for item in comparison_operators.items():
            html = self.doc_class(
                "<dtml-sqltest column type=nb op=%s>" %item[0])
            result = "column %s 'name'" %item[1]

            self.assertEqual(html(column='name'), result)


    def testCustomColumnName(self):
        html = self.doc_class(
            "<dtml-sqltest col column=col type=nb optional>")
        result1 = "col = 'name'"
        result2 = ""

        self.assertEqual(html(col='name'), result1)
        self.assertEqual(html(col=''), result2)
        self.assertEqual(html(), result2)


    def testOptional(self):
        html = self.doc_class("<dtml-sqltest column type=nb optional>")
        result1 = "column = 'name'"
        result2 = ""

        self.assertEqual(html(column='name'), result1)
        self.assertEqual(html(column=''), result2)
        self.assertEqual(html(), result2)


    def testMultiple(self):
        html = self.doc_class(
            "<dtml-sqltest column type=nb optional multiple>")
        result1 = "column in ('name1', 'name2')"
        result2 = ""

        self.assertEqual(html(column=('name1', 'name2')), result1)
        self.assertEqual(html(column=()), result2)
        self.assertEqual(html(), result2)


def test_suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(TestDT_SQLTest))
    return suite

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


=== Added File Zope3/src/zope/app/sqlscript/tests/testdt_sqlvar.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
#
##############################################################################
"""DT_SQLVar Tests

$Id: testdt_sqlvar.py,v 1.1.2.1 2004/02/20 19:42:41 philikon Exp $
"""

import unittest
from zope.app.sqlscript.dtml import SQLDTML

class TestDT_SQLVar(unittest.TestCase):

    doc_class = SQLDTML


    def testSimpleUse(self):
        html = self.doc_class("<dtml-sqlvar column type=nb>")
        result = "'name'"

        self.assertEqual(html(column='name'), result)


    def testIntType(self):
        html = self.doc_class("<dtml-sqlvar column type=int>")
        result = "3"

        self.assertEqual(html(column=3), result)
        self.assertEqual(html(column='3'), result)
        self.assertEqual(html(column=3.1), result)


    def testFloatType(self):
        html = self.doc_class("<dtml-sqlvar column type=float>")
        result = "3.1"

        self.assertEqual(html(column=3), "3.0")
        self.assertEqual(html(column='3'), "3")
        self.assertEqual(html(column='3.1'), result)
        self.assertEqual(html(column=3.1), result)


    def testStringTypeAndEscaping(self):
        html = self.doc_class("<dtml-sqlvar column type=nb>")

        self.assertEqual(html(column='name'), "'name'")
        self.assertEqual(html(column='Let\'s do it'), "'Let''s do it'")
        # Acid test :)
        self.assertEqual(html(column="\'\'"), "''''''")


    def testOptional(self):
        html = self.doc_class("""<dtml-sqlvar column type=nb optional>""")
        result = "null"

        self.assertEqual(html(column=None), result)
        self.assertEqual(html(column=''), result)
        self.assertEqual(html(), result)



def test_suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(TestDT_SQLVar))
    return suite

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




More information about the Zope3-Checkins mailing list