def test_non_conflicting_name_extensions2(self): # Verifies that FSConnection can write to 'script0.py' and 'script0' # at the same time conn = self.db.open() try: app = conn.root()['Application'] f = Folder() f.id = 'folder' app._setObject(f.id, f, set_owner=0) # It's OK to write to 'script0.py' then 'script0'. script = PythonScript('script0.py') script.write('##title=test script\nreturn "OK"') f._setObject(script.id, script, set_owner=0) script = PythonScript('script0') script.write('##title=test script\nreturn "Hello, world!"') f._setObject(script.id, script, set_owner=0) transaction.commit() conn2 = self.db.open() try: app = conn2.root()['Application'] f = app.folder self.assertEqual(f['script0.py'](), 'OK') self.assertEqual(f['script0'](), 'Hello, world!') finally: conn2.close() finally: conn.close()
def test_non_conflicting_name_extensions1(self): # Verifies that FSConnection can write to 'script0.py' then 'script0' conn = self.db.open() try: app = conn.root()['Application'] f = Folder() f.id = 'folder' app._setObject(f.id, f, set_owner=0) # It's OK to write to 'script0.py' then 'script0'. script = PythonScript('script0.py') script.write('##title=test script\nreturn "OK"') f._setObject(script.id, script, set_owner=0) transaction.commit() script = PythonScript('script0') script.write('##title=test script\nreturn "Hello, world!"') f._setObject(script.id, script, set_owner=0) transaction.commit() dir = os.path.join(self.conn.basepath, 'folder') names = os.listdir(dir) self.assert_(('script0.py') in names, names) self.assert_(('script0') in names, names) conn2 = self.db.open() try: app = conn2.root()['Application'] f = app.folder self.assertEqual(f['script0.py'](), 'OK') self.assertEqual(f['script0'](), 'Hello, world!') finally: conn2.close() finally: conn.close()
def test_constructContent_simple_STI(self): from AccessControl import Unauthorized from AccessControl.SecurityManagement import newSecurityManager from AccessControl.SecurityManager import setSecurityPolicy from Products.CMFCore.PortalFolder import PortalFolder from Products.CMFCore.TypesTool \ import ScriptableTypeInformation as STI from Products.CMFCore.tests.base.dummy import DummyFactoryDispatcher from Products.CMFCore.tests.base.tidata import STI_SCRIPT from Products.PythonScripts.PythonScript import PythonScript site = self._makeSite().__of__(self.root) acl_users = site.acl_users setSecurityPolicy(self._oldPolicy) newSecurityManager(None, acl_users.all_powerful_Oz) tool = self._makeOne().__of__(site) sti_baz = STI('Baz', permission='Add portal content', constructor_path='addBaz') tool._setObject('Baz', sti_baz) script = PythonScript('addBaz') script.write(STI_SCRIPT) tool._setObject('addBaz', script) folder = site._setObject( 'folder', PortalFolder(id='folder') ) folder.manage_addProduct = {'FooProduct': DummyFactoryDispatcher(folder) } folder._owner = (['acl_users'], 'user_foo') self.assertEqual( folder.getOwner(), acl_users.user_foo ) try: tool.constructContent('Baz', container=folder, id='page2') except Unauthorized: self.fail('CMF Collector issue #165 (Ownership bug): ' 'Unauthorized raised' ) self.assertEqual(folder.page2.portal_type, 'Baz')
def _newPS(self, txt, bind=None): from Products.PythonScripts.PythonScript import PythonScript ps = PythonScript('ps') #ps.ZBindings_edit(bind or {}) ps.write(txt) ps._makeFunction() return ps
def _createObjectByType( self, name, body, content_type ): if isinstance( body, unicode ): encoding = self.getEncoding() if encoding is None: body = body.encode() else: body = body.encode( encoding ) if name.endswith('.py'): ob = PythonScript( name ) ob.write( body ) elif name.endswith('.dtml'): ob = DTMLDocument( '', __name__=name ) ob.munge( body ) elif content_type in ('text/html', 'text/xml' ): ob = ZopePageTemplate( name, body , content_type=content_type ) elif content_type[:6]=='image/': ob=Image( name, '', body, content_type=content_type ) else: ob=File( name, '', body, content_type=content_type ) return ob
def _initDCWorkflowScripts( workflow, scripts, context ): """ Initialize DCWorkflow scripts """ for s_info in scripts: id = str( s_info[ 'script_id' ] ) # no unicode! meta_type = s_info[ 'meta_type' ] filename = s_info[ 'filename' ] file = '' if filename: file = context.readDataFile( filename ) if meta_type == PythonScript.meta_type: script = PythonScript( id ) script.write( file ) elif meta_type == ExternalMethod.meta_type: script = ExternalMethod( id , '' , s_info['module'] , s_info['function'] ) elif meta_type == DTMLMethod.meta_type: script = DTMLMethod( file, __name__=id ) if workflow.scripts.has_key(id): workflow.scripts._delObject(id) workflow.scripts._setObject( id, script )
def _createObjectByType(self, name, body, content_type): encoding = self.getEncoding() or 'utf-8' if six.PY2 and isinstance(body, six.text_type): body = body.encode(encoding) if name.endswith('.py'): ob = PythonScript(name) ob.write(body) return ob if name.endswith('.dtml'): ob = DTMLDocument('', __name__=name) ob.munge(body) return ob if content_type in ('text/html', 'text/xml'): return ZopePageTemplate(name, body, content_type=content_type) if isinstance(body, six.text_type): body = body.encode(encoding) if content_type[:6] == 'image/': return Image(name, '', body, content_type=content_type) return File(name, '', body, content_type=content_type)
def test_renameObjectByPaths_postonly(self): from Products.PythonScripts.PythonScript import PythonScript script = PythonScript('script') script._filepath = 'script' src = """context.plone_utils.renameObjectsByPaths(paths=['/plone/news'], new_ids=['news'], new_titles=['EVIL'], REQUEST=context.REQUEST)""" script.write(src) self.portal.evil = script csrf_token = self._get_authenticator() self.publish('/plone/evil', extra={'_authenticator': csrf_token}, request_method='POST') self.assertEqual('News', self.portal.news.Title()) owner_basic = ptc.portal_owner + ':' + ptc.default_password csrf_token = self._get_authenticator(owner_basic) self.publish('/plone/evil', extra={'_authenticator': csrf_token}, basic=owner_basic) self.assertEqual('News', self.portal.news.Title()) self.publish('/plone/evil', request_method='POST', extra={'_authenticator': csrf_token}, basic=owner_basic) self.assertEqual('EVIL', self.portal.news.Title()) self.setRoles(['Manager']) self.portal.news.setTitle('News') self.portal.plone_utils.renameObjectsByPaths(paths=['/plone/news'], new_ids=['news'], new_titles=['EVIL']) self.assertEqual('EVIL', self.portal.news.Title()) self.portal.news.setTitle('News') self.setRoles(['Member']) self.portal.plone_utils.renameObjectsByPaths(paths=['/plone/news'], new_ids=['news'], new_titles=['EVIL']) self.assertEqual('News', self.portal.news.Title())
def _createObjectByType( self, name, body, content_type ): if name.endswith('.py'): ob = PythonScript( name ) ob.write( body ) elif name.endswith('.dtml'): ob = DTMLDocument( '', __name__=name ) ob.munge( body ) elif content_type in ('text/html', 'text/xml' ): ob = ZopePageTemplate( name, str( body ) , content_type=content_type ) elif content_type[:6]=='image/': ob=Image( name, '', body, content_type=content_type ) else: ob=File( name, '', body, content_type=content_type ) return ob
def migrate_to_1_12(db): """ Convert resources script lib File into PythonScript and Image """ libs = db.resources.objectValues('File') for lib in libs: lib_id = lib.id() lib_data = lib.data content_type = lib.getContentType() if 'image' in content_type: db.resources.manage_delObjects(lib_id) lib_id = manage_addImage(db.resources, lib_id, lib_data) else: error_re = re.compile('^## Errors:$', re.MULTILINE) ps = PythonScript('testing') try: lib_data = asUnicode(lib_data) except UnicodeDecodeError, e: logger.info("Unknown encoding, skipping: %s" % lib_id) continue ps.write(lib_data) if not error_re.search(ps.read()): db.resources.manage_delObjects(lib_id) ignored = manage_addPythonScript(db.resources, lib_id) sc = db.resources._getOb(lib_id) sc.write(lib_data) logger.info("Converted to Script: %s" % lib_id) continue
def test_python_script(self, with_proxy_roles=0): conn = self.db.open() try: app = conn.root()['Application'] script = PythonScript('script') script.write('##title=test script\nreturn "OK"') script._makeFunction() app._setObject(script.id, script, set_owner=0) if with_proxy_roles: # set a proxy role and verify nothing breaks script._proxy_roles = ('System Administrator',) transaction.commit() conn2 = self.db.open() try: app = conn2.root()['Application'] script = app.script self.assertEqual(script.title, 'test script') res = script() self.assertEqual(res, 'OK') finally: conn2.close() finally: conn.close()
def test_renameObjectByPaths_postonly(self): from Products.PythonScripts.PythonScript import PythonScript script = PythonScript("script") script._filepath = "script" src = """context.plone_utils.renameObjectsByPaths(paths=['/plone/news'], new_ids=['news'], new_titles=['EVIL'], REQUEST=context.REQUEST)""" script.write(src) self.portal.evil = script csrf_token = self._get_authenticator() self.publish("/plone/evil", extra={"_authenticator": csrf_token}, request_method="POST") self.assertEqual("News", self.portal.news.Title()) owner_basic = SITE_OWNER_NAME + ":" + SITE_OWNER_PASSWORD csrf_token = self._get_authenticator(owner_basic) self.publish("/plone/evil", extra={"_authenticator": csrf_token}, basic=owner_basic) self.assertEqual("News", self.portal.news.Title()) self.publish("/plone/evil", request_method="POST", extra={"_authenticator": csrf_token}, basic=owner_basic) self.assertEqual("EVIL", self.portal.news.Title()) self.setRoles(["Manager"]) self.portal.news.setTitle("News") self.portal.plone_utils.renameObjectsByPaths(paths=["/plone/news"], new_ids=["news"], new_titles=["EVIL"]) self.assertEqual("EVIL", self.portal.news.Title()) self.portal.news.setTitle("News") self.setRoles(["Member"]) self.portal.plone_utils.renameObjectsByPaths(paths=["/plone/news"], new_ids=["news"], new_titles=["EVIL"]) self.assertEqual("News", self.portal.news.Title())
def test_preserve_names_with_extensions(self): # Verifies that FSConnection retains original object names # even though the object names already have extensions. conn = self.db.open() try: app = conn.root()['Application'] f = Folder() f.id = 'folder' app._setObject(f.id, f, set_owner=0) for n in range(3): script = PythonScript('script%d.py' % n) script.write('##title=test script\nreturn "OK"') f._setObject(script.id, script, set_owner=0) transaction.commit() conn2 = self.db.open() try: app = conn2.root()['Application'] f = app.folder for n in range(3): self.assert_(hasattr(f, 'script%d.py' % n)) self.assert_(not hasattr(f, 'script%d' % n)) # white box test: verify the scripts were actually stored # with .py extensions. dir = os.path.join(self.conn.basepath, 'folder') names = os.listdir(dir) for n in range(3): self.assert_(('script%d.py' % n) in names, names) finally: conn2.close() finally: conn.close()
def _write(self, text, compile): ''' Parses the source, storing the body, params, title, bindings, and source in self. If compile is set, compiles the function. ''' ps = PythonScript(self.id) ps.write(text) if compile: ps._makeFunction(1) self._v_f = f = ps._v_f if f is not None: self.func_code = f.func_code self.func_defaults = f.func_defaults else: # There were errors in the compile. # No signature. self.func_code = bad_func_code() self.func_defaults = None self._body = ps._body self._params = ps._params if not self.title: self.title = ps.title self._setupBindings(ps.getBindingAssignments().getAssignedNames()) self._source = ps.read() # Find out what the script sees.
def createPythonScript(self, id_, title, code): """Creare new Python Script object.""" ps = PythonScript(id_) if title: ps.ZPythonScript_setTitle(title) ps.write(code) ps._makeFunction() return ps
def manage_addZClass(self, id, title='', baseclasses=[], meta_type='', CreateAFactory=0, REQUEST=None, zope_object=0): """Add a Z Class """ if bad_id(id) is not None: raise 'Bad Request', ( 'The id %s is invalid as a class name.' % id) if not meta_type: meta_type=id r={} for data in self.aq_acquire('_getProductRegistryData')('zclasses'): r['%(product)s/%(id)s' % data]=data['meta_class'] bases=[] for b in baseclasses: if Products.meta_classes.has_key(b): bases.append(Products.meta_classes[b]) elif r.has_key(b): bases.append(r[b]) else: raise 'Invalid class', b Z=ZClass(id, title, bases, zope_object=zope_object) Z._zclass_.meta_type=meta_type self._setObject(id, Z) if CreateAFactory and meta_type: self.manage_addDTMLMethod( id+'_addForm', id+' constructor input form', addFormDefault % {'id': id, 'meta_type': meta_type}, ) constScript = PythonScript(id+'_add') constScript.write(addDefault % {'id': id, 'title':id+' constructor'}) self._setObject(constScript.getId(), constScript) self.manage_addPermission( id+'_add_permission', id+' constructor permission', 'Add %ss' % meta_type ) self.manage_addPrincipiaFactory( id+'_factory', id+' factory', meta_type, id+'_addForm', 'Add %ss' % meta_type ) Z=self._getOb(id) Z.propertysheets.permissions.manage_edit( selected=['Add %ss' % id]) Z.manage_setPermissionMapping( permission_names=['Create class instances'], class_permissions=['Add %ss' % meta_type] ) if REQUEST is not None: return self.manage_main(self,REQUEST, update_menu=1)
def Base_runPythonScript(self, code): script = PythonScript('Python Shell Script').__of__(self) code_line_list = code.split('\r\n') code = '\n'.join(code_line_list) script.write(code) if script._code is None: raise ValueError, repr(script.errors) return script()
def compileFormulaScript(self, script_id, formula, with_args=False): # disable CSRF to allow script saving if hasattr(self, "REQUEST"): alsoProvides(self.REQUEST, IDisableCSRFProtection) # Remember the current user member = self.getCurrentMember() if member.__class__.__name__ == "SpecialUser": user = member else: user = member.getUser() # Switch to the db's owner (formula must be compiled with the higher # access rights, but their execution will always be perform with the # current access rights) owner = self.getOwner() newSecurityManager(None, owner) ps = self.getFormulaScript(script_id) if not ps: ps = PythonScript(script_id) self.scripts._setObject(script_id, ps) ps = self.getFormulaScript(script_id) if with_args: ps._params = "*args" safe_utils = get_utils() import_list = [] for module in safe_utils: import_list.append( "from %s import %s" % ( module, ", ".join(safe_utils[module])) ) import_list = ";".join(import_list) formula = _expandIncludes(self, formula) if (formula.strip().count('\n') == 0 and not formula.startswith('return ')): formula = "return " + formula str_formula = STR_FORMULA % { 'script_id': script_id, 'import_list': import_list, 'formula': formula } ps.write(str_formula) if self.debugMode: logger.info(script_id + " compiled") # Switch back to the original user newSecurityManager(None, user) return ps
def _write(self, text): ps = PythonScript(self.id) ps.write(text) ps._makeFunction() ps._editedBindings() self._v_f = f = ps._v_f self._body = ps._body self._params = ps._params fc = f.func_code self._setFuncSignature(f.func_defaults, fc.co_varnames, fc.co_argcount)
def register_script_object(self, object_name): file_path = '%s/%s.py' % (self.scripts_home, object_name) try: content = open(file_path).read() if not content: raise CustomError('Empty file : %s' % file_path) content = content % {'libplugin_id' : self.config['id']} script_ob = PythonScript(object_name) script_ob.write(content) self.folder._setObject(object_name, script_ob) except Exception, err: LOG('', ERROR, err)
def _customizeScript(self,scriptName,params=""): message="" if not(scriptName in self.objectIds()): # if no scriptname script in current form manager defaultscript = getattr(self,scriptName) # gets the first script acquired scriptBody = defaultscript.body() script = PythonScript(scriptName) script.ZPythonScript_edit(params=params,body=scriptBody) script.write(scriptBody) self._setObject(scriptName,script) message+="portal_status_message=custom "+scriptName+" has been added"+scriptBody return message
def manage_addZClass(self, id, title="", baseclasses=[], meta_type="", CreateAFactory=0, REQUEST=None, zope_object=0): """Add a Z Class """ if bad_id(id) is not None: raise BadRequest, ("The id %s is invalid as a class name." % id) if not meta_type: meta_type = id r = {} for data in self.aq_acquire("_getProductRegistryData")("zclasses"): r["%(product)s/%(id)s" % data] = data["meta_class"] bases = [] for b in baseclasses: if Products.meta_classes.has_key(b): bases.append(Products.meta_classes[b]) elif r.has_key(b): bases.append(r[b]) else: raise ValueError, "Invalid class: %s" % b Z = ZClass(id, title, bases, zope_object=zope_object) Z._zclass_.meta_type = meta_type self._setObject(id, Z) if CreateAFactory and meta_type: self.manage_addDTMLMethod( id + "_addForm", id + " constructor input form", addFormDefault % {"id": id, "meta_type": meta_type} ) constScript = PythonScript(id + "_add") constScript.write(addDefault % {"id": id, "title": id + " constructor"}) self._setObject(constScript.getId(), constScript) self.manage_addPermission(id + "_add_permission", id + " constructor permission", "Add %ss" % meta_type) self.manage_addPrincipiaFactory( id + "_factory", id + " factory", meta_type, id + "_addForm", "Add %ss" % meta_type ) Z = self._getOb(id) Z.propertysheets.permissions.manage_edit(selected=["Add %ss" % id]) Z.manage_setPermissionMapping( permission_names=["Create class instances"], class_permissions=["Add %ss" % meta_type] ) if REQUEST is not None: return self.manage_main(self, REQUEST, update_menu=1)
def manage_doCustomize(self, folder_path, body=None, RESPONSE=None): ''' Makes a PythonScript with the same code. ''' custFolder = self.getCustomizableObject() fpath = tuple(split(folder_path, '/')) folder = self.restrictedTraverse(fpath) if body is None: body = self.read() id = self.getId() obj = PythonScript(id) folder._verifyObjectPaste(obj, validate_src=0) folder._setObject(id, obj) obj = folder._getOb(id) obj.write(body) if RESPONSE is not None: RESPONSE.redirect('%s/%s/manage_main' % ( folder.absolute_url(), id))
def _write(self, text, compile): ''' Parses the source, storing the body, params, title, bindings, and source in self. If compile is set, compiles the function. ''' ps = PythonScript(self.id) ps.write(text) if compile: ps._makeFunction() self._v_ft = ps._v_ft self.func_code = ps.func_code self.func_defaults = ps.func_defaults self._body = ps._body self._params = ps._params self.title = ps.title self._setupBindings(ps.getBindingAssignments().getAssignedNames()) self._source = ps.read() # Find out what the script sees.
def _initDCWorkflowScripts( workflow, scripts, context ): """ Initialize DCWorkflow scripts """ for s_info in scripts: id = str( s_info[ 'script_id' ] ) # no unicode! meta_type = s_info[ 'meta_type' ] filename = s_info[ 'filename' ] file = '' if filename: file = context.readDataFile( filename ) if meta_type == PythonScript.meta_type: script = PythonScript( id ) script.write( file ) elif meta_type == ExternalMethod.meta_type: script = ExternalMethod( id , '' , s_info['module'] , s_info['function'] ) elif meta_type == DTMLMethod.meta_type: script = DTMLMethod( file, __name__=id ) else: for mt in workflow.scripts.filtered_meta_types(): if mt['name']==meta_type: if hasattr(mt['instance'], 'write'): script = mt['instance'](id) script.write(file) else: script = mt['instance'](file, __name__=id) break else: raise ValueError, 'Invalid type: %s' % meta_type if workflow.scripts.has_key(id): workflow.scripts._delObject(id) workflow.scripts._setObject( id, script )
def test_resource_registry_vector(self): for vector in ('less-variables.js', 'less-modify.js'): src = ''' class ctx: def format(self, *args, **kwargs): self.foo=context return "foo" context.portal_registry['plone.lessvariables']['foo'] = ctx() context.portal_registry['plone.lessvariables']['bar'] = "{foo.foo.__class__}" js = context.restrictedTraverse("%s") return js() ''' % vector from Products.PythonScripts.PythonScript import PythonScript script = PythonScript('evil') script._filepath = 'evil' script.write(src) self.portal.evil = script output = self.publish('/plone/evil') self.assertFalse( 'Products.CMFPlone.Portal.PloneSite' in output.body)
def _initDCWorkflowScripts(workflow, scripts, context): """ Initialize DCWorkflow scripts """ for s_info in scripts: id = str(s_info['script_id']) # no unicode! meta_type = s_info['meta_type'] filename = s_info['filename'] file = context.readDataFile(filename) if meta_type == PythonScript.meta_type: script = PythonScript(id) script.write(file) #elif meta_type == ExternalMethod.meta_type: # script = ExternalMethod( id, title, module, function ) elif meta_type == DTMLMethod.meta_type: script = DTMLMethod(file, __name__=id) workflow.scripts._setObject(id, script)
def _initDCWorkflowScripts(workflow, scripts, context): """ Initialize DCWorkflow scripts """ for s_info in scripts: id = str(s_info['script_id']) # no unicode! meta_type = s_info['meta_type'] filename = s_info['filename'] file = '' if filename: file = context.readDataFile(filename) if meta_type == PythonScript.meta_type: script = PythonScript(id) script.write(file) elif meta_type == ExternalMethod.meta_type: script = ExternalMethod(id, '', s_info['module'], s_info['function']) elif meta_type == DTMLMethod.meta_type: script = DTMLMethod(file, __name__=id) else: for mt in workflow.scripts.filtered_meta_types(): if mt['name'] == meta_type: if hasattr(mt['instance'], 'write'): script = mt['instance'](id) script.write(file) else: script = mt['instance'](file, __name__=id) break else: raise ValueError, 'Invalid type: %s' % meta_type if workflow.scripts.has_key(id): workflow.scripts._delObject(id) workflow.scripts._setObject(id, script)
def test_auto_rename_on_extension_conflict(self): # When you create a Python Script called "script0", Ape adds a # .py extension. If, in a second transaction, you add # "script0.py", Ape must rename the current "script0.py" to # "script0" to make room for the new "script0.py". conn = self.db.open() try: app = conn.root()['Application'] f = Folder() f.id = 'folder' app._setObject(f.id, f, set_owner=0) # Can't write to 'script0' then 'script0.py'. script = PythonScript('script0') script.write('##title=test script\nreturn "OK"') f._setObject(script.id, script, set_owner=0) transaction.commit() dir = os.path.join(self.conn.basepath, 'folder') names = os.listdir(dir) self.assert_(('script0.py') in names, names) self.assert_(('script0') not in names, names) # script0.py already exists, so Ape should automatically rename. script = PythonScript('script0.py') script.write('##title=test script\nreturn "Hello, world!"') f._setObject(script.id, script, set_owner=0) transaction.commit() # Did it write them correctly? text = open(os.path.join(dir, 'script0')).read() self.assert_(text.find('OK') > 0, text) self.assert_(text.find('Hello, world!') < 0, text) text = open(os.path.join(dir, 'script0.py')).read() self.assert_(text.find('OK') < 0, text) self.assert_(text.find('Hello, world!') > 0, text) finally: conn.close()
def _write(self, text, compile): ''' Parses the source, storing the body, params, title, bindings, and source in self. If compile is set, compiles the function. ''' ps = PythonScript(self.id) ps.write(text) if compile: ps._makeFunction(1) self._v_f = f = ps._v_f if f is not None: self.func_code = f.func_code self.func_defaults = f.func_defaults else: # There were errors in the compile. # No signature. self.func_code = bad_func_code() self.func_defaults = None self._body = ps._body self._params = ps._params self.title = ps.title self._setupBindings(ps.getBindingAssignments().getAssignedNames()) self._source = ps.read() # Find out what the script sees.
def _createObjectByType(self, name, body, content_type): if name.endswith('.py'): ob = PythonScript(name) ob.write(body) elif name.endswith('.dtml'): ob = DTMLDocument('', __name__=name) ob.munge(body) elif content_type in ('text/html', 'text/xml'): ob = ZopePageTemplate(name, str(body), content_type=content_type) elif content_type[:6] == 'image/': ob = Image(name, '', body, content_type=content_type) else: ob = File(name, '', body, content_type=content_type) return ob
def test_constructContent_simple_STI(self): from AccessControl import Unauthorized from AccessControl.SecurityManagement import newSecurityManager from AccessControl.SecurityManager import setSecurityPolicy from Products.CMFCore.PortalFolder import PortalFolder from Products.CMFCore.TypesTool \ import ScriptableTypeInformation as STI from Products.CMFCore.tests.base.dummy import DummyFactoryDispatcher from Products.CMFCore.tests.base.tidata import STI_SCRIPT from Products.PythonScripts.PythonScript import PythonScript site = self._makeSite().__of__(self.root) acl_users = site.acl_users setSecurityPolicy(self._oldPolicy) newSecurityManager(None, acl_users.all_powerful_Oz) tool = self._makeOne().__of__(site) sti_baz = STI('Baz', permission='Add portal content', constructor_path='addBaz') tool._setObject('Baz', sti_baz) script = PythonScript('addBaz') script.write(STI_SCRIPT) tool._setObject('addBaz', script) folder = site._setObject('folder', PortalFolder(id='folder')) folder.manage_addProduct = { 'FooProduct': DummyFactoryDispatcher(folder) } folder._owner = (['acl_users'], 'user_foo') self.assertEqual(folder.getOwner(), acl_users.user_foo) try: tool.constructContent('Baz', container=folder, id='page2') except Unauthorized: self.fail('CMF Collector issue #165 (Ownership bug): ' 'Unauthorized raised') self.assertEqual(folder.page2.portal_type, 'Baz')
def _newPS(self, txt, bind=None): from Products.PythonScripts.PythonScript import PythonScript ps = PythonScript('ps') ps.write(txt) ps._makeFunction() return ps
def manage_addZClass(self, id, title='', baseclasses=[], meta_type='', CreateAFactory=0, REQUEST=None, zope_object=0): """Add a Z Class """ if bad_id(id) is not None: raise BadRequest, ('The id %s is invalid as a class name.' % id) if not meta_type: meta_type = id r = {} for data in self.aq_acquire('_getProductRegistryData')('zclasses'): r['%(product)s/%(id)s' % data] = data['meta_class'] bases = [] for b in baseclasses: if Products.meta_classes.has_key(b): bases.append(Products.meta_classes[b]) elif r.has_key(b): bases.append(r[b]) else: raise ValueError, 'Invalid class: %s' % b Z = ZClass(id, title, bases, zope_object=zope_object) Z._zclass_.meta_type = meta_type self._setObject(id, Z) if CreateAFactory and meta_type: self.manage_addDTMLMethod( id + '_addForm', id + ' constructor input form', addFormDefault % { 'id': id, 'meta_type': meta_type }, ) constScript = PythonScript(id + '_add') constScript.write(addDefault % { 'id': id, 'title': id + ' constructor' }) self._setObject(constScript.getId(), constScript) self.manage_addPermission(id + '_add_permission', id + ' constructor permission', 'Add %ss' % meta_type) self.manage_addPrincipiaFactory(id + '_factory', id + ' factory', meta_type, id + '_addForm', 'Add %ss' % meta_type) Z = self._getOb(id) Z.propertysheets.permissions.manage_edit(selected=['Add %ss' % id]) Z.manage_setPermissionMapping( permission_names=['Create class instances'], class_permissions=['Add %ss' % meta_type]) if REQUEST is not None: return self.manage_main(self, REQUEST, update_menu=1)
def _createZODBClone(self): """Create a ZODB (editable) equivalent of this object.""" obj = PythonScript(self.getId()) obj.write(self.read()) return obj
def load_py(filename): id = os.path.basename(filename) ob = PythonScript(id) ob.write(file(filename).read()) return ob
def _testScript(self,txt): theScript = PythonScript('test') theScript.ZBindings_edit({}) theScript.write(txt) theScript._makeFunction() return theScript()
def test_non_conflicting_name_extensions3(self): # Verifies that FSConnection can write to 'script0.py' # then 'script0.dtml', then 'script0'. # Then verifies that removal of items works correctly. conn = self.db.open() try: app = conn.root()['Application'] f = Folder() f.id = 'folder' app._setObject(f.id, f, set_owner=0) script = PythonScript('script0.py') script.write('##title=test script\nreturn "OK"') f._setObject(script.id, script, set_owner=0) transaction.commit() script = PythonScript('script0.dtml') script.write('##title=test script\nreturn "No DTML here"') f._setObject(script.id, script, set_owner=0) transaction.commit() script = PythonScript('script0') script.write('##title=test script\nreturn "Hello, world!"') f._setObject(script.id, script, set_owner=0) transaction.commit() dir = os.path.join(self.conn.basepath, 'folder') names = os.listdir(dir) self.assert_(('script0.py') in names, names) self.assert_(('script0.dtml') in names, names) self.assert_(('script0') in names, names) conn2 = self.db.open() try: app2 = conn2.root()['Application'] f2 = app2.folder self.assertEqual(f2['script0.py'](), 'OK') self.assertEqual(f2['script0.dtml'](), 'No DTML here') self.assertEqual(f2['script0'](), 'Hello, world!') finally: transaction.abort() conn2.close() f._delObject('script0.py') transaction.commit() names = os.listdir(dir) self.assert_(('script0.py') not in names, names) self.assert_(('script0.dtml') in names, names) self.assert_(('script0') in names, names) f._delObject('script0') transaction.commit() names = os.listdir(dir) self.assert_(('script0.py') not in names, names) self.assert_(('script0.dtml') in names, names) self.assert_(('script0') not in names, names) script = PythonScript('script0') script.write('##title=test script\nreturn "Hello, world!"') f._setObject(script.id, script, set_owner=0) transaction.commit() names = os.listdir(dir) self.assert_(('script0.py') not in names, names) self.assert_(('script0.dtml') in names, names) self.assert_(('script0') in names, names) f._delObject('script0.dtml') transaction.commit() names = os.listdir(dir) self.assert_(('script0.py') not in names, names) self.assert_(('script0.dtml') not in names, names) self.assert_(('script0') in names, names) finally: conn.close()
def evaluate(self): python_script = PythonScript('update_script_runner').__of__(self) python_script.write(self.update_script) return python_script()