def testTwoRequests(self): s1 = getattr(self, 's1') survey_id = s1.getSurveyId() app = makerequest(self.app) app.REQUEST.form['stq1'] = 'An answer' dummy_controller_state = ControllerState( id='survey_view', context=s1, button='submit', status='success', errors={}, next_action=None,) controller = self.portal.portal_form_controller controller_state = controller.validate(dummy_controller_state, app.REQUEST, ['validate_survey',]) assert controller_state.getErrors() == {}, "Validation error raised" app = makerequest(self.app) app.REQUEST.form['stq2'] = 'Another answer' app.REQUEST.form['survey_user_id'] = s1.getRespondents()[0] dummy_controller_state = ControllerState( id='survey_view', context=s1.ss1, button='submit', status='success', errors={}, next_action=None,) controller = self.portal.portal_form_controller controller_state = controller.validate(dummy_controller_state, app.REQUEST, ['validate_survey',]) assert controller_state.getErrors() == {}, "Validation error raised" respondents = s1.getRespondents() assert len(respondents) == 1, respondents
def test__OldCacheHeaders(self): from Products.CMFCore.utils import _OldCacheHeaders _FILE_MOD_TIME = 1000000000 _FILE_RFC_DATE = rfc1123_date(_FILE_MOD_TIME) class Obj(Implicit): def modified(self): return DateTime(_FILE_MOD_TIME) # date < _file_mod_time env = {'HTTP_IF_MODIFIED_SINCE': rfc1123_date(_FILE_MOD_TIME - 1)} obj = makerequest(Obj(), environ=env) _OldCacheHeaders(obj) self.assertEqual(obj.REQUEST.RESPONSE.getHeader('Last-Modified'), _FILE_RFC_DATE) # date > _file_mod_time env = {'HTTP_IF_MODIFIED_SINCE': rfc1123_date(_FILE_MOD_TIME + 1)} obj = makerequest(Obj(), environ=env) _OldCacheHeaders(obj) self.assertEqual(obj.REQUEST.RESPONSE.getHeader('Last-Modified'), None) # invalid date env = {'HTTP_IF_MODIFIED_SINCE': 'Fri, 37 Feb 3121 29:64:46'} obj = makerequest(Obj(), environ=env) _OldCacheHeaders(obj) self.assertEqual(obj.REQUEST.RESPONSE.getHeader('Last-Modified'), _FILE_RFC_DATE)
def export_site(app, options): plone = app.unrestrictedTraverse(options.path, None) if plone is None: raise RuntimeError('Plone site not found (%s)' % options.path) site_id = plone.getId() export_dir = os.path.join(options.output, site_id) if os.path.exists(export_dir): shutil.rmtree(export_dir, ignore_errors=True) os.makedirs(export_dir) log('Exporting Plone site: %s' % options.path) log('Export directory: %s' % os.path.abspath(export_dir)) # app = Zope.app() app = makerequest(app) uf = app.acl_users user = uf.getUser(options.username) if user is None: raise ValueError('Unknown user: %s' % options.username) newSecurityManager(None, user.__of__(uf)) # inject some extra data instead creating our own datastructure options.export_directory = export_dir options.plone = makerequest(plone) # The export show starts here export_groups(options) export_members(options) export_placeful_workflow(options) export_structure(options) export_content(options) log('Export done...releasing memory und Tschuessn')
def setUp(self): handle = self.webdav_handle if handle.exists(PREFIX): handle.removedir(PREFIX, False, True) handle.makedir(PREFIX) self.sample_xml = '{}/index.xml'.format(PREFIX) with handle.open(self.sample_xml, 'wb') as fp: fp.write(sample_xml) self.portal.connector.webdav_subpath = PREFIX makerequest(self.portal)
def main(app, data_dir): _policy=PermissiveSecurityPolicy() _oldpolicy=setSecurityPolicy(_policy) newSecurityManager(None, EvenMoreOmnipotentUser().__of__(app.acl_users)) app = makerequest(app) #uninstallProducts(app.plone) logger.info('Generating collections list') generateCollectionsList(app.plone, data_dir) logger.info('Generating modules list') generateModulesList(app.plone, data_dir) logger.info('Deleting groups') cleanoutGroups(app.plone, data_dir) transaction.savepoint(optimistic=True) logger.info('Deleting lenses') cleanoutLenses(app.plone, data_dir) transaction.savepoint(optimistic=True) logger.info('Deleting content') cleanoutRhaptosContent(app.plone, data_dir) transaction.savepoint(optimistic=True) logger.info('Deleting users') cleanoutUsers(app.plone, data_dir) transaction.savepoint(optimistic=True) postCleanoutPopularity(app.plone, data_dir) transaction.savepoint(optimistic=True) app.plone.portal_catalog.refreshCatalog(clear=1) transaction.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. transaction.savepoint(optimistic=True) except: self.connection.close() raise return self.app._getOb( 'folder1' ), self.app._getOb( 'folder2' )
def setUp(self): get_transaction().begin() self.app = makerequest(Zope.app()) # Log in as a god :-) newSecurityManager( None, UnrestrictedUser('god', 'god', ['Manager'], '') ) app = self.app app.REQUEST.set('URL1','http://foo/sorcerertest/test') try: app._delObject('CalendarTest') except AttributeError: pass app.manage_addProduct['CMFDefault'].manage_addCMFSite('CalendarTest') self.Site = app.CalendarTest manage_addExternalMethod(app.CalendarTest, id='install_events', title="Install Events", module="CMFCalendar.Install", function="install") ExMethod = app.restrictedTraverse('/CalendarTest/install_events') ExMethod() self.Tool = app.restrictedTraverse('/CalendarTest/portal_calendar') # sessioning bodge until we find out how to do this properly self.have_session = hasattr( app, 'session_data_manager' ) if self.have_session: app.REQUEST.set_lazy( 'SESSION' , app.session_data_manager.getSessionData )
def setUp(self): """ """ portal = makerequest(self.layer['portal']) self.request = portal.REQUEST alsoProvides(self.request, IPloneintranetDocconvClientLayer) setRoles(portal, TEST_USER_ID, ('Manager',)) gsettings = GlobalSettings(portal) self.storage_dir = mkdtemp() gsettings.storage_location = self.storage_dir # temporarily disable event handler so that we can test objects without # previews from ploneintranet.docconv.client import handlers _update_preview_images = handlers._update_preview_images handlers._update_preview_images = lambda obj, event: None self.workspace = api.content.create( type='Folder', title=u"Docconv Workspace", container=portal) ff = open(os.path.join(os.path.dirname(__file__), TEST_FILENAME), 'r') self.filedata = ff.read() ff.close() self.testfile = api.content.create( type='File', id='test-file', title=u"Test File", file=NamedBlobFile(data=self.filedata, filename=TEST_FILENAME), container=self.workspace) handlers._update_preview_images = _update_preview_images event.notify(BeforeTraverseEvent(portal, portal.REQUEST))
def main(app, id, title, dbauser, dbuser, dbname, dbserver, dbport): _policy=PermissiveSecurityPolicy() _oldpolicy=setSecurityPolicy(_policy) newSecurityManager(None, EvenMoreOmnipotentUser().__of__(app.acl_users)) app = makerequest(app) # Add Rhaptos Site factory = app.manage_addProduct['RhaptosSite'] factory.manage_addRhaptosSite(id, title=title, description='', dbauser=dbauser, dbapass=None, dbuser=dbuser, dbpass=None, dbname=dbname, dbserver=dbserver, dbport=dbport and int(dbport) or None) # Add Virtual Host Entry app.virtual_hosting.set_map('http://*.cnx.rice.edu/ /'+id+'\nhttp://localhost/ /'+id) # Apply cnx.org styles site = getattr(app, id) site.portal_setup.setImportContext( 'profile-Products.CNXPloneSite:default') site.portal_setup.manage_importSelectedSteps( ['cnx_install'], True, # run_dependencies app.REQUEST.RESPONSE) transaction.commit()
def setUp(self): self._trap_warning_output() transaction.begin() app = self.app = makerequest(Zope2.app()) # Log in as a god :-) newSecurityManager( None, UnrestrictedUser('god', 'god', ['Manager'], '') ) app.manage_addProduct['CMFDefault'].manage_addCMFSite('CalendarTest') self.Site = app.CalendarTest manage_addExternalMethod(app.CalendarTest, id='install_events', title="Install Events", module="CMFCalendar.Install", function="install") ExMethod = app.restrictedTraverse('/CalendarTest/install_events') ExMethod() self.Tool = app.CalendarTest.portal_calendar self.Site.clearCurrentSkin() self.Site.setupCurrentSkin(app.REQUEST) # sessioning setup if getattr(app, 'temp_folder', None) is None: temp_folder = MountedTemporaryFolder('temp_folder') app._setObject('temp_folder', temp_folder) if getattr(app.temp_folder, 'session_data', None) is None: session_data = TransientObjectContainer('session_data') app.temp_folder._setObject('session_data', session_data) app.REQUEST.set_lazy( 'SESSION', app.session_data_manager.getSessionData )
def setUpPloneSite(self, portal): login(portal, TEST_USER_NAME) setRoles(portal, TEST_USER_ID, ['Member', 'Manager',]) request = makerequest(portal.aq_parent).REQUEST # initialise skins support portal.clearCurrentSkin() portal.setupCurrentSkin(request) Products.PloneTestCase.setup._placefulSetUp(portal) self.applyProfile(portal, 'Products.CMFPlone:plone') self.applyProfile(portal, 'Products.CMFPlone:plone-content') self.applyProfile(portal, 'Products.CMFPlone:dependencies') self.applyProfile(portal, 'Products.CMFPlone:testfixture') self.applyProfile(portal, 'plone.app.iterate:plone.app.iterate') self.applyProfile(portal, 'collective.js.jqueryui:default') self.applyProfile(portal, 'bika.lims:default') request.form['submitted'] = 1 request.form['xlsx'] = "test" lsd = LoadSetupData(portal, request) lsd()
def setUp(self): super(ZPTMacros, self).setUp() zope.component.provideAdapter(DefaultTraversable, (None,)) transaction.begin() self.app = makerequest(Zope2.app()) f = self.app.manage_addProduct['PageTemplates'].manage_addPageTemplate self._addPT = f self.title = 'title of page template' self.text = """ <metal:block use-macro="template/macros/themacro"> <p metal:fill-slot="theslot"> This is in the slot </p> </metal:block> <tal:block condition="nothing"> <div metal:define-macro="themacro"> <h1>This is the header</h1> <p metal:define-slot="theslot"> This will be replaced </p> </div> </tal:block> """ self.result = """<div>
def run(self): i = 0 try: while 1: self.conn = self.db.open() self.app = self.conn.root()['Application'] self.app = makerequest.makerequest(self.app) try: self.run1() return except ReadConflictError: #traceback.print_exc() print "R", except BTreesConflictError: print "B", except ConflictError: print "W", except: transaction.abort() print log_time() traceback.print_exc() raise i = i + 1 transaction.abort() self.conn.close() time.sleep(random.randrange(10) * .1) finally: transaction.abort() self.conn.close() del self.app self.finished = 1 print '%s finished' % self.__class__
def test__init__userid_in_request_form_for_manager(self): # should allow for privileged users context = makerequest(SimpleItem('foo')) context.portal_membership = DummyPortalMembership(True) context.REQUEST.form['userid'] = 'bob' adapter = AccountPanelSchemaAdapter(context) self.assertEqual('bob', adapter.context)
def main(app=None, args=None): full_args = args if args is not None: full_args = args + sys.argv[1:] args = parser.parse_args(full_args) if args.upgrade_profiles: args.upgrade_all_profiles = False elif not (args.upgrade_portal or args.upgrade_all_profiles): parser.error('The supplied options would not upgrade any profiles') if app is None: import Zope2 from App import config if config._config is None: if not args.zope_conf: parser.error( 'Must give the "--zope-conf" option when not used as a ' 'zopectl "run" script.') Zope2.configure(args.zope_conf) app = Zope2.app() elif args.zope_conf: parser.error( 'Do not give the "--zope-conf" option when used as a ' 'zopectl "run" script.') root = logging.getLogger() root.setLevel(logging.INFO) stderr_handler, = [h for h in root.handlers if getattr(h, 'stream', None) is sys.__stderr__] stderr_handler.setLevel(logging.INFO) stderr_handler.addFilter(zodbupdate.main.duplicate_filter) log_file = logging.FileHandler(args.log_file) log_file.addFilter(zodbupdate.main.duplicate_filter) log_file.setFormatter(utils.formatter) root.addHandler(log_file) kw = dict( paths=args.portal_paths, upgrade_portal=args.upgrade_portal, upgrade_all_profiles=args.upgrade_all_profiles, upgrade_profiles=args.upgrade_profiles) if args.disable_link_integrity: kw['enable_link_integrity_checks'] = False from AccessControl import SpecialUsers from AccessControl.SecurityManagement import newSecurityManager newSecurityManager(None, SpecialUsers.system) from Testing.makerequest import makerequest app = makerequest(app) runner = app.restrictedTraverse('@@collective.upgrade.form') try: runner.upgrade(**kw) except: transaction.abort() runner.logger.exception('Exception running the upgrades.') pdb.post_mortem(sys.exc_info()[2]) raise
def setUp(self): transaction.begin() self.app = makerequest(Zope2.app()) f = self.app.manage_addProduct['PageTemplates'].manage_addPageTemplate self._addPT = f self.title = 'title of page template' self.text = 'text of page template'
def setUp(self): from Testing import makerequest db = _getDB() conn = db.open() root = conn.root() self.app = makerequest.makerequest(root['Application']) timeout = self.timeout = 1
def test_FTPList(self): from OFS.Folder import Folder om = makerequest(self._makeOne()) om.isTopLevelPrincipiaApplicationObject = True om._setObject('sub', Folder('sub')) om.sub._setObject('subsub', Folder('subsub')) req = om.REQUEST req.PARENTS = [om] # At the root we only see a single entry for the subfolder data = marshal.loads(om.manage_FTPlist(req)) self.assertEqual(len(data), 1) self.assertEqual(data[0][0], 'sub') # In the subfolder, we see an entry for the current folder # and the folder in it data = marshal.loads(om.sub.manage_FTPlist(req)) self.assertEqual(len(data), 2) self.assertEqual(data[0][0], '.') self.assertEqual(data[1][0], 'subsub') # In the leaf node we see entries for the parent and grandparent data = marshal.loads(om.sub.subsub.manage_FTPlist(req)) self.assertEqual(len(data), 2) self.assertEqual(data[0][0], '.') self.assertEqual(data[1][0], '..')
def setup_plone(app, dest_folder, site_id, products=(), profiles=()): app = makerequest(app) dest = app if dest_folder: if dest_folder not in app.objectIds(): log("Creating destination Folder: '%s'" % dest_folder) app.manage_addFolder(id=dest_folder) dest = dest.restrictedTraverse(dest_folder) if site_id in dest.objectIds(): log('%s already exists in %s - REMOVING IT' % (site_id, dest.absolute_url(1))) if dest.meta_type != 'Folder': raise RuntimeError('Destination must be a Folder instance (found %s)' % dest.meta_type) dest.manage_delObjects([site_id]) log('Creating new Plone site with extension profiles %s' % profiles) addPloneSite(dest, site_id, create_userfolder=True, extension_ids=profiles) plone = dest[site_id] log('Created Plone site at %s' % plone.absolute_url(1)) qit = plone.portal_quickinstaller ids = [p['id'] for p in qit.listInstallableProducts(skipInstalled=1) ] for product in products: if product in ids: qit.installProduct(product) if 'front-page' in plone.objectIds(): plone.manage_delObjects('front-page') return plone
def setUp(self): self.portal = self.layer['portal'] login(self.portal, TEST_USER_NAME) setRoles(self.portal, TEST_USER_ID, ['Manager']) self.portal.invokeFactory( 'Folder', id="basefolder", title="Folder Base" ) self.bf = self.portal.basefolder self.bf.reindexObject() for idx in range(0, 5): newid = "f{0:}".format(idx) self.bf.invokeFactory( 'Folder', id=newid, # title in reverse order title="Folder {0:}".format(4-idx) ) self.bf[newid].reindexObject() self.env = {'HTTP_ACCEPT_LANGUAGE': 'en', 'REQUEST_METHOD': 'POST'} self.request = makerequest(self.layer['app']).REQUEST self.request.environ.update(self.env) self.request.form = { 'selection': '["' + IUUID(self.bf) + '"]', '_authenticator': createToken(), 'folder': '/basefolder' } self.request.REQUEST_METHOD = 'POST'
def setUp(self): import transaction self.guarded_getattr = guarded_getattr_py transaction.manager.begin() self.app = makerequest(Zope2.app()) try: # Set up a manager user self.uf = self.app.acl_users self.uf._doAddUser('manager', 'secret', ['Manager'], []) self.login('manager') # Set up objects in the root that we want to aquire self.app.manage_addFolder('plain_folder') self.app._setObject('error_log2', ProtectedSiteErrorLog()) # We also want to be able to acquire simple attributes self.app.manage_addProperty(id='simple_type', type='string', value='a string') # Set up a subfolder and the objects we want to acquire from self.app.manage_addFolder('subfolder') self.folder = self.app.subfolder self.folder._setObject('allowed', AllowedItem()) self.folder._setObject('denied', DeniedItem()) self.folder._setObject('protected', ProtectedItem()) except: self.tearDown() raise
def testQuestionValidates(self): s1 = getattr(self, 's1') app = makerequest(self.app) # add your form variables app.REQUEST.form['stq1'] = 'Text Answer' # set up a dummy state object dummy_controller_state = ControllerState( id='survey_view', context=s1, button='submit', status='success', errors={}, next_action=None,) # get the form controller controller = self.portal.portal_form_controller # send the validate script to the form controller with the dummy state object controller_state = controller.validate(dummy_controller_state, app.REQUEST, ['validate_survey',]) # Do any relevant tests assert controller_state.getErrors() == {}, "Validation error raised" userid = s1.getSurveyId() assert userid == "test_user_1_", "Not default test user" questions = s1.getQuestions() for question in questions: if question.portal_type == 'Survey Text Question': question.addAnswer('Text answer') assert question.getAnswerFor(userid) == 'Text answer', "Answer not saved correctly"
def _install_zope(self, db): """Install a fresh Zope inside the new test DB. Eventually install an application afterwards. """ # Create the "application" newSecurityManager(None, AccessControl.User.system) connection = db.open() root = connection.root() root['Application'] = OFS.Application.Application() app = root['Application'] # Do a savepoint to get a _p_jar on the application transaction.savepoint() # Initialize the "application" try: TestAppInitializer( app, self.products, self.packages, self.users).initialize() self._install_application(makerequest( app, environ={'SERVER_NAME': 'localhost'})) except Exception as error: # There was an error during the application 'setUp'. Abort # the transaction and continue, otherwise test in other # layers might fail because of this failure. transaction.abort() raise error else: # Close transaction.commit() finally: # In any case, close the connection and continue connection.close() noSecurityManager()
def get_application(self): """Return root folder wrapped inside a test request, which is the same object you have when you are working on a real published request. """ return makerequest( self.get_root_folder(), environ={'SERVER_NAME': 'localhost'})
def _setup(app, site=None): """Set up our environment. Create a request, log in as admin and set the traversal hooks on the site. """ from Testing import makerequest # Do not import this at the module level! app = makerequest.makerequest(app) # Login as admin admin = app.acl_users.getUserById('admin') if admin is None: logger.error("No user called `admin` found in the database. " "Use --rootpassword to create one.") sys.exit(1) # Wrap the admin in the right context; from inside the site if we have one if site is not None: admin = admin.__of__(site.acl_users) site = app[site.getId()] else: admin = admin.__of__(app.acl_users) newSecurityManager(None, admin) # Set up local site manager, skins and language if site is not None: setHooks() setSite(site) site.setupCurrentSkin(site.REQUEST) site.REQUEST['HTTP_ACCEPT_LANGUAGE'] = site.Language() return (app, site)
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 setUp( self ): import transaction from zope.component.testing import setUp as componentSetUp from zope.component import provideUtility from zope.component import provideAdapter from zope.traversing.adapters import DefaultTraversable from zope.publisher.http import HTTPCharsets from Testing.ZopeTestCase import ZopeLite from Testing.makerequest import makerequest from Products.PageTemplates.interfaces \ import IUnicodeEncodingConflictResolver from Products.PageTemplates.unicodeconflictresolver \ import PreferredCharsetResolver componentSetUp() provideAdapter(DefaultTraversable, (None,)) provideUtility(PreferredCharsetResolver, IUnicodeEncodingConflictResolver) provideAdapter(HTTPCharsets) transaction.begin() app = ZopeLite.app() self.root = makerequest(app) # set the request charset to enable conversions to utf-8 self.root.REQUEST['HTTP_ACCEPT_CHARSET'] = '*'
def test_execute(self): from Acquisition import Implicit from Testing.makerequest import makerequest from plone.app.z3cform.csrf import AuthenticatedButtonActions from plone.protect import createToken class DummyForm(object): enableCSRFProtection = True class DummyAction(object): def isExecuted(self): return True def execute(self): self.called = True form = DummyForm() request = makerequest(Implicit()).REQUEST request.form['_authenticator'] = createToken() actions = AuthenticatedButtonActions(form, request, None) actions._data['foo'] = action = DummyAction() actions._data_keys = ['foo'] actions._data_values = [action] actions.execute()
def test__init__userid_in_request_form_for_non_manager(self): # disallow for non-privileged users context = makerequest(SimpleItem('foo')) context.portal_membership = DummyPortalMembership(False) context.REQUEST.form['userid'] = 'bob' adapter = AccountPanelSchemaAdapter(context) self.assertEqual('(authenticated)', adapter.context)
def setUpPloneSite(self, portal): login(portal, TEST_USER_NAME) setRoles(portal, TEST_USER_ID, ["Member", "Manager"]) request = makerequest(portal.aq_parent).REQUEST # initialise skins support portal.clearCurrentSkin() portal.setupCurrentSkin(request) Products.PloneTestCase.setup._placefulSetUp(portal) # Installs all the Plone stuff. Workflows etc. self.applyProfile(portal, "Products.CMFPlone:plone") # Install portal content. Including the Members folder! self.applyProfile(portal, "Products.CMFPlone:plone-content") self.applyProfile(portal, "plone.app.iterate:plone.app.iterate") self.applyProfile(portal, "bika.lims:default") xlsx = open(os.path.join(os.path.split(__file__)[0], "tests", "_test.xlsx")) request.form["submitted"] = 1 request.form["xlsx"] = xlsx lsd = LoadSetupData(portal, request) lsd()
def __init__(self, app=None, portal_id="", portal=None): self.folder_map = { "The OSH framework directive": ["1"], "Workplaces, equipment, signs, personal protective equipment/OSH directives": ["21", "9", "4", "3", "2"], "Workplaces, equipment, signs, personal protective equipment/OSH related aspects": [ "council-directive-2006-95", "directive-2006-42-ec-of-the-european-parliament-and-of-the-council", "53", "directive-98-37-ec-of-the-european-parliament-and-of-the-council", "42", "33", "35", "56", "34", "council-directive-89-106-eec", "41", "council-directive-85-374-eec", "39", "38", "37", "36", "40" ], "Exposure to chemical agents and chemical safety/OSH directives": [ "commission-directive-2006-15-ec", "directive.2008-02-07.5735076588", "directive.2008-05-22.7061217851", "75", "28", "25" ], "Exposure to chemical agents and chemical safety/OSH related aspects": [ "directive-2008-68-ec", "regulation-ec-no-1907-2006-of-the-european-parliament-and-of-the-council", "59", "64", "66", "council-directive-91-414-eec", "58" ], "Exposure to physical hazards/OSH directives": [ "directive-2006-25-ec-of-the-european-parliament-and-of-the-council-of-5-april-2006", "directive-2004-40-ec-of-the-european-parliament-and-of-the-council", "82", "19", "73" ], "Exposure to physical hazards/OSH related aspects": [ "council-directive-2009-71-euratom", "council-directive-2004-108-ec", "council-directive-2003-122-euratom", "directive-2000-14-ec", ], "Exposure to biological agents": ["77"], "Provisions on workload, ergonomical and psychosocial risks/OSH directives": ["5", "6"], "Provisions on workload, ergonomical and psychosocial risks/OSH related aspects": [ "directive-2003-88-ec", "directive-2002-15-ec", "council-directive-2000-79-ec" ], "Sector specific and worker related provisions/OSH directives": ["18", "13", "12", "11", "10", "15", "17", "16"], "Sector specific and worker related provisions/OSH related aspects": [ "council-directive-2006-54-ec", "directive.2005-01-03.0697184648", "council-directive-2000-78-ec" ], } # missing: # ['31', 'directive-2001-18-ec-of-the-european-parliament-and-of-the-council'] if portal: self.portal_root = portal self.portal = portal self.portal_path = "/" + portal.id + "/en" else: self.portal_root = app[portal_id] self.portal = makerequest(self.portal_root) self.portal_path = "/" + portal_id + "/en" self.directives_path = self.portal_path + "/legislation/directives/" portal_catalog = getToolByName(self.portal_root, 'portal_catalog') self.pc = portal_catalog
def spoofRequest(app): _policy = PermissiveSecurityPolicy() setSecurityPolicy(_policy) user = app.acl_users.getUser('admin') newSecurityManager(None, user.__of__(app.acl_users)) return makerequest(app)
def main(app, args): parser = OptionParser( usage="Usage: bin/instance xmlimport [options] <XML-files>") parser.add_option("-p", "--publish", help="Publish the imported sector.", action="store_true", dest="publish", default=False) parser.add_option("-S", "--site", help="id of the Plone site. Defaults to Plone", action="store", type="string", dest="site", default="Plone") parser.add_option("-L", "--logo", help="Filename for the sector logo.", action="store", type="string", dest="logo") parser.add_option("--main-colour", help="Main colour used for client pages.", action="store", type="string", dest="main_colour") parser.add_option("--support-colour", help="Support colour used for client pages.", action="store", type="string", dest="support_colour") parser.add_option("-c", "--country", help="The country where the branch/model should be created. " "Defaults to nl.", action="store", type="string", dest="country", default="nl") parser.add_option("-s", "--sector", help="The name of the sector where the survey should be created.", action="store", type="string", dest="sector") parser.add_option("-l", "--login", help="Login name for the sector. Also used as sector id.", action="store", type="string", dest="login") parser.add_option("-n", "--name", help="Override name for the imported survey.", action="store", type="string", dest="name") parser.add_option("-v", "--version-name", help="Name of the new survey version. Defaults to 'default'.", action="store", type="string", dest="version", default="default") (options, args) = parser.parse_args(args) if not args: raise Abort("Please specify a (single) XML file to import.") # The magic Zope2 setup dance zope2 = makerequest(app) hooks.setHooks() plone = getattr(zope2, options.site) hooks.setSite(plone) # Login as admin admin = zope2.acl_users.getUserById("admin") newSecurityManager(None, admin) for arg in args: transaction.begin() try: log.info("Importing %s", arg) ImportSector(plone, options, arg) trans = transaction.get() trans.setUser("-commandline-") trans.note("Import of %s" % arg) trans.commit() except lxml.etree.XMLSyntaxError as e: transaction.abort() log.error(e.message) log.error("Invalid input file") except RuntimeError as e: transaction.abort() log.error(e.message) except zExceptions.Unauthorized as e: transaction.abort() log.error(e.message) log.error("This is mostly likely due to too deep nesting " "in the survey.") except zExceptions.BadRequest as e: transaction.abort() log.error(e.message) log.error("This is mostly likely due to illegal input data.") except Exception as e: transaction.abort() raise
def setup_default_content(site): from Testing import makerequest wrapped = makerequest.makerequest(site) from intranett.policy.browser.defaultcontent import DefaultContent view = DefaultContent(wrapped, wrapped.REQUEST) view()
from Products.CMFCore.utils import getToolByName from StringIO import StringIO import transaction from AccessControl.SecurityManagement import newSecurityManager from AccessControl.SecurityManager import setSecurityPolicy from Testing.makerequest import makerequest from Products.CMFCore.tests.base.security import PermissiveSecurityPolicy, OmnipotentUser _policy = PermissiveSecurityPolicy() _oldpolicy = setSecurityPolicy(_policy) newSecurityManager(None, OmnipotentUser().__of__(app.acl_users)) app = makerequest(app) attool = app['plone.org'].archetype_tool def manage_updateSchema(self, REQUEST=None, update_all=None, remove_instance_schemas=None): """Make sure all objects' schema are up to date. """ out = StringIO() print >> out, 'Updating schema...' update_types = [] if REQUEST is None: # DM (avoid persistency bug): avoid code duplication update_types = [ti[0] for ti in self.getChangedSchema() if ti[1]] else: # DM (avoid persistency bug): update_types = [ti[0] for ti in self.getChangedSchema() if ti[1]]
def make_request(self): request = makerequest(self.layer['app'], environ=self.env).REQUEST self.request.environ.update(self.env) request.REQUEST_METHOD = 'POST' return request
def setUp(self): TransactionalTest.setUp(self) root = self.root = makerequest(self.root) self.REQUEST = root.REQUEST self.RESPONSE = root.REQUEST.RESPONSE
def setUp(self): SecurityTest.setUp(self) self.root = makerequest(self.root)
def test_environ(self): # You can pass an environ argument to use in the request. environ = {'foofoo': 'barbar'} item = makerequest(SimpleItem(), environ=environ) self.assertEqual(item.REQUEST.environ['foofoo'], 'barbar')
def app(): '''Opens a ZODB connection and returns the app object.''' app = Zope2.app() app = makerequest(app) connections.register(app) return app
def setUp(self): transaction.begin() self.root = makerequest(Zope2.app())
def __init__(self, app, zope_admin_name=''): self.set_admin_security_manager(app, zope_admin_name) self.app = makerequest.makerequest(app)
def _makeOne(self, *args, **kw): sdm = self._getTargetClass()(*args, **kw) from Testing.makerequest import makerequest return makerequest(sdm)
# Run as a script, this dumps all published places to KML if __name__ == '__main__': from Testing.makerequest import makerequest from pleiades.dump import getSite from pleiades.kml.dump import AllPlacesDocument, pt, main_macros, kml_macros site = getSite(app) context = makerequest(site) doc = pt(view=AllPlacesDocument(site), context=context, request=context.REQUEST, macros={ 'kml_template': main_macros, 'kml_macros': kml_macros }) sys.stdout.write(doc.encode('utf-8'))