Commit 63d108ec authored by Tres Seaver's avatar Tres Seaver

  o Land unit test cleanup from branch.

  o Known breakage as of 2001/10/17:

    - TAL test suite is very broken (TAL is currently suppressed in
      lib/python/.testinfo).

    - AccessControl tests don't run if run first;  lib/python/.testinfo
      pushes them to the end of the queue, at which point they *do* run.
      Global side effects suck!

    - lib/python/BTrees/testBTreesUnicode.py:  weird flakiness around
      comparison of ASCII and Unicode strings;  breaks in different
      ways under Python 2.1 and 2.2.

    - lib/python/Products/PageTemplates/tests:  three tests break due
      to security asserctions.
parent 00e3c197
App
BTrees
DateTime
DocumentTemplate
HelpSys
Interface
OFS
Persistence
Products
RestrictedPython
SearchIndex
Shared
StructuredText
Testing
ThreadedAsync
TreeDisplay
ZClasses
ZLogger
ZODB
ZPublisher
ZTUtils
Zope
webdav
zLOG
zdaemon
# WAAAA! Putting this at end makes it run!
AccessControl
# WAAAA! These tests are broken!
#TAL
...@@ -85,8 +85,8 @@ ...@@ -85,8 +85,8 @@
__doc__='''Support for owned objects __doc__='''Support for owned objects
$Id: Owned.py,v 1.12 2001/07/02 16:29:55 evan Exp $''' $Id: Owned.py,v 1.13 2001/10/17 20:00:31 tseaver Exp $'''
__version__='$Revision: 1.12 $'[11:-2] __version__='$Revision: 1.13 $'[11:-2]
import Globals, urlparse, SpecialUsers, ExtensionClass, string import Globals, urlparse, SpecialUsers, ExtensionClass, string
from AccessControl import getSecurityManager, Unauthorized from AccessControl import getSecurityManager, Unauthorized
...@@ -305,6 +305,8 @@ class EditUnowned(Exception): ...@@ -305,6 +305,8 @@ class EditUnowned(Exception):
def ownerInfo(user, def ownerInfo(user,
getattr=getattr, type=type, st=type(''), None=None): getattr=getattr, type=type, st=type(''), None=None):
if user is None:
return None
uid=user.getId() uid=user.getId()
if uid is None: return uid if uid is None: return uid
db=user.aq_inner.aq_parent db=user.aq_inner.aq_parent
......
##############################################################################
#
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
#
# Copyright (c) Digital Creations. All rights reserved.
#
# This license has been certified as Open Source(tm).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions in source code must retain the above copyright
# notice, this list of conditions, and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions, and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# 3. Digital Creations requests that attribution be given to Zope
# in any manner possible. Zope includes a "Powered by Zope"
# button that is installed by default. While it is not a license
# violation to remove this button, it is requested that the
# attribution remain. A significant investment has been put
# into Zope, and this effort will continue if the Zope community
# continues to grow. This is one way to assure that growth.
#
# 4. All advertising materials and documentation mentioning
# features derived from or use of this software must display
# the following acknowledgement:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# In the event that the product being advertised includes an
# intact Zope distribution (with copyright and license included)
# then this clause is waived.
#
# 5. Names associated with Zope or Digital Creations must not be used to
# endorse or promote products derived from this software without
# prior written permission from Digital Creations.
#
# 6. Modified redistributions of any form whatsoever must retain
# the following acknowledgment:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# Intact (re-)distributions of any official Zope release do not
# require an external acknowledgement.
#
# 7. Modifications are encouraged but must be packaged separately as
# patches to official Zope releases. Distributions that do not
# clearly separate the patches from the original work must be clearly
# labeled as unofficial distributions. Modifications which do not
# carry the name Zope may be packaged in any form, as long as they
# conform to all of the clauses above.
#
#
# Disclaimer
#
# THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations. Specific
# attributions are listed in the accompanying credits file.
#
##############################################################################
######################################################################
# Set up unit testing framework
#
# The following code should be at the top of every test module:
#
# import os, sys
# execfile(os.path.join(sys.path[0], 'framework.py'))
#
# ...and the following at the bottom:
#
# framework()
# Find the Testing package
if not sys.modules.has_key('Testing'):
p0 = sys.path[0]
if p0 and __name__ == '__main__':
os.chdir(p0)
p0 = ''
p = d = os.path.abspath(os.curdir)
while d:
if os.path.isdir(os.path.join(p, 'Testing')):
sys.path[:1] = [p0, os.pardir, p]
break
p, d = os.path.split(p)
else:
print 'Unable to locate Testing package.'
sys.exit(1)
import Testing, unittest
execfile(os.path.join(os.path.split(Testing.__file__)[0], 'common.py'))
...@@ -85,11 +85,10 @@ ...@@ -85,11 +85,10 @@
"""Test of AuthEncoding """Test of AuthEncoding
""" """
__rcs_id__='$Id: testPasswordDigest.py,v 1.1 2001/09/13 16:26:47 shane Exp $' __rcs_id__='$Id: testPasswordDigest.py,v 1.2 2001/10/17 20:00:32 tseaver Exp $'
__version__='$Revision: 1.1 $'[11:-2] __version__='$Revision: 1.2 $'[11:-2]
import os, sys import os, sys, unittest
execfile(os.path.join(sys.path[0], 'framework.py'))
from AccessControl import AuthEncoding from AccessControl import AuthEncoding
import unittest import unittest
...@@ -156,4 +155,14 @@ class PasswordDigestTests (unittest.TestCase): ...@@ -156,4 +155,14 @@ class PasswordDigestTests (unittest.TestCase):
pw = 'my-password' pw = 'my-password'
assert AuthEncoding.pw_validate(pw, pw) assert AuthEncoding.pw_validate(pw, pw)
framework()
def test_suite():
suite = unittest.TestSuite()
suite.addTest( unittest.makeSuite( PasswordDigestTests ) )
return suite
def main():
unittest.TextTestRunner().run(test_suite())
if __name__ == '__main__':
main()
...@@ -85,11 +85,10 @@ ...@@ -85,11 +85,10 @@
"""Document Template Tests """Document Template Tests
""" """
__rcs_id__='$Id: testSecurity.py,v 1.4 2001/08/06 17:28:08 evan Exp $' __rcs_id__='$Id: testSecurity.py,v 1.5 2001/10/17 20:00:32 tseaver Exp $'
__version__='$Revision: 1.4 $'[11:-2] __version__='$Revision: 1.5 $'[11:-2]
import os, sys import os, sys, unittest
execfile(os.path.join(sys.path[0], 'framework.py'))
import ZODB import ZODB
from DocumentTemplate import HTML from DocumentTemplate import HTML
...@@ -160,4 +159,14 @@ class SecurityTests (DTMLTests): ...@@ -160,4 +159,14 @@ class SecurityTests (DTMLTests):
assert res == '10', res assert res == '10', res
# Note: we need more tests! # Note: we need more tests!
framework()
def test_suite():
suite = unittest.TestSuite()
suite.addTest( unittest.makeSuite( SecurityTests ) )
return suite
def main():
unittest.TextTestRunner().run(test_suite())
if __name__ == '__main__':
main()
...@@ -85,11 +85,10 @@ ...@@ -85,11 +85,10 @@
"""User folder tests """User folder tests
""" """
__rcs_id__='$Id: testUserFolder.py,v 1.2 2001/10/02 16:16:25 matt Exp $' __rcs_id__='$Id: testUserFolder.py,v 1.3 2001/10/17 20:00:32 tseaver Exp $'
__version__='$Revision: 1.2 $'[11:-2] __version__='$Revision: 1.3 $'[11:-2]
import os, sys import os, sys, unittest
execfile(os.path.join(sys.path[0], 'framework.py'))
import ZODB import ZODB
from DocumentTemplate import HTML from DocumentTemplate import HTML
...@@ -141,5 +140,13 @@ class SecurityTests (DTMLTests): ...@@ -141,5 +140,13 @@ class SecurityTests (DTMLTests):
assert 0, "Raised overflow error erroneously" assert 0, "Raised overflow error erroneously"
def test_suite():
suite = unittest.TestSuite()
suite.addTest( unittest.makeSuite( SecurityTests ) )
return suite
framework() def main():
unittest.TextTestRunner().run(test_suite())
if __name__ == '__main__':
main()
##############################################################################
#
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
#
# Copyright (c) Digital Creations. All rights reserved.
#
# This license has been certified as Open Source(tm).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions in source code must retain the above copyright
# notice, this list of conditions, and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions, and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# 3. Digital Creations requests that attribution be given to Zope
# in any manner possible. Zope includes a "Powered by Zope"
# button that is installed by default. While it is not a license
# violation to remove this button, it is requested that the
# attribution remain. A significant investment has been put
# into Zope, and this effort will continue if the Zope community
# continues to grow. This is one way to assure that growth.
#
# 4. All advertising materials and documentation mentioning
# features derived from or use of this software must display
# the following acknowledgement:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# In the event that the product being advertised includes an
# intact Zope distribution (with copyright and license included)
# then this clause is waived.
#
# 5. Names associated with Zope or Digital Creations must not be used to
# endorse or promote products derived from this software without
# prior written permission from Digital Creations.
#
# 6. Modified redistributions of any form whatsoever must retain
# the following acknowledgment:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# Intact (re-)distributions of any official Zope release do not
# require an external acknowledgement.
#
# 7. Modifications are encouraged but must be packaged separately as
# patches to official Zope releases. Distributions that do not
# clearly separate the patches from the original work must be clearly
# labeled as unofficial distributions. Modifications which do not
# carry the name Zope may be packaged in any form, as long as they
# conform to all of the clauses above.
#
#
# Disclaimer
#
# THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations. Specific
# attributions are listed in the accompanying credits file.
#
##############################################################################
######################################################################
# Set up unit testing framework
#
# The following code should be at the top of every test module:
#
# import os, sys
# execfile(os.path.join(sys.path[0], 'framework.py'))
#
# ...and the following at the bottom:
#
# framework()
# Find the Testing package
if not sys.modules.has_key('Testing'):
p0 = sys.path[0]
if p0 and __name__ == '__main__':
os.chdir(p0)
p0 = ''
p = d = os.path.abspath(os.curdir)
while d:
if os.path.isdir(os.path.join(p, 'Testing')):
sys.path[:1] = [p0, os.pardir, p]
break
p, d = os.path.split(p)
else:
print 'Unable to locate Testing package.'
sys.exit(1)
import Testing, unittest
execfile(os.path.join(os.path.split(Testing.__file__)[0], 'common.py'))
...@@ -83,12 +83,11 @@ ...@@ -83,12 +83,11 @@
# #
############################################################################## ##############################################################################
import os, sys import os, sys, unittest
execfile(os.path.join(sys.path[0], 'framework.py'))
from SortEx import * from DocumentTemplate.sequence.SortEx import *
from ztestlib import * from DocumentTemplate.sequence.tests.ztestlib import *
from results import * from DocumentTemplate.sequence.tests.results import *
class TestCase( unittest.TestCase ): class TestCase( unittest.TestCase ):
...@@ -142,6 +141,21 @@ class TestCase( unittest.TestCase ): ...@@ -142,6 +141,21 @@ class TestCase( unittest.TestCase ):
#... and push out function onto the namespace #... and push out function onto the namespace
md._push({"myCmp" : myCmp}) md._push({"myCmp" : myCmp})
assert res7==SortEx(wordlist, (("weight",), ("key", "myCmp", "desc")), md, mapping=1) assert res7==SortEx( wordlist
, ( ("weight",)
, ("key", "myCmp", "desc")
)
, md
, mapping=1
)
framework() def test_suite():
suite = unittest.TestSuite()
suite.addTest( unittest.makeSuite( TestCase ) )
return suite
def main():
unittest.TextTestRunner().run(test_suite())
if __name__ == '__main__':
main()
...@@ -84,9 +84,9 @@ ...@@ -84,9 +84,9 @@
############################################################################## ##############################################################################
__doc__="""Object Manager __doc__="""Object Manager
$Id: ObjectManager.py,v 1.141 2001/07/06 18:06:57 brian Exp $""" $Id: ObjectManager.py,v 1.142 2001/10/17 20:00:32 tseaver Exp $"""
__version__='$Revision: 1.141 $'[11:-2] __version__='$Revision: 1.142 $'[11:-2]
import App.Management, Acquisition, Globals, CopySupport, Products import App.Management, Acquisition, Globals, CopySupport, Products
import os, App.FactoryDispatcher, re, Products import os, App.FactoryDispatcher, re, Products
...@@ -317,9 +317,10 @@ class ObjectManager( ...@@ -317,9 +317,10 @@ class ObjectManager(
if hasattr(object, '__ac_local_roles__'): if hasattr(object, '__ac_local_roles__'):
if object.__ac_local_roles__ is None: if object.__ac_local_roles__ is None:
user=getSecurityManager().getUser() user=getSecurityManager().getUser()
name=user.getUserName() if user is not None:
if name != 'Anonymous User': name=user.getUserName()
object.manage_setLocalRoles(name, ['Owner']) if name != 'Anonymous User':
object.manage_setLocalRoles(name, ['Owner'])
object.manage_afterAdd(object, self) object.manage_afterAdd(object, self)
return id return id
......
##############################################################################
#
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
#
# Copyright (c) Digital Creations. All rights reserved.
#
# This license has been certified as Open Source(tm).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions in source code must retain the above copyright
# notice, this list of conditions, and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions, and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# 3. Digital Creations requests that attribution be given to Zope
# in any manner possible. Zope includes a "Powered by Zope"
# button that is installed by default. While it is not a license
# violation to remove this button, it is requested that the
# attribution remain. A significant investment has been put
# into Zope, and this effort will continue if the Zope community
# continues to grow. This is one way to assure that growth.
#
# 4. All advertising materials and documentation mentioning
# features derived from or use of this software must display
# the following acknowledgement:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# In the event that the product being advertised includes an
# intact Zope distribution (with copyright and license included)
# then this clause is waived.
#
# 5. Names associated with Zope or Digital Creations must not be used to
# endorse or promote products derived from this software without
# prior written permission from Digital Creations.
#
# 6. Modified redistributions of any form whatsoever must retain
# the following acknowledgment:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# Intact (re-)distributions of any official Zope release do not
# require an external acknowledgement.
#
# 7. Modifications are encouraged but must be packaged separately as
# patches to official Zope releases. Distributions that do not
# clearly separate the patches from the original work must be clearly
# labeled as unofficial distributions. Modifications which do not
# carry the name Zope may be packaged in any form, as long as they
# conform to all of the clauses above.
#
#
# Disclaimer
#
# THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations. Specific
# attributions are listed in the accompanying credits file.
#
##############################################################################
######################################################################
# Set up unit testing framework
#
# The following code should be at the top of every test module:
#
# import os, sys
# execfile(os.path.join(sys.path[0], 'framework.py'))
#
# ...and the following at the bottom:
#
# framework()
# Find the Testing package
if not sys.modules.has_key('Testing'):
p0 = sys.path[0]
if p0 and __name__ == '__main__':
os.chdir(p0)
p0 = ''
p = d = os.path.abspath(os.curdir)
while d:
if os.path.isdir(os.path.join(p, 'Testing')):
sys.path[:1] = [p0, os.pardir, p]
break
p, d = os.path.split(p)
else:
print 'Unable to locate Testing package.'
sys.exit(1)
import Testing, unittest
execfile(os.path.join(os.path.split(Testing.__file__)[0], 'common.py'))
...@@ -82,9 +82,7 @@ ...@@ -82,9 +82,7 @@
# attributions are listed in the accompanying credits file. # attributions are listed in the accompanying credits file.
# #
############################################################################## ##############################################################################
import os, sys, unittest
import os, sys
execfile(os.path.join(sys.path[0], 'framework.py'))
import string, whrandom, cStringIO, time, re import string, whrandom, cStringIO, time, re
import Zope import Zope
...@@ -114,28 +112,34 @@ class TestRequestRange(unittest.TestCase): ...@@ -114,28 +112,34 @@ class TestRequestRange(unittest.TestCase):
# Test case setup and teardown # Test case setup and teardown
def setUp(self): def setUp(self):
self.responseOut = cStringIO.StringIO() self.responseOut = cStringIO.StringIO()
self.app = makerequest(Zope.app(), stdout=self.responseOut) self.connection = Zope.DB.open()
try: self.app._delObject(TESTFOLDER_NAME) try:
except AttributeError: pass self.root = self.connection.root()[ 'Application' ]
self.app.manage_addFolder(TESTFOLDER_NAME) self.app = makerequest(self.root, stdout=self.responseOut)
try: self.app._delObject(TESTFOLDER_NAME)
data = string.letters except AttributeError: pass
self.app[TESTFOLDER_NAME].manage_addFile('file', file=data, self.app.manage_addFolder(TESTFOLDER_NAME)
content_type='text/plain')
data = string.letters
self.file = self.app[TESTFOLDER_NAME].file self.app[TESTFOLDER_NAME].manage_addFile('file', file=data,
self.data = data content_type='text/plain')
# Hack, we need a _p_mtime for the file, so we make sure that it has self.file = self.app[TESTFOLDER_NAME].file
# one. We use a subtransaction, which means we can rollback later and self.data = data
# pretend we didn't touch the ZODB.
get_transaction().commit() # Hack, we need a _p_mtime for the file, so we make sure that it
# has one. We use a subtransaction, which means we can rollback
# later and pretend we didn't touch the ZODB.
get_transaction().commit()
except:
self.connection.close()
raise
def tearDown(self): def tearDown(self):
try: self.app._delObject(TESTFOLDER_NAME) try: self.app._delObject(TESTFOLDER_NAME)
except AttributeError: pass except AttributeError: pass
get_transaction().commit() get_transaction().commit()
self.app._p_jar.close() self.connection.close()
self.app = None self.app = None
del self.app del self.app
...@@ -395,4 +399,14 @@ class TestRequestRange(unittest.TestCase): ...@@ -395,4 +399,14 @@ class TestRequestRange(unittest.TestCase):
self.expectOK('21-25,10-20', self.expectOK('21-25,10-20',
if_range=self.file.http__etag() + 'bar') if_range=self.file.http__etag() + 'bar')
framework()
def test_suite():
suite = unittest.TestSuite()
suite.addTest( unittest.makeSuite( TestRequestRange ) )
return suite
def main():
unittest.TextTestRunner().run(test_suite())
if __name__ == '__main__':
main()
...@@ -83,10 +83,9 @@ ...@@ -83,10 +83,9 @@
# #
############################################################################## ##############################################################################
import os, sys import os, sys, unittest
execfile(os.path.join(sys.path[0], 'framework.py'))
import util from Products.PageTemplates.tests import util
from Products.PageTemplates.PageTemplate import PageTemplate from Products.PageTemplates.PageTemplate import PageTemplate
from Acquisition import Implicit from Acquisition import Implicit
...@@ -120,18 +119,18 @@ class DTMLTests(unittest.TestCase): ...@@ -120,18 +119,18 @@ class DTMLTests(unittest.TestCase):
</body></html> </body></html>
""" """
tal = read_input('DTML1.html') tal = util.read_input('DTML1.html')
self.t.write(tal) self.t.write(tal)
aa=util.argv(('one', 'two', 'three', 'cha', 'cha', 'cha')) aa=util.argv(('one', 'two', 'three', 'cha', 'cha', 'cha'))
o=self.t.__of__(aa)() o=self.t.__of__(aa)()
expect = read_output('DTML1a.html') expect = util.read_output('DTML1a.html')
util.check_xml(expect, o) util.check_xml(expect, o)
aa=util.argv(()) aa=util.argv(())
o=self.t.__of__(aa)() o=self.t.__of__(aa)()
expect = read_output('DTML1b.html') expect = util.read_output('DTML1b.html')
util.check_xml(expect, o) util.check_xml(expect, o)
def check3(self): def check3(self):
...@@ -164,7 +163,7 @@ class DTMLTests(unittest.TestCase): ...@@ -164,7 +163,7 @@ class DTMLTests(unittest.TestCase):
</body></html> </body></html>
""" """
tal = read_input('DTML3.html') tal = util.read_input('DTML3.html')
self.t.write(tal) self.t.write(tal)
aa=util.argv(('one', 'two', 'three', 'four', 'five', aa=util.argv(('one', 'two', 'three', 'four', 'five',
...@@ -172,10 +171,10 @@ class DTMLTests(unittest.TestCase): ...@@ -172,10 +171,10 @@ class DTMLTests(unittest.TestCase):
'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen',
'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty',
)) ))
import batch from Products.PageTemplates.tests import batch
o=self.t.__of__(aa)(batch=batch.batch(aa.args, 5)) o=self.t.__of__(aa)(batch=batch.batch(aa.args, 5))
expect = read_output('DTML3.html') expect = util.read_output('DTML3.html')
util.check_xml(expect, o) util.check_xml(expect, o)
def test_suite(): def test_suite():
......
import os, sys import os, sys, unittest
execfile(os.path.join(sys.path[0], 'framework.py'))
from Products.PageTemplates import Expressions from Products.PageTemplates import Expressions
......
...@@ -83,10 +83,9 @@ ...@@ -83,10 +83,9 @@
# #
############################################################################## ##############################################################################
import os, sys import os, sys, unittest
execfile(os.path.join(sys.path[0], 'framework.py'))
import util from Products.PageTemplates.tests import util
from Products.PageTemplates.PageTemplate import PageTemplate from Products.PageTemplates.PageTemplate import PageTemplate
from Acquisition import Implicit from Acquisition import Implicit
...@@ -117,82 +116,82 @@ class HTMLTests(unittest.TestCase): ...@@ -117,82 +116,82 @@ class HTMLTests(unittest.TestCase):
def check1(self): def check1(self):
laf = self.folder.laf laf = self.folder.laf
laf.write(read_input('TeeShopLAF.html')) laf.write(util.read_input('TeeShopLAF.html'))
expect = read_output('TeeShopLAF.html') expect = util.read_output('TeeShopLAF.html')
util.check_html(expect, laf()) util.check_html(expect, laf())
def check2(self): def check2(self):
self.folder.laf.write(read_input('TeeShopLAF.html')) self.folder.laf.write(util.read_input('TeeShopLAF.html'))
t = self.folder.t t = self.folder.t
t.write(read_input('TeeShop2.html')) t.write(util.read_input('TeeShop2.html'))
expect = read_output('TeeShop2.html') expect = util.read_output('TeeShop2.html')
out = t(getProducts=self.getProducts) out = t(getProducts=self.getProducts)
util.check_html(expect, out) util.check_html(expect, out)
def check3(self): def check3(self):
self.folder.laf.write(read_input('TeeShopLAF.html')) self.folder.laf.write(util.read_input('TeeShopLAF.html'))
t = self.folder.t t = self.folder.t
t.write(read_input('TeeShop1.html')) t.write(util.read_input('TeeShop1.html'))
expect = read_output('TeeShop1.html') expect = util.read_output('TeeShop1.html')
out = t(getProducts=self.getProducts) out = t(getProducts=self.getProducts)
util.check_html(expect, out) util.check_html(expect, out)
def checkSimpleLoop(self): def checkSimpleLoop(self):
t = self.folder.t t = self.folder.t
t.write(read_input('Loop1.html')) t.write(util.read_input('Loop1.html'))
expect = read_output('Loop1.html') expect = util.read_output('Loop1.html')
out = t() out = t()
util.check_html(expect, out) util.check_html(expect, out)
def checkGlobalsShadowLocals(self): def checkGlobalsShadowLocals(self):
t = self.folder.t t = self.folder.t
t.write(read_input('GlobalsShadowLocals.html')) t.write(util.read_input('GlobalsShadowLocals.html'))
expect = read_output('GlobalsShadowLocals.html') expect = util.read_output('GlobalsShadowLocals.html')
out = t() out = t()
util.check_html(expect, out) util.check_html(expect, out)
def checkStringExpressions(self): def checkStringExpressions(self):
t = self.folder.t t = self.folder.t
t.write(read_input('StringExpression.html')) t.write(util.read_input('StringExpression.html'))
expect = read_output('StringExpression.html') expect = util.read_output('StringExpression.html')
out = t() out = t()
util.check_html(expect, out) util.check_html(expect, out)
def checkReplaceWithNothing(self): def checkReplaceWithNothing(self):
t = self.folder.t t = self.folder.t
t.write(read_input('CheckNothing.html')) t.write(util.read_input('CheckNothing.html'))
expect = read_output('CheckNothing.html') expect = util.read_output('CheckNothing.html')
out = t() out = t()
util.check_html(expect, out) util.check_html(expect, out)
def checkWithXMLHeader(self): def checkWithXMLHeader(self):
t = self.folder.t t = self.folder.t
t.write(read_input('CheckWithXMLHeader.html')) t.write(util.read_input('CheckWithXMLHeader.html'))
expect = read_output('CheckWithXMLHeader.html') expect = util.read_output('CheckWithXMLHeader.html')
out = t() out = t()
util.check_html(expect, out) util.check_html(expect, out)
def checkNotExpression(self): def checkNotExpression(self):
t = self.folder.t t = self.folder.t
t.write(read_input('CheckNotExpression.html')) t.write(util.read_input('CheckNotExpression.html'))
expect = read_output('CheckNotExpression.html') expect = util.read_output('CheckNotExpression.html')
out = t() out = t()
util.check_html(expect, out) util.check_html(expect, out)
def checkPathNothing(self): def checkPathNothing(self):
t = self.folder.t t = self.folder.t
t.write(read_input('CheckPathNothing.html')) t.write(util.read_input('CheckPathNothing.html'))
expect = read_output('CheckPathNothing.html') expect = util.read_output('CheckPathNothing.html')
out = t() out = t()
util.check_html(expect, out) util.check_html(expect, out)
def checkPathAlt(self): def checkPathAlt(self):
t = self.folder.t t = self.folder.t
t.write(read_input('CheckPathAlt.html')) t.write(util.read_input('CheckPathAlt.html'))
expect = read_output('CheckPathAlt.html') expect = util.read_output('CheckPathAlt.html')
out = t() out = t()
util.check_html(expect, out) util.check_html(expect, out)
......
import os, sys import os, sys, unittest
execfile(os.path.join(sys.path[0], 'framework.py'))
from Products.PageTemplates import TALES from Products.PageTemplates import TALES
from Products.PageTemplates.tests import harness1 from Products.PageTemplates.tests import harness1
......
...@@ -174,3 +174,17 @@ def normalize_xml(s): ...@@ -174,3 +174,17 @@ def normalize_xml(s):
s = re.sub(r"(?s)\s+<", "<", s) s = re.sub(r"(?s)\s+<", "<", s)
s = re.sub(r"(?s)>\s+", ">", s) s = re.sub(r"(?s)>\s+", ">", s)
return s return s
import Products.PageTemplates.tests
dir = os.path.dirname( Products.PageTemplates.tests.__file__)
input_dir = os.path.join(dir, 'input')
output_dir = os.path.join(dir, 'output')
def read_input(filename):
filename = os.path.join(input_dir, filename)
return open(filename, 'r').read()
def read_output(filename):
filename = os.path.join(output_dir, filename)
return open(filename, 'r').read()
...@@ -87,7 +87,7 @@ ...@@ -87,7 +87,7 @@
""" """
__version__ = '$Revision: 1.21 $'[11:-2] __version__ = '$Revision: 1.22 $'[11:-2]
import string, re import string, re
...@@ -633,7 +633,6 @@ class TextIndex(PluggableIndex.PluggableIndex, Persistent, ...@@ -633,7 +633,6 @@ class TextIndex(PluggableIndex.PluggableIndex, Persistent,
def get_operands(self, q, i): def get_operands(self, q, i):
"""Evaluate and return the left and right operands for an operator""" """Evaluate and return the left and right operands for an operator"""
try: try:
left = q[i - 1] left = q[i - 1]
right = q[i + 1] right = q[i + 1]
...@@ -643,7 +642,7 @@ class TextIndex(PluggableIndex.PluggableIndex, Persistent, ...@@ -643,7 +642,7 @@ class TextIndex(PluggableIndex.PluggableIndex, Persistent,
operandType = type(left) operandType = type(left)
if operandType is IntType: if operandType is IntType:
left = self[left] left = self[left]
elif operandType in (StringType,UnicodeType): elif isinstance(left,StringType) or isinstance(left,UnicodeType):
left = self[left] left = self[left]
elif operandType is ListType: elif operandType is ListType:
left = self.evaluate(left) left = self.evaluate(left)
...@@ -651,7 +650,7 @@ class TextIndex(PluggableIndex.PluggableIndex, Persistent, ...@@ -651,7 +650,7 @@ class TextIndex(PluggableIndex.PluggableIndex, Persistent,
operandType = type(right) operandType = type(right)
if operandType is IntType: if operandType is IntType:
right = self[right] right = self[right]
elif operandType in (StringType,UnicodeType): elif isinstance(right,StringType) or isinstance(right,UnicodeType):
right = self[right] right = self[right]
elif operandType is ListType: elif operandType is ListType:
right = self.evaluate(right) right = self.evaluate(right)
......
##############################################################################
#
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
#
# Copyright (c) Digital Creations. All rights reserved.
#
# This license has been certified as Open Source(tm).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions in source code must retain the above copyright
# notice, this list of conditions, and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions, and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# 3. Digital Creations requests that attribution be given to Zope
# in any manner possible. Zope includes a "Powered by Zope"
# button that is installed by default. While it is not a license
# violation to remove this button, it is requested that the
# attribution remain. A significant investment has been put
# into Zope, and this effort will continue if the Zope community
# continues to grow. This is one way to assure that growth.
#
# 4. All advertising materials and documentation mentioning
# features derived from or use of this software must display
# the following acknowledgement:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# In the event that the product being advertised includes an
# intact Zope distribution (with copyright and license included)
# then this clause is waived.
#
# 5. Names associated with Zope or Digital Creations must not be used to
# endorse or promote products derived from this software without
# prior written permission from Digital Creations.
#
# 6. Modified redistributions of any form whatsoever must retain
# the following acknowledgment:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# Intact (re-)distributions of any official Zope release do not
# require an external acknowledgement.
#
# 7. Modifications are encouraged but must be packaged separately as
# patches to official Zope releases. Distributions that do not
# clearly separate the patches from the original work must be clearly
# labeled as unofficial distributions. Modifications which do not
# carry the name Zope may be packaged in any form, as long as they
# conform to all of the clauses above.
#
#
# Disclaimer
#
# THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations. Specific
# attributions are listed in the accompanying credits file.
#
##############################################################################
######################################################################
# Set up unit testing framework
#
# The following code should be at the top of every test module:
#
# import os, sys
# execfile(os.path.join(sys.path[0], 'framework.py'))
#
# ...and the following at the bottom:
#
# framework()
# Find the Testing package
if not sys.modules.has_key('Testing'):
p0 = sys.path[0]
if p0 and __name__ == '__main__':
os.chdir(p0)
p0 = ''
p = d = os.path.abspath(os.curdir)
while d:
if os.path.isdir(os.path.join(p, 'Testing')):
sys.path[:1] = [p0, os.pardir, p]
break
p, d = os.path.split(p)
else:
print 'Unable to locate Testing package.'
sys.exit(1)
import Testing, unittest
execfile(os.path.join(os.path.split(Testing.__file__)[0], 'common.py'))
...@@ -84,7 +84,6 @@ ...@@ -84,7 +84,6 @@
############################################################################## ##############################################################################
import os,sys import os,sys
execfile(os.path.join(sys.path[0],'framework.py'))
import unittest,locale import unittest,locale
from Products.PluginIndexes.TextIndex import Splitter from Products.PluginIndexes.TextIndex import Splitter
......
...@@ -83,25 +83,39 @@ ...@@ -83,25 +83,39 @@
# #
############################################################################## ##############################################################################
import sys, os import sys, os, unittest
execfile(os.path.join(sys.path[0],'framework.py'))
import zLOG import zLOG
def log_write(subsystem, severity, summary, detail, error): def log_write(subsystem, severity, summary, detail, error):
if severity >= zLOG.PROBLEM: if severity >= zLOG.PROBLEM:
assert 0, "%s(%s): %s" % (subsystem, severity, summary) assert 0, "%s(%s): %s" % (subsystem, severity, summary)
zLOG.log_write=log_write
import ZODB, ZODB.DemoStorage, ZODB.FileStorage import ZODB, ZODB.DemoStorage, ZODB.FileStorage
import TextIndex from Products.PluginIndexes.TextIndex import TextIndex
import GlobbingLexicon from Products.PluginIndexes.TextIndex import GlobbingLexicon
class Dummy:
def __init__( self, text ):
self._text = text
def text( self ):
return self._text
def __str__( self ):
return '<Dummy: %s>' % self._text
__repr__ = __str__
class Tests(unittest.TestCase): class Tests(unittest.TestCase):
def setUp(self): def setUp(self):
self.index=TextIndex.TextIndex('text') self.index=TextIndex.TextIndex('text')
self.doc=Dummy(text='this is the time, when all good zopes') self.doc=Dummy(text='this is the time, when all good zopes')
self.old_log_write = zLOG.log_write
zLOG.log_write=log_write
def dbopen(self): def dbopen(self):
n = 'fs_tmp__%s' % os.getpid() n = 'fs_tmp__%s' % os.getpid()
...@@ -124,6 +138,7 @@ class Tests(unittest.TestCase): ...@@ -124,6 +138,7 @@ class Tests(unittest.TestCase):
if hasattr(self, 'jar'): if hasattr(self, 'jar'):
self.dbclose() self.dbclose()
os.system('rm -f fs_tmp__*') os.system('rm -f fs_tmp__*')
zLOG.log_write=self.old_log_write
def checkSimpleAddDelete(self): def checkSimpleAddDelete(self):
"Check that we can add and delete an object without error" "Check that we can add and delete an object without error"
......
##############################################################################
#
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
#
# Copyright (c) Digital Creations. All rights reserved.
#
# This license has been certified as Open Source(tm).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions in source code must retain the above copyright
# notice, this list of conditions, and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions, and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# 3. Digital Creations requests that attribution be given to Zope
# in any manner possible. Zope includes a "Powered by Zope"
# button that is installed by default. While it is not a license
# violation to remove this button, it is requested that the
# attribution remain. A significant investment has been put
# into Zope, and this effort will continue if the Zope community
# continues to grow. This is one way to assure that growth.
#
# 4. All advertising materials and documentation mentioning
# features derived from or use of this software must display
# the following acknowledgement:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# In the event that the product being advertised includes an
# intact Zope distribution (with copyright and license included)
# then this clause is waived.
#
# 5. Names associated with Zope or Digital Creations must not be used to
# endorse or promote products derived from this software without
# prior written permission from Digital Creations.
#
# 6. Modified redistributions of any form whatsoever must retain
# the following acknowledgment:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# Intact (re-)distributions of any official Zope release do not
# require an external acknowledgement.
#
# 7. Modifications are encouraged but must be packaged separately as
# patches to official Zope releases. Distributions that do not
# clearly separate the patches from the original work must be clearly
# labeled as unofficial distributions. Modifications which do not
# carry the name Zope may be packaged in any form, as long as they
# conform to all of the clauses above.
#
#
# Disclaimer
#
# THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations. Specific
# attributions are listed in the accompanying credits file.
#
##############################################################################
######################################################################
# Set up unit testing framework
#
# The following code should be at the top of every test module:
#
# import os, sys
# execfile(os.path.join(sys.path[0], 'framework.py'))
#
# ...and the following at the bottom:
#
# framework()
# Find the Testing package
if not sys.modules.has_key('Testing'):
p0 = sys.path[0]
if p0 and __name__ == '__main__':
os.chdir(p0)
p0 = ''
p = d = os.path.abspath(os.curdir)
while d:
if os.path.isdir(os.path.join(p, 'Testing')):
sys.path[:1] = [p0, os.pardir, p]
break
p, d = os.path.split(p)
else:
print 'Unable to locate Testing package.'
sys.exit(1)
import Testing, unittest
execfile(os.path.join(os.path.split(Testing.__file__)[0], 'common.py'))
##############################################################################
#
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
#
# Copyright (c) Digital Creations. All rights reserved.
#
# This license has been certified as Open Source(tm).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions in source code must retain the above copyright
# notice, this list of conditions, and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions, and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# 3. Digital Creations requests that attribution be given to Zope
# in any manner possible. Zope includes a "Powered by Zope"
# button that is installed by default. While it is not a license
# violation to remove this button, it is requested that the
# attribution remain. A significant investment has been put
# into Zope, and this effort will continue if the Zope community
# continues to grow. This is one way to assure that growth.
#
# 4. All advertising materials and documentation mentioning
# features derived from or use of this software must display
# the following acknowledgement:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# In the event that the product being advertised includes an
# intact Zope distribution (with copyright and license included)
# then this clause is waived.
#
# 5. Names associated with Zope or Digital Creations must not be used to
# endorse or promote products derived from this software without
# prior written permission from Digital Creations.
#
# 6. Modified redistributions of any form whatsoever must retain
# the following acknowledgment:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# Intact (re-)distributions of any official Zope release do not
# require an external acknowledgement.
#
# 7. Modifications are encouraged but must be packaged separately as
# patches to official Zope releases. Distributions that do not
# clearly separate the patches from the original work must be clearly
# labeled as unofficial distributions. Modifications which do not
# carry the name Zope may be packaged in any form, as long as they
# conform to all of the clauses above.
#
#
# Disclaimer
#
# THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations. Specific
# attributions are listed in the accompanying credits file.
#
##############################################################################
import os, sys
execfile(os.path.join(sys.path[0], 'framework.py'))
import ZODB
from FieldIndex.FieldIndex import FieldIndex
class Dummy:
def __init__( self, foo ):
self._foo = foo
def foo( self ):
return self._foo
def __str__( self ):
return '<Dummy: %s>' % self._foo
__repr__ = __str__
class TestCase( unittest.TestCase ):
"""
Test FieldIndex objects.
"""
def setUp( self ):
"""
"""
self._index = FieldIndex( 'foo' )
self._marker = []
self._values = [ ( 0, Dummy( 'a' ) )
, ( 1, Dummy( 'ab' ) )
, ( 2, Dummy( 'abc' ) )
, ( 3, Dummy( 'abca' ) )
, ( 4, Dummy( 'abcd' ) )
, ( 5, Dummy( 'abce' ) )
, ( 6, Dummy( 'abce' ) )
, ( 7, Dummy( 0 ) ) # Collector #1959
, ( 8, Dummy(None) )]
self._forward = {}
self._backward = {}
for k, v in self._values:
self._backward[k] = v
keys = self._forward.get( v, [] )
self._forward[v] = keys
self._noop_req = { 'bar': 123 }
self._request = { 'foo': 'abce' }
self._min_req = { 'foo': 'abc'
, 'foo_usage': 'range:min'
}
self._max_req = { 'foo': 'abc'
, 'foo_usage': 'range:max'
}
self._range_req = { 'foo': ( 'abc', 'abcd' )
, 'foo_usage': 'range:min:max'
}
self._zero_req = { 'foo': 0 }
self._none_req = { 'foo': None }
def tearDown( self ):
"""
"""
def _populateIndex( self ):
for k, v in self._values:
self._index.index_object( k, v )
def _checkApply( self, req, expectedValues ):
result, used = self._index._apply_index( req )
if hasattr(result, 'keys'):
result = result.keys()
assert used == ( 'foo', )
assert len( result ) == len( expectedValues ), \
'%s | %s' % ( map( None, result ), expectedValues )
for k, v in expectedValues:
assert k in result
def testEmpty( self ):
"Test an empty FieldIndex."
assert len( self._index ) == 0
assert len( self._index.referencedObjects() ) == 0
assert self._index.getEntryForObject( 1234 ) is None
assert ( self._index.getEntryForObject( 1234, self._marker )
is self._marker )
self._index.unindex_object( 1234 ) # nothrow
assert self._index.hasUniqueValuesFor( 'foo' )
assert not self._index.hasUniqueValuesFor( 'bar' )
assert len( self._index.uniqueValues( 'foo' ) ) == 0
assert self._index._apply_index( self._noop_req ) is None
self._checkApply( self._request, [] )
self._checkApply( self._min_req, [] )
self._checkApply( self._max_req, [] )
self._checkApply( self._range_req, [] )
def testPopulated( self ):
""" Test a populated FieldIndex """
self._populateIndex()
values = self._values
assert len( self._index ) == len( values )-1 #'abce' is duplicate
assert len( self._index.referencedObjects() ) == len( values )
assert self._index.getEntryForObject( 1234 ) is None
assert ( self._index.getEntryForObject( 1234, self._marker )
is self._marker )
self._index.unindex_object( 1234 ) # nothrow
for k, v in values:
assert self._index.getEntryForObject( k ) == v.foo()
assert len( self._index.uniqueValues( 'foo' ) ) == len( values )-1
assert self._index._apply_index( self._noop_req ) is None
self._checkApply( self._request, values[ -4:-2 ] )
self._checkApply( self._min_req, values[ 2:-2 ] )
self._checkApply( self._max_req, values[ :3 ] + values[ -2: ] )
self._checkApply( self._range_req, values[ 2:5 ] )
def testZero( self ):
""" Make sure 0 gets indexed """
self._populateIndex()
values = self._values
self._checkApply( self._zero_req, values[ -2:-1 ] )
assert 0 in self._index.uniqueValues( 'foo' )
def testNone(self):
""" make sure None gets indexed """
self._populateIndex()
values = self._values
self._checkApply(self._none_req, values[-1:])
assert None in self._index.uniqueValues('foo')
def testRange(self):
"""Test a range search"""
index = FieldIndex( 'foo' )
for i in range(100):
index.index_object(i, Dummy(i%10))
r=index._apply_index({
'foo_usage': 'range:min:max',
'foo': [-99, 3]})
assert tuple(r[1])==('foo',), r[1]
r=list(r[0].keys())
expect=[
0, 1, 2, 3, 10, 11, 12, 13, 20, 21, 22, 23, 30, 31, 32, 33,
40, 41, 42, 43, 50, 51, 52, 53, 60, 61, 62, 63, 70, 71, 72, 73,
80, 81, 82, 83, 90, 91, 92, 93
]
assert r==expect, r
framework()
##############################################################################
#
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
#
# Copyright (c) Digital Creations. All rights reserved.
#
# This license has been certified as Open Source(tm).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions in source code must retain the above copyright
# notice, this list of conditions, and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions, and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# 3. Digital Creations requests that attribution be given to Zope
# in any manner possible. Zope includes a "Powered by Zope"
# button that is installed by default. While it is not a license
# violation to remove this button, it is requested that the
# attribution remain. A significant investment has been put
# into Zope, and this effort will continue if the Zope community
# continues to grow. This is one way to assure that growth.
#
# 4. All advertising materials and documentation mentioning
# features derived from or use of this software must display
# the following acknowledgement:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# In the event that the product being advertised includes an
# intact Zope distribution (with copyright and license included)
# then this clause is waived.
#
# 5. Names associated with Zope or Digital Creations must not be used to
# endorse or promote products derived from this software without
# prior written permission from Digital Creations.
#
# 6. Modified redistributions of any form whatsoever must retain
# the following acknowledgment:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# Intact (re-)distributions of any official Zope release do not
# require an external acknowledgement.
#
# 7. Modifications are encouraged but must be packaged separately as
# patches to official Zope releases. Distributions that do not
# clearly separate the patches from the original work must be clearly
# labeled as unofficial distributions. Modifications which do not
# carry the name Zope may be packaged in any form, as long as they
# conform to all of the clauses above.
#
#
# Disclaimer
#
# THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations. Specific
# attributions are listed in the accompanying credits file.
#
##############################################################################
import os, sys
execfile(os.path.join(sys.path[0], 'framework.py'))
from KeywordIndex.KeywordIndex import KeywordIndex
class Dummy:
def __init__( self, foo ):
self._foo = foo
def foo( self ):
return self._foo
def __str__( self ):
return '<Dummy: %s>' % self._foo
__repr__ = __str__
class TestCase( unittest.TestCase ):
"""
Test KeywordIndex objects.
"""
def setUp( self ):
"""
"""
self._index = KeywordIndex( 'foo' )
self._marker = []
self._values = [ ( 0, Dummy( ['a'] ) )
, ( 1, Dummy( ['a','b'] ) )
, ( 2, Dummy( ['a','b','c'] ) )
, ( 3, Dummy( ['a','b','c', 'a'] ) )
, ( 4, Dummy( ['a', 'b', 'c', 'd'] ) )
, ( 5, Dummy( ['a', 'b', 'c', 'e'] ) )
, ( 6, Dummy( ['a', 'b', 'c', 'e', 'f'] ))
, ( 7, Dummy( [0] ) )
]
self._noop_req = { 'bar': 123 }
self._all_req = { 'foo': ['a'] }
self._some_req = { 'foo': ['e'] }
self._overlap_req = { 'foo': ['c', 'e'] }
self._string_req = {'foo': 'a'}
self._zero_req = { 'foo': [0] }
def tearDown( self ):
"""
"""
def _populateIndex( self ):
for k, v in self._values:
self._index.index_object( k, v )
def _checkApply( self, req, expectedValues ):
result, used = self._index._apply_index( req )
assert used == ( 'foo', )
assert len(result) == len( expectedValues ), \
'%s | %s' % ( map( None, result ),
map(lambda x: x[0], expectedValues ))
if hasattr(result, 'keys'): result=result.keys()
for k, v in expectedValues:
assert k in result
def testAddObjectWOKeywords(self):
catch_log_errors()
try:
self._populateIndex()
self._index.index_object(999, None)
finally:
ignore_log_errors()
def testEmpty( self ):
assert len( self._index ) == 0
assert len( self._index.referencedObjects() ) == 0
assert self._index.getEntryForObject( 1234 ) is None
assert ( self._index.getEntryForObject( 1234, self._marker )
is self._marker ), self._index.getEntryForObject(1234)
self._index.unindex_object( 1234 ) # nothrow
assert self._index.hasUniqueValuesFor( 'foo' )
assert not self._index.hasUniqueValuesFor( 'bar' )
assert len( self._index.uniqueValues( 'foo' ) ) == 0
assert self._index._apply_index( self._noop_req ) is None
self._checkApply( self._all_req, [] )
self._checkApply( self._some_req, [] )
self._checkApply( self._overlap_req, [] )
self._checkApply( self._string_req, [] )
def testPopulated( self ):
self._populateIndex()
values = self._values
#assert len( self._index ) == len( values )
assert len( self._index.referencedObjects() ) == len( values )
assert self._index.getEntryForObject( 1234 ) is None
assert ( self._index.getEntryForObject( 1234, self._marker )
is self._marker )
self._index.unindex_object( 1234 ) # nothrow
for k, v in values:
assert self._index.getEntryForObject( k ) == v.foo()
assert (len( self._index.uniqueValues( 'foo' ) ) == len( values )-1,
len(values)-1)
assert self._index._apply_index( self._noop_req ) is None
self._checkApply( self._all_req, values[:-1])
self._checkApply( self._some_req, values[ 5:7 ] )
self._checkApply( self._overlap_req, values[2:7] )
self._checkApply( self._string_req, values[:-1] )
def testZero( self ):
self._populateIndex()
values = self._values
self._checkApply( self._zero_req, values[ -1: ] )
assert 0 in self._index.uniqueValues( 'foo' )
def testReindexChange(self):
self._populateIndex()
expected = Dummy(['x', 'y'])
self._index.index_object(6, expected)
result, used = self._index._apply_index({'foo': ['x', 'y']})
result=result.keys()
assert len(result) == 1
assert result[0] == 6
result, used = self._index._apply_index(
{'foo': ['a', 'b', 'c', 'e', 'f']}
)
result = result.keys()
assert 6 not in result
def testReindexNoChange(self):
self._populateIndex()
expected = Dummy(['foo', 'bar'])
self._index.index_object(8, expected)
result, used = self._index._apply_index(
{'foo': ['foo', 'bar']})
result = result.keys()
assert len(result) == 1
assert result[0] == 8
self._index.index_object(8, expected)
result, used = self._index._apply_index(
{'foo': ['foo', 'bar']})
result = result.keys()
assert len(result) == 1
assert result[0] == 8
framework()
##############################################################################
#
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
#
# Copyright (c) Digital Creations. All rights reserved.
#
# This license has been certified as Open Source(tm).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions in source code must retain the above copyright
# notice, this list of conditions, and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions, and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# 3. Digital Creations requests that attribution be given to Zope
# in any manner possible. Zope includes a "Powered by Zope"
# button that is installed by default. While it is not a license
# violation to remove this button, it is requested that the
# attribution remain. A significant investment has been put
# into Zope, and this effort will continue if the Zope community
# continues to grow. This is one way to assure that growth.
#
# 4. All advertising materials and documentation mentioning
# features derived from or use of this software must display
# the following acknowledgement:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# In the event that the product being advertised includes an
# intact Zope distribution (with copyright and license included)
# then this clause is waived.
#
# 5. Names associated with Zope or Digital Creations must not be used to
# endorse or promote products derived from this software without
# prior written permission from Digital Creations.
#
# 6. Modified redistributions of any form whatsoever must retain
# the following acknowledgment:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# Intact (re-)distributions of any official Zope release do not
# require an external acknowledgement.
#
# 7. Modifications are encouraged but must be packaged separately as
# patches to official Zope releases. Distributions that do not
# clearly separate the patches from the original work must be clearly
# labeled as unofficial distributions. Modifications which do not
# carry the name Zope may be packaged in any form, as long as they
# conform to all of the clauses above.
#
#
# Disclaimer
#
# THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations. Specific
# attributions are listed in the accompanying credits file.
#
##############################################################################
import os, sys
execfile(os.path.join(sys.path[0], 'framework.py'))
from PathIndex.PathIndex import PathIndex
class Dummy:
meta_type="foo"
def __init__( self, path):
self.path = path
def getPhysicalPath(self):
return self.path.split('/')
def __str__( self ):
return '<Dummy: %s>' % self.path
__repr__ = __str__
class TestCase( unittest.TestCase ):
"""
Test PathIndex objects.
"""
def setUp( self ):
"""
"""
self._index = PathIndex( 'path' )
self._values = {
1 : Dummy("/aa/aa/aa/1.html"),
2 : Dummy("/aa/aa/bb/2.html"),
3 : Dummy("/aa/aa/cc/3.html"),
4 : Dummy("/aa/bb/aa/4.html"),
5 : Dummy("/aa/bb/bb/5.html"),
6 : Dummy("/aa/bb/cc/6.html"),
7 : Dummy("/aa/cc/aa/7.html"),
8 : Dummy("/aa/cc/bb/8.html"),
9 : Dummy("/aa/cc/cc/9.html"),
10 : Dummy("/bb/aa/aa/10.html"),
11 : Dummy("/bb/aa/bb/11.html"),
12 : Dummy("/bb/aa/cc/12.html"),
13 : Dummy("/bb/bb/aa/13.html"),
14 : Dummy("/bb/bb/bb/14.html"),
15 : Dummy("/bb/bb/cc/15.html"),
16 : Dummy("/bb/cc/aa/16.html"),
17 : Dummy("/bb/cc/bb/17html"),
18 : Dummy("/bb/cc/cc/18html")
}
def tearDown( self ):
"""
"""
def _populateIndex( self ):
for k, v in self._values.items():
self._index.index_object( k, v )
def testEmpty( self ):
"Test an empty PathIndex."
assert len( self._index ) == 0
assert self._index.getEntryForObject( 1234 ) is None
self._index.unindex_object( 1234 ) # nothrow
assert self._index._apply_index( {"suxpath":"xxx"} ) is None
def testUnIndex( self ):
"Test to UnIndex PathIndex."
self._populateIndex()
for k in self._values.keys():
self._index.unindex_object(k)
assert len(self._index._index)==0
assert len(self._index._unindex)==0
def testPopulateIndex( self ):
self._populateIndex()
tests = [
("aa",0, [1,2,3,4,5,6,7,8,9]),
("aa",1, [1,2,3,10,11,12] ),
("bb",0, [10,11,12,13,14,15,16,17,18]),
("bb",1, [4,5,6,13,14,15] ),
("bb/cc",0, [16,17,18] ),
("bb/cc",1, [6,15] ),
("bb/aa",0, [10,11,12] ),
("bb/aa",1, [4,13] ),
("aa/cc",-1, [3,7,8,9,12] ),
("bb/bb",-1, [5,13,14,15] )
]
for comp,level,results in tests:
for path in [comp,"/"+comp,"/"+comp+"/"]:
res = self._index._apply_index({"path":{'query':path,"level":level}})
lst = list(res[0].keys())
assert lst==results,res
for comp,level,results in tests:
for path in [comp,"/"+comp,"/"+comp+"/"]:
res = self._index._apply_index({"path":{'query':( (path,level),)}})
lst = list(res[0].keys())
assert lst==results,res
framework()
##############################################################################
#
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
#
# Copyright (c) Digital Creations. All rights reserved.
#
# This license has been certified as Open Source(tm).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions in source code must retain the above copyright
# notice, this list of conditions, and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions, and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# 3. Digital Creations requests that attribution be given to Zope
# in any manner possible. Zope includes a "Powered by Zope"
# button that is installed by default. While it is not a license
# violation to remove this button, it is requested that the
# attribution remain. A significant investment has been put
# into Zope, and this effort will continue if the Zope community
# continues to grow. This is one way to assure that growth.
#
# 4. All advertising materials and documentation mentioning
# features derived from or use of this software must display
# the following acknowledgement:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# In the event that the product being advertised includes an
# intact Zope distribution (with copyright and license included)
# then this clause is waived.
#
# 5. Names associated with Zope or Digital Creations must not be used to
# endorse or promote products derived from this software without
# prior written permission from Digital Creations.
#
# 6. Modified redistributions of any form whatsoever must retain
# the following acknowledgment:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# Intact (re-)distributions of any official Zope release do not
# require an external acknowledgement.
#
# 7. Modifications are encouraged but must be packaged separately as
# patches to official Zope releases. Distributions that do not
# clearly separate the patches from the original work must be clearly
# labeled as unofficial distributions. Modifications which do not
# carry the name Zope may be packaged in any form, as long as they
# conform to all of the clauses above.
#
#
# Disclaimer
#
# THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations. Specific
# attributions are listed in the accompanying credits file.
#
##############################################################################
import os, sys
execfile(os.path.join(sys.path[0], 'framework.py'))
from TextIndex import Splitter
Splitter = Splitter.getSplitter()
class TestSplitter(unittest.TestCase):
def testSplitNormalText(self):
text = 'this is a long string of words'
a = Splitter(text)
r = map(None, a)
assert r == ['this', 'is', 'long', 'string', 'of', 'words']
def testDropNumeric(self):
text = '123 456 789 foobar without you nothing'
a = Splitter(text)
r = map(None, a)
assert r == ['foobar', 'without', 'you', 'nothing'], r
def testDropSingleLetterWords(self):
text = 'without you I nothing'
a = Splitter(text)
r = map(None, a)
assert r == ['without', 'you', 'nothing'], r
def testSplitOnNonAlpha(self):
text = 'without you I\'m nothing'
a = Splitter(text)
r = map(None, a)
assert r == ['without', 'you', 'nothing'], r
framework()
##############################################################################
#
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
#
# Copyright (c) Digital Creations. All rights reserved.
#
# This license has been certified as Open Source(tm).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions in source code must retain the above copyright
# notice, this list of conditions, and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions, and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# 3. Digital Creations requests that attribution be given to Zope
# in any manner possible. Zope includes a "Powered by Zope"
# button that is installed by default. While it is not a license
# violation to remove this button, it is requested that the
# attribution remain. A significant investment has been put
# into Zope, and this effort will continue if the Zope community
# continues to grow. This is one way to assure that growth.
#
# 4. All advertising materials and documentation mentioning
# features derived from or use of this software must display
# the following acknowledgement:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# In the event that the product being advertised includes an
# intact Zope distribution (with copyright and license included)
# then this clause is waived.
#
# 5. Names associated with Zope or Digital Creations must not be used to
# endorse or promote products derived from this software without
# prior written permission from Digital Creations.
#
# 6. Modified redistributions of any form whatsoever must retain
# the following acknowledgment:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# Intact (re-)distributions of any official Zope release do not
# require an external acknowledgement.
#
# 7. Modifications are encouraged but must be packaged separately as
# patches to official Zope releases. Distributions that do not
# clearly separate the patches from the original work must be clearly
# labeled as unofficial distributions. Modifications which do not
# carry the name Zope may be packaged in any form, as long as they
# conform to all of the clauses above.
#
#
# Disclaimer
#
# THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations. Specific
# attributions are listed in the accompanying credits file.
#
##############################################################################
import os, sys
execfile(os.path.join(sys.path[0], 'framework.py'))
from Testing.ZODButil import makeDB, cleanDB
from TextIndex import TextIndex, GlobbingLexicon
class Tests(unittest.TestCase):
def setUp(self):
self.index=TextIndex.TextIndex('text')
self.doc=Dummy(text='this is the time, when all good zopes')
def dbopen(self):
db = self.db = makeDB()
jar = self.jar = db.open()
if not jar.root().has_key('index'):
jar.root()['index'] = TextIndex.TextIndex('text')
get_transaction().commit()
return jar.root()['index']
def dbclose(self):
self.jar.close()
self.db.close()
del self.jar
del self.db
def tearDown(self):
get_transaction().abort()
if hasattr(self, 'jar'):
self.dbclose()
cleanDB()
self.__dict__.clear()
def testSimpleAddDelete(self):
"Test that we can add and delete an object without error"
self.index.index_object(0, self.doc)
self.index.index_object(1, self.doc)
self.doc.text='spam is good, spam is fine, span span span'
self.index.index_object(0, self.doc)
self.index.unindex_object(0)
def testPersistentUpdate1(self):
"Test simple persistent indexing"
index=self.dbopen()
self.doc.text='this is the time, when all good zopes'
index.index_object(0, self.doc)
get_transaction().commit()
self.doc.text='time waits for no one'
index.index_object(1, self.doc)
get_transaction().commit()
self.dbclose()
index=self.dbopen()
r = index._apply_index({})
assert r==None
r = index._apply_index({'text': 'python'})
assert len(r) == 2 and r[1]==('text',), 'incorrectly not used'
assert not r[0], "should have no results"
r = index._apply_index({'text': 'time'})
r=list(r[0].keys())
assert r == [0,1], r
def testPersistentUpdate2(self):
"Test less simple persistent indexing"
index=self.dbopen()
self.doc.text='this is the time, when all good zopes'
index.index_object(0, self.doc)
get_transaction().commit()
self.doc.text='time waits for no one'
index.index_object(1, self.doc)
get_transaction().commit()
self.doc.text='the next task is to test'
index.index_object(3, self.doc)
get_transaction().commit()
self.doc.text='time time'
index.index_object(2, self.doc)
get_transaction().commit()
self.dbclose()
index=self.dbopen()
r = index._apply_index({})
assert r==None
r = index._apply_index({'text': 'python'})
assert len(r) == 2 and r[1]==('text',), 'incorrectly not used'
assert not r[0], "should have no results"
r = index._apply_index({'text': 'time'})
r=list(r[0].keys())
assert r == [0,1,2], r
sample_texts = [
"""This is the time for all good men to come to
the aid of their country""",
"""ask not what your country can do for you,
ask what you can do for your country""",
"""Man, I can't wait to get to Montross!""",
"""Zope Public License (ZPL) Version 1.0""",
"""Copyright (c) Digital Creations. All rights reserved.""",
"""This license has been certified as Open Source(tm).""",
"""I hope I get to work on time""",
]
def globTest(self, qmap, rlist):
"Test a glob query"
index = getattr(self, '_v_index', None)
if index is None:
index=self.dbopen()
index._lexicon = GlobbingLexicon.GlobbingLexicon()
for i in range(len(self.sample_texts)):
self.doc.text=self.sample_texts[i]
index.index_object(i, self.doc)
get_transaction().commit()
self.dbclose()
index = self._v_index = self.dbopen()
r = list(index._apply_index(qmap)[0].keys())
assert r == rlist, r
def testStarQuery(self):
"Test a star query"
self.globTest({'text':'m*n'}, [0,2])
def testAndQuery(self):
"Test an AND query"
self.globTest({'text':'time and country'}, [0,])
def testOrQuery(self):
"Test an OR query"
self.globTest({'text':'time or country'}, [0,1,6])
def testDefOrQuery(self):
"Test a default OR query"
self.globTest({'text':'time country'}, [0,1,6])
self.globTest({'text':'time good country'}, [0,1,6])
def testNearQuery(self):
"""Test a NEAR query.. (NOTE:ACTUALLY AN 'AND' TEST!!)"""
# NEAR never worked, so Zopes post-2.3.1b3 define near to mean AND
self.globTest({'text':'time ... country'}, [0,])
def testQuotesQuery(self):
"""Test a quoted query"""
self.globTest({'text':'"This is the time"'}, [0,])
self.globTest({'text':'"now is the time"'}, [])
def testAndNotQuery(self):
"Test an ANDNOT query"
self.globTest({'text':'time and not country'}, [6,])
def testParenMatchingQuery(self):
"Test a query with parens"
self.globTest({'text':'(time and country) men'}, [0,])
self.globTest({'text':'(time and not country) or men'}, [0, 6])
def testTextIndexOperatorQuery(self):
"Test a query with 'operator' in the request"
self.globTest({'text': {'query': 'time men', 'operator':'and'}}, [0,])
def testNonExistentWord(self):
""" Test for nonexistent word """
self.globTest({'text':'zop'}, [])
def testShortWord(self):
""" Test for short word """
self.globTest({'text':'to'}, [0, 2, 6])
self.globTest({'text':'*to'}, [0, 2, 6])
self.globTest({'text':'to*'}, [0, 2, 6])
self.globTest({'text':'*to*'}, [0, 2, 6])
def testComplexQuery1(self):
""" Test complex query 1 """
self.globTest({'text':'((?ount* or get) and not wait) '
'"been *ert*"'}, [0, 1, 5, 6])
framework()
##############################################################################
#
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
#
# Copyright (c) Digital Creations. All rights reserved.
#
# This license has been certified as Open Source(tm).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions in source code must retain the above copyright
# notice, this list of conditions, and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions, and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# 3. Digital Creations requests that attribution be given to Zope
# in any manner possible. Zope includes a "Powered by Zope"
# button that is installed by default. While it is not a license
# violation to remove this button, it is requested that the
# attribution remain. A significant investment has been put
# into Zope, and this effort will continue if the Zope community
# continues to grow. This is one way to assure that growth.
#
# 4. All advertising materials and documentation mentioning
# features derived from or use of this software must display
# the following acknowledgement:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# In the event that the product being advertised includes an
# intact Zope distribution (with copyright and license included)
# then this clause is waived.
#
# 5. Names associated with Zope or Digital Creations must not be used to
# endorse or promote products derived from this software without
# prior written permission from Digital Creations.
#
# 6. Modified redistributions of any form whatsoever must retain
# the following acknowledgment:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# Intact (re-)distributions of any official Zope release do not
# require an external acknowledgement.
#
# 7. Modifications are encouraged but must be packaged separately as
# patches to official Zope releases. Distributions that do not
# clearly separate the patches from the original work must be clearly
# labeled as unofficial distributions. Modifications which do not
# carry the name Zope may be packaged in any form, as long as they
# conform to all of the clauses above.
#
#
# Disclaimer
#
# THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations. Specific
# attributions are listed in the accompanying credits file.
#
##############################################################################
######################################################################
# Set up unit testing framework
#
# The following code should be at the top of every test module:
#
# import os, sys
# execfile(os.path.join(sys.path[0], 'framework.py'))
#
# ...and the following at the bottom:
#
# framework()
# Find the Testing package
if not sys.modules.has_key('Testing'):
p0 = sys.path[0]
if p0 and __name__ == '__main__':
os.chdir(p0)
p0 = ''
p = d = os.path.abspath(os.curdir)
while d:
if os.path.isdir(os.path.join(p, 'Testing')):
sys.path[:1] = [p0, os.pardir, p]
break
p, d = os.path.split(p)
else:
print 'Unable to locate Testing package.'
sys.exit(1)
import Testing, unittest
execfile(os.path.join(os.path.split(Testing.__file__)[0], 'common.py'))
...@@ -82,8 +82,7 @@ ...@@ -82,8 +82,7 @@
# attributions are listed in the accompanying credits file. # attributions are listed in the accompanying credits file.
# #
############################################################################## ##############################################################################
import os, sys import os, sys, unittest
execfile(os.path.join(sys.path[0], 'framework.py'))
import ZODB import ZODB
from Products.PythonScripts.PythonScript import PythonScript from Products.PythonScripts.PythonScript import PythonScript
...@@ -91,10 +90,21 @@ from AccessControl.SecurityManagement import newSecurityManager ...@@ -91,10 +90,21 @@ from AccessControl.SecurityManagement import newSecurityManager
newSecurityManager(None, None) newSecurityManager(None, None)
if __name__=='__main__':
sys.path.append(os.path.join(os.pardir, os.pardir, os.pardir))
here = os.curdir
else:
from Products.PythonScripts import tests
from App.Common import package_home
here = package_home(tests.__dict__)
# Test Classes # Test Classes
def readf(name): def readf(name):
return open('tscripts/%s%s' % (name, '.ps'), 'r').read() return open( os.path.join( here
, 'tscripts'
, '%s.ps' % name
), 'r').read()
class TestPythonScriptNoAq(unittest.TestCase): class TestPythonScriptNoAq(unittest.TestCase):
def _newPS(self, txt, bind=None): def _newPS(self, txt, bind=None):
...@@ -208,5 +218,14 @@ class TestPythonScriptNoAq(unittest.TestCase): ...@@ -208,5 +218,14 @@ class TestPythonScriptNoAq(unittest.TestCase):
true = self._newPS(readf('boolean_map'))() true = self._newPS(readf('boolean_map'))()
assert true assert true
framework() def test_suite():
suite = unittest.TestSuite()
suite.addTest( unittest.makeSuite( TestPythonScriptNoAq ) )
return suite
def main():
unittest.TextTestRunner().run(test_suite())
if __name__ == '__main__':
main()
##############################################################################
#
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
#
# Copyright (c) Digital Creations. All rights reserved.
#
# This license has been certified as Open Source(tm).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions in source code must retain the above copyright
# notice, this list of conditions, and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions, and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# 3. Digital Creations requests that attribution be given to Zope
# in any manner possible. Zope includes a "Powered by Zope"
# button that is installed by default. While it is not a license
# violation to remove this button, it is requested that the
# attribution remain. A significant investment has been put
# into Zope, and this effort will continue if the Zope community
# continues to grow. This is one way to assure that growth.
#
# 4. All advertising materials and documentation mentioning
# features derived from or use of this software must display
# the following acknowledgement:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# In the event that the product being advertised includes an
# intact Zope distribution (with copyright and license included)
# then this clause is waived.
#
# 5. Names associated with Zope or Digital Creations must not be used to
# endorse or promote products derived from this software without
# prior written permission from Digital Creations.
#
# 6. Modified redistributions of any form whatsoever must retain
# the following acknowledgment:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# Intact (re-)distributions of any official Zope release do not
# require an external acknowledgement.
#
# 7. Modifications are encouraged but must be packaged separately as
# patches to official Zope releases. Distributions that do not
# clearly separate the patches from the original work must be clearly
# labeled as unofficial distributions. Modifications which do not
# carry the name Zope may be packaged in any form, as long as they
# conform to all of the clauses above.
#
#
# Disclaimer
#
# THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations. Specific
# attributions are listed in the accompanying credits file.
#
##############################################################################
######################################################################
# Set up unit testing framework
#
# The following code should be at the top of every test module:
#
# import os, sys
# execfile(os.path.join(sys.path[0], 'framework.py'))
#
# ...and the following at the bottom:
#
# framework()
# Find the Testing package
if not sys.modules.has_key('Testing'):
p0 = sys.path[0]
if p0 and __name__ == '__main__':
os.chdir(p0)
p0 = ''
p = d = os.path.abspath(os.curdir)
while d:
if os.path.isdir(os.path.join(p, 'Testing')):
sys.path[:1] = [p0, os.pardir, p]
break
p, d = os.path.split(p)
else:
print 'Unable to locate Testing package.'
sys.exit(1)
import Testing, unittest
execfile(os.path.join(os.path.split(Testing.__file__)[0], 'common.py'))
import os,sys import os,sys
execfile(os.path.join(sys.path[0],'framework.py'))
import unittest import unittest
import Zope import Zope
...@@ -113,5 +112,55 @@ class UnicodeTextIndexCatalogTest(unittest.TestCase): ...@@ -113,5 +112,55 @@ class UnicodeTextIndexCatalogTest(unittest.TestCase):
"%s: %s vs %s" % (q,str(r.getURL()),str(objs)) "%s: %s vs %s" % (q,str(r.getURL()),str(objs))
framework()
def test_suite():
return unittest.makeSuite(UnicodeTextIndexCatalogTest)
def main():
mb = os.path.join(here, 'zope.mbox')
if not os.path.isfile(mb):
print "do you want to get the zope.mbox file from lists.zope.org?"
print "it's required for testing (98MB, ~ 30mins on fast conn)"
print "it's also available at korak:/home/chrism/zope.mbox"
print "-- type 'Y' or 'N'"
a = raw_input()
if lower(a[:1]) == 'y':
server = 'lists.zope.org:80'
method = '/pipermail/zope.mbox/zope.mbox'
h = httplib.HTTP(server)
h.putrequest('GET', method)
h.putheader('User-Agent', 'silly')
h.putheader('Accept', 'text/html')
h.putheader('Accept', 'text/plain')
h.putheader('Host', server)
h.endheaders()
errcode, errmsg, headers = h.getreply()
if errcode != 200:
f = h.getfile()
data = f.read()
print data
raise "Error reading from host %s" % server
f = h.getfile()
out=open(mb,'w')
print "this is going to take a while..."
print "downloading mbox from %s" % server
while 1:
l = f.readline()
if not l: break
out.write(l)
alltests=test_suite()
runner = unittest.TextTestRunner()
runner.run(alltests)
def debug():
test_suite().debug()
if __name__=='__main__':
if len(sys.argv) > 1:
globals()[sys.argv[1]]()
else:
main()
##############################################################################
#
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
#
# Copyright (c) Digital Creations. All rights reserved.
#
# This license has been certified as Open Source(tm).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions in source code must retain the above copyright
# notice, this list of conditions, and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions, and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# 3. Digital Creations requests that attribution be given to Zope
# in any manner possible. Zope includes a "Powered by Zope"
# button that is installed by default. While it is not a license
# violation to remove this button, it is requested that the
# attribution remain. A significant investment has been put
# into Zope, and this effort will continue if the Zope community
# continues to grow. This is one way to assure that growth.
#
# 4. All advertising materials and documentation mentioning
# features derived from or use of this software must display
# the following acknowledgement:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# In the event that the product being advertised includes an
# intact Zope distribution (with copyright and license included)
# then this clause is waived.
#
# 5. Names associated with Zope or Digital Creations must not be used to
# endorse or promote products derived from this software without
# prior written permission from Digital Creations.
#
# 6. Modified redistributions of any form whatsoever must retain
# the following acknowledgment:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# Intact (re-)distributions of any official Zope release do not
# require an external acknowledgement.
#
# 7. Modifications are encouraged but must be packaged separately as
# patches to official Zope releases. Distributions that do not
# clearly separate the patches from the original work must be clearly
# labeled as unofficial distributions. Modifications which do not
# carry the name Zope may be packaged in any form, as long as they
# conform to all of the clauses above.
#
#
# Disclaimer
#
# THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations. Specific
# attributions are listed in the accompanying credits file.
#
##############################################################################
######################################################################
# Set up unit testing framework
#
# The following code should be at the top of every test module:
#
# import os, sys
# execfile(os.path.join(sys.path[0], 'framework.py'))
#
# ...and the following at the bottom:
#
# framework()
# Find the Testing package
if not sys.modules.has_key('Testing'):
p0 = sys.path[0]
if p0 and __name__ == '__main__':
os.chdir(p0)
p0 = ''
p = d = os.path.abspath(os.curdir)
while d:
if os.path.isdir(os.path.join(p, 'Testing')):
sys.path[:1] = [p0, os.pardir, p]
break
p, d = os.path.split(p)
else:
print 'Unable to locate Testing package.'
sys.exit(1)
import Testing, unittest
execfile(os.path.join(os.path.split(Testing.__file__)[0], 'common.py'))
#!/usr/bin/env python #!/usr/bin/env python, unittest
# Unittests for Catalog # Unittests for Catalog
import os,sys import os,sys, unittest
execfile(os.path.join(sys.path[0],'framework.py'))
os.environ['STUPID_LOG_FILE']= "debug.log"
import Zope import Zope
from Products.ZCatalog import ZCatalog,Vocabulary from Products.ZCatalog import ZCatalog,Vocabulary
...@@ -324,7 +322,8 @@ class objRS(ExtensionClass.Base): ...@@ -324,7 +322,8 @@ class objRS(ExtensionClass.Base):
class testRS(unittest.TestCase): class testRS(unittest.TestCase):
def setUp(self): def setUp(self):
self._vocabulary = Vocabulary.Vocabulary('Vocabulary','Vocabulary', globbing=1) self._vocabulary = Vocabulary.Vocabulary('Vocabulary','Vocabulary'
, globbing=1)
self._catalog = Catalog() self._catalog = Catalog()
index = FieldIndex('number') index = FieldIndex('number')
self._catalog.addIndex('number', index) self._catalog.addIndex('number', index)
...@@ -342,11 +341,25 @@ class testRS(unittest.TestCase): ...@@ -342,11 +341,25 @@ class testRS(unittest.TestCase):
m = whrandom.randint(0,20000) m = whrandom.randint(0,20000)
n = m + 1000 n = m + 1000
for r in self._catalog.searchResults( {"number" : (m,n) , for r in self._catalog.searchResults(
"length_usage" : "range:min:max" } { "number" : (m,n) ,
): "length_usage" : "range:min:max" } ):
size = r.number size = r.number
assert m<=size and size<=n , "%d vs [%d,%d]" % (r.number,m,n) assert m<=size and size<=n , "%d vs [%d,%d]" % (r.number,m,n)
framework()
def test_suite():
suite = unittest.TestSuite()
suite.addTest( unittest.makeSuite( TestAddDelColumn ) )
suite.addTest( unittest.makeSuite( TestAddDelIndexes ) )
suite.addTest( unittest.makeSuite( TestZCatalogObject ) )
suite.addTest( unittest.makeSuite( TestCatalogObject ) )
suite.addTest( unittest.makeSuite( testRS ) )
return suite
def main():
unittest.TextTestRunner().run(test_suite())
if __name__ == '__main__':
main()
...@@ -8,7 +8,7 @@ if __name__=='__main__': ...@@ -8,7 +8,7 @@ if __name__=='__main__':
import unittest import unittest
from RestrictedPython import compile_restricted, PrintCollector from RestrictedPython import compile_restricted, PrintCollector
from RestrictedPython.Eval import RestrictionCapableEval from RestrictedPython.Eval import RestrictionCapableEval
import security_in_syntax from RestrictedPython.tests import security_in_syntax
from types import FunctionType from types import FunctionType
if __name__=='__main__': if __name__=='__main__':
......
# Nothing to see here (deprecated module).
##############################################################################
#
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
#
# Copyright (c) Digital Creations. All rights reserved.
#
# This license has been certified as Open Source(tm).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions in source code must retain the above copyright
# notice, this list of conditions, and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions, and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# 3. Digital Creations requests that attribution be given to Zope
# in any manner possible. Zope includes a "Powered by Zope"
# button that is installed by default. While it is not a license
# violation to remove this button, it is requested that the
# attribution remain. A significant investment has been put
# into Zope, and this effort will continue if the Zope community
# continues to grow. This is one way to assure that growth.
#
# 4. All advertising materials and documentation mentioning
# features derived from or use of this software must display
# the following acknowledgement:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# In the event that the product being advertised includes an
# intact Zope distribution (with copyright and license included)
# then this clause is waived.
#
# 5. Names associated with Zope or Digital Creations must not be used to
# endorse or promote products derived from this software without
# prior written permission from Digital Creations.
#
# 6. Modified redistributions of any form whatsoever must retain
# the following acknowledgment:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# Intact (re-)distributions of any official Zope release do not
# require an external acknowledgement.
#
# 7. Modifications are encouraged but must be packaged separately as
# patches to official Zope releases. Distributions that do not
# clearly separate the patches from the original work must be clearly
# labeled as unofficial distributions. Modifications which do not
# carry the name Zope may be packaged in any form, as long as they
# conform to all of the clauses above.
#
#
# Disclaimer
#
# THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations. Specific
# attributions are listed in the accompanying credits file.
#
##############################################################################
######################################################################
# Set up unit testing framework
#
# The following code should be at the top of every test module:
#
# import os, sys
# execfile(os.path.join(sys.path[0], 'framework.py'))
#
# ...and the following at the bottom:
#
# framework()
# Find the Testing package
if not sys.modules.has_key('Testing'):
p0 = sys.path[0]
if p0 and __name__ == '__main__':
os.chdir(p0)
p0 = ''
p = d = os.path.abspath(os.curdir)
while d:
if os.path.isdir(os.path.join(p, 'Testing')):
sys.path[:1] = [p0, os.pardir, p]
break
p, d = os.path.split(p)
else:
print 'Unable to locate Testing package.'
sys.exit(1)
import Testing, unittest
execfile(os.path.join(os.path.split(Testing.__file__)[0], 'common.py'))
...@@ -188,13 +188,15 @@ class StructuredTextTests(unittest.TestCase): ...@@ -188,13 +188,15 @@ class StructuredTextTests(unittest.TestCase):
try: try:
open('_tmpout','w').write(html) open('_tmpout','w').write(html)
ndiff.fcompare(os.path.join(regressions,reg_fname),'_tmpout') ndiff.fcompare(os.path.join(regressions,reg_fname),
'_tmpout')
os.unlink('_tmpout') os.unlink('_tmpout')
finally: finally:
sys.stdout = oldStdout sys.stdout = oldStdout
raise AssertionError, \ raise AssertionError, \
'HTML regression test failed on %s\nDiff:\n%s\n' % (f,IO.getvalue()) 'HTML regression test failed on %s\nDiff:\n%s\n' % (f,
IO.getvalue())
class BasicTests(unittest.TestCase): class BasicTests(unittest.TestCase):
...@@ -216,11 +218,12 @@ class BasicTests(unittest.TestCase): ...@@ -216,11 +218,12 @@ class BasicTests(unittest.TestCase):
def testStrong(self): def testStrong(self):
""" strong """ """ strong """
self._test("xx **this is html** xx","xx <strong>this is html</strong> xx") self._test("xx **this is html** xx",
"xx <strong>this is html</strong> xx")
def testUnderlineThroughoutTags(self): def testUnderlineThroughoutTags(self):
"""Underlined text containing tags should not be transformed""" """Underlined text containing tags should not be transformed"""
self._test('<a href="index_html">index_html</a>', \ self._test('<a href="index_html">index_html</a>',
'<a href="index_html">index_html</a>') '<a href="index_html">index_html</a>')
...@@ -230,8 +233,14 @@ class BasicTests(unittest.TestCase): ...@@ -230,8 +233,14 @@ class BasicTests(unittest.TestCase):
self._test("this is '__a_literal__' eh", self._test("this is '__a_literal__' eh",
"<code>__a_literal__</code>") "<code>__a_literal__</code>")
def test_suite(): def test_suite():
return unittest.TestSuite((unittest.makeSuite(StructuredTextTests), suite = unittest.TestSuite()
unittest.makeSuite(BasicTests))) suite.addTest( unittest.makeSuite( StructuredTextTests ) )
suite.addTest( unittest.makeSuite( BasicTests ) )
return suite
def main():
unittest.TextTestRunner().run(test_suite())
if __name__ == '__main__':
main()
##############################################################################
#
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
#
# Copyright (c) Digital Creations. All rights reserved.
#
# This license has been certified as Open Source(tm).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions in source code must retain the above copyright
# notice, this list of conditions, and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions, and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# 3. Digital Creations requests that attribution be given to Zope
# in any manner possible. Zope includes a "Powered by Zope"
# button that is installed by default. While it is not a license
# violation to remove this button, it is requested that the
# attribution remain. A significant investment has been put
# into Zope, and this effort will continue if the Zope community
# continues to grow. This is one way to assure that growth.
#
# 4. All advertising materials and documentation mentioning
# features derived from or use of this software must display
# the following acknowledgement:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# In the event that the product being advertised includes an
# intact Zope distribution (with copyright and license included)
# then this clause is waived.
#
# 5. Names associated with Zope or Digital Creations must not be used to
# endorse or promote products derived from this software without
# prior written permission from Digital Creations.
#
# 6. Modified redistributions of any form whatsoever must retain
# the following acknowledgment:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# Intact (re-)distributions of any official Zope release do not
# require an external acknowledgement.
#
# 7. Modifications are encouraged but must be packaged separately as
# patches to official Zope releases. Distributions that do not
# clearly separate the patches from the original work must be clearly
# labeled as unofficial distributions. Modifications which do not
# carry the name Zope may be packaged in any form, as long as they
# conform to all of the clauses above.
#
#
# Disclaimer
#
# THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations. Specific
# attributions are listed in the accompanying credits file.
#
##############################################################################
######################################################################
# Set up unit testing framework
#
# The following code should be at the top of every test module:
#
# import os, sys
# execfile(os.path.join(sys.path[0], 'framework.py'))
#
# ...and the following at the bottom:
#
# if __name__ == '__main__':
# main()
import string
scriptdir = sys.path[0]
input_dir = os.path.join(scriptdir, 'input')
output_dir = os.path.join(scriptdir, 'output')
if not sys.modules.has_key('unittest'):
if os.path.abspath(scriptdir) == os.path.abspath('.'):
# We're in the tests directory, and need to find unittest.
cwd = os.getcwd()
while 1:
for ext in 'py', 'pyc', 'pyo', 'pyd':
if os.path.isfile(os.path.join(cwd, 'unittest.' + ext)):
break
else:
cwd, lastdir = os.path.split(cwd)
if lastdir:
continue
break
sys.path.insert(1, cwd)
else:
# We must be in the same directory as unittest
sys.path.insert(1, '')
import unittest
TestRunner = unittest.TextTestRunner
def read_input(filename):
filename = os.path.join(input_dir, filename)
return open(filename, 'r').read()
def read_output(filename):
filename = os.path.join(output_dir, filename)
return open(filename, 'r').read()
def main():
if len(sys.argv) > 1:
errs = globals()[sys.argv[1]]()
else:
errs = TestRunner().run(test_suite())
sys.exit(errs and 1 or 0)
def debug():
test_suite().debug()
def pdebug():
import pdb
pdb.run('debug()')
import os, sys import os, sys, unittest
execfile(os.path.join(sys.path[0], 'framework.py'))
import string import string
from ZTUtils import Batch from ZTUtils import Batch
......
import os, sys import os, sys, unittest
execfile(os.path.join(sys.path[0], 'framework.py'))
from ZTUtils import Iterator from ZTUtils import Iterator
......
...@@ -28,11 +28,12 @@ VERBOSE = 2 ...@@ -28,11 +28,12 @@ VERBOSE = 2
class TestRunner: class TestRunner:
"""Test suite runner""" """Test suite runner"""
def __init__(self, basepath, verbosity=VERBOSE, results=[]): def __init__(self, basepath, verbosity=VERBOSE, results=[], mega_suite=0):
# initialize python path # initialize python path
self.basepath=path=basepath self.basepath=path=basepath
self.verbosity = verbosity self.verbosity = verbosity
self.results = results self.results = results
self.mega_suite = mega_suite
pjoin=os.path.join pjoin=os.path.join
if sys.platform == 'win32': if sys.platform == 'win32':
sys.path.insert(0, pjoin(path, 'lib/python')) sys.path.insert(0, pjoin(path, 'lib/python'))
...@@ -51,12 +52,10 @@ class TestRunner: ...@@ -51,12 +52,10 @@ class TestRunner:
path, filename=os.path.split(filepath) path, filename=os.path.split(filepath)
name, ext=os.path.splitext(filename) name, ext=os.path.splitext(filename)
file, pathname, desc=imp.find_module(name, [path]) file, pathname, desc=imp.find_module(name, [path])
# Add path of imported module to sys.path, so local imports work. try:
sys.path.insert(0, path) module=imp.load_module(name, file, pathname, desc)
try: module=imp.load_module(name, file, pathname, desc) finally:
finally: file.close() file.close()
# Remove extra path again.
sys.path.remove(path)
function=getattr(module, 'test_suite', None) function=getattr(module, 'test_suite', None)
if function is None: if function is None:
return None return None
...@@ -83,32 +82,90 @@ class TestRunner: ...@@ -83,32 +82,90 @@ class TestRunner:
self.results.append(runner.run(suite)) self.results.append(runner.run(suite))
def report(self, message): def report(self, message):
print message sys.stderr.write( '%s\n' % message )
print
def runAllTests(self): def runAllTests(self):
"""Run all tests found in the current working directory and """Run all tests found in the current working directory and
all subdirectories.""" all subdirectories."""
self.runPath(self.basepath) self.runPath(self.basepath)
def listTestableNames( self, pathname ):
"""
Return a list of the names to be traversed to build tests.
"""
names = os.listdir(pathname)
if '.testinfo' in names: # allow local control
f = open( os.path.join( pathname, '.testinfo' ) )
lines = filter( None, f.readlines() )
lines = map( lambda x: x[-1]=='\n' and x[:-1] or x, lines )
names = filter( lambda x: x and x[0] != '#', lines )
f.close()
return names
def extractSuite( self, pathname ):
"""
Extract and return the appropriate test suite.
"""
if os.path.isdir( pathname ):
suite = unittest.TestSuite()
for name in self.listTestableNames( pathname ):
fullpath = os.path.join( pathname, name )
sub_suite = self.extractSuite( fullpath )
if sub_suite:
suite.addTest( sub_suite )
return suite.countTestCases() and suite or None
elif self.smellsLikeATest( pathname ):
working_dir = os.getcwd()
try:
dirname, name = os.path.split(pathname)
if dirname:
os.chdir(dirname)
try:
suite = self.getSuiteFromFile(name)
except:
self.report('No test suite found in file:\n%s\n' % pathname)
if self.verbosity > 1:
traceback.print_exc()
suite = None
finally:
os.chdir(working_dir)
return suite
else: # no test there!
return None
def runPath(self, pathname): def runPath(self, pathname):
"""Run all tests found in the directory named by pathname """Run all tests found in the directory named by pathname
and all subdirectories.""" and all subdirectories."""
if not os.path.isabs(pathname): if not os.path.isabs(pathname):
pathname = os.path.join(self.basepath, pathname) pathname = os.path.join(self.basepath, pathname)
names=os.listdir(pathname)
for name in names: if self.mega_suite:
fullpath=os.path.join(pathname, name) suite = self.extractSuite( pathname )
if os.path.isdir(fullpath): self.runSuite( suite )
self.runPath(fullpath) else:
elif self.smellsLikeATest(fullpath): for name in self.listTestableNames(pathname):
self.runFile(fullpath) fullpath=os.path.join(pathname, name)
if os.path.isdir(fullpath):
self.runPath(fullpath)
elif self.smellsLikeATest(fullpath):
self.runFile(fullpath)
def runFile(self, filename): def runFile(self, filename):
"""Run the test suite defined by filename.""" """Run the test suite defined by filename."""
working_dir = os.getcwd() working_dir = os.getcwd()
dirname, name = os.path.split(filename) dirname, name = os.path.split(filename)
if dirname: if dirname:
if self.verbosity > 2:
sys.stderr.write( '*** Changing directory to: %s\n' % dirname )
os.chdir(dirname) os.chdir(dirname)
self.report('Running: %s' % filename) self.report('Running: %s' % filename)
try: suite=self.getSuiteFromFile(name) try: suite=self.getSuiteFromFile(name)
...@@ -119,6 +176,8 @@ class TestRunner: ...@@ -119,6 +176,8 @@ class TestRunner:
self.runSuite(suite) self.runSuite(suite)
else: else:
self.report('No test suite found in file:\n%s\n' % filename) self.report('No test suite found in file:\n%s\n' % filename)
if self.verbosity > 2:
sys.stderr.write( '*** Restoring directory to: %s\n' % working_dir )
os.chdir(working_dir) os.chdir(working_dir)
...@@ -139,6 +198,24 @@ def main(args): ...@@ -139,6 +198,24 @@ def main(args):
working directory. This is the default if no options are working directory. This is the default if no options are
specified. specified.
-m
Run all tests in a single, giant suite (consolidates error
reporting). [default]
-M
Run each test file's suite separately (noisier output, may
help in isolating global effects later).
-p
Add 'lib/python' to the Python search path. [default]
-P
*Don't* add 'lib/python' to the Python search path.
-d dirpath -d dirpath
Run all tests found in the directory specified by dirpath, Run all tests found in the directory specified by dirpath,
...@@ -177,14 +254,24 @@ def main(args): ...@@ -177,14 +254,24 @@ def main(args):
filename=None filename=None
test_all=None test_all=None
verbosity = VERBOSE verbosity = VERBOSE
mega_suite = 1
set_python_path = 1
options, arg=getopt.getopt(args, 'ahd:f:v:q') options, arg=getopt.getopt(args, 'amPhd:f:v:q')
if not options: if not options:
err_exit(usage_msg) err_exit(usage_msg)
for name, value in options: for name, value in options:
name=name[1:] name=name[1:]
if name == 'a': if name == 'a':
test_all=1 test_all=1
elif name == 'm':
mega_suite = 1
elif name == 'M':
mega_suite = 0
elif name == 'p':
set_python_path = 1
elif name == 'P':
set_python_path = 0
elif name == 'd': elif name == 'd':
pathname=string.strip(value) pathname=string.strip(value)
elif name == 'f': elif name == 'f':
...@@ -198,7 +285,19 @@ def main(args): ...@@ -198,7 +285,19 @@ def main(args):
else: else:
err_exit(usage_msg) err_exit(usage_msg)
testrunner = TestRunner(os.getcwd(), verbosity=verbosity) testrunner = TestRunner( os.getcwd()
, verbosity=verbosity
, mega_suite=mega_suite)
if set_python_path:
script = sys.argv[0]
script_dir = os.path.split( os.path.abspath( script ) )[0]
zope_dir = os.path.abspath( os.path.join( script_dir, '..' ) )
sw_home = os.path.join( zope_dir, 'lib', 'python' )
if verbosity > 1:
testrunner.report( "Adding %s to sys.path." % sw_home )
sys.path.insert( 0, sw_home )
if test_all: if test_all:
testrunner.runAllTests() testrunner.runAllTests()
elif pathname: elif pathname:
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment