def setUp(self): super(TestGetBranchTips, self).setUp() self.distro = self.factory.makeDistribution() series_1 = self.series_1 = self.factory.makeDistroSeries(self.distro) series_2 = self.series_2 = self.factory.makeDistroSeries(self.distro) source_package = self.factory.makeSourcePackage(distroseries=series_1) branch = self.factory.makeBranch(sourcepackage=source_package) unofficial_branch = self.factory.makeBranch( sourcepackage=source_package) registrant = self.factory.makePerson() now = datetime.now(pytz.UTC) sourcepackagename = self.factory.makeSourcePackageName() SeriesSourcePackageBranchSet.new(series_1, PackagePublishingPocket.RELEASE, sourcepackagename, branch, registrant, now) SeriesSourcePackageBranchSet.new(series_2, PackagePublishingPocket.RELEASE, sourcepackagename, branch, registrant, now) self.factory.makeRevisionsForBranch(branch) self.branch_name = branch.unique_name self.unofficial_branch_name = unofficial_branch.unique_name self.branch_last_scanned_id = branch.last_scanned_id endInteraction() self.lp = launchpadlib_for("anonymous-access") self.lp_distro = self.lp.distributions[self.distro.name]
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 run_with_login(login_id, function, *args, **kwargs): """Run 'function' logged in with 'login_id'. The first argument passed to 'function' will be the Launchpad `Person` object corresponding to 'login_id'. The exception is when the requesting login ID is `LAUNCHPAD_SERVICES`. In that case, we'll pass through the `LAUNCHPAD_SERVICES` variable and the method will do whatever security proxy hackery is required to provide read privileges to the Launchpad services. """ if login_id == LAUNCHPAD_SERVICES or login_id == LAUNCHPAD_ANONYMOUS: # Don't pass in an actual user. Instead pass in LAUNCHPAD_SERVICES # and expect `function` to use `removeSecurityProxy` or similar. return function(login_id, *args, **kwargs) if isinstance(login_id, basestring): requester = getUtility(IPersonSet).getByName(login_id) else: requester = getUtility(IPersonSet).get(login_id) if requester is None: raise NotFoundError("No person with id %s." % login_id) setupInteractionForPerson(requester) try: return function(requester, *args, **kwargs) finally: endInteraction()
def test_write_without_permission_gives_Unauthorized(self): distro = self.factory.makeDistribution() endInteraction() lp = launchpadlib_for("anonymous-access") lp_distro = lp.load(api_url(distro)) lp_distro.active = False self.assertRaises(Unauthorized, lp_distro.lp_save)
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_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(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 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 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 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(self): super(TestGetBranchTips, self).setUp() self.distro = self.factory.makeDistribution() series_1 = self.series_1 = self.factory.makeDistroSeries(self.distro) series_2 = self.series_2 = self.factory.makeDistroSeries(self.distro) source_package = self.factory.makeSourcePackage(distroseries=series_1) branch = self.factory.makeBranch(sourcepackage=source_package) unofficial_branch = self.factory.makeBranch( sourcepackage=source_package) registrant = self.factory.makePerson() now = datetime.now(pytz.UTC) sourcepackagename = self.factory.makeSourcePackageName() SeriesSourcePackageBranchSet.new( series_1, PackagePublishingPocket.RELEASE, sourcepackagename, branch, registrant, now) SeriesSourcePackageBranchSet.new( series_2, PackagePublishingPocket.RELEASE, sourcepackagename, branch, registrant, now) self.factory.makeRevisionsForBranch(branch) self.branch_name = branch.unique_name self.unofficial_branch_name = unofficial_branch.unique_name self.branch_last_scanned_id = branch.last_scanned_id endInteraction() self.lp = launchpadlib_for("anonymous-access") self.lp_distro = self.lp.distributions[self.distro.name]
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() # 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 publish_and_retry(self): """Publish the request into the response and retry if it fails. """ try: data = self.publish_and_render_errors() except (ConflictError, Retry): self.abort() self.publication_done = True if self.request.supports_retry() and not self.data_sent: # If can still retry, and didn't send any data yet, do it. logger.info('Conflict, retrying request %s' % ( reconstruct_url_from_environ(self.request.environ))) endInteraction() request = self.request.retry() try: publication = self.__class__( self.app, request, self.response) data = publication.publish_and_retry() self.publication_done = publication.publication_done finally: request.close() else: # Otherwise, just render a plain error. logger.error('Conflict error for request %s' % ( reconstruct_url_from_environ(self.request.environ))) self.response.setStatus(503) self.response.setBody(RETRY_FAIL_ERROR_TEMPLATE) data = self.result() return data
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 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 setUpDebug(test): placelesssetup.setUp(test) test.real_stderr = sys.stderr test.real_argv = list(sys.argv) test.olddir = os.getcwd() os.chdir(os.path.join(os.path.dirname(__file__), 'testdata')) from zope.security.management import endInteraction endInteraction()
def setUp(self): super(DebugLayer, self).setUp() self.stderr = sys.stderr self.argv = list(sys.argv) self.olddir = os.getcwd() os.chdir(os.path.join(os.path.dirname(__file__), 'testdata')) from zope.security.management import endInteraction 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): 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 _call_manage_main(self): self.setRoles(['Manager']) # temporaryPlacelessSetUp insists in creating an interaction # which the WSGI publisher does not expect. endInteraction() response = self.publish( f'/{Testing.ZopeTestCase.folder_name}/manage_main', basic=basic_auth) return str(response)
def test_distroseries_architectures_anonymous(self): """Test anonymous DistroArchSeries API Access.""" distroseries = self._makeDistroArchSeries() endInteraction() launchpad = launchpadlib_for('test', person=None, version='devel') ws_distroseries = ws_object(launchpad, distroseries) # Note, we test the length of architectures.entries, not # architectures due to the removal of the entries by lazr self.assertEqual(1, len(ws_distroseries.architectures.entries))
def _call_manage_main(self): self.setRoles(['Manager']) # temporaryPlacelessSetUp insists in creating an interaction # which the WSGI publisher does not expect. endInteraction() response = self.publish( '/{0.folder_name}/manage_main'.format(Testing.ZopeTestCase), basic=basic_auth) return str(response)
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 test_anon_access_to_public_bug_attachment(self): # Attachments of public bugs can be accessed by anonymous users. # # Need to endInteraction() because launchpadlib_for_anonymous() will # setup a new one. endInteraction() launchpad = launchpadlib_for('test', None, version='devel') ws_bug = ws_object(launchpad, self.bug) ws_bugattachment = ws_bug.attachments[0] self.assertEqual('file content', ws_bugattachment.data.open().read())
def _get_bug_for_user(self, user=None): """Convenience function to get the api bug reference.""" endInteraction() if user is not None: lp = launchpadlib_for("test", user) else: lp = launchpadlib_for("test") bug_entry = lp.load('/bugs/%s/' % self.bug.id) return bug_entry
def test_anonymous_cannot_access(self): # An anonymous launchpadlib connection cannot see email addresses. # Need to endInteraction() because launchpadlib_for() will # setup a new one. endInteraction() lp = launchpadlib_for('test', person=None, version='devel') person = lp.people['target'] emails = list(person.confirmed_email_addresses) self.assertEqual([], emails)
def logout(): """Tear down after login(...), ending the current interaction. Note that this is done automatically in LaunchpadFunctionalTestCase's tearDown method so you generally won't need to call this. """ # Ensure the launchbag developer flag is off when logging out. getUtility(ILaunchBag).setDeveloper(False) endInteraction()
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 test_anon_access_to_public_bug_attachment(self): # Attachments of public bugs can be accessed by anonymous users. # # Need to endInteraction() because launchpadlib_for_anonymous() will # setup a new one. endInteraction() launchpad = launchpadlib_for('test', None, version='devel') ws_bug = ws_object(launchpad, self.bug) ws_bugattachment = ws_bug.attachments[0] self.assertEqual( 'file content', ws_bugattachment.data.open().read())
def setUp(test): componentSetUp() endInteraction() provideAdapter(AttributeAnnotations) provideAdapter(AnnotationPrincipalPermissionManager, (IAnnotatable,), IPrincipalPermissionManager) provideAdapter(AnnotationPrincipalRoleManager, (IAnnotatable,), IPrincipalRoleManager) provideAdapter(AnnotationRolePermissionManager, (IAnnotatable,), IRolePermissionManager) provideAdapter(AnnotationGrantInfo, (IAnnotatable,), IGrantInfo)
def test_anonymous_access_to_collection(self): product = self.factory.makeProduct() self.factory.makeSpecification(product=product, name="spec1") self.factory.makeSpecification(product=product, name="spec2") # Need to endInteraction() because launchpadlib_for_anonymous() will # setup a new one. endInteraction() lplib = launchpadlib_for('lplib-test', person=None, version='devel') ws_product = ws_object(lplib, removeSecurityProxy(product)) self.assertNamesOfSpecificationsAre(["spec1", "spec2"], ws_product.all_specifications)
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_anonymous_access_to_collection(self): product = self.factory.makeProduct() self.factory.makeSpecification(product=product, name="spec1") self.factory.makeSpecification(product=product, name="spec2") # Need to endInteraction() because launchpadlib_for_anonymous() will # setup a new one. endInteraction() lplib = launchpadlib_for('lplib-test', person=None, version='devel') ws_product = ws_object(lplib, removeSecurityProxy(product)) self.assertNamesOfSpecificationsAre( ["spec1", "spec2"], ws_product.all_specifications)
def setUp(test): placelesssetup.setUp() testing.setUp() endInteraction() principal = principalregistry.UnauthenticatedPrincipal('anon','anon','') component.provideUtility( principal, IFallbackUnauthenticatedPrincipal) component.provideUtility( principalregistry.principalRegistry, IAuthentication)
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 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 tearDown(self): sys.stderr = self.stderr sys.argv[:] = self.argv if hasattr(sys, 'ps1'): del sys.ps1 os.chdir(self.olddir) # make sure we don't leave environment variables that would cause # Python to open an interactive console if 'PYTHONINSPECT' in os.environ: del os.environ['PYTHONINSPECT'] from zope.security.management import endInteraction endInteraction() super(DebugLayer, self).tearDown()
def _zope_response(self): """Get the response.""" current_principal = None # End and save the current interaction, since HTTPCaller creates # its own interaction. if queryInteraction(): current_principal = get_current_principal() endInteraction() if self._response is None: self._response = self.caller(self._data_to_send) # Restore the interaction to what it was before. setupInteraction(current_principal) return self._response
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 interaction(self): """Context manager for interaction as the given user. If an interaction is already in progress this is a no-op, otherwise it sets up an interaction on entry and ends it on exit. """ if queryInteraction() is None: setupInteraction(self._principal, login=self._login) try: yield finally: endInteraction() else: yield
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 test_getBranchVisibilityInfo(self): """Test the test_getBranchVisibilityInfo API.""" self.factory.makePerson(name='fred') owner = self.factory.makePerson() visible_branch = self.factory.makeBranch() visible_name = visible_branch.unique_name invisible_branch = self.factory.makeBranch( owner=owner, information_type=InformationType.USERDATA) invisible_name = removeSecurityProxy(invisible_branch).unique_name branches = [visible_branch.unique_name, invisible_name] endInteraction() lp = launchpadlib_for("test", person=owner) person = lp.people['fred'] info = lp.branches.getBranchVisibilityInfo(person=person, branch_names=branches) self.assertEqual('Fred', info['person_name']) self.assertEqual([visible_name], info['visible_branches'])
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 __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 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 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 test_setOwner(self): """Test setOwner via the web API does not raise a 404.""" branch_owner = self.factory.makePerson(name='fred') product = self.factory.makeProduct(name='myproduct') self.factory.makeProductBranch( name='mybranch', product=product, owner=branch_owner) self.factory.makeTeam(name='barney', owner=branch_owner) endInteraction() lp = launchpadlib_for("test", person=branch_owner) ws_branch = lp.branches.getByUniqueName( unique_name='~fred/myproduct/mybranch') ws_new_owner = lp.people['barney'] ws_branch.setOwner(new_owner=ws_new_owner) # Check the result. renamed_branch = lp.branches.getByUniqueName( unique_name='~barney/myproduct/mybranch') self.assertIsNotNone(renamed_branch) self.assertEqual( '~barney/myproduct/mybranch', renamed_branch.unique_name)
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)