def _testBaseTags(self, url, expected): # Make sure I1 and O1 are visible in the module namespace # so that the classes can be pickled. import transaction pub = BrowserPublication(self.db) ztapi.browserView(I1, 'view', DummyView) ztapi.setDefaultViewName(I1, 'view') ztapi.browserViewProviding(None, TestTraverser, IBrowserPublisher) ob = O1() ## the following is for running the tests standalone principalRegistry.defineDefaultPrincipal( 'tim', 'timbot', 'ai at its best') # now place our object inside the application connection = self.db.open() app = connection.root()['Application'] app.somepath = ob transaction.commit() connection.close() defineChecker(app.__class__, NamesChecker(somepath='xxx')) req = self._createRequest(url, pub) response = req.response publish(req, handle_errors=0) self.assertEqual(response.getBase(), expected)
def _testBaseTags(self, url, expected): # Make sure I1 and O1 are visible in the module namespace # so that the classes can be pickled. import transaction pub = BrowserPublication(self.db) ztapi.browserView(I1, 'view', DummyView) ztapi.setDefaultViewName(I1, 'view') ztapi.browserViewProviding(None, TestTraverser, IBrowserPublisher) ob = O1() ## the following is for running the tests standalone principalRegistry.defineDefaultPrincipal('tim', 'timbot', 'ai at its best') # now place our object inside the application connection = self.db.open() app = connection.root()['Application'] app.somepath = ob transaction.commit() connection.close() defineChecker(app.__class__, NamesChecker(somepath='xxx')) req = self._createRequest(url, pub) response = req.response publish(req, handle_errors=0) self.assertEqual(response.getBase(), expected)
def setUp(test): test.globs['rootFolder'] = setup.placefulSetUp(True) class RootModule(str): implements(IAPIDocRootModule) ztapi.provideUtility(IAPIDocRootModule, RootModule('zope'), "zope") module = CodeModule() module.__name__ = '' directlyProvides(module, IContainmentRoot) ztapi.provideUtility(IDocumentationModule, module, "Code") module = ZCMLModule() module.__name__ = '' directlyProvides(module, IContainmentRoot) ztapi.provideUtility(IDocumentationModule, module, "ZCML") # Register Renderer Components ztapi.provideUtility(IFactory, ReStructuredTextSourceFactory, 'zope.source.rest') ztapi.browserView(IReStructuredTextSource, '', ReStructuredTextToHTMLRenderer) # Cheat and register the ReST factory for STX as well. ztapi.provideUtility(IFactory, ReStructuredTextSourceFactory, 'zope.source.stx') # Register ++apidoc++ namespace from zope.app.apidoc.apidoc import apidocNamespace from zope.app.traversing.interfaces import ITraversable ztapi.provideAdapter(None, ITraversable, apidocNamespace, name="apidoc") ztapi.provideView(None, None, ITraversable, "apidoc", apidocNamespace) # Register ++apidoc++ namespace from zope.app.traversing.namespace import view from zope.app.traversing.interfaces import ITraversable ztapi.provideAdapter(None, ITraversable, view, name="view") ztapi.provideView(None, None, ITraversable, "view", view) context = xmlconfig.string(meta) # Fix up path for tests. global old_context old_context = zope.app.appsetup.appsetup.__config_context zope.app.appsetup.appsetup.__config_context = context # Fix up path for tests. global old_source_file old_source_file = zope.app.appsetup.appsetup.__config_source zope.app.appsetup.appsetup.__config_source = os.path.join( os.path.dirname(zope.app.__file__), 'meta.zcml') # Register the index.html view for codemodule.class_.Class from zope.app.apidoc.codemodule.class_ import Class from zope.app.apidoc.codemodule.browser.class_ import ClassDetails from zope.app.publisher.browser import BrowserView class Details(ClassDetails, BrowserView): pass ztapi.browserView(Class, 'index.html', Details)
def testNoNameGiven(self): container = Container() request = TestRequest() adding = Adding(container, request) ztapi.browserView(IAdding, "Thing", CreationView) self.assertEqual(adding.contentName, None) view = adding.publishTraverse(request, 'Thing=') self.assertEqual(adding.contentName, '')
def test_flowplayerlink(self): self.folder.invokeFactory("Link", "fp") link = self.folder["fp"] link.setRemoteUrl("http://www.example.org/myvideo.flv") zope.interface.alsoProvides(link, IVideo) if zope.component.queryMultiAdapter((link, self.app.REQUEST), name="flowplayer") == None: ztapi.browserView(zope.interface.Interface, "flowplayer", DummyView) dispatcher = VideoLink(link, self.app.REQUEST) self.assertEqual(dispatcher._view.__name__, "flowplayer")
def setUp(self): super(TraverserTest, self).setUp() # Create a small object tree self.foo = self._getContainer() foo2 = self._getContainer(Foo=self.foo) # Initiate a request self.request = TestRequest() # Create the traverser self.traverser = self._getTraverser(foo2, self.request) # Define a simple view for the container ztapi.browserView(IReadContainer, 'viewfoo', View)
def testTraverseNameView(self): pub = self.klass(self.db) class I(Interface): pass class C(object): implements(I) ob = C() class V(object): def __init__(self, context, request): pass r = self._createRequest('/@@spam',pub) ztapi.browserView(I, 'spam', V) ob2 = pub.traverseName(r, ob, '@@spam') self.assertEqual(ob2.__class__, V)
def setUp(test): placelesssetup.setUp() # Register Renderer Components ztapi.provideUtility(IFactory, ReStructuredTextSourceFactory, 'zope.source.rest') ztapi.browserView(IReStructuredTextSource, '', ReStructuredTextToHTMLRenderer) # Cheat and register the ReST renderer as the STX one as well. ztapi.provideUtility(IFactory, ReStructuredTextSourceFactory, 'zope.source.stx') ztapi.browserView(IReStructuredTextSource, '', ReStructuredTextToHTMLRenderer) setup.setUpTestAsModule(test, 'zope.app.apidoc.doctest')
def setUp(test): placelesssetup.setUp() setup.setUpTraversal() ztapi.provideAdapter(IInterface, IUniqueId, LocationUniqueId) # Register Renderer Components ztapi.provideUtility(IFactory, ReStructuredTextSourceFactory, 'zope.source.rest') ztapi.browserView(IReStructuredTextSource, '', ReStructuredTextToHTMLRenderer) # Cheat and register the ReST factory for STX as well ztapi.provideUtility(IFactory, ReStructuredTextSourceFactory, 'zope.source.stx')
def test_operationalerror_view_integration(self): # Test setup. self.useFixture(Urllib2Fixture()) class BrokenView(object): """A view that raises an OperationalError""" def __call__(self, *args, **kw): raise OperationalError() ztapi.browserView(None, "error-test", BrokenView()) url = 'http://launchpad.dev/error-test' error = self.getHTTPError(url) self.assertEqual(httplib.SERVICE_UNAVAILABLE, error.code) self.assertThat(error.read(), Contains(OperationalErrorView.reason))
def test(self): container = Container() request = TestRequest() adding = Adding(container, request) ztapi.browserView(IAdding, "Thing", CreationView) self.assertEqual(adding.contentName, None) view = adding.publishTraverse(request, 'Thing=foo') self.assertEqual(view.action(), 'been there, done that') self.assertEqual(adding.contentName, 'foo') o = object() result = adding.add(o) # Check the state of the container and result self.assertEqual(container["foo"], o) self.assertEqual(result, o)
def test_operationalerror_view_integration(self): # Test setup. self.useFixture(Urllib2Fixture()) class BrokenView(object): """A view that raises an OperationalError""" def __call__(self, *args, **kw): raise OperationalError() ztapi.browserView(None, "error-test", BrokenView()) url = "http://launchpad.dev/error-test" error = self.getHTTPError(url) self.assertEqual(httplib.SERVICE_UNAVAILABLE, error.code) self.assertThat(error.read(), Contains(OperationalErrorView.reason))
def setUp(self): super(TestAbsoluteURL, self).setUp() from zope.app.traversing.browser import AbsoluteURL, SiteAbsoluteURL ztapi.browserView(None, 'absolute_url', AbsoluteURL) ztapi.browserView(IRoot, 'absolute_url', SiteAbsoluteURL) ztapi.browserView(None, '', AbsoluteURL, providing=IAbsoluteURL) ztapi.browserView(IRoot, '', SiteAbsoluteURL, providing=IAbsoluteURL) ztapi.provideAdapter(IHTTPRequest, IUserPreferredCharsets, HTTPCharsets)
def setUp(self, doctesttest=None): CAPlacelessSetup.setUp(self) EventPlacelessSetup.setUp(self) ContainerPlacelessSetup.setUp(self) I18nPlacelessSetup.setUp(self) setUpPasswordManagers() ztapi.browserView(None, 'absolute_url', AbsoluteURL) ztapi.browserViewProviding(None, AbsoluteURL, IAbsoluteURL) from zope.security.testing import addCheckerPublic addCheckerPublic() from zope.security.management import newInteraction newInteraction() setVocabularyRegistry(None)
def testTraverseNameView(self): pub = self.klass(self.db) class I(Interface): pass class C(object): implements(I) ob = C() class V(object): def __init__(self, context, request): pass r = self._createRequest('/@@spam', pub) ztapi.browserView(I, 'spam', V) ob2 = pub.traverseName(r, ob, '@@spam') self.assertEqual(ob2.__class__, V)
def setUp(test): root_folder = setup.placefulSetUp(True) ztapi.provideAdapter(IInterface, IUniqueId, LocationUniqueId) # Set up apidoc module test.globs['apidoc'] = APIDocumentation(root_folder, '++apidoc++') # Register InterfaceModule ztapi.provideUtility(IDocumentationModule, InterfaceModule(), "Interface") # Register Renderer Components ztapi.provideUtility(IFactory, ReStructuredTextSourceFactory, 'zope.source.rest') ztapi.browserView(IReStructuredTextSource, '', ReStructuredTextToHTMLRenderer) # Cheat and register the ReST factory for STX as well ztapi.provideUtility(IFactory, ReStructuredTextSourceFactory, 'zope.source.stx')
def test_template_context_wrapping(self): class AU(BrowserView): def __str__(self): name = self.context.__name__ if name is None: return 'None' return name defineChecker(AU, NamesChecker(['__str__'])) from zope.traversing.namespace import view ztapi.provideNamespaceHandler('view', view) ztapi.browserView(IZPTPage, 'name', AU) page = ZPTPage() page.setSource(u'<p tal:replace="template/@@name" />') page = contained(page, None, name='zpt') request = TestRequest() self.assertEquals(page.render(request), u'zpt')
def setUp(self, doctesttest=None): CAPlacelessSetup.setUp(self) ContainerPlacelessSetup.setUp(self) EventPlacelessSetup.setUp(self) I18nPlacelessSetup.setUp(self) AuthenticationPlacelessSetup.setUp(self) # Register app-specific security declarations protect() ztapi.browserView(None, 'absolute_url', AbsoluteURL) ztapi.browserViewProviding(None, AbsoluteURL, IAbsoluteURL) from zope.app.security.tests import addCheckerPublic addCheckerPublic() from zope.security.management import newInteraction newInteraction() setVocabularyRegistry(None)
def test_template_context_wrapping(self): class AU(BrowserView): def __str__(self): name = self.context.__name__ if name is None: return 'None' return name defineChecker(AU, NamesChecker(['__str__'])) from zope.app.traversing.namespace import view ztapi.provideNamespaceHandler('view', view) ztapi.browserView(IZPTPage, 'name', AU) page = ZPTPage() page.setSource( u'<p tal:replace="template/@@name" />' ) page = contained(page, None, name='zpt') request = TestRequest() self.assertEquals(page.render(request), 'zpt\n')
def test_configInfo(self): class V(BrowserView): def setPrefix(self, p): self._prefix = p ztapi.browserView(I, 'ItemEdit', V) c1 = C() c2 = C() c7 = C() d = Container({'1': c1, '2': c2, '7': c7}) c1.__parent__ = d; c1.__name__ = '1' c2.__parent__ = d; c2.__name__ = '2' c7.__parent__ = d; c7.__name__ = '7' view = EditRegistration(d, TestRequest()) info = view.configInfo() self.assertEqual(len(info), 3) self.assertEqual(info[0]['name'], '1') self.assertEqual(info[1]['name'], '2') self.assertEqual(info[2]['name'], '7')
def testXMLTreeViews(self): rcxov = ReadContainerXmlObjectView treeView = rcxov(self.folder1, TestRequest()).singleBranchTree check_xml(treeView(), util.read_output("test1.xml")) treeView = rcxov(self.folder1, TestRequest()).children check_xml(treeView(), util.read_output("test2.xml")) treeView = rcxov(self.folder1_1_1, TestRequest()).children check_xml(treeView(), util.read_output("test3.xml")) treeView = rcxov(self.rootFolder, TestRequest()).children check_xml(treeView(), util.read_output("test4.xml")) file1 = File() self.folder1_1_1["file1"] = file1 self.file1 = traverse(self.rootFolder, "/folder1/folder1_1/folder1_1_1/file1") class ReadContainerView(ReadContainerXmlObjectView): implements(IBrowserPublisher) def browserDefault(self, request): return self, () def publishTraverse(self, request, name): raise NotFound(self, name, request) def __call__(self): return self.singleBranchTree() ztapi.browserView(IReadContainer, "singleBranchTree.xml", ReadContainerView) treeView = rcxov(self.folder1_1_1, TestRequest()).singleBranchTree check_xml(treeView(), util.read_output("test5.xml")) treeView = XmlObjectView(self.file1, TestRequest()).singleBranchTree check_xml(treeView(), util.read_output("test5.xml"))
def test_action(self): container = Container() container = contained(container, Root(), "container") request = TestRequest() adding = Adding(container, request) adding.__name__ = "+" ztapi.browserView(IAdding, "Thing", CreationView) ztapi.browserView(Interface, "absolute_url", AbsoluteURL) ztapi.browserView(None, "", AbsoluteURL, providing=IAbsoluteURL) self.assertRaises(UserError, adding.action, "", "foo") adding.action("Thing", "foo") self.assertEqual(adding.request.response.getHeader("location"), "/container/+/Thing=foo") adding.action("Thing/screen1", "foo") self.assertEqual(adding.request.response.getHeader("location"), "/container/+/Thing/screen1=foo")
def test_action(self): container = Container() container = contained(container, Root(), "container") request = TestRequest() adding = Adding(container, request) adding.__name__ = '+' ztapi.browserView(IAdding, "Thing", CreationView) ztapi.browserView(Interface, "absolute_url", AbsoluteURL) ztapi.browserView(None, '', AbsoluteURL, providing=IAbsoluteURL) self.assertRaises(UserError, adding.action, '', 'foo') adding.action('Thing', 'foo') self.assertEqual(adding.request.response.getHeader('location'), '/container/+/Thing=foo') adding.action('Thing/screen1', 'foo') self.assertEqual(adding.request.response.getHeader('location'), '/container/+/Thing/screen1=foo')
def setUpTraversal(): from zope.app.traversing.browser import SiteAbsoluteURL, AbsoluteURL ztapi.provideAdapter(None, ITraverser, Traverser) ztapi.provideAdapter(None, ITraversable, DefaultTraversable) ztapi.provideAdapter( ISimpleReadContainer, ITraversable, ContainerTraversable) ztapi.provideAdapter( None, IPhysicallyLocatable, LocationPhysicallyLocatable) ztapi.provideAdapter( IContainmentRoot, IPhysicallyLocatable, RootPhysicallyLocatable) # set up etc namespace ztapi.provideAdapter(None, ITraversable, etc, name="etc") ztapi.provideView(None, None, ITraversable, "etc", etc) ztapi.browserView(None, "absolute_url", AbsoluteURL) ztapi.browserView(IContainmentRoot, "absolute_url", SiteAbsoluteURL) ztapi.browserView(None, '', AbsoluteURL, providing=IAbsoluteURL) ztapi.browserView(IContainmentRoot, '', SiteAbsoluteURL, providing=IAbsoluteURL)
from zope.app.testing import ztapi from dummy import ISOAPException, SOAPExceptionView ztapi.browserView(ISOAPException, u'index.html', SOAPExceptionView) and then within your SOAP logic raise a SOAP exception where needed: from dummy import SOAPException raise SOAPException(request) """ def __init__(self, context, request): self.context = context self.request = request def __call__(self): faultstring = self.request['faultexc'].__class__.__name__ self.request.response.setStatus('InternalServerError', reason=faultstring) faultcode = 'Server' fault = make_soap_fault(faultstring, faultcode, detail=None) self.request.response.setHeader('Content-Type', 'text/xml') return ElementTree.tostring(fault, encoding=string_encoding) # The following registers 'SOAPExceptionView' as an adapter that knows how to # display (generate and return the XML source for a SOAP fault) for anything # that implements the 'ISOAPException' interface. ztapi.browserView(ISOAPException, u'index.html', SOAPExceptionView)
def setUp(test=None): """Set up the test fixture for schooltool.app.browser doctests. Performs what is called a "placeless setup" in the Zope 3 world, then sets up annotations, relationships, and registers widgets as views for some schema fields. In effect, duplicates a subset of ZCML configuration -- just enough to actually render our page templates in unit tests. """ setup.placefulSetUp() setup.setUpAnnotations() setup.setUpTraversal() # relationships setUpRelationships() # widgets ztapi.browserViewProviding(IPassword, PasswordWidget, IInputWidget) ztapi.browserViewProviding(ITextLine, TextWidget, IInputWidget) ztapi.browserViewProviding(IText, TextAreaWidget, IInputWidget) ztapi.browserViewProviding(IBytes, BytesWidget, IInputWidget) ztapi.browserViewProviding(IBool, CheckBoxWidget, IInputWidget) ztapi.browserViewProviding(IDate, DateWidget, IInputWidget) ztapi.browserViewProviding(IInt, IntWidget, IInputWidget) ztapi.browserViewProviding(IChoice, ChoiceInputWidget, IInputWidget) ztapi.browserViewProviding(ICollection, CollectionInputWidget, IInputWidget) ztapi.provideMultiView((IChoice, IIterableVocabulary), IBrowserRequest, IInputWidget, '', DropdownWidget) ztapi.provideMultiView((ISet, IChoice), IBrowserRequest, IInputWidget, '', ChoiceCollectionInputWidget) ztapi.provideMultiView((IList, IChoice), IBrowserRequest, IInputWidget, '', ChoiceCollectionInputWidget) ztapi.provideMultiView((IList, IVocabularyTokenized), IBrowserRequest, IInputWidget, '', OrderedMultiSelectWidget) # XXX MultiSelectWidget doesn't work with sets :/ # http://www.zope.org/Collectors/Zope3-dev/360 ztapi.provideMultiView((ISet, IIterableVocabulary), IBrowserRequest, IInputWidget, '', MultiSelectWidget) # errors in forms ztapi.browserViewProviding(IWidgetInputError, WidgetInputErrorView, IWidgetInputErrorView) # Now, the question is: does the speed of the tests run with the # setup below justify this complex setup that duplicates the ZCML? # For now, I say yes. -- not mg, perhaps alga or gintas # ++view++ ztapi.provideView(None, None, ITraversable, 'view', view) ztapi.provideView(None, None, ITraversable, 'resource', resource) # schooltool: namespace in tal provideAdapter(SchoolToolAPI, (None,), IPathAdapter, 'schooltool') # sortby: namespace in tal provideAdapter(SortBy, (None,), IPathAdapter, 'sortby') # standard_macros, schooltool_macros and schooltool_navigation ztapi.browserView(None, 'standard_macros', StandardMacros) ztapi.browserView(None, 'view_macros', SimpleViewClass("../../skin/templates/view_macros.pt")) ztapi.browserView(None, 'schooltool_macros', SchoolToolMacros) ztapi.browserView(None, 'calendar_macros', SimpleViewClass("./templates/calendar_macros.pt")) ztapi.browserView(None, 'generic_macros', SimpleViewClass("../../skin/templates/generic_macros.pt")) # form macros ztapi.browserView(None, 'form_macros', FormMacros) import zope.formlib base = zope.formlib.__path__[0] ztapi.browserView(None, 'widget_macros', SimpleViewClass(os.path.join(base, 'widget_macros.pt'))) # resources class ResourceStub: def __init__(self, request): self.request = request def __getitem__(self, key): return ResourceStub(self.request) def __call__(self): return "a dummy resource" for name in ['layout.css', 'schooltool.css', 'schooltool.js', 'next.png', 'prev.png', 'favicon.ico', 'print.css', 'jquery.js', 'zonki-regular.png']: ztapi.browserResource(name, ResourceStub) # menus ztapi.browserView(None, 'view_get_menu', MenuAccessView) provideUtility(BrowserMenuStub('schooltool_actions'), IBrowserMenu, 'schooltool_actions') # `provider` TALES namespaces from zope.browserpage import metaconfigure from zope.contentprovider import tales metaconfigure.registerType('provider', tales.TALESProviderExpression) # viewlet manager registrations from zope.viewlet import manager from schooltool import skin name = 'schooltool.Header' provideAdapter( manager.ViewletManager(name, skin.IHeaderManager), (Interface, IDefaultBrowserLayer, IBrowserView), skin.IHeaderManager, name=name) name = 'schooltool.JavaScript' provideAdapter( manager.ViewletManager(name, skin.IJavaScriptManager), (Interface, IDefaultBrowserLayer, IBrowserView), skin.IJavaScriptManager, name=name) name = 'schooltool.CSS' provideAdapter( manager.ViewletManager(name, skin.ICSSManager), (Interface, IDefaultBrowserLayer, IBrowserView), skin.ICSSManager, name=name) name = 'schooltool.MenuBar' provideAdapter( manager.ViewletManager(name, skin.skin.IMenuBarMenuManager), (Interface, IDefaultBrowserLayer, IBrowserView), skin.skin.IMenuBarMenuManager, name=name) name = 'schooltool.NavigationMenu' provideAdapter( manager.ViewletManager(name, skin.skin.INavigationManager), (Interface, IDefaultBrowserLayer, IBrowserView), skin.skin.INavigationManager, name=name) name = 'schooltool.ActionsMenu' provideAdapter( manager.ViewletManager(name, skin.skin.IActionMenuManager), (Interface, IDefaultBrowserLayer, IBrowserView), skin.skin.IActionMenuManager, name=name)
def setUp(self): PlacefulSetup.setUp(self) PlacefulSetup.buildFolders(self) ztapi.browserView(IExternallyEditable, "external_edit", ExternalEditor) ztapi.provideAdapter(IExternallyEditable, IReadFile, ReadFileAdapter) directlyProvides(IEditableFile, IContentType)
def setUp(self): super(CookieTreeViewTest, self).setUp() ztapi.browserView(None, 'cookie_tree', CookieTreeView)
def setUp(self): super(StatefulTreeViewTest, self).setUp() self.makeItems() # provide the view for all objects (None) ztapi.browserView(None, 'stateful_tree', StatefulTreeView)
def testView(self): ztapi.browserView(IContent, 'foo', View) ob = Content() v = view(ob, TestRequest()).traverse('foo', ()) self.assertEqual(v.__class__, View)
def setUp(self): PlacefulSetup.setUp(self) ztapi.browserView(I, "page1", page1) ztapi.browserView(I, "collides_with_page1", collides_with_page1) ztapi.browserView(I, "works_with_page1", works_with_page1)
def setUp(): """Setup for tests.""" testing.setUp() ztapi.browserView(IFoo, '', FooWidget, providing=IFooWidget) ztapi.browserView(IBar, '', BarWidget, providing=IBarWidget)
def setUp(self): super(ZPTSourceTest, self).setUp() ztapi.browserView(IZPTPage, 'source.html', ZPTSourceView)