def test_dataContextCreation(self): data = {'foo': 'oof', 'bar': 'rab'} doc = tags.p(data=data)[tags.slot('foo'), tags.slot('bar')] doc.fillSlots('foo', tags.invisible(data=tags.directive('foo'), render=str)) doc.fillSlots('bar', lambda ctx, data: data['bar']) self.assertEquals(flat.flatten(doc), '<p>oofrab</p>')
class GroupFragment(rend.Fragment): docFactory = loaders.stan( T.fieldset(id=T.slot('id'), class_=T.slot('cssClass'), render=T.directive('group'))[ T.legend[T.slot('label')], T.div(class_='description')[T.slot('description')], T.slot('items'), ]) def __init__(self, group): super(GroupFragment, self).__init__() self.group = group def render_group(self, ctx, data): # Get a reference to the group, for simpler code. group = self.group # Build the CSS class string cssClass = ['group'] if group.cssClass is not None: cssClass.append(group.cssClass) cssClass = ' '.join(cssClass) # Fill the slots tag = ctx.tag tag.fillSlots('id', util.render_cssid(group.key)) tag.fillSlots('cssClass', cssClass) tag.fillSlots('label', group.label) tag.fillSlots('description', group.description or '') tag.fillSlots('items', [inevow.IRenderer(item) for item in group.items]) return ctx.tag
class SubmitFieldGroupFragment(form.GroupFragment): docFactory = loaders.stan( T.div(id=T.slot('id'), _class=T.slot('cssClass'), render=T.directive('group'))[ T.slot('items') ] ) def __init__(self, group): super(SubmitFieldGroupFragment, self).__init__(group) def render_group(self, ctx, data): group = self.group # Build the CSS class string cssClass = ['group', 'submit-group'] if group.cssClass is not None: cssClass.append(group.cssClass) cssClass = ' '.join(cssClass) # Fill the slots ctx.tag.fillSlots('id', util.render_cssid(group.key)) ctx.tag.fillSlots('cssClass', cssClass) items = [inevow.IRenderer(item) for item in group.items] items.append(T.span(_class='submit-group-clear')) ctx.tag.fillSlots('items', items) return ctx.tag
def test_realDeferredSupport(self): doc = tags.html[tags.slot('foo'), tags.slot('foo')] doc.fillSlots('foo', defer.succeed(tags.span['Foo!!!'])) self.r = rend.Page(docFactory=loaders.stan(doc)) req = self.renderIt() self.assertEquals( req.v, '<html><span>Foo!!!</span><span>Foo!!!</span></html>')
def render(self, ctx, key, args, errors): if errors: value = args.get(key,[None])[0] else: if args is not None: value = iforms.IStringConvertible(self.original).fromType(args.get(key)) def render_node(ctx, data): tag = ctx.tag data = self.nodeInterface(data) tag.fillSlots('value',data.value) tag.fillSlots('label',data.label) if str(data.value) == str(value): tag = tag(checked='checked') return tag template = T.div()[ T.input(pattern='item', render=render_node, type='radio', name=key, value=T.slot('value'))[ T.slot('label') ], T.input(pattern='itemdisabled', render=render_node, disabled="disabled", type='radio', name=key, value=T.slot('value'))[ T.slot('label') ] ] return T.invisible(data=self.tree, render=tree.render)[template]
def test_blogsRenderer(self): """ Test that L{hyperbola_view.BlogListFragment.blogs} renders a list of blogs. """ site = self.siteStore.findUnique(SiteConfiguration) site.hostname = u'blogs.renderer' blog1 = self._shareAndGetProxy(self._makeBlurb(FLAVOR.BLOG)) blog2 = self._shareAndGetProxy(self._makeBlurb(FLAVOR.BLOG)) blf = hyperbola_view.BlogListFragment( athena.LivePage(), self.publicPresence) blf.docFactory = loaders.stan( tags.div(pattern='blog')[ tags.span[tags.slot('title')], tags.span[tags.slot('link')], tags.span[tags.slot('post-url')]]) tag = tags.invisible markup = flat.flatten(tags.div[blf.blogs(None, tag)]) doc = minidom.parseString(markup) blogNodes = doc.firstChild.getElementsByTagName('div') self.assertEqual(len(blogNodes), 2) for (blogNode, blog) in zip(blogNodes, (blog1, blog2)): (title, blogURL, postURL) = blogNode.getElementsByTagName('span') blogURL = blogURL.firstChild.nodeValue expectedBlogURL = str(websharing.linkTo(blog)) self.assertEqual(blogURL, expectedBlogURL) postURL = postURL.firstChild.nodeValue self.assertEqual( postURL, 'https://blogs.renderer' + expectedBlogURL + '/post')
class CollapsibleGroupFragment(rend.Fragment): docFactory = loaders.stan( T.fieldset(id=T.slot('id'), _class=T.slot('cssClass'), render=T.directive('group'))[ T.input(_class='collapsible-group-hidden-state', type='hidden', render=T.directive('collapsedstate')), T.legend[T.span(_class='collapse-controls'), T.slot('label')], T.div(_class='description')[T.slot('description')], T.div(_class='collapsible-group-summary')[T.div(render=T.directive('display_summary'))[T.slot('summary')]], T.div(_class='collapsible-group-contents')[T.div(render=T.directive('display_contents'))[T.slot('items')]], ]) def __init__(self, group): super(CollapsibleGroupFragment, self).__init__() self.group = group def render_collapsedstate(self, ctx, data): ctx.tag(name=self.group.getCollapsedKey()) if self.group.collapsible and self.group.collapsed: value = '1' else: value = '0' ctx.tag(value=value) return ctx.tag def render_display_summary(self, ctx, data): if self.group.collapsible and self.group.collapsed: return ctx.tag(_class='collapsible-show') else: return ctx.tag(_class='collapsible-hide') def render_display_contents(self, ctx, data): if self.group.collapsible and self.group.collapsed: return ctx.tag(_class='collapsible-hide') else: return ctx.tag(_class='collapsible-show') def render_group(self, ctx, data): group = self.group # Build the CSS class string cssClass = ['group'] if self.group.collapsible: cssClass.append('collapsible-group') if group.cssClass is not None: cssClass.append(group.cssClass) cssClass = ' '.join(cssClass) # Fill the slots ctx.tag.fillSlots('id', util.render_cssid(group.key)) ctx.tag.fillSlots('cssClass', cssClass) ctx.tag.fillSlots('label', group.label) ctx.tag.fillSlots('description', group.description or '') if self.group.summary is not None: ctx.tag.fillSlots('summary', self.group.summary) else: ctx.tag.fillSlots('summary', _default_summary_clicktoexpand) ctx.tag.fillSlots('items', [inevow.IRenderer(item) for item in group.items]) return ctx.tag
def test_precompiledSlotFilledWithSlot(self): """ A L{_PrecompiledSlot} slot which is filled with another slot is replaced with the value the other slot is filled with. """ tag = invisible[oldPrecompile(div[slot("foo")])] tag.fillSlots("foo", slot("bar")) tag.fillSlots("bar", '"&<>') self.assertStringEqual(self.flatten(tag), '<div>"&<></div>')
def test_deeplyNestedSlot(self): """ Flattening succeeds for an object with a level of slot nesting significantly greater than the Python maximum recursion limit. """ tag = div()[slot("foo-0")] for i in xrange(1000): tag.fillSlots("foo-" + str(i), slot("foo-" + str(i + 1))) tag.fillSlots("foo-1000", "bar") self._nestingTest(tag, "<div>bar</div>")
def _render(self, ctx, key, args, errors, value, tag): def data_facets(ctx, data): storeSession = util.getStoreSession(ctx) avatar = util.getAvatar(ctx) @defer.deferredGenerator def loadCategories(facets): d = defer.waitForDeferred(avatar.getCategoryManager(storeSession)) yield d categories = d.getResult() rv = [] for f in facets: facetData = FacetData() facetData.label = f[2] facetData.textid = f[1] rv.append(facetData) d = defer.waitForDeferred(categories.loadCategories(facetData.textid)) yield d facetData.tree = d.getResult().children yield rv d = avatar.getCategoryManager(storeSession) d.addCallback(lambda categories: categories.loadFacets()) d.addCallback(loadCategories) return d def render_facet(ctx, data): tag = ctx.tag tag.fillSlots("facetlabel", data.label) return tag def render_node(ctx, data): tag = ctx.tag tag.fillSlots("value", data.path) tag.fillSlots("label", data.label) if data.path in value: tag.children[0] = tag.children[0](checked="checked") else: tag.children[0](checked=None) return tag template = T.div(class_="categorieswidget")[ T.p(class_="opener")["click to open/close"], T.ul(class_="panel", data=data_facets, render=rend.sequence)[ T.li(pattern="item", render=render_facet)[ T.slot("facetlabel"), T.div(data=T.directive("tree"), render=tree.render)[ T.invisible(pattern="item", render=render_node)[tag, T.slot("label")] ], ] ], ] return T.invisible()[template]
def test_reusedDeferredSupport(self): """ Two occurrences of a particular slot are each replaced with the result of the Deferred which is used to fill that slot. """ doc = tags.html[ tags.slot('foo'), tags.slot('foo')] doc.fillSlots('foo', defer.succeed(tags.span['Foo!!!'])) self.r = rend.Page(docFactory=loaders.stan(doc)) req = self.renderIt() self.assertEqual(req.v, '<html><span>Foo!!!</span><span>Foo!!!</span></html>')
def test_slots(self): tag = tags.html[ tags.body[ tags.table(data={'one': 1, 'two': 2}, render=rend.mapping)[ tags.tr[tags.td["Header one."], tags.td["Header two."]], tags.tr[ tags.td["One: ", tags.slot("one")], tags.td["Two: ", tags.slot("two")] ] ] ] ] self.assertEquals(self.render(tag), "<html><body><table><tr><td>Header one.</td><td>Header two.</td></tr><tr><td>One: 1</td><td>Two: 2</td></tr></table></body></html>")
def test_slots(self): tag = tags.html[ tags.body[ tags.table(data={'one': 1, 'two': 2}, render=rend.mapping)[ tags.tr[tags.td["Header one."], tags.td["Header two."]], tags.tr[ tags.td["One: ", tags.slot("one")], tags.td["Two: ", tags.slot("two")] ] ] ] ] self.assertEqual(self.render(tag), "<html><body><table><tr><td>Header one.</td><td>Header two.</td></tr><tr><td>One: 1</td><td>Two: 2</td></tr></table></body></html>")
class Uploader(formrender.Form): """A renderer allowing for updates to individual records using file upload. This renderer exposes a form with a file widget. It is likely that the interface will change. """ name = "upload" def render_uploadInfo(self, ctx, data): if data is None: return T.invisible() else: for key, val in data.original.getPrimaryTable().rows[0].iteritems(): ctx.tag.fillSlots(key, str(val)) return ctx.tag docFactory = loaders.stan(T.html[ T.head[ T.title["Upload"], T.invisible(render=T.directive("commonhead")), ], T.body(render=T.directive("withsidebar"))[ T.h1(render=T.directive("meta"))["title"], T.p(class_="procMessage", data=T.directive("result"), render=T.directive("uploadInfo"))[ T.slot(name="nAffected"), " record(s) modified." ], T.invisible(render=T.directive("form genForm")) ] ])
def test_unfilledPrecompiledSlot(self): """ Flattening a L{_PrecompiledSlot} for which no value has been supplied results in an L{FlattenerError} exception. """ tag = oldPrecompile(div[slot("foo")]) self.assertRaises(FlattenerError, self.flatten, tag)
def test_urlSlot(self): u = url.URL.fromString('http://localhost/').child(r'<c:\foo\bar&>') tag = tags.img(src=tags.slot('src')) tag.fillSlots('src', u) self.assertEquals( flatten(tag), '<img src="http://localhost/%3Cc%3A%5Cfoo%5Cbar%26%3E" />')
def test_unfilledSlotDeferredResult(self): """ Flattening a L{Deferred} which results in an unfilled L{slot} results in a L{FlattenerError} failure. """ return self.assertFailure(self.deferflatten(succeed(slot("foo"))), FlattenerError)
def test_unfilledSlot(self): """ Flattening a slot which has no known value results in an L{FlattenerError} exception which has an L{UnfilledSlot} exception in its arguments. """ exc = self.assertRaises(FlattenerError, self.flatten, slot("foo")) self.assertTrue(isinstance(exc.args[0], UnfilledSlot))
class SubheadingFieldFragment(form.FieldFragment): docFactory = loaders.stan( T.div(id=T.slot('fieldId'), _class=T.slot('fieldClass'), render=T.directive('field'))[ T.div(_class='formal-subheading-field')[ T.slot('fieldContents') ] ]) def render_field(self, ctx, data): # No fancy widget-stuff here ourform = iformal.IForm(ctx) classes = ['field', 'subheading-field'] ctx.tag.fillSlots('fieldId', '%s-%s-field' % (ourform.name, self.field.name)) # XXX: unused... ctx.tag.fillSlots('fieldClass', ' '.join(classes)) ctx.tag.fillSlots('fieldContents', self.field.label) return ctx.tag
def test_precompileSlotData(self): """Test that tags with slotData are not precompiled out of the stan tree. """ tag = tags.p[tags.slot('foo')] tag.fillSlots('foo', 'bar') precompiled = self.render(tag, precompile=True) self.assertEquals(self.render(precompiled), '<p>bar</p>')
def test_precompiledSlotTagAttribute(self): """ A L{_PrecompiledSlot} which is the value of an attribute is replaced with the value of the slot with XML attribute quoting applied. """ tag = invisible[oldPrecompile(div(foo=slot("foo")))] tag.fillSlots("foo", '"&<>') self.assertStringEqual(self.flatten(tag), '<div foo=""&<>"></div>')
class Tester(livepage.LivePage): addSlash = True child_css = static.File(os.path.join(resourceDirectory, 'livetest.css')) child_scripts = static.File(os.path.join(resourceDirectory, 'livetest.js')) child_postscripts = static.File( os.path.join(resourceDirectory, 'livetest-postscripts.js')) docFactory = loaders.stan(tags.html[ tags.head[tags.script(src="scripts"), tags.link(rel="stylesheet", type="text/css", href="css")], tags.body[tags.table(id="testprogress")[ tags.tr[tags.th["Tests"], tags.th["Pass"], tags.th["Fail"]], tags. tr[tags.td(id="test-status")["Running"], tags.td(id="test-passes", _class="test-passes")[entities.nbsp], tags.td(id="test-failures", _class="test-failures")[entities. nbsp]]], tags. table(id="testresults", render=tags.directive('table') )[tags. tr(pattern="item", render=tags.directive('test'))[ tags.td[tags.slot('action')], tags.td[tags.slot('target')], tags.td[tags.slot('parameter')]]], tags.iframe(id="testframe", src="asdf"), tags.script(src="postscripts"), livepage.glue]]) def render_table(self, ctx, suite): self.testId = 0 driver = Driver(suite) handle = livepage.IClientHandle(ctx) driver.notifyWhenTestsComplete().addCallback(self.testsComplete, handle) driver.setHandle(handle) driver.nextTest() return rend.sequence(ctx, suite) def render_test(self, ctx, test): ctx.tag(id=("test-", self.testId)) action, target, parameter = test ctx.fillSlots('action', action) ctx.fillSlots('target', str(target)) ctx.fillSlots('parameter', parameter) self.testId += 1 return ctx.tag def testsComplete(self, results, handle): handle.set('test-status', 'Complete')
def test_precompileSlotData(self): """Test that tags with slotData are not precompiled out of the stan tree. """ tag = tags.p[tags.slot('foo')] tag.fillSlots('foo', 'bar') precompiled = self.render(tag, precompile=True) self.assertEqual(self.render(precompiled), '<p>bar</p>')
def test_filledSlotTagChildEscaping(self): """ Flattening a slot as a child of a L{Tag} which has been given a string value results in that string value being XML escaped in the output. """ tag = div[slot("foo")] tag.fillSlots("foo", '"&<>') self.assertStringEqual(self.flatten(tag), '<div>"&<></div>')
def test_unfilledSlotDeferredResult(self): """ Flattening a L{Deferred} which results in an unfilled L{slot} results in a L{FlattenerError} failure. """ return self.assertFailure( self.deferflatten(succeed(slot("foo"))), FlattenerError)
def test_slotFilledWithProto(self): """ Filling a slot with a L{Proto} results in the slot being replaced with the serialized form of the tag in the output. """ tag = div[slot("foo")] tag.fillSlots("foo", br) self.assertStringEqual(self.flatten(tag), "<div><br /></div>")
def test_precompiledSlot(self): """ A L{_PrecompiledSlot} is replaced with the value of that slot when flattened. """ tag = invisible[oldPrecompile(div[slot("foo")])] tag.fillSlots("foo", '"&<>') self.assertStringEqual(self.flatten(tag), '<div>"&<></div>')
def test_slotsNestedInRenderResult(self): """ A L{slot} in the return value of a render function is replaced by the value of that slot as found on the tag which had the render directive. """ tag = div(render="foo") tag.fillSlots("bar", '"&<>') renderable = RenderRenderable([], "foo", tag, slot("bar")) self.assertStringEqual(self.flatten(renderable), '"&<>')
def getTestContainer(self): """ Return a Nevow DOM object (generally a tag) with a C{widget} slot in it. This will be used as the top-level DOM for this test case, and the actual widget will be used to fill the C{widget} slot. Subclasses may want to override this. """ return tags.invisible[tags.slot('widget')]
def test_filledSlotTagAttribute(self): """ Flattening a slot which is the value of an attribute of a L{Tag} results in the value of the slot appearing as the attribute value in the output. """ tag = div(foo=slot("bar")) tag.fillSlots("bar", "baz") self.assertStringEqual(self.flatten(tag), '<div foo="baz"></div>')
def test_filledSlotNestedTagChild(self): """ Flattening a slot as a child of a L{Tag} which is itself a child of a L{Tag} which has been given a value for that slot results in the slot being replaced with the value in the output. """ tag = div[div[slot("foo")]] tag.fillSlots("foo", "bar") self.assertStringEqual(self.flatten(tag), "<div><div>bar</div></div>")
def test_leaky(self): def foo(ctx, data): ctx.tag.fillSlots('bar', tags.invisible(data="two")) return ctx.tag result = self.render( tags.div(render=foo, data="one")[ tags.slot("bar"), tags.invisible(render=str)]) self.assertEquals(result, '<div>one</div>')
def render_cssid(fieldKey, *extras): """ Render the CSS id for the form field's key. """ l = [tags.slot('formName'), '-', '-'.join(fieldKey.split('.'))] for extra in extras: l.append('-') l.append(extra) return l
def test_slotAttributeEscapingWhenPrecompiled(self): def render_searchResults(ctx, remoteCursor): ctx.fillSlots('old-query', '"meow"') return ctx.tag tag = tags.invisible(render=render_searchResults)[ tags.input(value=tags.slot('old-query')), ] precompiled = self.render(tag, precompile=True) self.assertEquals(self.render(precompiled), '<input value=""meow"" />')
def test_synchronousDeferredSlot(self): """ Flattening a L{slot} which is filled with a L{Deferred} which has a result already results in the result of the L{Deferred}. """ tag = div[slot("foo")] tag.fillSlots("foo", succeed("bar")) flattened = self.deferflatten(tag) flattened.addCallback(self.assertStringEqual, "<div>bar</div>") return flattened
def test_slotQueryParam(self): original = 'http://foo/bar?baz=bamf' u = url.URL.fromString(original) u = u.add('toot', tags.slot('param')) def fillIt(ctx, data): ctx.fillSlots('param', 5) return ctx.tag self.assertEquals(flatten(tags.invisible(render=fillIt)[u]), original + '&toot=5')
def test_childQueryParam(self): original = "http://foo/bar" u = url.URL.fromString(original) u = u.child(tags.slot("param")) def fillIt(ctx, data): ctx.fillSlots("param", "baz") return ctx.tag self.assertEqual(flatten(tags.invisible(render=fillIt)[u]), original + "/baz")
def test_slotQueryParam(self): original = "http://foo/bar?baz=bamf" u = url.URL.fromString(original) u = u.add("toot", tags.slot("param")) def fillIt(ctx, data): ctx.fillSlots("param", 5) return ctx.tag self.assertEqual(flatten(tags.invisible(render=fillIt)[u]), original + "&toot=5")
def test_slotFromRenderable(self): """ An L{IRenderable} provider which returns a C{Tag} inside a C{slot} from its C{render} method has that slot filled with the slot data available on the tag. """ tag = div[slot("foo")] tag.fillSlots("foo", "bar") renderable = TrivialRenderable(tag) self.assertStringEqual(self.flatten(renderable), "<div>bar</div>")
def test_childQueryParam(self): original = 'http://foo/bar' u = url.URL.fromString(original) u = u.child(tags.slot('param')) def fillIt(ctx, data): ctx.fillSlots('param', 'baz') return ctx.tag self.assertEquals(flatten(tags.invisible(render=fillIt)[u]), original + '/baz')
def render(self, ctx, key, args, errors): if errors: value = args.get(key, [None]) else: if args is not None: value = iforms.ISequenceConvertible(self.original).fromType(args.get(key)) if value is None: value = [None] tag = T.input(type="checkbox", name=key, value=T.slot("value")) return self._render(ctx, key, args, errors, value, tag)
def test_childQueryParam(self): original = 'http://foo/bar' u = url.URL.fromString(original) u = u.child(tags.slot('param')) def fillIt(ctx, data): ctx.fillSlots('param', 'baz') return ctx.tag self.assertEqual(flatten(tags.invisible(render=fillIt)[u]), original + '/baz')
def test_legacySerializableReturnsSlot(self): """ A slot returned by a flattener registered with L{registerFlattener} is filled with the value of a slot from "outside" the L{ISerializable}. """ request = FakeRequest() result = slot('foo') serializable = LegacySerializable(result) tag = div(foo=serializable) tag.fillSlots("foo", "bar") self.assertEqual(self.flatten(tag, request), '<div foo="bar"></div>')