def test_list_directive(self): d = directive('2') ctx = self.makeContext([0, 1, 42, 3, 4]) self.assertEquals(42, convertToData(d, ctx)) self.assertRaises(IndexError, convertToData, directive('9999'), ctx) self.assertRaises(ValueError, convertToData, directive('HAHAHAHA'), ctx)
def test_2_dictOriginal(self): data = {'hello': 'world'} ctx = context.WovenContext() ctx.remember(APage(data), inevow.IData) self.assertEquals(data, convertToData(ctx.locate(inevow.IData), ctx)) self.assertEquals('foo', convertToData(directive('foo'), ctx)) self.assertEquals('world', convertToData(directive('hello'), ctx))
def test_2_dictOriginal(self): data = {'hello': 'world'} ctx = context.WovenContext() ctx.remember(APage(data), inevow.IData) # IGettable should return our dictionary self.assertEquals(data, convertToData(ctx.locate(inevow.IData), ctx)) # IContainer on the *Page*, not the dictionary, should work self.assertEquals('foo', convertToData(directive('foo'), ctx)) # IContainer on the Page should delegate to IContainer(self.original) if no data_ method self.assertEquals('world', convertToData(directive('hello'), ctx))
def startElementNS(self, ns_and_name, qname, attrs): ns, name = ns_and_name if ns == nevow.namespace: if name == 'invisible': name = '' elif name == 'slot': el = slot(attrs[(None,'name')]) self.stack.append(el) self.current.append(el) self.current = el.children return attrs = dict(attrs) specials = {} attributes = self.attributeList directives = self.directiveMapping for k, v in attrs.items(): att_ns, nons = k if att_ns != nevow.namespace: continue if nons in directives: ## clean this up by making the names more consistent specials[directives[nons]] = directive(v) del attrs[k] if nons in attributes: specials[nons] = v del attrs[k] no_ns_attrs = {} for (attrNs, attrName), v in attrs.items(): nsPrefix = self.prefixMap.get(attrNs) if nsPrefix is None: no_ns_attrs[attrName] = v else: no_ns_attrs['%s:%s'%(nsPrefix,attrName)] = v if ns == nevow.namespace and name == 'attr': if not self.stack: # TODO: define a better exception for this? raise AssertionError( '<nevow:attr> as top-level element' ) if 'name' not in no_ns_attrs: # TODO: same here raise AssertionError( '<nevow:attr> requires a name attribute' ) el = Tag('', specials=specials) self.stack[-1].attributes[no_ns_attrs['name']] = el self.stack.append(el) self.current = el.children return # Apply any xmlns attributes if self.xmlnsAttrs: no_ns_attrs.update(dict(self.xmlnsAttrs)) self.xmlnsAttrs = [] el = Tag(name, attributes=dict(no_ns_attrs), specials=specials) self.stack.append(el) self.current.append(el) self.current = el.children
def startElementNS(self, ns_and_name, qname, attrs): ns, name = ns_and_name if ns == nevow.namespace: if name == 'invisible': name = '' elif name == 'slot': el = slot(attrs[(None, 'name')]) self.stack.append(el) self.current.append(el) self.current = el.children return attrs = dict(attrs) specials = {} attributes = self.attributeList directives = self.directiveMapping for k, v in attrs.items(): att_ns, nons = k if att_ns != nevow.namespace: continue if nons in directives: ## clean this up by making the names more consistent specials[directives[nons]] = directive(v) del attrs[k] if nons in attributes: specials[nons] = v del attrs[k] no_ns_attrs = {} for (attrNs, attrName), v in attrs.items(): nsPrefix = self.prefixMap.get(attrNs) if nsPrefix is None: no_ns_attrs[attrName] = v else: no_ns_attrs['%s:%s' % (nsPrefix, attrName)] = v if ns == nevow.namespace and name == 'attr': if not self.stack: # TODO: define a better exception for this? raise AssertionError('<nevow:attr> as top-level element') if 'name' not in no_ns_attrs: # TODO: same here raise AssertionError('<nevow:attr> requires a name attribute') el = Tag('', specials=specials) self.stack[-1].attributes[no_ns_attrs['name']] = el self.stack.append(el) self.current = el.children return # Apply any xmlns attributes if self.xmlnsAttrs: no_ns_attrs.update(dict(self.xmlnsAttrs)) self.xmlnsAttrs = [] el = Tag(name, attributes=dict(no_ns_attrs), specials=specials) self.stack.append(el) self.current.append(el) self.current = el.children
def test_function_accessor(self): def foo(context, data): return 42 ctx = self.makeContext() self.assertEquals(42, convertToData(foo, ctx)) d = directive('this wont work') ctx2 = self.makeContext(foo) self.assertRaises(NoAccessor, convertToData, d, ctx2)
class VirtualHostList(rend.Page): def __init__(self, nvh): rend.Page.__init__(self) self.nvh = nvh stylesheet = """ body { border: 0; padding: 0; margin: 0; background-color: #efefef; } h1 {padding: 0.1em; background-color: #777; color: white; border-bottom: thin white dashed;} """ def getStyleSheet(self): return self.stylesheet def data_hostlist(self, context, data): return self.nvh.hosts.keys() def render_hostlist(self, context, data): host = data req = context.locate(inevow.IRequest) proto = req.clientproto.split('/')[0].lower() port = req.getHeader('host').split(':')[1] link = "%s://%s" % (proto, host) if port != 80: link += ":%s" % port link += req.path return context.tag[tags.a(href=link)[host]] def render_title(self, context, data): req = context.locate(inevow.IRequest) proto = req.clientproto.split('/')[0].lower() host = req.getHeader('host') return context.tag["Virtual Host Listing for %s://%s" % (proto, host)] def render_stylesheet(self, context, data): return tags.style(type="text/css")[self.getStyleSheet()] docFactory = loaders.stan(tags.html[tags.head[ tags.title(render=render_title), tags.directive('stylesheet'), ], tags.body[ tags.h1(render=render_title), tags.ul(data=directive("hostlist"), render=directive("sequence") )[tags.li(pattern="item", render=render_hostlist)]]])
def MicroDomElementSerializer(element, context): directiveMapping = { 'render': 'render', 'data': 'data', 'macro': 'macro', } attributeList = [ 'pattern', 'key', ] name = element.tagName if name.startswith('nevow:'): _, name = name.split(':') if name == 'invisible': name = '' elif name == 'slot': return slot(element.attributes['name'])[precompile( serialize(element.childNodes, context), context)] attrs = dict(element.attributes) # get rid of CaseInsensitiveDict specials = {} attributes = attributeList directives = directiveMapping for k, v in list(attrs.items()): # I know, this is totally not the way to do xml namespaces but who cares right now ## I'll fix it later -dp ### no you won't *I'll* fix it later -glyph if isinstance(k, tuple): if k[0] != 'http://nevow.com/ns/nevow/0.1': continue else: nons = k[1] elif not k.startswith('nevow:'): continue else: _, nons = k.split(':') if nons in directives: ## clean this up by making the names more consistent specials[directives[nons]] = directive(v) del attrs[k] if nons in attributes: specials[nons] = v del attrs[k] # TODO: there must be a better way than this ... # Handle any nevow:attr elements. If we don't do it now then this tag will # be serialised and it will too late. childNodes = [] for child in element.childNodes: if getattr(child, 'tagName', None) == 'nevow:attr': attrs[child.attributes['name']] = child.childNodes else: childNodes.append(child) tag = Tag(name, attributes=attrs, children=childNodes, specials=specials) return serialize(tag, context)
def MicroDomElementSerializer(element, context): directiveMapping = { 'render': 'render', 'data': 'data', 'macro': 'macro', } attributeList = [ 'pattern', 'key', ] name = element.tagName if name.startswith('nevow:'): _, name = name.split(':') if name == 'invisible': name = '' elif name == 'slot': return slot(element.attributes['name'])[ precompile(serialize(element.childNodes, context), context)] attrs = dict(element.attributes) # get rid of CaseInsensitiveDict specials = {} attributes = attributeList directives = directiveMapping for k, v in attrs.items(): # I know, this is totally not the way to do xml namespaces but who cares right now ## I'll fix it later if not k.startswith('nevow:'): continue _, nons = k.split(':') if nons in directives: ## clean this up by making the names more consistent specials[directives[nons]] = directive(v) del attrs[k] if nons in attributes: specials[nons] = v del attrs[k] # TODO: there must be a better way than this ... # Handle any nevow:attr elements. If we don't do it now then this tag will # be serialised and it will too late. childNodes = [] for child in element.childNodes: if getattr(child,'tagName',None) == 'nevow:attr': attrs[child.attributes['name']] = child.childNodes else: childNodes.append(child) tag = Tag( name, attributes=attrs, children=childNodes, specials=specials ) return serialize(tag, context)
def MicroDomElementSerializer(element, context): directiveMapping = {"render": "render", "data": "data", "macro": "macro"} attributeList = ["pattern", "key"] name = element.tagName if name.startswith("nevow:"): _, name = name.split(":") if name == "invisible": name = "" elif name == "slot": return slot(element.attributes["name"])[precompile(serialize(element.childNodes, context), context)] attrs = dict(element.attributes) # get rid of CaseInsensitiveDict specials = {} attributes = attributeList directives = directiveMapping for k, v in attrs.items(): # I know, this is totally not the way to do xml namespaces but who cares right now ## I'll fix it later -dp ### no you won't *I'll* fix it later -glyph if isinstance(k, tuple): if k[0] != "http://nevow.com/ns/nevow/0.1": continue else: nons = k[1] elif not k.startswith("nevow:"): continue else: _, nons = k.split(":") if nons in directives: ## clean this up by making the names more consistent specials[directives[nons]] = directive(v) del attrs[k] if nons in attributes: specials[nons] = v del attrs[k] # TODO: there must be a better way than this ... # Handle any nevow:attr elements. If we don't do it now then this tag will # be serialised and it will too late. childNodes = [] for child in element.childNodes: if getattr(child, "tagName", None) == "nevow:attr": attrs[child.attributes["name"]] = child.childNodes else: childNodes.append(child) tag = Tag(name, attributes=attrs, children=childNodes, specials=specials) return serialize(tag, context)
def MicroDomElementSerializer(element, context): directiveMapping = { 'render': 'render', 'data': 'data', 'macro': 'macro', } attributeList = [ 'pattern', 'key', ] name = element.tagName if name.startswith('nevow:'): _, name = name.split(':') if name == 'invisible': name = '' elif name == 'slot': return slot(element.attributes['name'])[ precompile(serialize(element.childNodes, context), context)] attrs = dict(element.attributes) # get rid of CaseInsensitiveDict specials = {} attributes = attributeList directives = directiveMapping for k, v in attrs.items(): if not k.startswith('nevow:'): continue _, nons = k.split(':') if nons in directives: specials[directives[nons]] = directive(v) del attrs[k] if nons in attributes: specials[nons] = v del attrs[k] childNodes = [] for child in element.childNodes: if getattr(child,'tagName',None) == 'nevow:attr': attrs[child.attributes['name']] = child.childNodes else: childNodes.append(child) tag = Tag( name, attributes=attrs, children=childNodes, specials=specials ) return serialize(tag, context)
class Mine(rend.Page): addSlash = True docFactory = loaders.stan(T.html[T.head[T.title["This is title"]], T.body[ T.h1(id="header")["Welcome"], T.ol(data=directive("theList"), render=directive("sequence"))[ T.span(pattern="header")["HEADER"], T.li(pattern="item")["Stuff: ", T.span(render=directive("string")), "!"], T.span(pattern="divider")["-----"], T.div(pattern="empty")["Nothing."], T.span(pattern="footer")["FOOTER"], ], T.ol(data=directive("empty"), render=directive("sequence"))[ T.span(pattern="header")["HEADER"], T.li(pattern="item")["Stuff: ", T.span(render=directive("string")), "!"], T.span(pattern="divider")["-----"], T.div(pattern="empty")["Nothing."], T.span(pattern="footer")["FOOTER"], ], T.span(render=directive("foo"))[ "This entire node, including the span tag, will be replaced by \ a randomly chosen node from below:", T.div(pattern="one", style="color: red")["one"], T.table(pattern="two")[T.tr[T.td["two"], T.td["two"], T.td["two"]]], T.ol(pattern="three")[T.li["three"], T.li["three"], T.li["three"], ]]]]) def render_foo(self, context, data): return inevow.IQ(context).onePattern( random.choice(['one', 'two', 'three'])) def data_theList(self, context, data): return [random.randint(0, 5000) for x in range(random.randint(0, 10))] def data_empty(self, context, data): return []
def test_missing(self): self.assertRaises(rend.DataNotFoundError, self.makeContext, directive('missing'))
def test_dict_directive(self): d = directive('one') ctx = self.makeContext({'one': 1, 'two': 2}) self.assertEquals(1, convertToData(d, ctx)) self.assertRaises(KeyError, convertToData, directive('asdfasdf'), ctx)
def test_1_noneOriginal(self): data = None ctx = context.WovenContext() ctx.remember(APage(data), inevow.IData) self.assertEquals(data, convertToData(ctx.locate(inevow.IData), ctx)) self.assertEquals('foo', convertToData(directive('foo'), ctx))
def startElementNS(self, ns_and_name, qname, attrs): filename = self.sourceFilename lineNumber = self.locator.getLineNumber() columnNumber = self.locator.getColumnNumber() ns, name = ns_and_name if ns == nevow.namespace: if name == 'invisible': name = '' elif name == 'slot': try: # Try to get the default value for the slot default = attrs[(None, 'default')] except KeyError: # If there wasn't one, then use None to indicate no # default. default = None el = slot( attrs[(None, 'name')], default=default, filename=filename, lineNumber=lineNumber, columnNumber=columnNumber) self.stack.append(el) self.current.append(el) self.current = el.children return attrs = dict(attrs) specials = {} attributes = self.attributeList directives = self.directiveMapping for k, v in list(attrs.items()): att_ns, nons = k if att_ns != nevow.namespace: continue if nons in directives: ## clean this up by making the names more consistent specials[directives[nons]] = directive(v) del attrs[k] if nons in attributes: specials[nons] = v del attrs[k] no_ns_attrs = {} for (attrNs, attrName), v in list(attrs.items()): nsPrefix = self.prefixMap.get(attrNs) if nsPrefix is None: no_ns_attrs[attrName] = v else: no_ns_attrs['%s:%s'%(nsPrefix,attrName)] = v if ns == nevow.namespace and name == 'attr': if not self.stack: # TODO: define a better exception for this? raise AssertionError( '<nevow:attr> as top-level element' ) if 'name' not in no_ns_attrs: # TODO: same here raise AssertionError( '<nevow:attr> requires a name attribute' ) el = Tag('', specials=specials, filename=filename, lineNumber=lineNumber, columnNumber=columnNumber) self.stack[-1].attributes[no_ns_attrs['name']] = el self.stack.append(el) self.current = el.children return # Apply any xmlns attributes if self.xmlnsAttrs: no_ns_attrs.update(dict(self.xmlnsAttrs)) self.xmlnsAttrs = [] # Add the prefix that was used in the parsed template for non-Nevow # namespaces (which Nevow will consume anyway). if ns != nevow.namespace and ns is not None: prefix = self.prefixMap[ns] if prefix is not None: name = '%s:%s' % (self.prefixMap[ns],name) el = Tag( name, attributes=dict(no_ns_attrs), specials=specials, filename=filename, lineNumber=lineNumber, columnNumber=columnNumber) self.stack.append(el) self.current.append(el) self.current = el.children
def test_list_through_directive(self): d1, d2 = directive('list'), directive('1') ctx = self.makeContext(d1) self.assertEquals(99, convertToData(d2, ctx))
] _dir = Proto('dir') _del = Proto('del') _object = Proto('object') _map = Proto('map') globs = globals() for t in tags: globs[t] = Proto(t) for x in range(100): globs['_%s' % x] = directive(x) def drange(x): return [globs['_%s' % i] for i in range(x)] __all__ = tags + ['invisible', 'comment', '_dir', '_del', '_object', '_map', 'drange', 'Tag', 'directive', 'xml', 'raw', 'slot', 'cdata', 'inlineJS'] + ['_%s' % x for x in range(100)] ######################## #### ######################## #### ######################## ####
def test_list_directive(self): d= directive('2') ctx = self.makeContext([0, 1, 42, 3, 4]) self.assertEquals(42, convertToData(d, ctx)) self.assertRaises(IndexError, convertToData, directive('9999'), ctx) self.assertRaises(ValueError, convertToData, directive('HAHAHAHA'), ctx)
def test_simple(self): d = directive('foo') ctx = self.makeContext() self.assertEquals(thefoo, convertToData(d, ctx))
def test_dict_through_directive(self): d1, d2 = directive('dict'), directive('one') ctx = self.makeContext(d1) self.assertEquals(1, convertToData(d2, ctx))
def test_roundAndRound(self): ctx = self.makeContext(directive('factory'), directive('0'), directive('factory')) self.assertEquals(f, convertToData(directive('0'), ctx))
def test_roundAndRound(self): ctx = self.makeContext( directive('factory'), directive('0'), directive('factory') ) self.assertEquals(f, convertToData(directive('0'), ctx))
'pre', 'q', 's', 'samp', 'script', 'select', 'small', 'span', 'strike', 'strong', 'style', 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'tt', 'u', 'ul', 'var' ] _dir = Proto('dir') _del = Proto('del') _object = Proto('object') _map = Proto('map') globs = globals() for t in tags: globs[t] = Proto(t) for x in range(100): globs['_%s' % x] = directive(x) def drange(x): return [globs['_%s' % i] for i in range(x)] __all__ = tags + [ 'invisible', 'comment', '_dir', '_del', '_object', '_map', 'drange', 'Tag', 'directive', 'xml', 'raw', 'slot', 'cdata' ] + ['_%s' % x for x in range(100)] ######################## #### ######################## ####