Commit 5e0076fc authored by Stefan H. Holek's avatar Stefan H. Holek

Update to ZopeTestCase 0.9.2+

parent c7baa885
......@@ -14,19 +14,22 @@
# getPortal() returns a usable portal object to the setup code.
#
# $Id: PortalTestCase.py,v 1.24 2004/03/29 01:14:14 shh42 Exp $
# $Id: PortalTestCase.py,v 1.29 2004/09/09 18:48:59 shh42 Exp $
import ZopeTestCase
import base
import types
from AccessControl import getSecurityManager
from AccessControl.SecurityManagement import newSecurityManager
from AccessControl.SecurityManagement import noSecurityManager
from Acquisition import aq_base
portal_name = 'portal'
user_name = ZopeTestCase.user_name
from ZopeTestCase import user_name
from ZopeTestCase import user_password
class PortalTestCase(ZopeTestCase.ZopeTestCase):
class PortalTestCase(base.TestCase):
'''Base test case for testing CMF-style portals
__implements__ = (IPortalTestCase, ISimpleSecurity, IExtensibleSecurity)
......@@ -37,9 +40,11 @@ class PortalTestCase(ZopeTestCase.ZopeTestCase):
_configure_portal = 1
def getPortal(self):
'''Returns the portal object for use by the setup
code. Will typically be overridden by subclasses
to return the object serving as the portal.
'''Returns the portal object to the setup code.
Will typically be overridden by subclasses
to return the object serving as the "portal".
Note: This method should not be called by tests!
'''
return self.app[portal_name]
......@@ -67,7 +72,9 @@ class PortalTestCase(ZopeTestCase.ZopeTestCase):
raise
def _setup(self):
'''Configures the portal. Framework authors may override.'''
'''Configures the portal. Framework authors may
override.
'''
if self._configure_portal:
self._setupUserFolder()
self._setupUser()
......@@ -82,7 +89,7 @@ class PortalTestCase(ZopeTestCase.ZopeTestCase):
def _setupUser(self):
'''Creates the default user.'''
uf = self.portal.acl_users
uf._doAddUser(user_name, 'secret', ['Member'], [])
uf.userFolderAddUser(user_name, user_password, ['Member'], [])
def _setupHomeFolder(self):
'''Creates the default user's home folder.'''
......@@ -97,30 +104,31 @@ class PortalTestCase(ZopeTestCase.ZopeTestCase):
if hasattr(self.portal, 'setupCurrentSkin'):
self.portal.setupCurrentSkin()
def _clear(self, call_close_hook=0):
'''Clears the fixture.'''
# No automagic cleanups here. We rely on
# transaction abort. Those who commit are
# required to clean up their own mess.
if call_close_hook:
self.beforeClose()
self._close()
self.logout()
self.afterClear()
# Security interfaces
def setRoles(self, roles, name=user_name):
'''Changes the user's roles.'''
self.assertEqual(type(roles), types.ListType)
uf = self.portal.acl_users
uf._doChangeUser(name, None, roles, [])
uf.userFolderEditUser(name, None, roles, [])
if name == getSecurityManager().getUser().getId():
self.login(name)
def getRoles(self, name=user_name):
'''Returns the user's roles.'''
uf = self.portal.acl_users
return uf.getUserById(name).getRoles()
def setPermissions(self, permissions, role='Member'):
'''Changes the user's permissions.'''
'''Changes the permissions assigned to role.'''
self.assertEqual(type(permissions), types.ListType)
self.portal.manage_role(role, permissions)
def getPermissions(self, role='Member'):
'''Returns the permissions assigned to role.'''
perms = self.portal.permissionsOfRole(role)
return [p['name'] for p in perms if p['selected']]
def login(self, name=user_name):
'''Logs in.'''
uf = self.portal.acl_users
......@@ -129,6 +137,21 @@ class PortalTestCase(ZopeTestCase.ZopeTestCase):
user = user.__of__(uf)
newSecurityManager(None, user)
def logout(self):
'''Logs out.'''
noSecurityManager()
# b/w compatibility methods
def _setRoles(self, roles, name=user_name):
self.setRoles(roles, name)
def _setPermissions(self, permissions, role='Member'):
self.setPermissions(permissions, role)
def _login(self, name=user_name):
self.login(name)
def _logout(self):
self.logout()
# b/w compatibility names
_portal_name = portal_name
......
......@@ -12,7 +12,7 @@
# app = Zope.app()
#
# $Id: ZopeLite.py,v 1.19 2004/03/19 13:51:32 shh42 Exp $
# $Id: ZopeLite.py,v 1.24 2004/08/18 09:28:54 shh42 Exp $
import os, sys, time
......@@ -20,7 +20,7 @@ import os, sys, time
sys.setcheckinterval(2500)
# Shut up if we are not in control of the import process
_quiet = 'Zope' in sys.modules.keys()
_quiet = sys.modules.has_key('Zope')
def _print(msg):
'''Writes 'msg' to stderr and flushes the stream.'''
......@@ -48,6 +48,10 @@ try:
except ImportError:
pass # Zope < 2.7
else:
# Configure logging
if not sys.modules.has_key('logging'):
import logging
logging.basicConfig()
# Need to import Zope early on as the
# ZTUtils package relies on it
config = App.config.getConfiguration()
......
......@@ -11,15 +11,11 @@
# and 'View' permissions given to his role.
#
# $Id: ZopeTestCase.py,v 1.15 2004/03/29 01:14:13 shh42 Exp $
# $Id: ZopeTestCase.py,v 1.21 2004/09/04 18:01:08 shh42 Exp $
import ZopeLite as Zope
import base
import types
import unittest
import utils
import profiler
import transaction
from AccessControl import getSecurityManager
from AccessControl.SecurityManagement import newSecurityManager
from AccessControl.SecurityManagement import noSecurityManager
......@@ -28,30 +24,12 @@ from AccessControl.Permissions import view
folder_name = 'test_folder_1_'
user_name = 'test_user_1_'
user_password = 'secret'
user_role = 'test_role_1_'
standard_permissions = [access_contents_information, view]
_connections = utils.ConnectionRegistry()
def app():
'''Opens a ZODB connection and returns the app object.'''
app = Zope.app()
_connections.register(app._p_jar)
return utils.makerequest(app)
def close(app):
'''Closes the app's ZODB connection.'''
_connections.close(app._p_jar)
def closeConnections():
'''Closes all registered ZODB connections.'''
_connections.closeAll()
class ZopeTestCase(profiler.Profiled, unittest.TestCase):
class ZopeTestCase(base.TestCase):
'''Base test case for Zope testing
__implements__ = (IZopeTestCase, ISimpleSecurity, IExtensibleSecurity)
......@@ -61,70 +39,10 @@ class ZopeTestCase(profiler.Profiled, unittest.TestCase):
_setup_fixture = 1
def afterSetUp(self):
'''Called after setUp() has completed. This is
far and away the most useful hook.
'''
pass
def beforeTearDown(self):
'''Called before tearDown() is executed.
Note that tearDown() is not called if
setUp() fails.
'''
pass
def afterClear(self):
'''Called after the fixture has been cleared.
Note that this may occur during setUp() *and*
tearDown().
'''
pass
def beforeSetUp(self):
'''Called before the ZODB connection is opened,
at the start of setUp(). By default begins
a new transaction.
'''
transaction.begin()
def beforeClose(self):
'''Called before the ZODB connection is closed,
at the end of tearDown(). By default aborts
the transaction.
'''
get_transaction().abort()
def setUp(self):
'''Sets up the fixture. Do not override,
use the hooks instead.
'''
try:
self.beforeSetUp()
self.app = self._app()
self._setup()
self.afterSetUp()
except:
self._clear()
raise
def tearDown(self):
'''Tears down the fixture. Do not override,
use the hooks instead.
'''
try:
self.beforeTearDown()
self._clear(1)
except:
self._clear()
raise
def _app(self):
'''Returns the app object for a test.'''
return app()
def _setup(self):
'''Sets up the fixture. Framework authors may override.'''
'''Sets up the fixture. Framework authors may
override.
'''
if self._setup_fixture:
self._setupFolder()
self._setupUserFolder()
......@@ -145,37 +63,43 @@ class ZopeTestCase(profiler.Profiled, unittest.TestCase):
def _setupUser(self):
'''Creates the default user.'''
uf = self.folder.acl_users
uf._doAddUser(user_name, 'secret', [user_role], [])
uf.userFolderAddUser(user_name, user_password, [user_role], [])
def _clear(self, call_close_hook=0):
'''Clears the fixture.'''
if self._setup_fixture:
try: self.app._delObject(folder_name)
except (AttributeError, RuntimeError): pass
if call_close_hook:
self.beforeClose()
self._close()
self.logout()
self.afterClear()
def _close(self):
'''Closes the ZODB connection.'''
get_transaction().abort()
closeConnections()
# This code is a wart from the olden days.
try:
if base._connections.contains(self.app._p_jar):
self.app._delObject(folder_name)
except:
pass
base.TestCase._clear(self, call_close_hook)
# Security interfaces
def setRoles(self, roles, name=user_name):
'''Changes the user's roles.'''
self.assertEqual(type(roles), types.ListType)
uf = self.folder.acl_users
uf._doChangeUser(name, None, roles, [])
uf.userFolderEditUser(name, None, roles, [])
if name == getSecurityManager().getUser().getId():
self.login(name)
def getRoles(self, name=user_name):
'''Returns the user's roles.'''
uf = self.folder.acl_users
return uf.getUserById(name).getRoles()
def setPermissions(self, permissions, role=user_role):
'''Changes the user's permissions.'''
self.assertEqual(type(permissions), types.ListType)
self.folder.manage_role(role, permissions)
def getPermissions(self, role=user_role):
'''Returns the user's permissions.'''
perms = self.folder.permissionsOfRole(role)
return [p['name'] for p in perms if p['selected']]
def login(self, name=user_name):
'''Logs in.'''
uf = self.folder.acl_users
......@@ -205,4 +129,7 @@ _folder_name = folder_name
_user_name = user_name
_user_role = user_role
_standard_permissions = standard_permissions
from base import app
from base import close
from base import closeConnections
......@@ -2,7 +2,7 @@
# Names exported by the ZopeTestCase module
#
# $Id: __init__.py,v 1.11 2004/02/06 18:00:02 shh42 Exp $
# $Id: __init__.py,v 1.13 2004/08/19 15:52:55 shh42 Exp $
import ZopeLite as Zope
import utils
......@@ -11,8 +11,13 @@ from ZopeLite import installProduct
from ZopeLite import hasProduct
from ZopeLite import _print
from base import TestCase
from base import app
from base import close
from ZopeTestCase import folder_name
from ZopeTestCase import user_name
from ZopeTestCase import user_password
from ZopeTestCase import user_role
from ZopeTestCase import standard_permissions
from ZopeTestCase import ZopeTestCase
......@@ -24,10 +29,6 @@ from profiler import Profiled
from sandbox import Sandboxed
from functional import Functional
from ZopeTestCase import app
from ZopeTestCase import close
from ZopeTestCase import closeConnections
from unittest import main
# Convenience class for functional unit testing
......@@ -40,4 +41,5 @@ _user_name = user_name
_user_role = user_role
_standard_permissions = standard_permissions
_portal_name = portal_name
from base import closeConnections
#
# Test case for Zope testing
#
# $Id: base.py,v 1.1 2004/08/19 13:59:41 shh42 Exp $
import ZopeLite as Zope
import unittest
import transaction
import profiler
import utils
from AccessControl.SecurityManagement import noSecurityManager
_connections = utils.ConnectionRegistry()
def app():
'''Opens a ZODB connection and returns the app object.'''
app = Zope.app()
_connections.register(app._p_jar)
return utils.makerequest(app)
def close(app):
'''Closes the app's ZODB connection.'''
_connections.close(app._p_jar)
def closeConnections():
'''Closes all registered ZODB connections.'''
_connections.closeAll()
class TestCase(profiler.Profiled, unittest.TestCase):
'''Base test case for Zope testing
__implements__ = (IZopeTestCase,)
See doc/IZopeTestCase.py for more
'''
def afterSetUp(self):
'''Called after setUp() has completed. This is
far and away the most useful hook.
'''
pass
def beforeTearDown(self):
'''Called before tearDown() is executed.
Note that tearDown() is not called if
setUp() fails.
'''
pass
def afterClear(self):
'''Called after the fixture has been cleared.
Note that this may occur during setUp() *and*
tearDown().
'''
pass
def beforeSetUp(self):
'''Called before the ZODB connection is opened,
at the start of setUp(). By default begins
a new transaction.
'''
transaction.begin()
def beforeClose(self):
'''Called before the ZODB connection is closed,
at the end of tearDown(). By default aborts
the transaction.
'''
transaction.abort()
def setUp(self):
'''Sets up the fixture. Do not override,
use the hooks instead.
'''
try:
self.beforeSetUp()
self.app = self._app()
self._setup()
self.afterSetUp()
except:
self._clear()
raise
def tearDown(self):
'''Tears down the fixture. Do not override,
use the hooks instead.
'''
try:
self.beforeTearDown()
self._clear(1)
except:
self._clear()
raise
def _app(self):
'''Returns the app object for a test.'''
return app()
def _setup(self):
'''Sets up the fixture. Framework authors may
override.
'''
def _clear(self, call_close_hook=0):
'''Clears the fixture.'''
if call_close_hook:
self.beforeClose()
self._close()
self.logout()
self.afterClear()
def _close(self):
'''Closes the ZODB connection.'''
transaction.abort()
closeConnections()
def logout(self):
'''Logs out.'''
noSecurityManager()
......@@ -17,6 +17,8 @@ Module Testing.ZopeTestCase
user_name
user_password
user_role
standard_permissions
......@@ -39,6 +41,8 @@ Module Testing.ZopeTestCase
Classes
TestCase
ZopeTestCase
PortalTestCase
......@@ -81,19 +85,9 @@ Module ZopeLite
Module ZopeTestCase
Default test case and fixture for Zope testing
Constants
folder_name
user_name
user_role
Module base
standard_permissions
Bare-bones base test case for Zope testing
Functions
......@@ -103,17 +97,14 @@ Module ZopeTestCase
Classes
ZopeTestCase
TestCase
Class ZopeTestCase
Base test case for Zope testing
Attributes
Class TestCase
_setup_fixture = 1
Bare-bones base test case for Zope testing
(derived from unittest.TestCase)
Methods
......@@ -127,10 +118,45 @@ Class ZopeTestCase
beforeClose()
Module ZopeTestCase
Test case and fixture for Zope testing
Constants
folder_name
user_name
user_password
user_role
standard_permissions
Classes
ZopeTestCase
Class ZopeTestCase
Base test case for Zope testing
(derived from base.TestCase)
Methods
setRoles(roles, name=user_name)
getRoles(name=user_name)
setPermissions(permissions, role=user_role)
getPermissions(role=user_role)
login(name=user_name)
logout()
......@@ -147,6 +173,8 @@ Module PortalTestCase
user_name
user_password
Classes
PortalTestCase
......@@ -156,10 +184,7 @@ Module PortalTestCase
Class PortalTestCase
Base test case for CMF testing
Attributes
_configure_portal = 1
(derived from base.TestCase)
Methods
......@@ -167,19 +192,13 @@ Class PortalTestCase
createMemberarea(name)
afterSetUp()
beforeTearDown()
afterClear()
setRoles(roles, name=user_name)
beforeSetUp()
getRoles(name=user_name)
beforeClose()
setPermissions(permissions, role='Member')
setRoles(roles, name=user_name)
setPermissions(permissions, role=user_role)
getPermissions(role='Member')
login(name=user_name)
......@@ -271,3 +290,5 @@ Module utils
importObjectFromFile(container, filename, quiet=0)
appcall(func, *args, **kw)
0.9.2
- Introduced new base.TestCase class which contains the bare-
bones framework code and serves as baseclass for ZTC and PTC.
- ZopeLite now configures the logging module in Zope >= 2.7.
- Teardown sequence is now compatible with Zope trunk (again).
- Added getRoles() and getPermissions() methods to security API.
- setRoles() now asserts 'roles' argument is ListType.
- setPermissions() now asserts 'permissions' argument is ListType.
0.9.0
- No longer support Zope 2.4 as its DemoStorage is broken.
- Made PortalTestCase derive from ZopeTestCase (again).
......
......@@ -4,9 +4,6 @@ Installation Instructions for ZopeTestCase
Requires Python 2.1 and Zope 2.5 or higher
Upgrade Notice: Please remove an existing installation
of ZopeTestCase before installing version 0.9.0!
1. Extract the tarball into the 'lib/python/Testing'
directory of your Zope installation.
......
from Interface import Interface
# $Id: IZopeTestCase.py,v 1.13 2004/02/21 18:54:38 shh42 Exp $
# $Id: IZopeTestCase.py,v 1.14 2004/09/04 18:01:11 shh42 Exp $
#
......@@ -17,9 +17,15 @@ class ISimpleSecurity(Interface):
def setRoles(roles):
'''Changes the user's roles.'''
def getRoles():
'''Returns the user's roles.'''
def setPermissions(permissions):
'''Changes the user's permissions.'''
def getPermissions():
'''Returns the user's permissions.'''
def login():
'''Logs in.'''
......@@ -32,9 +38,15 @@ class IExtensibleSecurity(Interface):
def setRoles(roles, name):
'''Changes the roles assigned to a user.'''
def getRoles(name):
'''Returns the specified user's roles.'''
def setPermissions(permissions, role):
'''Changes the permissions assigned to a role.'''
def getPermissions(role):
'''Returns the permissions assigned to a role.'''
def login(name):
'''Logs in as the specified user.'''
......@@ -57,7 +69,7 @@ class IZopeTestCase(Interface):
def afterClear():
'''Called after the fixture has been cleared.
Note that this is done during setUp() *and*
Note that this may occur during setUp() *and*
tearDown().
'''
......@@ -77,9 +89,11 @@ class IZopeTestCase(Interface):
class IPortalTestCase(IZopeTestCase):
def getPortal():
'''Returns the portal object for use by the setup
code. Will typically be overridden by subclasses
to return the object serving as the portal.
'''Returns the portal object to the setup code.
Will typically be overridden by subclasses
to return the object serving as the "portal".
Note: This method should not be called by tests!
'''
def createMemberarea(member_id):
......
......@@ -21,7 +21,8 @@ Default Fixture
- **'self.folder.acl_users'** is the user folder providing a security context to the work area.
A default user account is added to the user folder with name 'test_user_1_' and password 'secret'.
You should use the 'ZopeTestCase.user_name' constant when you need the user's name.
You should use the 'ZopeTestCase.user_name' constant when you need the user's name, the
'ZopeTestCase.user_password' constant when you need the user's password.
The default user has a single role, 'ZopeTestCase.user_role'.
......@@ -32,10 +33,16 @@ Security API
- **'self.setRoles(roles, name=user_name)'** allows to change the roles assigned to a user.
If the 'name' argument is omitted, changes the roles of the default user.
- **'self.getRoles(name=user_name)'** returns the roles assigned to a user. If the name argument is
omitted, returns the roles assigned to the default user.
- **'self.setPermissions(permissions, role=user_role)'** allows to change the permissions
assigned to a role. If the 'role' argument is omitted, changes the permissions of the
default role.
- **'self.getPermissions(role=user_role)'** return the permissions assigned to a role. If the role
argument is omitted, returns the permissions assigned to the default role.
- **'self.login(name=user_name)'** allows to log in as a specified user.
If the 'name' argument is omitted, logs in as the default user.
......
ZopeTestCase 0.9.0
ZopeTestCase 0.9.2
(c) 2002-2004, Stefan H. Holek, stefan@epy.co.at
http://zope.org/Members/shh/ZopeTestCase
License: ZPL
Zope: 2.5-2.7
Zope: 2.5-2.8
#
# Support for functional unit testing in ZTC
# After Marius Gedmina's functional.py module for Zope3.
# After Marius Gedminas' functional.py module for Zope3.
#
# $Id: functional.py,v 1.2 2004/01/14 12:41:32 shh42 Exp $
# $Id: functional.py,v 1.3 2004/09/12 16:49:59 shh42 Exp $
import sys, re, base64
import transaction
import sandbox
......@@ -25,7 +26,7 @@ class Functional(sandbox.Sandboxed):
from ZPublisher.Test import publish_module
# Commit the sandbox for good measure
get_transaction().commit()
transaction.commit()
if env is None:
env = {}
......
......@@ -2,9 +2,10 @@
# Support for ZODB sandboxes in ZTC
#
# $Id: sandbox.py,v 1.1 2004/01/09 15:03:04 shh42 Exp $
# $Id: sandbox.py,v 1.2 2004/08/19 15:31:26 shh42 Exp $
import ZopeLite as Zope
import transaction
import utils
......@@ -24,7 +25,7 @@ class Sandboxed:
def _close(self):
'''Clears the transaction and the AppZapper.'''
get_transaction().abort()
transaction.abort()
AppZapper().clear()
......@@ -55,6 +56,7 @@ def __bobo_traverse__(self, REQUEST=None, name=None):
from ZODB.ZApplication import ZApplicationWrapper
ZApplicationWrapper.__old_bobo_traverse__ = ZApplicationWrapper.__bobo_traverse__
ZApplicationWrapper.__bobo_traverse__ = __bobo_traverse__
if not hasattr(ZApplicationWrapper, '__old_bobo_traverse__'):
ZApplicationWrapper.__old_bobo_traverse__ = ZApplicationWrapper.__bobo_traverse__
ZApplicationWrapper.__bobo_traverse__ = __bobo_traverse__
#
# Tests the base.TestCase class
#
# NOTE: This is *not* an example TestCase. Do not
# use this file as a blueprint for your own tests!
#
# See testPythonScript.py and testShoppingCart.py for
# example test cases. See testSkeleton.py for a quick
# way of getting started.
#
# $Id: testBaseTestCase.py,v 1.2 2004/09/04 18:56:41 shh42 Exp $
import os, sys
if __name__ == '__main__':
execfile(os.path.join(sys.path[0], 'framework.py'))
from Testing.ZopeTestCase import base
from Testing.ZopeTestCase import utils
from AccessControl import getSecurityManager
from AccessControl.SecurityManagement import newSecurityManager
class HookTest(base.TestCase):
def setUp(self):
self._called = []
base.TestCase.setUp(self)
def beforeSetUp(self):
self._called.append('beforeSetUp')
base.TestCase.beforeSetUp(self)
def _setup(self):
self._called.append('_setup')
base.TestCase._setup(self)
def afterSetUp(self):
self._called.append('afterSetUp')
base.TestCase.afterSetUp(self)
def beforeTearDown(self):
self._called.append('beforeTearDown')
base.TestCase.beforeTearDown(self)
def beforeClose(self):
self._called.append('beforeClose')
base.TestCase.beforeClose(self)
def afterClear(self):
self._called.append('afterClear')
base.TestCase.afterClear(self)
def assertHooks(self, sequence):
self.assertEqual(self._called, sequence)
class TestTestCase(HookTest):
def testSetUp(self):
self.assertHooks(['beforeSetUp', '_setup', 'afterSetUp'])
def testTearDown(self):
self._called = []
self.tearDown()
self.assertHooks(['beforeTearDown', 'beforeClose', 'afterClear'])
def testAppOpensConnection(self):
self.assertEqual(len(base._connections), 1)
self._app()
self.assertEqual(len(base._connections), 2)
def testClearCallsCloseHook(self):
self._called = []
self._clear(1)
self.assertHooks(['beforeClose', 'afterClear'])
def testClearSkipsCloseHook(self):
self._called = []
self._clear()
self.assertHooks(['afterClear'])
def testClearAbortsTransaction(self):
self.assertEqual(len(self.getObjectsInTransaction()), 0)
self.app.foo = 1
self.assertEqual(len(self.getObjectsInTransaction()), 1)
self._clear()
self.assertEqual(len(self.getObjectsInTransaction()), 0)
def testClearClosesConnection(self):
self.assertEqual(len(base._connections), 1)
self._clear()
self.assertEqual(len(base._connections), 0)
def testClearClosesAllConnections(self):
self._app()
self.assertEqual(len(base._connections), 2)
self._clear()
self.assertEqual(len(base._connections), 0)
def testClearLogsOut(self):
uf = self.app.acl_users
uf.userFolderAddUser('user_1', '', [], [])
newSecurityManager(None, uf.getUserById('user_1').__of__(uf))
self.assertEqual(getSecurityManager().getUser().getUserName(), 'user_1')
self._clear()
self.assertEqual(getSecurityManager().getUser().getUserName(), 'Anonymous User')
def testCloseAbortsTransaction(self):
self.assertEqual(len(self.getObjectsInTransaction()), 0)
self.app.foo = 1
self.assertEqual(len(self.getObjectsInTransaction()), 1)
self._close()
self.assertEqual(len(self.getObjectsInTransaction()), 0)
def testCloseClosesConnection(self):
self.assertEqual(len(base._connections), 1)
self._close()
self.assertEqual(len(base._connections), 0)
def testCloseClosesAllConnections(self):
self._app()
self.assertEqual(len(base._connections), 2)
self._close()
self.assertEqual(len(base._connections), 0)
def testLogoutLogsOut(self):
uf = self.app.acl_users
uf.userFolderAddUser('user_1', '', [], [])
newSecurityManager(None, uf.getUserById('user_1').__of__(uf))
self.assertEqual(getSecurityManager().getUser().getUserName(), 'user_1')
self.logout()
self.assertEqual(getSecurityManager().getUser().getUserName(), 'Anonymous User')
def getObjectsInTransaction(self):
# Let's us spy into the transaction
t = get_transaction()
if hasattr(t, '_objects'): # Zope < 2.8
return t._objects
elif hasattr(t, '_resources'): # Zope >= 2.8
return t._resources
else:
raise Exception, 'Unknown version'
class TestSetUpRaises(HookTest):
class Error: pass
def setUp(self):
try:
HookTest.setUp(self)
except self.Error:
self.assertHooks(['beforeSetUp', '_setup', 'afterClear'])
# Connection has been closed
self.assertEqual(len(base._connections), 0)
def _setup(self):
HookTest._setup(self)
raise self.Error
def testTrigger(self):
pass
class TestTearDownRaises(HookTest):
class Error: pass
def tearDown(self):
self._called = []
try:
HookTest.tearDown(self)
except self.Error:
self.assertHooks(['beforeTearDown', 'beforeClose', 'afterClear'])
# Connection has been closed
self.assertEqual(len(base._connections), 0)
def beforeClose(self):
HookTest.beforeClose(self)
raise self.Error
def testTrigger(self):
pass
class TestConnectionRegistry(base.TestCase):
class Conn:
closed = 0
def close(self):
self.closed = 1
def afterSetUp(self):
self.reg = utils.ConnectionRegistry()
self.conns = [self.Conn(), self.Conn(), self.Conn()]
def testRegister(self):
# Should be able to register connections
for conn in self.conns:
self.reg.register(conn)
assert len(self.reg) == 3
def testCloseConnection(self):
# Should be able to close a single registered connection
for conn in self.conns:
self.reg.register(conn)
assert len(self.reg) == 3
self.reg.close(self.conns[0])
assert len(self.reg) == 2
assert self.conns[0].closed == 1
assert self.conns[1].closed == 0
assert self.conns[2].closed == 0
def testCloseSeveralConnections(self):
# Should be able to close all registered connections one-by-one
for conn in self.conns:
self.reg.register(conn)
assert len(self.reg) == 3
self.reg.close(self.conns[0])
assert len(self.reg) == 2
assert self.conns[0].closed == 1
assert self.conns[1].closed == 0
assert self.conns[2].closed == 0
self.reg.close(self.conns[2])
assert len(self.reg) == 1
assert self.conns[0].closed == 1
assert self.conns[1].closed == 0
assert self.conns[2].closed == 1
self.reg.close(self.conns[1])
assert len(self.reg) == 0
assert self.conns[0].closed == 1
assert self.conns[1].closed == 1
assert self.conns[2].closed == 1
def testCloseForeignConnection(self):
# Should be able to close a connection that has not been registered
for conn in self.conns:
self.reg.register(conn)
assert len(self.reg) == 3
conn = self.Conn()
self.reg.close(conn)
assert len(self.reg) == 3
assert self.conns[0].closed == 0
assert self.conns[1].closed == 0
assert self.conns[2].closed == 0
assert conn.closed == 1
def testCloseAllConnections(self):
# Should be able to close all registered connections at once
for conn in self.conns:
self.reg.register(conn)
assert len(self.reg) == 3
self.reg.closeAll()
assert len(self.reg) == 0
assert self.conns[0].closed == 1
assert self.conns[1].closed == 1
assert self.conns[2].closed == 1
def testContains(self):
# Should be able to check if a connection is registered
for conn in self.conns:
self.reg.register(conn)
assert len(self.reg) == 3
assert self.reg.contains(self.conns[0])
assert self.reg.contains(self.conns[1])
assert self.reg.contains(self.conns[2])
class TestRequestVariables(base.TestCase):
'''Makes sure the REQUEST contains required variables'''
def testRequestVariables(self):
request = self.app.REQUEST
self.failIfEqual(request.get('SERVER_NAME', ''), '')
self.failIfEqual(request.get('SERVER_PORT', ''), '')
self.failIfEqual(request.get('REQUEST_METHOD', ''), '')
self.failIfEqual(request.get('URL', ''), '')
self.failIfEqual(request.get('SERVER_URL', ''), '')
self.failIfEqual(request.get('URL0', ''), '')
self.failIfEqual(request.get('URL1', ''), '')
self.failIfEqual(request.get('BASE0', ''), '')
self.failIfEqual(request.get('BASE1', ''), '')
self.failIfEqual(request.get('BASE2', ''), '')
def test_suite():
from unittest import TestSuite, makeSuite
suite = TestSuite()
suite.addTest(makeSuite(TestTestCase))
suite.addTest(makeSuite(TestSetUpRaises))
suite.addTest(makeSuite(TestTearDownRaises))
suite.addTest(makeSuite(TestConnectionRegistry))
suite.addTest(makeSuite(TestRequestVariables))
return suite
if __name__ == '__main__':
framework()
......@@ -2,7 +2,7 @@
# Example functional ZopeTestCase
#
# $Id: testFunctional.py,v 1.5 2004/04/09 12:38:37 shh42 Exp $
# $Id: testFunctional.py,v 1.7 2004/09/04 18:01:08 shh42 Exp $
import os, sys
if __name__ == '__main__':
......@@ -13,11 +13,11 @@ from Testing import ZopeTestCase
ZopeTestCase.installProduct('PythonScripts')
class TestZPublication(ZopeTestCase.Functional, ZopeTestCase.ZopeTestCase):
class TestFunctional(ZopeTestCase.Functional, ZopeTestCase.ZopeTestCase):
def afterSetUp(self):
self.folder_path = self.folder.absolute_url(1)
self.basic_auth = '%s:secret' % ZopeTestCase.user_name
self.folder_path = '/%s' % self.folder.absolute_url(1)
self.basic_auth = '%s:%s' % (ZopeTestCase.user_name, ZopeTestCase.user_password)
self.folder.addDTMLMethod('index_html', file='foo')
......@@ -30,41 +30,41 @@ class TestZPublication(ZopeTestCase.Functional, ZopeTestCase.ZopeTestCase):
file='''<dtml-call "manage_changeProperties(title=REQUEST.get('title'))">''')
def testPublishDocument(self):
response = self.publish('/%s/index_html' % self.folder_path)
response = self.publish(self.folder_path+'/index_html')
self.assertEqual(response.getStatus(), 200)
self.assertEqual(response.getBody(), 'foo')
def testPublishScript(self):
response = self.publish('/%s/script' % self.folder_path)
response = self.publish(self.folder_path+'/script')
self.assertEqual(response.getStatus(), 200)
self.assertEqual(response.getBody(), '1')
def testPublishScriptWithArgument(self):
response = self.publish('/%s/script?a:int=2' % self.folder_path)
response = self.publish(self.folder_path+'/script?a:int=2')
self.assertEqual(response.getStatus(), 200)
self.assertEqual(response.getBody(), '3')
def testServerError(self):
response = self.publish('/%s/script?a=2' % self.folder_path)
response = self.publish(self.folder_path+'/script?a=2')
self.assertEqual(response.getStatus(), 500)
def testUnauthorized(self):
self.folder.index_html.manage_permission('View', ['Owner'])
response = self.publish('/%s/index_html' % self.folder_path)
response = self.publish(self.folder_path+'/index_html')
self.assertEqual(response.getStatus(), 401)
def testBasicAuthentication(self):
self.folder.index_html.manage_permission('View', ['Owner'])
response = self.publish('/%s/index_html'
% self.folder_path, self.basic_auth)
response = self.publish(self.folder_path+'/index_html',
self.basic_auth)
self.assertEqual(response.getStatus(), 200)
self.assertEqual(response.getBody(), 'foo')
def testModifyObject(self):
from AccessControl.Permissions import manage_properties
self.setPermissions([manage_properties])
response = self.publish('/%s/object/change_title?title=Foo'
% self.folder_path, self.basic_auth)
response = self.publish(self.folder_path+'/object/change_title?title=Foo',
self.basic_auth)
self.assertEqual(response.getStatus(), 200)
self.assertEqual(self.folder.object.title_or_id(), 'Foo')
......@@ -72,7 +72,7 @@ class TestZPublication(ZopeTestCase.Functional, ZopeTestCase.ZopeTestCase):
def test_suite():
from unittest import TestSuite, makeSuite
suite = TestSuite()
suite.addTest(makeSuite(TestZPublication))
suite.addTest(makeSuite(TestFunctional))
return suite
if __name__ == '__main__':
......
......@@ -16,7 +16,7 @@
# example instead.
#
# $Id: testWebserver.py,v 1.14 2004/04/09 12:38:37 shh42 Exp $
# $Id: testWebserver.py,v 1.15 2004/09/04 18:01:08 shh42 Exp $
import os, sys
if __name__ == '__main__':
......@@ -53,7 +53,7 @@ class TestWebserver(ZopeTestCase.ZopeTestCase):
def afterSetUp(self):
uf = self.folder.acl_users
uf._doAddUser('manager', 'secret', ['Manager'], [])
uf.userFolderAddUser('manager', 'secret', ['Manager'], [])
manager = uf.getUserById('manager').__of__(uf)
self.folder.addDTMLMethod('index_html', file='index_html called')
......
......@@ -3,7 +3,7 @@
# be imported more selectively.
#
# $Id: threadutils.py,v 1.5 2004/01/09 14:35:08 shh42 Exp $
# $Id: threadutils.py,v 1.6 2004/08/19 15:31:26 shh42 Exp $
from threading import Thread
from StringIO import StringIO
......@@ -41,6 +41,7 @@ def QuietPublisher(self, accept):
from ZServer.PubCore.ZServerPublisher import ZServerPublisher
ZServerPublisher.__old_init__ = ZServerPublisher.__init__
ZServerPublisher.__init__ = QuietPublisher
if not hasattr(ZServerPublisher, '__old_init__'):
ZServerPublisher.__old_init__ = ZServerPublisher.__init__
ZServerPublisher.__init__ = QuietPublisher
......@@ -5,7 +5,7 @@
# module level to add functionality to the test environment.
#
# $Id: utils.py,v 1.13 2004/02/17 19:34:36 shh42 Exp $
# $Id: utils.py,v 1.16 2004/08/19 13:59:41 shh42 Exp $
def setupCoreSessions(app=None):
......@@ -105,6 +105,7 @@ def startZServer(number_of_threads=1, log=None):
t = QuietThread(target=zserverRunner, args=(_Z2HOST, _Z2PORT, log))
t.setDaemon(1)
t.start()
time.sleep(0.1) # Sandor Palfy
return _Z2HOST, _Z2PORT
......@@ -127,13 +128,13 @@ def makerequest(app, stdout=sys.stdout):
def appcall(function, *args, **kw):
'''Calls a function passing 'app' as first argument.'''
import ZopeTestCase
app = ZopeTestCase.app()
from base import app, close
app = app()
args = (app,) + args
try:
return function(*args, **kw)
finally:
ZopeTestCase.close(app)
close(app)
class ConnectionRegistry:
......@@ -160,3 +161,6 @@ class ConnectionRegistry:
def __len__(self):
return len(self._conns)
def contains(self, conn):
return conn in self._conns
......@@ -7,7 +7,7 @@
# 'ZopeTestCase', 'ztc_common.py'))
#
# $Id: ztc_common.py,v 1.13 2004/03/30 16:40:04 shh42 Exp $
# $Id: ztc_common.py,v 1.14 2004/05/27 15:06:24 shh42 Exp $
# Overwrites the default framework() method to expose the
......@@ -28,9 +28,9 @@ def framework(stream=sys.stderr, descriptions=1, verbosity=1):
else:
sys.exit(globals()[arg]() and 1 or 0)
errors = TestRunner(stream, descriptions, verbosity).run(test_suite())
result = TestRunner(stream, descriptions, verbosity).run(test_suite())
from Testing.ZopeTestCase import profiler; profiler.print_stats()
sys.exit(errors and 1 or 0)
sys.exit(len(result.errors) + len(result.failures))
# Configures the Zope environment
......
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