def publish(request, module_name, _get_module_info=get_module_info, # only for testing ): (bobo_before, bobo_after, object, realm, debug_mode, err_hook, validated_hook, transactions_manager, ) = _get_module_info(module_name) notify(PubStart(request)) newInteraction() try: request.processInputs() response = request.response if bobo_after is not None: response.after_list += (bobo_after,) if debug_mode: response.debug_mode = debug_mode if realm and not request.get('REMOTE_USER', None): response.realm = realm if bobo_before is not None: bobo_before() # Get the path list. # According to RFC1738 a trailing space in the path is valid. path = request.get('PATH_INFO') request['PARENTS'] = [object] object = request.traverse(path, validated_hook=validated_hook) notify(PubAfterTraversal(request)) if transactions_manager: transactions_manager.recordMetaData(object, request) result = mapply(object, request.args, request, call_object, 1, missing_name, dont_publish_class, request, bind=1, ) if result is not response: response.setBody(result) finally: endInteraction() notify(PubBeforeCommit(request)) return response
def setUp(test): functional.FunctionalTestSetup().setUp() newInteraction() root = functional.getRootFolder() setSite(root) sm = root.getSiteManager() # IIntIds root['ids'] = IntIds() sm.registerUtility(root['ids'], IIntIds) root['ids'].register(root) # catalog root['catalog'] = Catalog() sm.registerUtility(root['catalog'], ICatalog) # setup default role roles = sm.getUtility(IPortalRoles) if 'site.member' not in roles: role = PortalRole(title = u'Site Member') event.notify(ObjectCreatedEvent(role)) roles['site.member'] = role roleId = role.id sm.getUtility(IDefaultPortalRole).roles = [role.id] endInteraction()
def test_newInteraction(self): from zope.security.management import newInteraction from zope.security.management import queryInteraction newInteraction() interaction = queryInteraction() self.assertTrue(interaction is not None)
def transaction_pubevents(request, tm=transaction.manager): ok_exception = None try: setDefaultSkin(request) newInteraction() tm.begin() notify(pubevents.PubStart(request)) try: yield None except (HTTPOk, HTTPRedirection) as exc: ok_exception = exc notify(pubevents.PubBeforeCommit(request)) if tm.isDoomed(): tm.abort() else: tm.commit() notify(pubevents.PubSuccess(request)) except Exception: exc_info = sys.exc_info() notify( pubevents.PubBeforeAbort(request, exc_info, request.supports_retry())) tm.abort() notify( pubevents.PubFailure(request, exc_info, request.supports_retry())) raise finally: endInteraction() if ok_exception is not None: raise ok_exception
def test_query_new_end_restore_Interaction(self): from zope.security.management import queryInteraction self.assertEquals(queryInteraction(), None) from zope.security.management import newInteraction newInteraction() interaction = queryInteraction() self.assert_(interaction is not None) self.assertRaises(AssertionError, newInteraction) from zope.security.management import endInteraction endInteraction() self.assertEquals(queryInteraction(), None) from zope.security.management import restoreInteraction restoreInteraction() self.assert_(interaction is queryInteraction()) endInteraction() self.assertEquals(queryInteraction(), None) endInteraction() self.assertEquals(queryInteraction(), None) newInteraction() self.assert_(queryInteraction() is not None) restoreInteraction() # restore to no interaction self.assert_(queryInteraction() is None)
def wrapper(*a, **kw): from zope.security.management import newInteraction from zope.security.management import endInteraction newInteraction(SystemConfigurationParticipation()) result = func(*a, **kw) endInteraction() return result
def setUp(test): functional.FunctionalTestSetup().setUp() newInteraction() root = functional.getRootFolder() setSite(root) sm = root.getSiteManager() # IIntIds root['ids'] = IntIds() sm.registerUtility(root['ids'], IIntIds) root['ids'].register(root) # catalog root['catalog'] = Catalog() sm.registerUtility(root['catalog'], ICatalog) # space space = ContentSpace(title=u'Space') event.notify(ObjectCreatedEvent(space)) root['space'] = space # people people = PersonalSpaceManager(title=u'People') event.notify(ObjectCreatedEvent(people)) root['people'] = people sm.registerUtility(root['people'], IPersonalSpaceManager) endInteraction()
def test_project_create_cancel(self): login(self.portal, testing.SITE_ADMIN) challenges = self.portal["challenges"] challenges.invokeFactory(id="challenge", type_name="cnrd.Challenge") intids = component.getUtility(IIntIds) challenge_intid = intids.getId(challenges["challenge"]) add_view = self.portal.restrictedTraverse("workspaces/++add++cnrd.Project") add_view.request.form["challenge"] = str(challenge_intid) add_view.update() edit_location = add_view.request.response.getHeader('Location') edit_path = add_view.request.physicalPathFromURL(edit_location) self.assertEqual(edit_path[-2:], ['project-draft', 'edit']) self.assertIn(edit_path[-2], self.portal["workspaces"]) edit_path[-1] = "@@" + edit_path[-1] edit_view = self.portal.restrictedTraverse(edit_path) edit_view.request['SESSION'] = {} edit_view.request.form = { "form.buttons.cancel": 1 } newInteraction() edit_view.update() endInteraction() location = edit_view.request.response.getHeader('Location') path = add_view.request.physicalPathFromURL(location) self.assertEqual(path[-2:], ['challenges', 'challenge']) self.assertNotIn(edit_path[-2], self.portal["workspaces"])
def test_checkPermission(self): from zope.security import checkPermission from zope.security.management import setSecurityPolicy from zope.security.management import queryInteraction from zope.security.management import newInteraction, endInteraction from zope.security.interfaces import NoInteraction permission = 'zope.Test' obj = object() class PolicyStub(object): def checkPermission(s, p, o,): self.assert_(p is permission) self.assert_(o is obj) self.assert_(s is queryInteraction() or s is interaction) return s is interaction setSecurityPolicy(PolicyStub) newInteraction() interaction = queryInteraction() self.assertEquals(checkPermission(permission, obj), True) endInteraction() self.assertRaises(NoInteraction, checkPermission, permission, obj)
def setUp(test): functional.FunctionalTestSetup().setUp() newInteraction() root = functional.getRootFolder() setSite(root) sm = root.getSiteManager() sm.getUtility(INameChooserConfiglet).short_url_enabled = True # IIntIds root['ids'] = IntIds() sm.registerUtility(root['ids'], IIntIds) root['ids'].register(root) # catalog root['catalog'] = Catalog() sm.registerUtility(root['catalog'], ICatalog) setattr(root, 'principalId', 'zope.mgr') # space space = ContentSpace(title=u'Space') event.notify(ObjectCreatedEvent(space)) root['space'] = space setattr(root, 'principal', getUtility(IAuthentication).getPrincipal('zope.mgr')) # people people = PersonalSpaceManager(title=u'People') event.notify(ObjectCreatedEvent(people)) root['people'] = people sm.registerUtility(root['people'], IPersonalSpaceManager) endInteraction()
def test_checkPermission(self): from zope.security import checkPermission from zope.security.management import setSecurityPolicy from zope.security.management import queryInteraction from zope.security.management import newInteraction, endInteraction from zope.security.interfaces import NoInteraction permission = 'zope.Test' obj = object() class PolicyStub(object): def checkPermission( s, p, o, ): self.assert_(p is permission) self.assert_(o is obj) self.assert_(s is queryInteraction() or s is interaction) return s is interaction setSecurityPolicy(PolicyStub) newInteraction() interaction = queryInteraction() self.assertEquals(checkPermission(permission, obj), True) endInteraction() self.assertRaises(NoInteraction, checkPermission, permission, obj)
def setUp(test): functional.FunctionalTestSetup().setUp() newInteraction() root = functional.getRootFolder() setSite(root) sm = root.getSiteManager() sm.getUtility(INameChooserConfiglet).short_url_enabled = True # IIntIds root["ids"] = IntIds() sm.registerUtility(root["ids"], IIntIds) root["ids"].register(root) # catalog root["catalog"] = Catalog() sm.registerUtility(root["catalog"], ICatalog) # space space = ContentSpace(title=u"Space") event.notify(ObjectCreatedEvent(space)) root["space"] = space # people people = PersonalSpaceManager(title=u"People") event.notify(ObjectCreatedEvent(people)) root["people"] = people sm.registerUtility(root["people"], IPersonalSpaceManager) endInteraction()
def test_endInteraction(self): from zope.security.management import endInteraction from zope.security.management import newInteraction from zope.security.management import queryInteraction newInteraction() endInteraction() self.assertEqual(queryInteraction(), None)
def setUp(self): super(PlacefulSetup, self).setUp() cSetUp() setUpTraversal() from zope.security.management import newInteraction newInteraction()
def start(self): """Start the publication process. """ notify(interfaces.PublicationStart(self.request)) newInteraction() noSecurityManager() self.app.transaction.begin() self.request.processInputs()
def login(id, request=None): if request is None: participation = Participation(Principal(id)) newInteraction(participation) else: principal = Principal(id) request.setPrincipal(principal) newInteraction(request)
def test_restoreInteraction_after_new(self): from zope.security.management import newInteraction from zope.security.management import queryInteraction from zope.security.management import restoreInteraction newInteraction() self.assertTrue(queryInteraction() is not None) restoreInteraction() # restore to no interaction self.assertTrue(queryInteraction() is None)
def transaction_pubevents(request, response, tm=transaction.manager): try: setDefaultSkin(request) newInteraction() tm.begin() notify(pubevents.PubStart(request)) yield notify(pubevents.PubBeforeCommit(request)) if tm.isDoomed(): tm.abort() else: tm.commit() notify(pubevents.PubSuccess(request)) except Exception as exc: # Normalize HTTP exceptions # (For example turn zope.publisher NotFound into zExceptions NotFound) exc_type, _ = upgradeException(exc.__class__, None) if not isinstance(exc, exc_type): exc = exc_type(str(exc)) # Create new exc_info with the upgraded exception. exc_info = (exc_type, exc, sys.exc_info()[2]) try: # Raise exception from app if handle-errors is False # (set by zope.testbrowser in some cases) if request.environ.get('x-wsgiorg.throw_errors', False): reraise(*exc_info) if isinstance(exc, Unauthorized): # _unauthorized modifies the response in-place. If this hook # is used, an exception view for Unauthorized has to merge # the state of the response and the exception instance. exc.setRealm(response.realm) response._unauthorized() response.setStatus(exc.getStatus()) # Handle exception view exc_view_created = _exc_view_created_response( exc, request, response) notify( pubevents.PubBeforeAbort(request, exc_info, request.supports_retry())) tm.abort() notify( pubevents.PubFailure(request, exc_info, request.supports_retry())) if not (exc_view_created or isinstance(exc, Unauthorized)): reraise(*exc_info) finally: # Avoid traceback / exception reference cycle. del exc, exc_info finally: endInteraction()
def lockingSetUp(test): placelesssetup.setUp(test) z3c.etree.testing.etreeSetup(test) # create principal participation = TestRequest(environ = {"REQUEST_METHOD": "PUT"}) participation.setPrincipal(Principal("michael")) if queryInteraction() is not None: queryInteraction().add(participation) else: newInteraction(participation) events = test.globs["events"] = [] zope.event.subscribers.append(events.append) gsm = zope.component.getGlobalSiteManager() gsm.registerAdapter(DemoKeyReference, (IDemo,), zope.app.keyreference.interfaces.IKeyReference) gsm.registerAdapter(PhysicallyLocatable, (Demo,)) gsm.registerAdapter(PhysicallyLocatable, (DemoFolder,)) gsm.registerAdapter(DemoKeyReference, (IDemoFolder,), zope.app.keyreference.interfaces.IKeyReference) gsm.registerAdapter(SiteManagerAdapter, (zope.interface.Interface,), IComponentLookup) gsm.registerAdapter(DemoAbsoluteURL, (IDemo, zope.interface.Interface), zope.traversing.browser.interfaces.IAbsoluteURL) gsm.registerAdapter(DemoAbsoluteURL, (IDemoFolder, zope.interface.Interface), zope.traversing.browser.interfaces.IAbsoluteURL) # register some IDAVWidgets so that we can render the activelock and # supportedlock widgets. gsm.registerAdapter(z3c.dav.widgets.ListDAVWidget, (zope.schema.interfaces.IList, z3c.dav.interfaces.IWebDAVRequest)) gsm.registerAdapter(z3c.dav.widgets.ObjectDAVWidget, (zope.schema.interfaces.IObject, z3c.dav.interfaces.IWebDAVRequest)) gsm.registerAdapter(z3c.dav.widgets.TextDAVWidget, (zope.schema.interfaces.IText, z3c.dav.interfaces.IWebDAVRequest)) gsm.registerAdapter(z3c.dav.properties.OpaqueWidget, (z3c.dav.properties.DeadField, z3c.dav.interfaces.IWebDAVRequest)) gsm.registerAdapter(z3c.dav.widgets.TextDAVWidget, (zope.schema.interfaces.IURI, z3c.dav.interfaces.IWebDAVRequest)) # Need connection to a database to manage locking db = test.globs["db"] = ZODB.DB(ZODB.MappingStorage.MappingStorage()) test.globs["conn"] = db.open() # expose these classes to the test test.globs["Demo"] = Demo test.globs["DemoFolder"] = DemoFolder
def setUp(self): ZCMLFileLayer.setUp(self) zope.component.hooks.setHooks() # Set up site site = rootFolder() site.setSiteManager(LocalSiteManager(site)) zope.component.hooks.setSite(site) security.newInteraction(Participation(Principal('zope.mgr')))
def setUp(test): functional.FunctionalTestSetup().setUp() newInteraction() def fake_utcnow(self): return datetime.datetime(2015, 7, 30, 8, 0, 0) curse(datetime.datetime, 'utcnow', classmethod(fake_utcnow)) root = functional.getRootFolder() setSite(root) sm = root.getSiteManager() # IIntIds root['intids'] = IntIds() sm.registerUtility(root['intids'], IIntIds) root['intids'].register(root) # catalog root['catalog'] = Catalog() sm.registerUtility(root['catalog'], ICatalog) # PluggableAuthentication pau = PluggableAuthentication(u'') event.notify(ObjectCreatedEvent(pau)) sm[u'auth'] = pau sm.registerUtility(pau, IAuthentication) # Credentials Plugin defaultCreds.install() defaultCreds.activate() # people people = PersonalSpaceManager(title=u'People') event.notify(ObjectCreatedEvent(people)) root['people'] = people sm.registerUtility(root['people'], IPersonalSpaceManager) user = sm.getUtility(IAuthentication).getPrincipal('zope.mgr') people.assignPersonalSpace(user) user = sm.getUtility(IAuthentication).getPrincipal('zope.user') people.assignPersonalSpace(user) # default content content = Content(u'Content1', u'Some Content1') event.notify(ObjectCreatedEvent(content)) IOwnership(content).ownerId = 'zope.user' root['content1'] = content content = Content(u'Content2', u'Some Content2') event.notify(ObjectCreatedEvent(content)) IOwnership(content).ownerId = 'zope.user' root['content2'] = content endInteraction()
def transaction_pubevents(request, response, tm=transaction.manager): try: setDefaultSkin(request) newInteraction() tm.begin() notify(pubevents.PubStart(request)) yield notify(pubevents.PubBeforeCommit(request)) if tm.isDoomed(): tm.abort() else: tm.commit() notify(pubevents.PubSuccess(request)) except Exception as exc: # Normalize HTTP exceptions # (For example turn zope.publisher NotFound into zExceptions NotFound) exc_type, _ = upgradeException(exc.__class__, None) if not isinstance(exc, exc_type): exc = exc_type(str(exc)) # Create new exc_info with the upgraded exception. exc_info = (exc_type, exc, sys.exc_info()[2]) try: # Raise exception from app if handle-errors is False # (set by zope.testbrowser in some cases) if request.environ.get('x-wsgiorg.throw_errors', False): reraise(*exc_info) if isinstance(exc, Unauthorized): # _unauthorized modifies the response in-place. If this hook # is used, an exception view for Unauthorized has to merge # the state of the response and the exception instance. exc.setRealm(response.realm) response._unauthorized() response.setStatus(exc.getStatus()) # Handle exception view exc_view_created = _exc_view_created_response( exc, request, response) notify(pubevents.PubBeforeAbort( request, exc_info, request.supports_retry())) tm.abort() notify(pubevents.PubFailure( request, exc_info, request.supports_retry())) if not (exc_view_created or isinstance(exc, Unauthorized)): reraise(*exc_info) finally: # Avoid traceback / exception reference cycle. del exc, exc_info finally: endInteraction()
def setUp(test): zope.component.testing.setUp(test) from zope.security.management import newInteraction newInteraction() zope.component.provideUtility(password.PlainTextPasswordManager(), name='SSHA') zope.component.provideUtility(password.PlainTextPasswordManager(), name='Plain Text')
def test_no_cache_when_there_is_no_request(self): # Calling login() would cause a new interaction to be setup with a # LaunchpadTestRequest, so we need to call newInteraction() manually # here. newInteraction() menu = TestMenu(object()) menu._get_link('test_link') self.assertEquals(menu.times_called, 1) menu._get_link('test_link') self.assertEquals(menu.times_called, 2)
def test_no_cache_when_there_is_no_request(self): # Calling login() would cause a new interaction to be setup with a # LaunchpadTestRequest, so we need to call newInteraction() manually # here. newInteraction() menu = TestMenu(object()) menu._get_link("test_link") self.assertEquals(menu.times_called, 1) menu._get_link("test_link") self.assertEquals(menu.times_called, 2)
def setUp(test): zope.component.testing.setUp(test) from zope.security.management import newInteraction newInteraction() zope.component.provideUtility( password.PlainTextPasswordManager(), name='SSHA') zope.component.provideUtility( password.PlainTextPasswordManager(), name='Plain Text')
def test_restoreInteraction_after_end(self): from zope.security.management import endInteraction from zope.security.management import newInteraction from zope.security.management import queryInteraction from zope.security.management import restoreInteraction newInteraction() interaction = queryInteraction() endInteraction() restoreInteraction() self.assertTrue(interaction is queryInteraction())
def beforeTraversal(self, request): # Try to authenticate against the default global registry. p = prin_reg.authenticate(request) if p is None: p = prin_reg.unauthenticatedPrincipal() if p is None: raise Unauthorized # If there's no default principal request.setPrincipal(p) newInteraction(request) transaction.begin()
def _setPrincipal(self, id): from zope.security.management import newInteraction class DummyPrincipal(object): title = 'TITLE' description = 'DESCRIPTION' def __init__(self, id): self.id = id if id is None: newInteraction(DummyRequest(None)) else: newInteraction(DummyRequest(DummyPrincipal(id)))
def setUp(test): functional.FunctionalTestSetup().setUp() newInteraction() root = functional.getRootFolder() setSite(root) sm = root.getSiteManager() auth = sm.getUtility(IAuthentication) p = auth.getPrincipal('zope.mgr') setattr(root, 'principal', p) setattr(root, 'owner', p) endInteraction()
def test_principal_from_iteraction(self): principal = _Principal('bob') participation = _Participation(principal) newInteraction(participation) try: interaction = queryInteraction() p_from_i = IPrincipal(interaction) assert_that(p_from_i.username, is_(principal.username)) finally: endInteraction()
def test_post_deletion(self): login(self.portal, testing.SITE_ADMIN) post_id = self.post.id newInteraction() delete_view = self.post.restrictedTraverse('@@delete_confirmation') delete_view.request["form.button.Delete"] = 1 delete_view.update() endInteraction() self.assertFalse(post_id in self.ws)
def testItemDenied(self): endInteraction() newInteraction(ParticipationStub('no one')) defineChecker(C, Checker({'item': 'Waaaa', 'folder': CheckerPublic})) tr = Traverser(ProxyFactory(self.root)) folder = self.folder self.assertRaises(Unauthorized, tr.traverse, ('', 'folder', 'item')) self.assertRaises(Unauthorized, tr.traverse, ('folder', 'item')) self.assertEqual(tr.traverse(('', 'folder')), folder) self.assertEqual(tr.traverse(('folder', '..', 'folder')), folder) self.assertEqual(tr.traverse(('folder', )), folder)
def _render(self, form_values=None, method='GET'): self.request = self.request_class( method=method, form=form_values, PATH_INFO='/', environ=self.request_environ) if queryInteraction() is not None: self.request.setPrincipal(get_current_principal()) # Setup a new interaction using self.request, create the view, # initialize() it and then restore the original interaction. endInteraction() newInteraction(self.request) self.view = self.view_class(self.context, self.request) self.view.initialize() restoreInteraction()
def __enter__(self): current = queryInteraction() new = self.participation if self.replace is False and current is not None: current.add(new) else: self.previous = current endInteraction() newInteraction(new) self.current = new.interaction return new.interaction
def _render(self, form_values=None, method='GET'): self.request = self.request_class(method=method, form=form_values, PATH_INFO='/', environ=self.request_environ) if queryInteraction() is not None: self.request.setPrincipal(get_current_principal()) # Setup a new interaction using self.request, create the view, # initialize() it and then restore the original interaction. endInteraction() newInteraction(self.request) self.view = self.view_class(self.context, self.request) self.view.initialize() restoreInteraction()
def testException(self): # nail the fact that AttributeError raised in a @property # decorated method gets masked by traversal self.root.foobar = ExceptionRaiser('foobar') endInteraction() newInteraction(ParticipationStub('no one')) tr = Traverser(self.root) # AttributeError becomes LocationError if there's no __getitem__ # on the object self.assertRaises(LocationError, tr.traverse, ('foobar', 'attributeerror')) # Other exceptions raised as usual self.assertRaises(ValueError, tr.traverse, ('foobar', 'valueerror'))
def beforeTraversal(self, request): # Try to authenticate against the root authentication utility. auth = zope.component.getGlobalSiteManager().getUtility( zope.authentication.interfaces.IAuthentication) principal = auth.authenticate(request) if principal is None: principal = auth.unauthenticatedPrincipal() if principal is None: # Get the fallback unauthenticated principal principal = zope.component.getUtility( IFallbackUnauthenticatedPrincipal) request.setPrincipal(principal) newInteraction(request) transaction.begin()
def beforeTraversal(self, request): # Try to authenticate against the root authentication utility. auth = zope.component.getGlobalSiteManager().getUtility( zope.app.security.interfaces.IAuthentication) principal = auth.authenticate(request) if principal is None: principal = auth.unauthenticatedPrincipal() if principal is None: # Get the fallback unauthenticated principal principal = zope.component.getUtility( IFallbackUnauthenticatedPrincipal) request.setPrincipal(principal) newInteraction(request) transaction.begin()
def testItemDenied(self): endInteraction() newInteraction(ParticipationStub('no one')) defineChecker(C, Checker({'item': 'Waaaa', 'folder': CheckerPublic})) tr = Traverser(ProxyFactory(self.root)) folder = self.folder self.assertRaises(Unauthorized, tr.traverse, ('', 'folder', 'item')) self.assertRaises(Unauthorized, tr.traverse, ('folder', 'item')) self.assertEquals(tr.traverse(('', 'folder')), folder) self.assertEquals(tr.traverse(('folder', '..', 'folder')), folder) self.assertEquals(tr.traverse(('folder',)), folder)
def setUpFieldConfig(test): test.globs = {'root': placefulSetUp(True)} # placeful setup root = test.globs['root'] setUpZCML(test) hooks.setSite(root) interaction = newInteraction() testing.generateCategorizableItemDescriptions(root)
def setUp(self): super(SearchTests, self).setUp() self.root = placefulSetUp(True) setUpZCML(self) import quotationtool.search XMLConfig('configure.zcml', quotationtool.search)() hooks.setSite(self.root) # we need a transaction from zope.security.management import newInteraction interaction = newInteraction() testing.generateCategorizableItemDescriptions(self.root) testing.generateCategoriesContainer(self.root) testing.setUpIntIds(self) testing.setUpIndices(self) testing.setUpRelationCatalog(self) self.root['item1'] = item1 = testing.Categorizable() self.root['item2'] = item2 = testing.Categorizable() from zope.intid.interfaces import IIntIds self.intids = zope.component.getUtility(IIntIds, context=self.root) self.intids.register(self.root['item1']) self.intids.register(self.root['item2']) attribution1 = interfaces.IAttribution(item1) attribution1.set(('cat11', 'cat21', 'cat31',)) attribution2 = interfaces.IAttribution(item2) attribution2.set(('cat12', 'cat22', 'cat32',)) from quotationtool.search.searcher import QuotationtoolSearchFilter zope.interface.classImplements( QuotationtoolSearchFilter, interfaces.IAttributionSearchFilter)
def setUp(self): super(AttributionTests, self).setUp() self.root = placefulSetUp(True) setUpZCML(self) hooks.setSite(self.root) # we need a transaction from zope.security.management import newInteraction interaction = newInteraction() testing.generateCategorizableItemDescriptions(self.root) testing.generateCategoriesContainer(self.root) testing.setUpIntIds(self) testing.setUpIndices(self) testing.setUpRelationCatalog(self) from quotationtool.workflow import testing as workflowtesting workflowtesting.setUpWorkLists(self.root) workflowtesting.setUpIndices(self) from quotationtool.workflow.interfaces import IWorkList self.editor_items = zope.component.getUtility(IWorkList, name='editor', context=self.root) self.contributor_items = zope.component.getUtility(IWorkList, name='contributor', context=self.root) # create item and its intid from quotationtool.workflow.interfaces import IHasWorkflowHistory zope.interface.classImplements(testing.Categorizable, IHasWorkflowHistory) self.root['item'] = item = testing.Categorizable() from zope.intid.interfaces import IIntIds self.intids = zope.component.getUtility(IIntIds, context=self.root) self.intids.register(self.root['item'])
def setUpRelatedAttribution(test): placelesssetup.setUp(test) setUpZCML(test) test.globs['root'] = root = rootFolder() testing.setUpIndices(test) testing.setUpIntIds(test) interaction = newInteraction()
def test_checkPermission_forbidden_policy(self): from zope.security import checkPermission from zope.security.checker import CheckerPublic from zope.security.management import setSecurityPolicy from zope.security.management import newInteraction obj = object() class ForbiddenPolicyStub(object): def checkPermission(s, p, o): return False setSecurityPolicy(ForbiddenPolicyStub) newInteraction() self.assertEqual(checkPermission('zope.Test', obj), False) self.assertEqual(checkPermission(None, obj), True) self.assertEqual(checkPermission(CheckerPublic, obj), True)
def setUpDataManager(test): tearDownPlaces(test) test.globs = {'root': placefulSetUp(True)} # placeful setup root = test.globs['root'] setUpZCML(test) hooks.setSite(root) testing.generateCategorizableItemDescriptions(root) from zope.security.management import newInteraction interaction = newInteraction()
def __checkSecurity(self, data): """ Returns a boolean indicating whether *data* passes the security checks defined for this subscription. If we are not able to make the security check because the principal or permission we are supposed to use is not defined, returns the special (false) value `None`. This can be used to distinguish the case where access is denied by the security policy from the case where requested principals are missing. """ if not self.permission_id and not self.owner_id: # If no security is requested, we're good. return True # OK, now we need to find the permission and the principal. # Both should be found in the context of the data; if not # there, then check the currently installed site. principal = self._find_principal(data) permission = self._find_permission(data) if principal is None or permission is None: # A missing permission causes zope.security to grant full access. # It's treated the same as zope.Public. So don't let that happen. return None # Now, we need to set up the interaction and do the security check. participation = Participation(principal) current_interaction = queryInteraction() if current_interaction is not None: # Cool, we can add our participation to the interaction. current_interaction.add(participation) else: newInteraction(participation) try: # Yes, this needs the ID of the permission, not the permission object. return checkPermission(self.permission_id, data) finally: if current_interaction is not None: current_interaction.remove(participation) else: endInteraction()
def fake_interaction(): """Context manager that temporarily sets up a fake IInteraction. This may be needed in cases where no real request is being processed (there's no actual publishing going on), but still a call to checkPermission() is necessary. That call would otherwise fail with zope.security.interfaces.NoInteraction. Initially needed for standalone testing of z3c.forms, inspired by from z3c/formwidget//query/README.txt. For more details see zope.security.management and ZPublisher.Publish. """ newInteraction() try: yield finally: endInteraction()
def make_fake_request(url, traversed_objects=None): """Return a fake request object for menu testing. :param traversed_objects: A list of objects that becomes the request's traversed_objects attribute. """ url_parts = urlsplit(url) server_url = '://'.join(url_parts[0:2]) path_info = url_parts[2] request = LaunchpadTestRequest( SERVER_URL=server_url, PATH_INFO=path_info) request._traversed_names = path_info.split('/')[1:] if traversed_objects is not None: request.traversed_objects = traversed_objects[:] # After making the request, setup a new interaction. endInteraction() newInteraction(request) return request
def __call__(self, environ, start_response): request = environ[REQUEST_KEY] auth = getGlobalSiteManager().getUtility(IAuthentication) principal = auth.authenticate(request) if principal is None: if self.local_auth: hooks = environ.setdefault(TRAVERSAL_HOOKS_KEY, []) hooks.append(placeful_auth) principal = auth.unauthenticatedPrincipal() if principal is None: # Get the fallback unauthenticated principal principal = getUtility(IFallbackUnauthenticatedPrincipal) request.principal = principal newInteraction(request) try: return self.next_app(environ, start_response) finally: endInteraction()
def _createAndRenderView(self, response, view_class=StubbedOpenIDCallbackView): request = LaunchpadTestRequest( form={'starting_url': 'http://launchpad.dev/after-login'}, environ={'PATH_INFO': '/'}) # The layer we use sets up an interaction (by calling login()), but we # want to use our own request in the interaction, so we logout() and # setup a newInteraction() using our request. logout() newInteraction(request) view = view_class(object(), request) view.initialize() view.openid_response = response # Monkey-patch getByOpenIDIdentifier() to make sure the view uses the # master DB. This mimics the problem we're trying to avoid, where # getByOpenIDIdentifier() doesn't find a newly created account because # it looks in the slave database. with IAccountSet_getByOpenIDIdentifier_monkey_patched(): html = view.render() return view, html
def beforeTraversal(self, request): notify(StartRequestEvent(request)) request._traversalticks_start = tickcount.tickcount() threadid = thread.get_ident() threadrequestfile = open_for_writing( 'logs/thread-%s.request' % threadid, 'w') try: request_txt = unicode(request).encode('UTF-8') except Exception: request_txt = 'Exception converting request to string\n\n' try: request_txt += traceback.format_exc() except: request_txt += 'Unable to render traceback!' threadrequestfile.write(request_txt) threadrequestfile.close() # Tell our custom database adapter that the request has started. da.set_request_started() newInteraction(request) transaction.begin() # Now we are logged in, install the correct IDatabasePolicy for # this request. db_policy = IDatabasePolicy(request) getUtility(IStoreSelector).push(db_policy) getUtility(IOpenLaunchBag).clear() # Set the default layer. adapters = getGlobalSiteManager().adapters layer = adapters.lookup((providedBy(request), ), IDefaultSkin, '') if layer is not None: layers.setAdditionalLayer(request, layer) principal = self.getPrincipal(request) request.setPrincipal(principal) self.maybeRestrictToTeam(request) maybe_block_offsite_form_post(request)
def setUp(self): super(AttributionTests, self).setUp() setUpZCML(self) self.root = rootFolder() testing.setUpIntIds(self) interaction = newInteraction() # needed for generation of categories testing.generateCategorizableItemDescriptions(self.root) testing.generateCategoriesContainer(self.root) testing.setUpIndices(self) from quotationtool.categorization.interfaces import ICategoriesContainer self.categories = zope.component.getUtility(ICategoriesContainer, context=self.root)