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 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 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(u'Change 1') t.commit() time.sleep(0.02) # wait at least one Windows clock tick hi.title = 'Second title' t = transaction.get() t.note(u'Change 2') t.commit() time.sleep(0.02) # wait at least one Windows clock tick hi.title = 'Third title' t = transaction.get() t.note(u'Change 3') t.commit()
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 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 setUp(self): global conf if conf is None: conf = load_conf('sql') conn = self.get_connection() self.conf = conf resource = StaticResource(self.conf) self.conns = {'db': conn} storage = ApeStorage(resource, self.conns, clear_all=1, debug_conflicts=1) self.storage = storage self.assertEqual(conn.transaction_started, False) self.db = ApeDB(storage, resource) try: c = self.db.open() try: if not c.root().has_key('Application'): from OFS.Application import Application c.root()['Application'] = Application() transaction.commit() finally: transaction.abort() c.close() except: self.db.close() raise self.assertEqual(conn.transaction_started, False)
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 setUp(self): 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 _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 render_object(obj, path, where, append_html=True, output_root='', raise_errors=False): path = path.strip('/') assert '..' not in path outputfile = os.path.join(where, path) outputdir = os.path.dirname(outputfile) environ = {'SERVER_NAME': 'localhost', 'SERVER_PORT': '80'} stdin = StringIO() response = Response(stdout=sys.stdout, stderr=sys.stderr) request = Request(stdin, environ, response) if output_root: request['SERVER_URL'] = relpath(output_root, outputdir) setDefaultSkin(request) app = Application().__of__(RequestContainer(REQUEST=request)) obj = obj.__of__(app) request.other['VirtualRootPhysicalPath'] = obj.getPhysicalPath() obj = obj.unrestrictedTraverse(path) if getattr(obj, 'index_html', None) is not None: obj = obj.index_html try: result = mapply(obj, request.args, request) except Exception, e: print >> sys.stderr, "cannot render %s: %s: %s" % ( path, e.__class__.__name__, e) if raise_errors: raise
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 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 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 _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(): 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 _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 _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): import io 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 = io.BytesIO() 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.ascii_letters.encode('ascii') 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 Exception: self.connection.close() raise
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'