def __BBB_old_getComponent(self, path): service_manager = zapi.getSiteManager(self) # Get the root and unproxy it if path.startswith("/"): # Absolute path root = removeAllProxies(zapi.getRoot(service_manager)) component = zapi.traverse(root, path) else: # Relative path. ancestor = self.__parent__.__parent__ component = zapi.traverse(ancestor, path) if self.permission: if type(component) is Proxy: # There should be at most one security Proxy around an object. # So, if we're going to add a new security proxy, we need to # remove any existing one. component = removeSecurityProxy(component) interface = self.getInterface() checker = InterfaceChecker(interface, self.permission) component = Proxy(component, checker) return component
def addUtility(sitemanager, name, iface, utility, suffix=''): """Add a utility to a site manager This helper function is useful for tests that need to set up utilities. """ folder_name = (name or (iface.__name__ + 'Utility')) + suffix default = zapi.traverse(sitemanager, 'default') default[folder_name] = utility registration = UtilityRegistration(name, iface, default[folder_name]) key = default.registrationManager.addRegistration(registration) zapi.traverse(default.registrationManager, key).status = ActiveStatus return default[folder_name]
def test_traverseToField(self): context = xmlconfig.file("fields.zcml", zope.app.schema.tests) s = self.s s.addField(u'alpha', self.alpha) s = ProxyFactory(s) f1 = ProxyFactory(s[u'alpha']) order = f1.order f1 = zapi.traverse(s, 'alpha') self.assertEquals(f1.order, self.alpha.order) title = zapi.traverse(f1, 'title') self.assertEquals(title, self.alpha.title) fields = getFieldsInOrder(s) for k, v in fields: self.failUnless(v.title is not None)
def addService(servicemanager, name, service, suffix=''): """Add a service to a service manager This utility is useful for tests that need to set up services. """ # Most local services implement ISimpleService in ZCML; therefore make # sure we got it here as well. zope.interface.directlyProvides(service, ISimpleService) default = zapi.traverse(servicemanager, 'default') default[name+suffix] = service registration = UtilityRegistration(name, IService, service, default) key = default.registrationManager.addRegistration(registration) zapi.traverse(default.registrationManager, key).status = ActiveStatus return default[name+suffix]
def pasteable(self): """Decide if there is anything to paste """ target = self.context clipboard = getPrincipalClipboard(self.request) items = clipboard.getContents() for item in items: try: obj = zapi.traverse(target, item['target']) except TraversalError: pass else: if item['action'] == 'cut': mover = IObjectMover(obj) moveableTo = self.safe_getattr(mover, 'moveableTo', None) if moveableTo is None or not moveableTo(target): return False elif item['action'] == 'copy': copier = IObjectCopier(obj) copyableTo = self.safe_getattr(copier, 'copyableTo', None) if copyableTo is None or not copyableTo(target): return False else: raise return True
def hasClipboardContents(self): """Interogate the ``PrinicipalAnnotation`` to see if clipboard contents exist.""" if not self.supportsPaste: return False # touch at least one item to in clipboard confirm contents clipboard = getPrincipalClipboard(self.request) items = clipboard.getContents() for item in items: try: zapi.traverse(self.context, item['target']) except TraversalError: pass else: return True return False
def findAllClasses(self): """Find all classes Examples:: >>> from zope.app import zapi >>> from zope.app.apidoc.codemodule.class_ import Class >>> from zope.app.apidoc.interfaces import IDocumentationModule >>> cm = zapi.getUtility(IDocumentationModule, 'Code') >>> mod = cm['zope']['app']['apidoc']['codemodule']['browser'] Setup a couple of classes and register them. >>> class Foo(object): ... pass >>> mod._children['Foo'] = Class(mod, 'Foo', Foo) >>> class Foo2(object): ... pass >>> mod._children['Foo2'] = Class(mod, 'Foo2', Foo2) >>> class Blah(object): ... pass >>> mod._children['Blah'] = Class(mod, 'Blah', Blah) Setup the view. >>> from zope.app.apidoc.codemodule.browser.menu import Menu >>> from zope.publisher.browser import TestRequest >>> menu = Menu() >>> menu.context = None Testing the method with various inputs. >>> menu.request = TestRequest(form={'path': 'Foo'}) >>> info = menu.findAllClasses() >>> len(info) > 3 True """ classModule = zapi.getUtility(IDocumentationModule, "Code") classModule.setup() # run setup if not yet done results = [] counter = 0 for p in classRegistry.keys(): klass = zapi.traverse(classModule, p.replace('.', '/')) results.append( {'path': p, 'url': zapi.absoluteURL(klass, self.request), 'counter': counter }) counter += 1 results.sort(lambda x, y: cmp(x['path'], y['path'])) return results
def __get__(self, inst, cls=None): if inst is None: return self try: # Use __dict__ directly to avoid infinite recursion root = inst.__dict__['rootFolder'] except KeyError: root = inst.rootFolder = setup.buildSampleFolderTree() return zapi.traverse(root, self.path)
def __call__(self): """See zope.app.browser.interfaces.form.IBrowserWidget""" # Render as a link to the component field = self.context context = field.context if interfaces.registration.IRegistration.providedBy(context): # It's a registration object. Just get the corresponding attr path = getattr(context, field.__name__) # The path may be relative; then interpret relative to ../.. if not path.startswith("/"): context = zapi.traverse(context, "../..") component = zapi.traverse(context, path) else: # It must be a component that is about to be configured. component = context # Always use a relative path (just the component name) path = zapi.name(context) url = zapi.absoluteURL(component, self.request) return ('<a href="%s/@@SelectedManagementView.html">%s</a>' % (url, path))
def __init__(self, context, request): super(Introspector, self).__init__(context, request) path = apidoc.utilities.getPythonPath( context.__class__).replace('.', '/') # the ++apidoc++ namespace overrides the skin, so make sure we can get # it back. direct = list(directlyProvidedBy(request)) self.klassView = zapi.traverse( TraversalRoot(), '/++apidoc++/Code/%s/@@index.html' %path, request=request) directlyProvides(request, direct)
def pasteObjects(self): """Paste ojects in the user clipboard to the container """ target = self.context clipboard = getPrincipalClipboard(self.request) items = clipboard.getContents() moved = False not_pasteable_ids = [] for item in items: duplicated_id = False try: obj = zapi.traverse(target, item['target']) except TraversalError: pass else: if item['action'] == 'cut': mover = IObjectMover(obj) try: mover.moveTo(target) moved = True except DuplicateIDError: duplicated_id = True elif item['action'] == 'copy': copier = IObjectCopier(obj) try: copier.copyTo(target) except DuplicateIDError: duplicated_id = True else: raise if duplicated_id: not_pasteable_ids.append(zapi.getName(obj)) if moved: # Clear the clipboard if we do a move, but not if we only do a copy clipboard.clearContents() if not_pasteable_ids != []: # Show the ids of objects that can't be pasted because # their ids are already taken. # TODO Can't we add a 'copy_of' or something as a prefix # instead of raising an exception ? raise UserError( _("The given name(s) %s is / are already being used" %( str(not_pasteable_ids))))
def setUp(self): from zope.app.intid import IntIds from zope.app.intid.interfaces import IIntIds BrowserTestCase.setUp(self) self.basepath = '/++etc++site/default' root = self.getRootFolder() sm = zapi.traverse(root, '/++etc++site') setup.addUtility(sm, 'intid', IIntIds, IntIds()) commit() type_name = 'BrowserAdd__zope.app.intid.IntIds' response = self.publish( self.basepath + '/contents.html', basic='mgr:mgrpw', form={'type_name': type_name, 'new_value': 'mgr' })
def registerHelpTopic(self, parent_path, id, title, doc_path, interface=None, view=None, class_=None, resources=None): "See zope.app.onlineHelp.interfaces.IOnlineHelp" if not os.path.exists(doc_path): raise ConfigurationError( "Help Topic definition %s does not exist" % doc_path ) if class_ is None: class_ = OnlineHelpTopic # Create topic base on the custom class or OnlinHelpTopic topic = class_(id, title, doc_path, parent_path, interface, view) # add resources to topic if resources is not None: topic.addResources(resources) # add topic to onlinehelp hierarchy parent = None try: parent = zapi.traverse(self, parent_path) parent[id] = topic except KeyError: pass for t in zapi.getUtilitiesFor(IOnlineHelpTopic): if parent is None: if t[1].getTopicPath() == parent_path: t[1][id] = topic if topic.getTopicPath() == t[1].parentPath: topic[t[1].id] = t[1] # Add topic to utilities registry #utils = zapi.getService(Utilities) #utils.provideUtility(IOnlineHelpTopic, topic, topic.getTopicPath()) zapi.getGlobalSiteManager().provideUtility( IOnlineHelpTopic, topic, topic.getTopicPath())
def _listClasses(self, classes): """Prepare a list of classes for presentation.""" info = [] codeModule = zapi.getUtility(IDocumentationModule, "Code") for cls in classes: # We need to removeAllProxies because the security checkers for # zope.app.container.contained.ContainedProxy and # zope.app.i18n.messagecatalog.MessageCatalog prevent us from # accessing __name__ and __module__. unwrapped_cls = removeAllProxies(cls) path = getPythonPath(unwrapped_cls) url = None try: klass = zapi.traverse(codeModule, path.replace('.', '/')) url = zapi.absoluteURL(klass, self.request) except TraversalError: # If one of the classes is implemented in C, we will not # be able to find it. pass info.append({'path': path or None, 'url': url}) return info
def test_external_edit(self): basic = "Basic %s" % encodestring("%s:%s" % ("testuser", "testpass")) env = {"HTTP_AUTHORIZATION": basic} request = TestRequest(environ=env) container = zapi.traverse(self.rootFolder, "folder1") file = EditableFile("Foobar", "text/plain") self.assertEqual(file.contentType, "text/plain") self.assertEqual(file.data, "Foobar") file = contained(file, container, "file") view = zapi.queryMultiAdapter((file, request), name="external_edit") self.failIf(view is None) expected = ( """\ url:http://127.0.0.1/folder1/file content_type:text/plain meta_type:IEditableFile auth:%s cookie: Foobar""" % basic[:-1] ) self.assertEqual(view(), expected)
def setUp(self): setup.placefulSetUp() self.rootFolder = setup.buildSampleFolderTree() sm = zapi.getGlobalSiteManager() de_catalog = MessageCatalog("de", "default") de_catalog.setMessage("short_greeting", "Hallo!", 10) # Create global translation domain and add the catalog. domain = GlobalTranslationDomain("default") domain.addCatalog(de_catalog) sm.provideUtility(ITranslationDomain, domain, "default") # Create Domain in root folder mgr = setup.createSiteManager(self.rootFolder) self.trans = setup.addDomain(mgr, Translation, TranslationDomain()) # Create Domain in folder1 mgr = setup.createSiteManager(zapi.traverse(self.rootFolder, "folder1")) td = TranslationDomain() td.domain = "default" de_catalog = MessageCatalog("de", "default") de_catalog.setMessage("short_greeting", "Hallo Welt!", 10) td["de-default-1"] = de_catalog self.trans1 = setup.addDomain(mgr, Translation, ts)
def findClasses(self): """Find the classes that match a partial path. Examples:: >>> from zope.app import zapi >>> from zope.app.apidoc.codemodule.class_ import Class >>> from zope.app.apidoc.interfaces import IDocumentationModule >>> cm = zapi.getUtility(IDocumentationModule, 'Code') >>> mod = cm['zope']['app']['apidoc']['codemodule']['browser'] Setup a couple of classes and register them. >>> class Foo(object): ... pass >>> mod._children['Foo'] = Class(mod, 'Foo', Foo) >>> class Foo2(object): ... pass >>> mod._children['Foo2'] = Class(mod, 'Foo2', Foo2) >>> class Blah(object): ... pass >>> mod._children['Blah'] = Class(mod, 'Blah', Blah) Setup the view. >>> from zope.app.apidoc.codemodule.browser.menu import Menu >>> from zope.publisher.browser import TestRequest >>> menu = Menu() >>> menu.context = None Testing the method with various inputs. >>> menu.request = TestRequest(form={'path': 'Foo'}) >>> info = menu.findClasses() >>> pprint(info) [{'path': 'zope.app.apidoc.codemodule.browser.Foo', 'url': 'http://127.0.0.1/zope/app/apidoc/codemodule/browser/Foo/'}, {'path': 'zope.app.apidoc.codemodule.browser.Foo2', 'url': 'http://127.0.0.1/zope/app/apidoc/codemodule/browser/Foo2/'}] >>> menu.request = TestRequest(form={'path': 'o2'}) >>> info = menu.findClasses() >>> pprint(info) [{'path': 'zope.app.apidoc.codemodule.browser.Foo2', 'url': 'http://127.0.0.1/zope/app/apidoc/codemodule/browser/Foo2/'}] >>> menu.request = TestRequest(form={'path': 'Blah'}) >>> info = menu.findClasses() >>> pprint(info) [{'path': 'zope.app.apidoc.codemodule.browser.Blah', 'url': 'http://127.0.0.1/zope/app/apidoc/codemodule/browser/Blah/'}] """ path = self.request.get('path', None) if path is None: return [] classModule = zapi.getUtility(IDocumentationModule, "Code") results = [] for p in classRegistry.keys(): if p.find(path) >= 0: klass = zapi.traverse(classModule, p.replace('.', '/')) results.append( {'path': p, 'url': zapi.absoluteURL(klass, self.request) + '/' }) results.sort(lambda x, y: cmp(x['path'], y['path'])) return results
def createSiteManager(folder, setsite=False): if not ISite.providedBy(folder): folder.setSiteManager(LocalSiteManager(folder)) if setsite: setSite(folder) return zapi.traverse(folder, "++etc++site")
def makeSite(self, path='/'): folder = zapi.traverse(self.rootFolder, path) return setup.createSiteManager(folder, True)
def populate(self): # TODO: I think this should be moved to the functional test. self.context.register(zapi.traverse(self.context, "/")) self.context.register(zapi.traverse(self.context, "/++etc++site")) self.request.response.redirect('index.html')