def setUp(self): import cStringIO import string import transaction from OFS.Application import Application from OFS.Folder import manage_addFolder from OFS.Image import manage_addFile from Testing.makerequest import makerequest self.responseOut = cStringIO.StringIO() self.connection = makeConnection() try: r = self.connection.root() a = Application() r['Application'] = a self.root = a self.app = makerequest(self.root, stdout=self.responseOut) try: self.app._delObject(TESTFOLDER_NAME) except AttributeError: pass manage_addFolder(self.app, TESTFOLDER_NAME) folder = getattr( self.app, TESTFOLDER_NAME ) data = string.letters manage_addFile( folder, 'file' , file=data, content_type='text/plain') self.file = folder.file self.data = data # 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. transaction.commit() except: self.connection.close() raise
def setUp(self): # set up a zodb # we can't use DemoStorage here 'cos it doesn't support History self.dir = tempfile.mkdtemp() self.s = FileStorage(os.path.join(self.dir, 'testHistory.fs'), create=True) self.connection = ZODB.DB(self.s).open() r = self.connection.root() a = Application() r['Application'] = a self.root = a # create a python script manage_addPythonScript(a, 'test') self.ps = ps = a.test # commit some changes ps.write('return 1') t = transaction.get() # undo note made by Application instantiation above. t.description = None t.note('Change 1') t.commit() ps.write('return 2') t = transaction.get() t.note('Change 2') t.commit() ps.write('return 3') t = transaction.get() t.note('Change 3') t.commit()
def getZopeApp(): from cStringIO import StringIO from OFS.Application import Application from OFS.Application import initialize as initialize_app from Testing.makerequest import makerequest global _conn if _conn is None: # or fresh_db: _conn = makeConnection() try: root = _conn.root() app = Application() root['Application'] = app responseOut = StringIO() app = makerequest(app, stdout=responseOut) get_transaction().commit(1) initialize_app(app) get_transaction().commit(1) return app except: _conn.close() _conn = None raise else: app = _conn.root()['Application'] responseOut = StringIO() return makerequest(app, stdout=responseOut)
def _initFolders( self ): from Products.CMFCore.PortalFolder import PortalFolder self.connection = makeConnection() try: r = self.connection.root() a = Application() r['Application'] = a self.root = a responseOut = self.responseOut = cStringIO.StringIO() self.app = makerequest( self.root, stdout=responseOut ) self.app._setObject( 'folder1', PortalFolder( 'folder1' ) ) self.app._setObject( 'folder2', PortalFolder( 'folder2' ) ) folder1 = getattr( self.app, 'folder1' ) folder2 = getattr( self.app, 'folder2' ) manage_addFile( folder1, 'file' , file='', content_type='text/plain') # 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 get_transaction().begin() return self.app._getOb( 'folder1' ), self.app._getOb( 'folder2' )
def setUp(self): global original_config if original_config is None: # stow away original config so we can reset it original_config = App.config.getConfiguration() databases = [ TestDBConfig('test_main.fs', ['/']).getDB(), TestDBConfig('test_mount1.fs', ['/mount1']).getDB(), TestDBConfig('test_mount2.fs', ['/mount2']).getDB(), ] mount_points = {} mount_factories = {} for database in databases: points = database.getVirtualMountPaths() name = database.config.getSectionName() mount_factories[name] = database for point in points: mount_points[point] = name conf = DBTab(mount_factories, mount_points) d = App.config.DefaultConfiguration() d.dbtab = conf App.config.setConfiguration(d) self.conf = conf db = conf.getDatabase('/') conn = db.open() root = conn.root() root['Application'] = app = Application() self.app = app transaction.commit() # Get app._p_jar set manage_addMounts(app, ('/mount1', '/mount2')) transaction.commit() # Get the mount points ready
def mount(self, out=None): """ Mount catalogs """ if out is None: out = StringIO() to_mount = manage_getMountStatus(self) items = [item for item in to_mount if 'catalog' in item['path'] and '** Something is in the way **' in item['status']] msg = 'Mounting... %s catalogs' % len(items) logger.warn(msg) out.write(msg) for item in items: path = item['path'] logger.info('Mounting %s', path) oid = path.split('/')[-1] old_obj = self.unrestrictedTraverse(path) old_parent = old_obj.aq_parent.aq_base db_name = item['name'] db = getConfiguration().dbtab.getDatabase(path) new_trans = db.open() root = new_trans.root() if not root.has_key('Application'): from OFS.Application import Application root['Application'] = Application() transaction.savepoint(optimistic=True) root = root['Application'] f = tempfile.TemporaryFile() old_obj._p_jar.exportFile(old_obj._p_oid, f) f.seek(0) new_obj = root._p_jar.importFile(f) f.close() blazer = CustomTrailblazer(root) obj = blazer.traverseOrConstruct(path) obj.aq_parent._setOb(oid, new_obj) mo = MountedObject(path) mo._create_mount_points = True old_parent._p_jar.add(mo) old_parent._setOb(oid, mo) setMountPoint(old_parent, oid, mo) msg = "Path: %s, mounted to db:%s" % (path, db_name) logger.warn(msg) out.write(msg) msg = ("Done mounting 1 catalog. Breaking. " "Please rerun this until all catalogs are mounted") logger.warn(msg) out.write(msg) break return out.getvalue()
def _initFolders(self): self.connection = makeConnection() try: r = self.connection.root() a = Application() r['Application'] = a self.root = a responseOut = self.responseOut = io.BytesIO() self.app = makerequest(self.root, stdout=responseOut) manage_addFolder(self.app, 'folder1') manage_addFolder(self.app, 'folder2') folder1 = getattr(self.app, 'folder1') manage_addFile(folder1, 'file', file=b'', content_type='text/plain') # 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. transaction.commit() except Exception: transaction.abort() self.connection.close() raise transaction.begin() return self.app._getOb('folder1'), self.app._getOb('folder2')
def setUp(self): # set up a zodb # we can't use DemoStorage here 'cos it doesn't support History self.dir = tempfile.mkdtemp() fs_path = os.path.join(self.dir, 'testHistory.fs') self.s = FileStorage(fs_path, create=True) self.connection = ZODB.DB(self.s).open() r = self.connection.root() a = Application() r['Application'] = a self.root = a # create a python script a['test'] = HistoryItem() self.hi = hi = a.test # commit some changes hi.title = 'First title' t = transaction.get() # undo note made by Application instantiation above. t.description = None t.note('Change 1') t.commit() time.sleep(0.02) # wait at least one Windows clock tick hi.title = 'Second title' t = transaction.get() t.note('Change 2') t.commit() time.sleep(0.02) # wait at least one Windows clock tick hi.title = 'Third title' t = transaction.get() t.note('Change 3') t.commit()
def setUp(self): self.app = Application() self.app.ob = Folder() self.ob = self.app.ob self.ob.__ac_local_roles__ = { '(Group) Administrators': ['Manager', 'Member'], '(Group) Users': ['Member'], } self.ob._View_Permission = ('Member', 'Manager') self.ob._View_management_screens_Permission = ('Manager', )
def _traverseToMountedRoot(self, root, mount_parent): """Hook for getting the object to be mounted. """ params = self._v_mount_params if params is None: params = self._loadMountParams() real_root, real_path, container_class = params if real_root is None: real_root = 'Application' try: obj = root[real_root] except KeyError: # DM 2005-05-17: why should we require 'container_class'? # if container_class or self._create_mount_points: if self._create_mount_points: # Create a database automatically. from OFS.Application import Application obj = Application() root[real_root] = obj # Get it into the database transaction.savepoint(optimistic=True) else: raise if real_path is None: real_path = self._path if six.PY2 and isinstance(real_path, six.text_type): real_path = real_path.encode('utf8') if real_path and real_path != '/': try: obj = obj.unrestrictedTraverse(real_path) except (KeyError, AttributeError): # DM 2005-05-13: obviously, we do not want automatic # construction when "_create_mount_points" is false # if container_class or self._create_mount_points: if container_class and self._create_mount_points: blazer = CustomTrailblazer(obj, container_class) obj = blazer.traverseOrConstruct(real_path) else: raise return obj
def setUp(self): self.app = Application() self.app.id = 'App' mgr = BrowserIdManager('browser_id_manager') self.app._setObject('browser_id_manager', mgr) self.m = self.app.browser_id_manager resp = HTTPResponse() environ['SERVER_NAME']='fred' environ['SERVER_PORT']='80' self.req = HTTPRequest(stdin, environ, resp) self.req['TraversalRequestNameStack'] = ['foo', 'bar'] self.app.REQUEST = self.req
def setUp(self): app= Application() catalog= ZCatalog('Catalog') app._setObject('Catalog',catalog) self.catalog= catalog= app._getOb('Catalog') install_products(app, 'ManagableIndex') # field self.fi = self._createIndex('id', FieldIndex) # keyword self.ki= self._createIndex('kw', KeywordIndex) # range self.ri = self._createIndex( 'ri', RangeIndex, dict(CombineType='aggregate', ValueProviders=[ dict(id='rlow', type='AttributeLookup'), dict(id='rhigh', type='AttributeLookup'), ] ), ) # word lexicon = Lexicon(Splitter()) app._setObject('lexicon', lexicon) self.wi = self._createIndex('wi', WordIndex, dict(Lexicon='lexicon')) # simple text self.sti = self._createIndex('sti', SimpleTextIndex, dict(Lexicon='lexicon')) # path self.pi= self._createIndex('pi', PathIndex) # create objects self.obj1= obj1= _Object() obj1.kw= (1,2) obj1.fkw= _Caller(lambda obj: obj.kw) obj1.fid= _Caller(lambda obj: obj.id) self.obj2= obj2= _Object().__of__(obj1) obj2.id= 'id'
def setUp(self): import io import transaction from AccessControl import SecurityManager from AccessControl.SecurityManagement import newSecurityManager from OFS.Application import Application from OFS.Folder import manage_addFolder from OFS.Image import manage_addFile from Testing.makerequest import makerequest from ZODB.DB import DB from ZODB.DemoStorage import DemoStorage s = DemoStorage() self.connection = DB(s).open() try: r = self.connection.root() a = Application() r['Application'] = a self.root = a responseOut = self.responseOut = io.BytesIO() self.app = makerequest(self.root, stdout=responseOut) manage_addFolder(self.app, 'folder1') folder1 = getattr(self.app, 'folder1') setattr(folder1, '+something', 'plus') folder1.all_meta_types = ({ 'name': 'File', 'action': 'manage_addFile', 'permission': 'Add images and files' }, ) manage_addFile(folder1, 'file', file=b'', content_type='text/plain') # 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. transaction.commit() except Exception: self.connection.close() raise transaction.begin() self.folder1 = getattr(self.app, 'folder1') self.policy = UnitTestSecurityPolicy() self.oldPolicy = SecurityManager.setSecurityPolicy(self.policy) newSecurityManager(None, self._makeUser().__of__(self.root))
def _getDB(): db = stuff.get('db') if not db: ds = DemoStorage() db = ZODB.DB(ds) conn = db.open() root = conn.root() app = Application() root['Application'] = app _populate(app) transaction.commit() stuff['db'] = db conn.close() return db
def setUp(self): self.db, self.conn = self.open_database() self.conf = conf self.path = tmpdir c = self.db.open() try: if not c.root().has_key('Application'): from OFS.Application import Application c.root()['Application'] = Application() transaction.commit() finally: c.close() transaction.begin() self.clear_caches()
def _getDB(): db = stuff.get('db') if not db: ds = DemoStorage(quota=(1 << 20)) db = ZODB.DB(ds, pool_size=60) conn = db.open() root = conn.root() app = Application() root['Application'] = app transaction.savepoint(optimistic=True) _populate(app) stuff['db'] = db conn.close() return db
def _getApp(): app = stuff.get('app', None) if not app: ds = DemoStorage() db = ZODB.DB(ds) conn = db.open() root = conn.root() app = Application() root['Application'] = app transaction.commit() stuff['app'] = app stuff['conn'] = conn stuff['db'] = db return app
def _getDB(): from OFS.Application import Application import transaction db = stuff.get('db') if not db: from ZODB import DB from ZODB.DemoStorage import DemoStorage ds = DemoStorage() db = DB(ds, pool_size=60) conn = db.open() root = conn.root() app = Application() root['Application'] = app transaction.savepoint(optimistic=True) _populate(app) stuff['db'] = db conn.close() return db
def setUp(self): with open(filedata, 'rb') as fd: self.data = fd.read() self.connection = makeConnection() self.eventCatcher = EventCatcher() try: r = self.connection.root() a = Application() r['Application'] = a self.root = a responseOut = self.responseOut = BytesIO() self.app = makerequest(self.root, stdout=responseOut) self.app.dcm = DummyCacheManager() factory = getattr(self.app, self.factory) factory('file', file=self.data, content_type=self.content_type) self.app.file.ZCacheable_setManagerId('dcm') self.app.file.ZCacheable_setEnabled(enabled=1) setattr(self.app, ZCM_MANAGERS, ('dcm',)) # Hack, we need a _p_mtime for the file, so we make sure that it # has one. transaction.commit() except Exception: transaction.abort() self.connection.close() raise transaction.begin() self.file = getattr(self.app, 'file') # Since we do the create here, let's test the events here too self.assertEqual(1, len(self.eventCatcher.created)) self.assertTrue( aq_base(self.eventCatcher.created[0].object) is aq_base(self.file)) self.assertEqual(1, len(self.eventCatcher.modified)) self.assertTrue( aq_base(self.eventCatcher.created[0].object) is aq_base(self.file)) self.eventCatcher.reset()
def __call__(self, request): from OFS.Application import Application app = Application() from ZPublisher.HTTPRequest import HTTPRequest from zExceptions import Forbidden app.REQUEST = zope_request = get_zope_request(request) try: name = request.path[1:] or 'index_html' method = getattr(self.ui.__of__(app), name) except AttributeError: return HTTPNotFound() else: headers = {} zope_request.RESPONSE.setHeader = Mock(side_effect=headers.__setitem__) zope_request.SESSION = self.session try: body = method(zope_request) except Forbidden: return HTTPForbidden() else: return Response(body, headers=headers)
def setUp(self): self.connection = makeConnection() try: r = self.connection.root() a = Application() r['Application'] = a self.root = a responseOut = self.responseOut = cStringIO.StringIO() self.app = makerequest(self.root, stdout=responseOut) manage_addFolder(self.app, 'folder1') folder1 = getattr(self.app, 'folder1') setattr(folder1, '+something', 'plus') folder1.all_meta_types = \ ( { 'name' : 'File' , 'action' : 'manage_addFile' , 'permission' : 'Add images and files' } , ) manage_addFile(folder1, 'file', file='', content_type='text/plain') # 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. transaction.commit() except: self.connection.close() raise transaction.begin() self.folder1 = getattr(self.app, 'folder1') self.policy = UnitTestSecurityPolicy() self.oldPolicy = SecurityManager.setSecurityPolicy(self.policy) newSecurityManager(None, UnitTestUser().__of__(self.root))
def render_folder(root, path, where, object_types=['Page Template', 'File', 'Image'], folder_types=['Folder'], output_root=None, raise_errors=False): path = path.strip('/') assert '..' not in path outputdir = os.path.join(where, path) os.makedirs(outputdir) if output_root is None: output_root = where app = Application() obj = root.__of__(app) folder = obj.unrestrictedTraverse(path) names = folder.objectIds(object_types) if 'index_html' not in names: names.append('index_html') for name in names: render_object(root, path + '/' + name, where, append_html=False, output_root=output_root, raise_errors=raise_errors) os.symlink('index_html', os.path.join(outputdir, 'index.html')) names = folder.objectIds(folder_types) for name in names: render_folder(root, path + '/' + name, where, object_types=object_types, folder_types=folder_types, output_root=output_root, raise_errors=raise_errors)
def setUp(self): self.connection = makeConnection() try: r = self.connection.root() a = Application() r['Application'] = a self.root = a responseOut = self.responseOut = StringIO() self.app = makerequest(self.root, stdout=responseOut) self.app.dcm = DummyCacheManager() factory = getattr(self.app, self.factory) factory('file', file=self.data, content_type=self.content_type) self.app.file.ZCacheable_setManagerId('dcm') self.app.file.ZCacheable_setEnabled(enabled=1) setattr(self.app, ZCM_MANAGERS, ('dcm', )) # Hack, we need a _p_mtime for the file, so we make sure that it # has one. transaction.commit() except: self.connection.close() raise transaction.begin() self.file = getattr(self.app, 'file')
def setUp(self): app = Application() catalog = ZCatalog('Catalog') app._setObject('Catalog', catalog) self.catalog = catalog = app._getOb('Catalog') install_products(app, 'ManagableIndex') # field self.fi = self._createIndex('id', FieldIndex) # keyword self.ki = self._createIndex('kw', KeywordIndex) # range self.ri = self._createIndex( 'ri', RangeIndex, dict(CombineType='aggregate', ValueProviders=[ dict(id='rlow', type='AttributeLookup'), dict(id='rhigh', type='AttributeLookup'), ]), ) # word lexicon = Lexicon(Splitter()) app._setObject('lexicon', lexicon) self.wi = self._createIndex('wi', WordIndex, dict(Lexicon='lexicon')) # simple text self.sti = self._createIndex('sti', SimpleTextIndex, dict(Lexicon='lexicon')) # path self.pi = self._createIndex('pi', PathIndex) # create objects self.obj1 = obj1 = _Object() obj1.kw = (1, 2) obj1.fkw = _Caller(lambda obj: obj.kw) obj1.fid = _Caller(lambda obj: obj.id) self.obj2 = obj2 = _Object().__of__(obj1) obj2.id = 'id'
def setUp(self): app= Application() catalog= ZCatalog('Catalog') app._setObject('Catalog',catalog) self.catalog= catalog= app._getOb('Catalog') # create indexes -- avoid the official API because it requires # product setup and this takes ages cat= catalog._catalog # field fi= FieldIndex('id'); cat.addIndex('id',fi) self.fi= cat.getIndex('id') # keyword ki= KeywordIndex('kw'); cat.addIndex('kw',ki) self.ki= cat.getIndex('kw') # range ri= RangeIndex('ri'); cat.addIndex('ri',ri) self.ri = ri = cat.getIndex('ri') ri._delObject('ri'); ri.CombineType = 'aggregate' ri.addValueProvider('rlow','AttributeLookup') ri.addValueProvider('rhigh','AttributeLookup') # word lexicon = Lexicon(Splitter()) app._setObject('lexicon', lexicon) wi = WordIndex('wi'); cat.addIndex('wi',wi) wi.Lexicon = 'lexicon' self.wi = cat.getIndex('wi') # path pi= PathIndex('pi'); cat.addIndex('pi',pi) self.pi= cat.getIndex('pi') # create objects self.obj1= obj1= _Object() obj1.kw= (1,2) obj1.fkw= _Caller(lambda obj: obj.kw) obj1.fid= _Caller(lambda obj: obj.id) self.obj2= obj2= _Object().__of__(obj1) obj2.id= 'id'
class TestBrowserIdManager(TestCase): def setUp(self): self.app = Application() self.app.id = 'App' mgr = BrowserIdManager('browser_id_manager') self.app._setObject('browser_id_manager', mgr) self.m = self.app.browser_id_manager resp = HTTPResponse() environ = {} environ['SERVER_NAME'] = 'fred' environ['SERVER_PORT'] = '80' self.req = HTTPRequest(stdin, environ, resp) self.req['TraversalRequestNameStack'] = ['foo', 'bar'] self.app.REQUEST = self.req def tearDown(self): del self.m self.app.REQUEST = None del self.app def testSetBrowserIdName(self): self.m.setBrowserIdName('foo') self.failUnless(self.m.getBrowserIdName() == 'foo') def testSetBadBrowserIdName(self): self.assertRaises(BrowserIdManagerErr, lambda self=self: self.m.setBrowserIdName('')) self.assertRaises(BrowserIdManagerErr, lambda self=self: self.m.setBrowserIdName(1)) def testSetBadNamespaces(self): d = ('gummy', 'froopy') self.assertRaises( BrowserIdManagerErr, lambda self=self, d=d: self.m.setBrowserIdNamespaces(d)) def testSetGoodNamespaces(self): d = ('cookies', 'url', 'form') self.m.setBrowserIdNamespaces(d) self.failUnless(self.m.getBrowserIdNamespaces() == d) def testSetBadCookiePath(self): path = '/;' self.assertRaises( BrowserIdManagerErr, lambda self=self, path=path: self.m.setCookiePath(path)) def testSetGoodCookiePath(self): self.m.setCookiePath('/foo') self.failUnless(self.m.getCookiePath() == '/foo') def testSetBadCookieLifeDays(self): self.assertRaises(BrowserIdManagerErr, lambda self=self: self.m.setCookieLifeDays('')) def testSetGoodCookieLifeDays(self): self.m.setCookieLifeDays(1) self.failUnless(self.m.getCookieLifeDays() == 1) def testSetBadCookieDomain(self): self.assertRaises(BrowserIdManagerErr, lambda self=self: self.m.setCookieDomain('gubble')) def testSetGoodCookieLifeDays(self): self.m.setCookieLifeDays(1) self.failUnless(self.m.getCookieLifeDays() == 1) def testSetNoCookieDomain(self): domain = '' self.m.setCookieDomain(domain) setdomain = self.m.getCookieDomain() self.failUnless(setdomain == domain) def testSetBadCookieDomain(self): # not enough dots, must be stringtype, semicolon follows respectively for domain in ('zope.org', {1: 1}, '.zope.org;'): self.assertRaises(BrowserIdManagerErr, lambda self=self, domain=domain: self.m. setCookieDomain(domain)) def testSetGoodCookieDomain(self): self.m.setCookieDomain('.zope.org') setdomain = self.m.getCookieDomain() self.failUnless(setdomain == '.zope.org', "%s" % setdomain) def testSetCookieSecure(self): self.m.setCookieSecure(1) self.failUnless(self.m.getCookieSecure() == 1) def testGetBrowserIdCookie(self): token = self.m.getBrowserId() self.m.REQUEST.browser_id_ = token self.m.REQUEST.browser_id_ns_ = 'cookies' tokenkey = self.m.getBrowserIdName() self.m.REQUEST.cookies[tokenkey] = token a = self.m.getBrowserId() self.failUnless(a == token, repr(a)) self.failUnless(self.m.isBrowserIdFromCookie()) def testSetBrowserIdDontCreate(self): a = self.m.getBrowserId(0) self.failUnless(a == None) def testSetBrowserIdCreate(self): a = self.m.getBrowserId(1) tokenkey = self.m.getBrowserIdName() b = self.m.REQUEST.RESPONSE.cookies[tokenkey] self.failUnless(a == b['value']) def testHasBrowserId(self): self.failUnless(not self.m.hasBrowserId()) a = self.m.getBrowserId() self.failUnless(self.m.hasBrowserId()) def testBrowserIdIsNew(self): a = self.m.getBrowserId() self.failUnless(self.m.isBrowserIdNew()) def testIsBrowserIdFromCookieOnly(self): token = self.m.getBrowserId() self.m.REQUEST.browser_id_ = token self.m.REQUEST.browser_id_ns_ = 'cookies' tokenkey = self.m.getBrowserIdName() self.m.REQUEST.form[tokenkey] = token self.m.setBrowserIdNamespaces(('cookies', )) a = self.m.getBrowserId() self.failUnless(self.m.isBrowserIdFromCookie()) self.failUnless(not self.m.isBrowserIdFromForm()) def testIsBrowserIdFromFormOnly(self): token = self.m.getBrowserId() self.m.REQUEST.browser_id_ = token self.m.REQUEST.browser_id_ns_ = 'form' tokenkey = self.m.getBrowserIdName() self.m.REQUEST.form[tokenkey] = token self.m.setBrowserIdNamespaces(('form', )) a = self.m.getBrowserId() self.failUnless(not self.m.isBrowserIdFromCookie()) self.failUnless(self.m.isBrowserIdFromForm()) def testIsBrowserIdFromUrlOnly(self): token = self.m.getBrowserId() self.m.REQUEST.browser_id_ = token self.m.REQUEST.browser_id_ns_ = 'url' self.m.setBrowserIdNamespaces(('url', )) a = self.m.getBrowserId() self.failUnless(not self.m.isBrowserIdFromCookie()) self.failUnless(self.m.isBrowserIdFromUrl()) def testFlushBrowserIdCookie(self): token = self.m.getBrowserId() self.m.REQUEST.browser_id_ = token self.m.REQUEST.browser_id_ns_ = 'cookies' tokenkey = self.m.getBrowserIdName() self.m.REQUEST.cookies[tokenkey] = token a = self.m.getBrowserId() self.failUnless(a == token, repr(a)) self.failUnless(self.m.isBrowserIdFromCookie()) self.m.flushBrowserIdCookie() c = self.m.REQUEST.RESPONSE.cookies[tokenkey] self.failUnless(c['value'] == 'deleted') def testSetBrowserIdCookieByForce(self): token = self.m.getBrowserId() self.m.REQUEST.browser_id_ = token self.m.REQUEST.browser_id_ns_ = 'cookies' tokenkey = self.m.getBrowserIdName() self.m.REQUEST.cookies[tokenkey] = token a = self.m.getBrowserId() self.failUnless(a == token) self.failUnless(self.m.isBrowserIdFromCookie()) token = 'abcdefghijk' self.m.setBrowserIdCookieByForce(token) c = self.m.REQUEST.RESPONSE.cookies[tokenkey] self.failUnless(c['value'] == token) def testEncodeUrl(self): keystring = self.m.getBrowserIdName() key = self.m.getBrowserId() u = '/home/chrism/foo' r = self.m.encodeUrl(u) self.failUnless(r == '%s?%s=%s' % (u, keystring, key)) u = 'http://www.zope.org/Members/mcdonc?foo=bar&spam=eggs' r = self.m.encodeUrl(u) self.failUnless(r == '%s&%s=%s' % (u, keystring, key)) r = self.m.encodeUrl(u, style='inline') self.failUnless( r == 'http://www.zope.org/%s/%s/Members/mcdonc?foo=bar&spam=eggs' % (keystring, key)) def testGetHiddenFormField(self): keystring = self.m.getBrowserIdName() key = self.m.getBrowserId() html = self.m.getHiddenFormField() expected = ('<input type="hidden" name="%s" value="%s">' % (keystring, key)) self.failUnless(html == expected) def testAutoUrlEncoding(self): self.m.setAutoUrlEncoding(1) self.m.setBrowserIdNamespaces(('url', )) self.m.updateTraversalData() traverser = BrowserIdManagerTraverser() traverser(self.app, self.req) self.failUnless(isAWellFormedBrowserId(self.req.browser_id_)) self.failUnless(self.req.browser_id_ns_ == None) self.failUnless(self.req._script[-1] == self.req.browser_id_) self.failUnless(self.req._script[-2] == '_ZopeId') def testUrlBrowserIdIsFound(self): bid = '43295340A0bpcu4nkCI' name = '_ZopeId' resp = HTTPResponse() environ = {} environ['SERVER_NAME'] = 'fred' environ['SERVER_PORT'] = '80' self.req = HTTPRequest(stdin, environ, resp) self.req['TraversalRequestNameStack'] = ['foo', 'bar', bid, name] self.app.REQUEST = self.req self.m.setAutoUrlEncoding(1) self.m.setBrowserIdNamespaces(('url', )) self.m.updateTraversalData() traverser = BrowserIdManagerTraverser() traverser(self.app, self.req) self.failUnless(isAWellFormedBrowserId(self.req.browser_id_)) self.failUnless(self.req.browser_id_ns_ == 'url') self.failUnless(self.req._script[-1] == self.req.browser_id_) self.failUnless(self.req._script[-2] == '_ZopeId') self.failUnless( self.req['TraversalRequestNameStack'] == ['foo', 'bar']) def testUpdateTraversalData(self): self.m.setBrowserIdNamespaces(('url', )) self.m.updateTraversalData() self.failUnless(self.m.hasTraversalHook(self.app)) self.failUnless(queryBeforeTraverse(self.app, 'BrowserIdManager')) self.m.setBrowserIdNamespaces(('cookies', 'form')) self.m.updateTraversalData() self.failUnless(not queryBeforeTraverse(self.app, 'BrowserIdManager'))
class TestBrowserIdManager(TestCase): def setUp(self): self.app = Application() self.app.id = 'App' mgr = BrowserIdManager('browser_id_manager') self.app._setObject('browser_id_manager', mgr) self.m = self.app.browser_id_manager resp = HTTPResponse() environ = {} environ['SERVER_NAME']='fred' environ['SERVER_PORT']='80' self.req = HTTPRequest(stdin, environ, resp) self.req['TraversalRequestNameStack'] = ['foo', 'bar'] self.app.REQUEST = self.req def tearDown(self): del self.m self.app.REQUEST = None del self.app def testSetBrowserIdName(self): self.m.setBrowserIdName('foo') self.failUnless(self.m.getBrowserIdName()== 'foo') def testSetBadBrowserIdName(self): self.assertRaises(BrowserIdManagerErr, lambda self=self: self.m.setBrowserIdName('')) self.assertRaises(BrowserIdManagerErr, lambda self=self: self.m.setBrowserIdName(1)) def testSetBadNamespaces(self): d = ('gummy', 'froopy') self.assertRaises(BrowserIdManagerErr, lambda self=self,d=d: self.m.setBrowserIdNamespaces(d)) def testSetGoodNamespaces(self): d = ('cookies', 'url', 'form') self.m.setBrowserIdNamespaces(d) self.failUnless(self.m.getBrowserIdNamespaces() == d) def testSetBadCookiePath(self): path = '/;' self.assertRaises(BrowserIdManagerErr, lambda self=self, path=path:self.m.setCookiePath(path)) def testSetGoodCookiePath(self): self.m.setCookiePath('/foo') self.failUnless(self.m.getCookiePath() == '/foo') def testSetBadCookieLifeDays(self): self.assertRaises(BrowserIdManagerErr, lambda self=self: self.m.setCookieLifeDays('')) def testSetGoodCookieLifeDays(self): self.m.setCookieLifeDays(1) self.failUnless(self.m.getCookieLifeDays() == 1) def testSetBadCookieDomain(self): self.assertRaises(BrowserIdManagerErr, lambda self=self: self.m.setCookieDomain('gubble')) def testSetGoodCookieLifeDays(self): self.m.setCookieLifeDays(1) self.failUnless(self.m.getCookieLifeDays() == 1) def testSetNoCookieDomain(self): domain = '' self.m.setCookieDomain(domain) setdomain = self.m.getCookieDomain() self.failUnless(setdomain == domain) def testSetBadCookieDomain(self): # not enough dots, must be stringtype, semicolon follows respectively for domain in ('zope.org', {1:1}, '.zope.org;'): self.assertRaises(BrowserIdManagerErr, lambda self=self, domain=domain: self.m.setCookieDomain(domain)) def testSetGoodCookieDomain(self): self.m.setCookieDomain('.zope.org') setdomain = self.m.getCookieDomain() self.failUnless( setdomain == '.zope.org', "%s" % setdomain ) def testSetCookieSecure(self): self.m.setCookieSecure(1) self.failUnless( self.m.getCookieSecure() == 1 ) def testGetBrowserIdCookie(self): token = self.m.getBrowserId() self.m.REQUEST.browser_id_ = token self.m.REQUEST.browser_id_ns_ = 'cookies' tokenkey = self.m.getBrowserIdName() self.m.REQUEST.cookies[tokenkey] = token a = self.m.getBrowserId() self.failUnless( a == token, repr(a) ) self.failUnless( self.m.isBrowserIdFromCookie() ) def testSetBrowserIdDontCreate(self): a = self.m.getBrowserId(0) self.failUnless( a == None ) def testSetBrowserIdCreate(self): a = self.m.getBrowserId(1) tokenkey = self.m.getBrowserIdName() b = self.m.REQUEST.RESPONSE.cookies[tokenkey] self.failUnless( a == b['value'] ) def testHasBrowserId(self): self.failUnless( not self.m.hasBrowserId() ) a = self.m.getBrowserId() self.failUnless( self.m.hasBrowserId() ) def testBrowserIdIsNew(self): a = self.m.getBrowserId() self.failUnless( self.m.isBrowserIdNew() ) def testIsBrowserIdFromCookieOnly(self): token = self.m.getBrowserId() self.m.REQUEST.browser_id_ = token self.m.REQUEST.browser_id_ns_ = 'cookies' tokenkey = self.m.getBrowserIdName() self.m.REQUEST.form[tokenkey] = token self.m.setBrowserIdNamespaces(('cookies',)) a = self.m.getBrowserId() self.failUnless( self.m.isBrowserIdFromCookie() ) self.failUnless( not self.m.isBrowserIdFromForm() ) def testIsBrowserIdFromFormOnly(self): token = self.m.getBrowserId() self.m.REQUEST.browser_id_ = token self.m.REQUEST.browser_id_ns_ = 'form' tokenkey = self.m.getBrowserIdName() self.m.REQUEST.form[tokenkey] = token self.m.setBrowserIdNamespaces(('form',)) a = self.m.getBrowserId() self.failUnless( not self.m.isBrowserIdFromCookie() ) self.failUnless( self.m.isBrowserIdFromForm() ) def testIsBrowserIdFromUrlOnly(self): token = self.m.getBrowserId() self.m.REQUEST.browser_id_ = token self.m.REQUEST.browser_id_ns_ = 'url' self.m.setBrowserIdNamespaces(('url',)) a = self.m.getBrowserId() self.failUnless( not self.m.isBrowserIdFromCookie() ) self.failUnless( self.m.isBrowserIdFromUrl() ) def testFlushBrowserIdCookie(self): token = self.m.getBrowserId() self.m.REQUEST.browser_id_ = token self.m.REQUEST.browser_id_ns_ = 'cookies' tokenkey = self.m.getBrowserIdName() self.m.REQUEST.cookies[tokenkey] = token a = self.m.getBrowserId() self.failUnless( a == token, repr(a) ) self.failUnless( self.m.isBrowserIdFromCookie() ) self.m.flushBrowserIdCookie() c = self.m.REQUEST.RESPONSE.cookies[tokenkey] self.failUnless( c['value'] == 'deleted' ) def testSetBrowserIdCookieByForce(self): token = self.m.getBrowserId() self.m.REQUEST.browser_id_ = token self.m.REQUEST.browser_id_ns_ = 'cookies' tokenkey = self.m.getBrowserIdName() self.m.REQUEST.cookies[tokenkey] = token a = self.m.getBrowserId() self.failUnless( a == token ) self.failUnless( self.m.isBrowserIdFromCookie() ) token = 'abcdefghijk' self.m.setBrowserIdCookieByForce(token) c = self.m.REQUEST.RESPONSE.cookies[tokenkey] self.failUnless( c['value'] == token ) def testEncodeUrl(self): keystring = self.m.getBrowserIdName() key = self.m.getBrowserId() u = '/home/chrism/foo' r = self.m.encodeUrl(u) self.failUnless( r == '%s?%s=%s' % (u, keystring, key) ) u = 'http://www.zope.org/Members/mcdonc?foo=bar&spam=eggs' r = self.m.encodeUrl(u) self.failUnless( r == '%s&%s=%s' % (u, keystring, key) ) r = self.m.encodeUrl(u, style='inline') self.failUnless( r == 'http://www.zope.org/%s/%s/Members/mcdonc?foo=bar&spam=eggs' % (keystring, key)) def testGetHiddenFormField(self): keystring = self.m.getBrowserIdName() key = self.m.getBrowserId() html = self.m.getHiddenFormField() expected = ('<input type="hidden" name="%s" value="%s">' % (keystring, key)) self.failUnless( html == expected ) def testAutoUrlEncoding(self): self.m.setAutoUrlEncoding(1) self.m.setBrowserIdNamespaces(('url',)) self.m.updateTraversalData() traverser = BrowserIdManagerTraverser() traverser(self.app, self.req) self.failUnless(isAWellFormedBrowserId(self.req.browser_id_)) self.failUnless(self.req.browser_id_ns_ == None) self.failUnless(self.req._script[-1] == self.req.browser_id_) self.failUnless(self.req._script[-2] == '_ZopeId') def testUrlBrowserIdIsFound(self): bid = '43295340A0bpcu4nkCI' name = '_ZopeId' resp = HTTPResponse() environ = {} environ['SERVER_NAME']='fred' environ['SERVER_PORT']='80' self.req = HTTPRequest(stdin, environ, resp) self.req['TraversalRequestNameStack'] = ['foo', 'bar', bid, name] self.app.REQUEST = self.req self.m.setAutoUrlEncoding(1) self.m.setBrowserIdNamespaces(('url',)) self.m.updateTraversalData() traverser = BrowserIdManagerTraverser() traverser(self.app, self.req) self.failUnless(isAWellFormedBrowserId(self.req.browser_id_)) self.failUnless(self.req.browser_id_ns_ == 'url') self.failUnless(self.req._script[-1] == self.req.browser_id_) self.failUnless(self.req._script[-2] == '_ZopeId') self.failUnless(self.req['TraversalRequestNameStack'] == ['foo','bar']) def testUpdateTraversalData(self): self.m.setBrowserIdNamespaces(('url',)) self.m.updateTraversalData() self.failUnless(self.m.hasTraversalHook(self.app)) self.failUnless(queryBeforeTraverse(self.app, 'BrowserIdManager')) self.m.setBrowserIdNamespaces(('cookies', 'form')) self.m.updateTraversalData() self.failUnless(not queryBeforeTraverse(self.app,'BrowserIdManager'))