def test_call_proxies(self): baz = DummyContext() bar = DummyContext(baz) foo = DummyContext(bar) root = DummyContext(foo) from zope.proxy import isProxy policy = self._makeOne(root) environ = self._getEnviron(PATH_INFO='/foo/bar/baz') result = policy(environ) ctx, name, subpath, traversed, vroot, vroot_path = ( result['context'], result['view_name'], result['subpath'], result['traversed'], result['virtual_root'], result['virtual_root_path']) self.assertEqual(name, '') self.assertEqual(subpath, ()) self.assertEqual(ctx, baz) self.failUnless(isProxy(ctx)) self.assertEqual(ctx.__name__, 'baz') self.assertEqual(ctx.__parent__, bar) self.failUnless(isProxy(ctx.__parent__)) self.assertEqual(ctx.__parent__.__name__, 'bar') self.assertEqual(ctx.__parent__.__parent__, foo) self.failUnless(isProxy(ctx.__parent__.__parent__)) self.assertEqual(ctx.__parent__.__parent__.__name__, 'foo') self.assertEqual(ctx.__parent__.__parent__.__parent__, root) self.failUnless(isProxy(ctx.__parent__.__parent__.__parent__)) self.assertEqual(ctx.__parent__.__parent__.__parent__.__name__, None) self.assertEqual(ctx.__parent__.__parent__.__parent__.__parent__, None) self.assertEqual(traversed, (u'foo', u'bar', u'baz',)) self.assertEqual(vroot, root) self.assertEqual(vroot_path, ())
def what_changed(sqlobject_modified_event): before = sqlobject_modified_event.object_before_modification after = sqlobject_modified_event.object fields = sqlobject_modified_event.edited_fields changes = {} for fieldname in fields: # XXX 2011-01-21 gmb bug=705955: # Sometimes, something (webservice, I'm looking at you # here), will create an ObjectModifiedEvent where the # edited_fields list is actually a list of field instances # instead of strings. We special-case that here, but we # shouldn't have to. if IField.providedBy(fieldname): fieldname = fieldname.getName() val_before = getattr(before, fieldname, None) val_after = getattr(after, fieldname, None) #XXX Bjorn Tillenius 2005-06-09: This shouldn't be necessary. # peel off the zope stuff if isProxy(val_before): val_before = removeSecurityProxy(val_before) if isProxy(val_after): val_after = removeSecurityProxy(val_after) before_string = get_string_representation(val_before) after_string = get_string_representation(val_after) if before_string != after_string: changes[fieldname] = [before_string, after_string] return changes
def test_call_proxies(self): baz = DummyContext() bar = DummyContext(baz) foo = DummyContext(bar) root = DummyContext(foo) from zope.proxy import isProxy policy = self._makeOne(root) environ = self._getEnviron(PATH_INFO='/foo/bar/baz') result = policy(environ) ctx, name, subpath, traversed, vroot, vroot_path = ( result['context'], result['view_name'], result['subpath'], result['traversed'], result['virtual_root'], result['virtual_root_path']) self.assertEqual(name, '') self.assertEqual(subpath, ()) self.assertEqual(ctx, baz) self.failUnless(isProxy(ctx)) self.assertEqual(ctx.__name__, 'baz') self.assertEqual(ctx.__parent__, bar) self.failUnless(isProxy(ctx.__parent__)) self.assertEqual(ctx.__parent__.__name__, 'bar') self.assertEqual(ctx.__parent__.__parent__, foo) self.failUnless(isProxy(ctx.__parent__.__parent__)) self.assertEqual(ctx.__parent__.__parent__.__name__, 'foo') self.assertEqual(ctx.__parent__.__parent__.__parent__, root) self.failUnless(isProxy(ctx.__parent__.__parent__.__parent__)) self.assertEqual(ctx.__parent__.__parent__.__parent__.__name__, None) self.assertEqual(ctx.__parent__.__parent__.__parent__.__parent__, None) self.assertEqual(traversed, ( u'foo', u'bar', u'baz', )) self.assertEqual(vroot, root) self.assertEqual(vroot_path, ())
def default(self, o, **settings): if proxy.isProxy(o, JSONEncoderSettingsProxy): o, settings = proxy.getProxiedObject(o), o.__json_settings__ if proxy.isProxy(o): o = proxy.removeAllProxies(o) return o adapter = self.adapters.lookup_adapter(providedBy(o)) if adapter is None: raise TypeError("%r is not JSON serializable" % o) return adapter(o, **settings)
def test_located_proxy_factory(self): # Passing locate results in a security proxy around a location proxy from zope.proxy import isProxy from zope.security.proxy import removeSecurityProxy from zope.component.testfiles.components import Content from zope.component.testfiles.adapter import I1 from zope.security.checker import ProxyFactory from zope.location.location import LocationProxy self._runSnippet(''' <adapter for="zope.component.testfiles.components.IContent" provides="zope.component.testfiles.adapter.I1" factory="zope.component.testfiles.adapter.A1" trusted="yes" locate="yes" /> ''') ob = Content() p = ProxyFactory(ob) a = I1(p) self.assertTrue(isProxy(a)) self.assertTrue(type(removeSecurityProxy(a)) is LocationProxy)
def testProxy(self): path = os.path.join(test_directory, 'testfiles') request = TestRequest() factory = DirectoryResourceFactory(path, checker, 'testfiles') resource = factory(request) file = ProxyFactory(resource['test.txt']) self.assertTrue(isProxy(file))
def testProxy(self): path = os.path.join(test_directory, 'testfiles') request = TestRequest() factory = DirectoryResourceFactory(path, checker, 'testfiles') resource = factory(request) file = ProxyFactory(resource['test.txt']) self.assert_(isProxy(file))
def test_function_namespaces_return_secured_proxies(self): # See https://bugs.launchpad.net/zope3/+bug/98323 from zope.component import provideAdapter from zope.traversing.interfaces import IPathAdapter from zope.pagetemplate.engine import _Engine from zope.proxy import isProxy provideAdapter(DummyNamespace, (None, ), IPathAdapter, name='test') engine = _Engine() namespace = engine.getFunctionNamespace('test') self.failUnless(isProxy(namespace))
def test_function_namespaces_return_secured_proxies(self): # See https://bugs.launchpad.net/zope3/+bug/98323 from zope.component import provideAdapter from zope.traversing.interfaces import IPathAdapter from zope.pagetemplate.engine import _Engine from zope.proxy import isProxy provideAdapter(DummyNamespace, (None,), IPathAdapter, name='test') engine = _Engine() namespace = engine.getFunctionNamespace('test') self.failUnless(isProxy(namespace))
def test_security_proxy(self): """Our vocabularies should be registered with <securedutility>.""" vocabularies = getUtilitiesFor(IVocabularyFactory) for name, vocab in vocabularies: # If the vocabulary is not in a security proxy, check # whether it is a vocabulary defined by zope, which are # not registered with <securedutility> and can be ignored. if not isProxy(vocab) and vocab.__module__[:5] != 'zope.': raise AssertionError( '%s.%s vocabulary is not wrapped in a security proxy.' % ( vocab.__module__, name))
def test_security_proxy(self): """Our vocabularies should be registered with <securedutility>.""" vocabularies = getUtilitiesFor(IVocabularyFactory) for name, vocab in vocabularies: # If the vocabulary is not in a security proxy, check # whether it is a vocabulary defined by zope, which are # not registered with <securedutility> and can be ignored. if not isProxy(vocab) and vocab.__module__[:5] != 'zope.': raise AssertionError( '%s.%s vocabulary is not wrapped in a security proxy.' % (vocab.__module__, name))
def test_extraBuildArgs_channels(self): # If the build needs particular channels, extraBuildArgs sends them. job = self.makeJob(channels={"snapcraft": "edge"}) expected_archives, expected_trusted_keys = ( yield get_sources_list_for_building(job.build, job.build.distro_arch_series, None)) with dbuser(config.builddmaster.dbuser): args = yield job.extraBuildArgs() self.assertFalse(isProxy(args["channels"])) self.assertEqual({"snapcraft": "edge"}, args["channels"])
def test_extraBuildArgs_channels_feature_flag_real_channel(self): # If the snap.channels.snapcraft feature flag is set, it identifies # the default channel to be used for snapcraft. self.useFixture( FeatureFixture({SNAP_SNAPCRAFT_CHANNEL_FEATURE_FLAG: "stable"})) job = self.makeJob() expected_archives, expected_trusted_keys = ( yield get_sources_list_for_building(job.build, job.build.distro_arch_series, None)) with dbuser(config.builddmaster.dbuser): args = yield job.extraBuildArgs() self.assertFalse(isProxy(args["channels"])) self.assertEqual({"snapcraft": "stable"}, args["channels"])
def test_izapi(self): """ Ensure that the zapi module provides the IZAPI interface """ from zope.app import zapi # deprecation proxies don't seem to always work with # verifyObject, so remove any proxies if isProxy(zapi): zapi = removeAllProxies(zapi) # we don't want to generate warnings for deprecated # attrs import zope.deprecation zope.deprecation.__show__.off() verifyObject(IZAPI, zapi) zope.deprecation.__show__.on()
def setUpEditWidgets(view, schema, source=None, prefix=None, ignoreStickyValues=False, names=None, context=None, degradeInput=False, degradeDisplay=False): """Sets up widgets to collect input on a view. See `setUpWidgets` for details on `view`, `schema`, `prefix`, `ignoreStickyValues`, `names`, and `context`. `source`, if specified, is an object from which initial widget values are read. If source is not specified, the view context is used as the source. `degradeInput` is a flag that changes the behavior when a user does not have permission to edit a field in the names. By default, the function raises Unauthorized. If degradeInput is True, the field is changed to an IDisplayWidget. `degradeDisplay` is a flag that changes the behavior when a user does not have permission to access a field in the names. By default, the function raises Unauthorized. If degradeDisplay is True, the field is removed from the form. Returns a list of names, equal to or a subset of the names that were supposed to be drawn, with uninitialized undrawn fields missing. """ if context is None: context = view.context if source is None: source = view.context security_proxied = isProxy(source, Proxy) res_names = [] for name, field in _fieldlist(names, schema): try: value = field.get(source) except ForbiddenAttribute: raise except AttributeError, v: value = no_value except Unauthorized: if degradeDisplay: continue else: raise
def __call__(self, object, path_items, econtext): """Traverses a sequence of names, first trying attributes then items. """ request = getattr(econtext, 'request', None) path_items = list(path_items) path_items.reverse() while path_items: name = path_items.pop() # special-case dicts for performance reasons if getattr(object, '__class__', None) == dict: object = object[name] elif isinstance(object, dict) and not isProxy(object): object = object[name] else: object = traversePathElement(object, name, path_items, request=request) object = self.proxify(object) return object
def test_with_proxy_factory_public_permission(self): # Using the public permission doesn't give you a location proxy from zope.proxy import isProxy from zope.security.proxy import removeSecurityProxy from zope.component.testfiles.components import Content from zope.component.testfiles.adapter import I1, A1 from zope.security.checker import ProxyFactory self._runSnippet(''' <adapter for="zope.component.testfiles.components.IContent" provides="zope.component.testfiles.adapter.I1" factory="zope.component.testfiles.adapter.A1" permission="zope.Public" trusted="yes" />''') ob = Content() p = ProxyFactory(ob) a = I1(p) self.assertTrue(isProxy(a)) self.assertTrue(type(removeSecurityProxy(a)) is A1)
def setUpEditWidgets(view, schema, source=None, prefix=None, ignoreStickyValues=False, names=None, context=None, degradeInput=False, degradeDisplay=False): """Sets up widgets to collect input on a view. See `setUpWidgets` for details on `view`, `schema`, `prefix`, `ignoreStickyValues`, `names`, and `context`. `source`, if specified, is an object from which initial widget values are read. If source is not specified, the view context is used as the source. `degradeInput` is a flag that changes the behavior when a user does not have permission to edit a field in the names. By default, the function raises Unauthorized. If degradeInput is True, the field is changed to an IDisplayWidget. `degradeDisplay` is a flag that changes the behavior when a user does not have permission to access a field in the names. By default, the function raises Unauthorized. If degradeDisplay is True, the field is removed from the form. Returns a list of names, equal to or a subset of the names that were supposed to be drawn, with uninitialized undrawn fields missing. """ if context is None: context = view.context if source is None: source = view.context security_proxied = isProxy(source, Proxy) res_names = [] for name, field in _fieldlist(names, schema): try: value = field.get(source) except ForbiddenAttribute: raise except AttributeError: value = no_value except Unauthorized: if degradeDisplay: continue else: raise if field.readonly: viewType = IDisplayWidget else: if security_proxied: is_accessor = IMethod.providedBy(field) if is_accessor: set_name = field.writer.__name__ authorized = security.canAccess(source, set_name) else: set_name = name authorized = security.canWrite(source, name) if not authorized: if degradeInput: viewType = IDisplayWidget else: raise Unauthorized(set_name) else: viewType = IInputWidget else: # if object is not security proxied, might be a standard # adapter without a registered checker. If the feature of # paying attention to the users ability to actually set a # field is decided to be a must-have for the form machinery, # then we ought to change this case to have a deprecation # warning. viewType = IInputWidget setUpWidget(view, name, field, viewType, value, prefix, ignoreStickyValues, context) res_names.append(name) return res_names
def _callFUT(self, *args): from zope.proxy import isProxy return isProxy(*args)
def test_function_namespaces_return_secured_proxies(self): # See https://bugs.launchpad.net/zope3/+bug/98323 from zope.proxy import isProxy engine = self._makeOne() namespace = engine.getFunctionNamespace('test') self.assertTrue(isProxy(namespace))