[Zope-Checkins] SVN: Zope/branches/2.12/src/AccessControl/tests/testUser.py Normalize / slim down tests.

Tres Seaver tseaver at palladion.com
Sun May 16 11:26:09 EDT 2010


Log message for revision 112352:
  Normalize / slim down tests.
  
  - Avoid module-scope imports.
  
  - Avoid complex shared setup.
  
  - Remove run-as-script cruft.
  

Changed:
  U   Zope/branches/2.12/src/AccessControl/tests/testUser.py

-=-
Modified: Zope/branches/2.12/src/AccessControl/tests/testUser.py
===================================================================
--- Zope/branches/2.12/src/AccessControl/tests/testUser.py	2010-05-16 15:10:03 UTC (rev 112351)
+++ Zope/branches/2.12/src/AccessControl/tests/testUser.py	2010-05-16 15:26:08 UTC (rev 112352)
@@ -10,138 +10,160 @@
 # FOR A PARTICULAR PURPOSE.
 #
 ##############################################################################
-"""User folder tests.
-
-$Id$
+""" Unit tests for AccessControl.User
 """
-
 import unittest
-import Testing
-import Zope2
-Zope2.startup()
 
-import os, sys, base64
 
-import transaction
-from Testing.makerequest import makerequest
-
-from AccessControl import Unauthorized
-from AccessControl.SecurityManagement import newSecurityManager
-from AccessControl.SecurityManagement import noSecurityManager
-from AccessControl.User import BasicUserFolder, UserFolder
-from AccessControl.User import User
-
-
 class UserFolderTests(unittest.TestCase):
 
     def setUp(self):
+        import transaction
         transaction.begin()
-        self.app = makerequest(Zope2.app())
-        try:
-            # Set up a user and role
-            self.uf = UserFolder().__of__(self.app)    
-            self.uf._doAddUser('user1', 'secret', ['role1'], [])
-            self.app._addRole('role1')
-            self.app.manage_role('role1', ['View'])
-            # Set up a published object accessible to user
-            self.app.addDTMLMethod('doc', file='')
-            self.app.doc.manage_permission('View', ['role1'], acquire=0)
-            # Rig the REQUEST so it looks like we traversed to doc
-            self.app.REQUEST.set('PUBLISHED', self.app.doc)
-            self.app.REQUEST.set('PARENTS', [self.app])
-            self.app.REQUEST.steps = ['doc']
-            self.basic = 'Basic %s' % base64.encodestring('user1:secret')
-        except:
-            self.tearDown()
-            raise
 
     def tearDown(self):
+        import transaction
+        from AccessControl.SecurityManagement import noSecurityManager
         noSecurityManager()
         transaction.abort()
-        self.app._p_jar.close()
 
-    def login(self, name):
-        user = self.uf.getUserById(name)
-        user = user.__of__(self.uf)
+    def _getTargetClass(self):
+        from AccessControl.User import UserFolder
+        return UserFolder
+
+    def _makeOne(self, app=None):
+        if app is None:
+            app = self._makeApp()
+        uf = self._getTargetClass()().__of__(app)
+        uf._doAddUser('user1', 'secret', ['role1'], [])
+        return uf
+
+    def _makeApp(self):
+        from Testing.makerequest import makerequest
+        from Testing.ZopeTestCase import ZopeLite
+        app = makerequest(ZopeLite.app())
+        # Set up a user and role
+        app._addRole('role1')
+        app.manage_role('role1', ['View'])
+        # Set up a published object accessible to user
+        app.addDTMLMethod('doc', file='')
+        app.doc.manage_permission('View', ['role1'], acquire=0)
+        # Rig the REQUEST so it looks like we traversed to doc
+        app.REQUEST.set('PUBLISHED', app.doc)
+        app.REQUEST.set('PARENTS', [app])
+        app.REQUEST.steps = ['doc']
+        return app
+
+    def _makeBasicAuthToken(self, creds='user1:secret'):
+        import base64
+        return 'Basic %s' % base64.encodestring(creds)
+
+    def _login(self, uf, name):
+        from AccessControl.SecurityManagement import newSecurityManager
+        user = uf.getUserById(name)
+        user = user.__of__(uf)
         newSecurityManager(None, user)
 
-    def test_z3interfaces(self):
+    def test_class_conforms_to_IStandardUserFolder(self):
         from AccessControl.interfaces import IStandardUserFolder
-        from AccessControl.User import UserFolder
         from zope.interface.verify import verifyClass
+        verifyClass(IStandardUserFolder, self._getTargetClass())
 
-        verifyClass(IStandardUserFolder, UserFolder)
-
     def testGetUser(self):
-        self.failIfEqual(self.uf.getUser('user1'), None)
+        uf = self._makeOne()
+        self.failIfEqual(uf.getUser('user1'), None)
 
     def testGetBadUser(self):
-        self.assertEqual(self.uf.getUser('user2'), None)
+        uf = self._makeOne()
+        self.assertEqual(uf.getUser('user2'), None)
 
     def testGetUserById(self):
-        self.failIfEqual(self.uf.getUserById('user1'), None)
+        uf = self._makeOne()
+        self.failIfEqual(uf.getUserById('user1'), None)
 
     def testGetBadUserById(self):
-        self.assertEqual(self.uf.getUserById('user2'), None)
+        uf = self._makeOne()
+        self.assertEqual(uf.getUserById('user2'), None)
 
     def testGetUsers(self):
-        users = self.uf.getUsers()
+        uf = self._makeOne()
+        users = uf.getUsers()
         self.failUnless(users)
         self.assertEqual(users[0].getUserName(), 'user1')
 
     def testGetUserNames(self):
-        names = self.uf.getUserNames()
+        uf = self._makeOne()
+        names = uf.getUserNames()
         self.failUnless(names)
         self.assertEqual(names[0], 'user1')
 
     def testIdentify(self):
-        name, password = self.uf.identify(self.basic)
+        uf = self._makeOne()
+        name, password = uf.identify(self._makeBasicAuthToken())
         self.assertEqual(name, 'user1')
         self.assertEqual(password, 'secret')
 
     def testGetRoles(self):
-        user = self.uf.getUser('user1')
+        uf = self._makeOne()
+        user = uf.getUser('user1')
         self.failUnless('role1' in user.getRoles())
 
     def testGetRolesInContext(self):
-        user = self.uf.getUser('user1')
-        self.app.manage_addLocalRoles('user1', ['Owner'])
-        roles = user.getRolesInContext(self.app)
+        app = self._makeApp()
+        uf = self._makeOne(app)
+        user = uf.getUser('user1')
+        app.manage_addLocalRoles('user1', ['Owner'])
+        roles = user.getRolesInContext(app)
         self.failUnless('role1' in roles)
         self.failUnless('Owner' in roles)
 
     def testHasRole(self):
-        user = self.uf.getUser('user1')
-        self.failUnless(user.has_role('role1', self.app))
+        app = self._makeApp()
+        uf = self._makeOne(app)
+        user = uf.getUser('user1')
+        self.failUnless(user.has_role('role1', app))
 
     def testHasLocalRole(self):
-        user = self.uf.getUser('user1')
-        self.app.manage_addLocalRoles('user1', ['Owner'])
-        self.failUnless(user.has_role('Owner', self.app))
+        app = self._makeApp()
+        uf = self._makeOne(app)
+        user = uf.getUser('user1')
+        app.manage_addLocalRoles('user1', ['Owner'])
+        self.failUnless(user.has_role('Owner', app))
 
     def testHasPermission(self):
-        user = self.uf.getUser('user1')
-        self.failUnless(user.has_permission('View', self.app))
-        self.app.manage_role('role1', ['Add Folders'])
-        self.failUnless(user.has_permission('Add Folders', self.app))
+        app = self._makeApp()
+        uf = self._makeOne(app)
+        user = uf.getUser('user1')
+        self.failUnless(user.has_permission('View', app))
+        app.manage_role('role1', ['Add Folders'])
+        self.failUnless(user.has_permission('Add Folders', app))
 
     def testHasLocalRolePermission(self):
-        user = self.uf.getUser('user1')
-        self.app.manage_role('Owner', ['Add Folders'])
-        self.app.manage_addLocalRoles('user1', ['Owner'])
-        self.failUnless(user.has_permission('Add Folders', self.app))
+        app = self._makeApp()
+        uf = self._makeOne(app)
+        user = uf.getUser('user1')
+        app.manage_role('Owner', ['Add Folders'])
+        app.manage_addLocalRoles('user1', ['Owner'])
+        self.failUnless(user.has_permission('Add Folders', app))
         
     def testAuthenticate(self):
-        user = self.uf.getUser('user1')
-        self.failUnless(user.authenticate('secret', self.app.REQUEST))
+        app = self._makeApp()
+        uf = self._makeOne(app)
+        user = uf.getUser('user1')
+        self.failUnless(user.authenticate('secret', app.REQUEST))
 
     def testValidate(self):
-        user = self.uf.validate(self.app.REQUEST, self.basic, ['role1'])
+        app = self._makeApp()
+        uf = self._makeOne(app)
+        user = uf.validate(app.REQUEST, self._makeBasicAuthToken(),
+                           ['role1'])
         self.failIfEqual(user, None)
         self.assertEqual(user.getUserName(), 'user1')
 
     def testNotValidateWithoutAuth(self):
-        user = self.uf.validate(self.app.REQUEST, '', ['role1'])
+        app = self._makeApp()
+        uf = self._makeOne(app)
+        user = uf.validate(app.REQUEST, '', ['role1'])
         self.assertEqual(user, None)
 
     def testValidateWithoutRoles(self):
@@ -152,30 +174,39 @@
         # really should have expected success, since the user and the
         # object being checked both have the role 'role1', even though no
         # roles are passed explicitly to the userfolder validate method.
-        user = self.uf.validate(self.app.REQUEST, self.basic)
+        app = self._makeApp()
+        uf = self._makeOne(app)
+        user = uf.validate(app.REQUEST, self._makeBasicAuthToken())
         self.assertEqual(user.getUserName(), 'user1')
 
     def testNotValidateWithEmptyRoles(self):
-        user = self.uf.validate(self.app.REQUEST, self.basic, [])
+        app = self._makeApp()
+        uf = self._makeOne(app)
+        user = uf.validate(app.REQUEST, self._makeBasicAuthToken(), [])
         self.assertEqual(user, None)
 
     def testNotValidateWithWrongRoles(self):
-        user = self.uf.validate(self.app.REQUEST, self.basic, ['Manager'])
+        app = self._makeApp()
+        uf = self._makeOne(app)
+        user = uf.validate(app.REQUEST, self._makeBasicAuthToken(),
+                           ['Manager'])
         self.assertEqual(user, None)
 
     def testAllowAccessToUser(self):
-        self.login('user1')
-        try:
-            self.app.restrictedTraverse('doc')
-        except Unauthorized:
-            self.fail('Unauthorized')
+        app = self._makeApp()
+        uf = self._makeOne(app)
+        self._login(uf, 'user1')
+        app.restrictedTraverse('doc')
 
     def testDenyAccessToAnonymous(self):
-        self.assertRaises(Unauthorized, self.app.restrictedTraverse, 'doc')
+        from AccessControl import Unauthorized
+        app = self._makeApp()
+        self.assertRaises(Unauthorized, app.restrictedTraverse, 'doc')
 
     def testMaxListUsers(self):
         # create a folder-ish thing which contains a roleManager,
         # then put an acl_users object into the folde-ish thing
+        from AccessControl.User import BasicUserFolder
 
         class Folderish(BasicUserFolder):
             def __init__(self, size, count):
@@ -220,7 +251,7 @@
         USER_ID = 'not_yet_encrypted'
         PASSWORD = 'password'
 
-        uf = UserFolder().__of__(self.app)    
+        uf = self._makeOne()
         uf.encrypt_passwords = True
         self.failIf(uf._isPasswordEncrypted(PASSWORD))
 
@@ -236,7 +267,7 @@
         USER_ID = 'already_encrypted'
         PASSWORD = 'password'
 
-        uf = UserFolder().__of__(self.app)    
+        uf = self._makeOne()
         uf.encrypt_passwords = True
         ENCRYPTED = uf._encryptPassword(PASSWORD)
 
@@ -249,34 +280,41 @@
 
 class UserTests(unittest.TestCase):
 
+    def _getTargetClass(self):
+        from AccessControl.User import User
+        return User
+
+    def _makeOne(self, name, password, roles, domains):
+        return self._getTargetClass()(name, password, roles, domains)
+
     def testGetUserName(self):
-        f = User('chris', '123', ['Manager'], [])
+        f = self._makeOne('chris', '123', ['Manager'], [])
         self.assertEqual(f.getUserName(), 'chris')
         
     def testGetUserId(self):
-        f = User('chris', '123', ['Manager'], [])
+        f = self._makeOne('chris', '123', ['Manager'], [])
         self.assertEqual(f.getId(), 'chris')
 
     def testBaseUserGetIdEqualGetName(self):
         # this is true for the default user type, but will not
         # always be true for extended user types going forward (post-2.6)
-        f = User('chris', '123', ['Manager'], [])
+        f = self._makeOne('chris', '123', ['Manager'], [])
         self.assertEqual(f.getId(), f.getUserName())
 
     def testGetPassword(self):
-        f = User('chris', '123', ['Manager'], [])
+        f = self._makeOne('chris', '123', ['Manager'], [])
         self.assertEqual(f._getPassword(), '123')
 
     def testGetRoles(self):
-        f = User('chris', '123', ['Manager'], [])
+        f = self._makeOne('chris', '123', ['Manager'], [])
         self.assertEqual(f.getRoles(), ('Manager', 'Authenticated'))
 
     def testGetDomains(self):
-        f = User('chris', '123', ['Manager'], [])
+        f = self._makeOne('chris', '123', ['Manager'], [])
         self.assertEqual(f.getDomains(), ())
 
     def testRepr(self):
-        f = User('flo', '123', ['Manager'], [])
+        f = self._makeOne('flo', '123', ['Manager'], [])
         self.assertEqual(repr(f), "<User 'flo'>")
 
     def testReprSpecial(self):
@@ -291,11 +329,9 @@
         self.assertEqual(repr(system),
                          "<UnrestrictedUser 'System Processes'>")
 
+
 def test_suite():
     suite = unittest.TestSuite()
     suite.addTest(unittest.makeSuite(UserFolderTests))
     suite.addTest(unittest.makeSuite(UserTests))
     return suite
-
-if __name__ == '__main__':
-    unittest.main(defaultTest='test_suite')



More information about the Zope-Checkins mailing list