def test_macroInsideSpecialScope(self): """http://divmod.org/trac/ticket/490 """ class Base(rend.Page): def macro_content(self, ctx): return p["content"] class Page1(Base): docFactory = loaders.stan(html[body(render=directive('foo'))[p( macro=directive('content'))]]) def render_foo(self, ctx, data): return ctx.tag class Page2(Base): docFactory = loaders.stan( html[body[p(macro=directive('content'))]]) p1 = Page1() p2 = Page2() ctx1 = context.WovenContext() ctx2 = context.WovenContext() ctx1.remember(p1, inevow.IRendererFactory) ctx2.remember(p2, inevow.IRendererFactory) p1_str = p1.renderSynchronously(ctx1) p2_str = p2.renderSynchronously(ctx2) self.assertEqual(p1_str, p2_str)
def test_factoryContextRemembers(self): basectx = TestContext() ctx = context.WovenContext(parent=basectx) bar1 = IBar(ctx) ctx = context.WovenContext(parent=basectx) bar2 = IBar(ctx) self.assertEqual(bar1, bar2)
def makeContext(self, *args): ctx = context.WovenContext() ctx.remember(convertToData(self.remember, ctx), inevow.IData) for a in args: ctx = context.WovenContext(ctx, invisible()) ctx.remember(convertToData(a, ctx), inevow.IData) return ctx
def test_basic(self): top = context.WovenContext() middle = context.WovenContext(top, tags.invisible()) bottom = context.WovenContext(middle, tags.invisible()) top.remember(0, IStuff) self.assertEquals(bottom.locate(IStuff), 0) middle.remember(1, IStuff) self.assertEquals(bottom.locate(IStuff), 1) self.assertEquals(bottom.locate(IStuff, depth=2), 0)
def setupContext(self, precompile=False, setupRequest=lambda r:r): fr = setupRequest(FakeRequest(uri='/', currentSegments=[''])) ctx = context.RequestContext(tag=fr) ctx.remember(fr, inevow.IRequest) ctx.remember(None, inevow.IData) ctx = context.WovenContext(parent=ctx, precompile=precompile) return ctx
def _getRequestContext(destFile): """returns a very simple nevow context writing to destFile. """ req = FakeRequest(destFile) ctx = context.WovenContext() ctx.remember(req) return ctx
def test_reloadAfterPrecompile(self): """ """ # Get a filename temp = self.mktemp() # Write some content f = file(temp, 'w') f.write('<p>foo</p>') f.close() # Precompile the doc ctx = context.WovenContext() doc = loaders.htmlfile(temp) pc = flat.precompile(flat.flatten(doc), ctx) before = ''.join(flat.serialize(pc, ctx)) # Write the file with different content and make sure the # timestamp changes f = file(temp, 'w') f.write('<p>bar</p>') f.close() os.utime(temp, (os.path.getatime(temp), os.path.getmtime(temp)+5)) after = ''.join(flat.serialize(pc, ctx)) self.assertIn('foo', before) self.assertIn('bar', after) self.failIfEqual(before, after)
def _formatOutput(self, res, ctx): """actually delivers the whole document. This is basically nevow's rend.Page._renderHTTP, changed to provide less blocks. """ request = inevow.IRequest(ctx) if isinstance(res.original, tuple): # core returned a complete document (mime and string) mime, payload = res.original request.setHeader("content-type", mime) request.setHeader( 'content-disposition', 'attachment; filename=result%s' % common.getExtForMime(mime)) return streaming.streamOut(lambda f: f.write(payload), request) self.result = res if "response" in self.service.templates: self.customTemplate = self.service.getTemplate("response") ctx = context.PageContext(parent=ctx, tag=self) self.rememberStuff(ctx) doc = self.docFactory.load(ctx) ctx = context.WovenContext(ctx, T.invisible[doc]) return deliverYielding(doc, ctx, request)
def precompile(self, parent): ctx = context.WovenContext(parent=parent, precompile=True) from nevow import flat doc = flat.precompile(self.getDoc(), ctx) if self.pattern: tag = tags.invisible[doc] doc = [tag.onePattern(self.pattern)] return doc
def test_formPostFailureDeferred(self): class FormPage(rend.Page): bind_test1 = defer.succeed(([('foo', annotate.Integer())])) def test1(self, foo): return foo ctx = context.WovenContext() result = FormPage().postForm(ctx, 'test1', {'foo': ['hello, world!']}) return self.assertFailure(result, annotate.ValidateError)
def test_formPostDeferred(self): class FormPage(rend.Page): bind_test1 = defer.succeed(([('foo', annotate.Integer())])) def test1(self, foo): return foo ctx = context.WovenContext() result = FormPage().postForm(ctx, 'test1', {'foo': ['42']}) return result.addCallback(lambda result: self.assertEqual(result, 42))
def testXML(self): t = '<a xmlns:n="http://nevow.com/ns/nevow/0.1" href="#"><n:attr name="href">href</n:attr>label</a>' result = flat.flatten(loaders.xmlstr(t).load()) self.assertEqual(result, '<a href="href">label</a>') t = '<a xmlns:n="http://nevow.com/ns/nevow/0.1" href="#"><n:attr name="href"><n:slot name="href"/></n:attr>label</a>' ctx = context.WovenContext() ctx.fillSlots('href', 'href') result = flat.flatten(flat.precompile(loaders.xmlstr(t).load()), ctx) self.assertEqual(result, '<a href="href">label</a>')
def testHTML(self): t = '<a href="#"><nevow:attr name="href">href</nevow:attr>label</a>' doc = flat.flatten(loaders.htmlstr(t).load()) self.assertEqual(doc, '<a href="href">label</a>') t = '<a href="#"><nevow:attr name="href"><nevow:slot name="href"/></nevow:attr>label</a>' precompiled = loaders.htmlstr(t).load() ctx = context.WovenContext(tag=tags.invisible[precompiled]) ctx.fillSlots('href', 'href') result = flat.flatten(precompiled, ctx) self.assertEqual(result, '<a href="href">label</a>')
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 test_parentCtx(self): class IFoo(Interface): pass ctx = context.WovenContext() ctx.remember('Hello!', IFoo) class Page(rend.Page): def render_foo(self, ctx, data): return IFoo(ctx) docFactory = loaders.stan(p[render_foo]) self.assertEqual(Page().renderSynchronously(ctx), '<p>Hello!</p>')
def flatten(self, obj): """ Flatten the given object using L{twist.deferflatten} and a simple context. Return the Deferred returned by L{twist.deferflatten}. it. """ # Simple context with None IData ctx = context.WovenContext() ctx.remember(None, inevow.IData) return twist.deferflatten(obj, ctx, lambda bytes: None)
def test_macro(self): doc = """ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xmlns:n="http://nevow.com/ns/nevow/0.1"> <body> <n:invisible n:macro="content" /> </body> </html> """ temp = self.mktemp() f = file(temp, 'w') f.write(doc) f.close() class Base(rend.Page): docFactory = loaders.xmlfile(temp) class Page1(Base): def macro_content(self, ctx): return p["Page1"] class Page2(Base): def macro_content(self, ctx): return p["Page2"] p1 = Page1() p2 = Page2() ctx1 = context.WovenContext() ctx2 = context.WovenContext() ctx1.remember(p1, inevow.IRendererFactory) ctx2.remember(p2, inevow.IRendererFactory) p1_str = p1.renderSynchronously(ctx1) p2_str = p2.renderSynchronously(ctx2) self.assertNotEqual(p1_str, p2_str)
def test_handlerWithIdentifier(self): gatherer = LiveGatherer() ctx = context.WovenContext() ctx.remember(gatherer, livepage.IClientHandle) oneQual = util.qual(oneHandler) twoQual = util.qual(twoHandler) ## Subscribe both handlers to the same identifier livepage.handler(oneHandler, identifier='same')(ctx, None) livepage.handler(twoHandler, identifier='same')(ctx, None) gatherer.handleInput('same') self.assertEquals(gatherer.heard, ['one', 'two'])
def test_parentCtx(self): class IFoo(Interface): pass ctx = context.WovenContext() ctx.remember('Hello!', IFoo) class Page(rend.Page): def render_foo(self, ctx, data): return IFoo(ctx) docFactory = loaders.stan(p[render_foo]) return Page().renderString(ctx).addCallback( lambda result: self.assertEqual(result, '<p>Hello!</p>'))
def makePage(self, content): _ = i18n.Translator(translator=mockTranslator) page = rend.Page( docFactory=loaders.stan(tags.invisible(render=tags.directive('i18n'))[content])) page.render_i18n = i18n.render(_) doc = page.docFactory.load() ctx = context.WovenContext(context.PageContext(tag=page), tags.invisible[doc]) page.rememberStuff(ctx) io = StringIO() writer = io.write def finisher(result): return io.getvalue() return page.flattenFactory(doc, ctx, writer, finisher)
def test_data(self): ctx = context.WovenContext() ctx.remember('foo', inevow.IData) tag = p(render=rend.data) self.assertEqual(flat.flatten(tag, ctx), '<p>foo</p>') ctx.remember('\xc2\xa3'.decode('utf-8'), inevow.IData) tag = p(render=rend.data) self.assertEqual(flat.flatten(tag, ctx), '<p>\xc2\xa3</p>') ctx.remember([1, 2, 3, 4, 5], inevow.IData) tag = p(render=rend.data) self.assertEqual(flat.flatten(tag, ctx), '<p>12345</p>') ctx.remember({'foo': 'bar'}, inevow.IData) tag = p(data=directive('foo'), render=rend.data) self.assertEqual(flat.flatten(tag, ctx), '<p>bar</p>')
def test_inlineJS(self): # there is a tendency for people to change inlineJS to something like this: # # return script(type="text/javascript")[xml('\n//<![CDATA[\n'), s, xml(\n//]]>\n'] # # however, this is broken because it replaces & < and > with entities, # which is wrong. If the CDATA thingers are omitted, then it is correct # by the XML spec, but not in reality, because browsers do not resolve # entities in script tags for historic reasons, and the content of # script tags is defined to be CDATA by XHTML, even without CDATA # directives. # # Anyway, the end result is that & becomes & resulting in a syntax # error. ctx = context.WovenContext() tag = tags.inlineJS('correct && elegant;') flatted = flat.flatten(tag, ctx) self.failIf('&' in flatted)
def _processForm(form, ctx, name): # Remember the form ctx.remember(form, iformal.IForm) # Create a keyed tag that will render the form when flattened. tag = T.invisible(key=name)[inevow.IRenderer(form)] # Create a new context, referencing the above tag, so that we don't # pollute the current context with anything the form needs during # rendering. ctx = context.WovenContext(parent=ctx, tag=tag) # Find errors for *this* form and remember things on the context if form.errors: ctx.remember(form.errors.data, iformal.IFormData) else: ctx.remember(form.data or {}, iformal.IFormData) return ctx
def benchmark_longContextChainArg(self): from nevow import testutil ctx = context.RequestContext(tag=testutil.FakeRequest( args=dict(foo=["foo"], bar=["bar"]))) for x in range(5): ## Do some factory contexts ctx = TestContext(parent=ctx) for x in range(100): ## Do a bunch of crap ctx = context.WovenContext(parent=ctx) ## Look for some request arguments loops = 1e4 before = time.clock() for x in xrange(loops): ignored = ctx.arg('foo') ignored = ctx.arg('bar') after = time.clock() self.recordStat({"arg/(cpu sec)": loops / (after - before)})
def test_renderNestedDeferredCallables(self): """ Test flattening of a renderer which returns a Deferred which fires with a renderer which returns a Deferred. """ def render_inner(ctx, data): return defer.succeed('') def render_outer(ctx, data): return defer.succeed(render_inner) ctx = context.WovenContext() ctx.remember(None, inevow.IData) out = [] d = twist.deferflatten(render_outer, ctx, out.append) def flattened(ign): self.assertEqual(out, ['']) d.addCallback(flattened) return d
def test_renderNestedDeferredErrorHandling(self): """ Test that flattening a renderer which returns a Deferred which fires with a renderer which raises an exception causes the outermost Deferred to errback. """ class NestedException(Exception): pass def render_inner(ctx, data): raise NestedException() def render_outer(ctx, data): return defer.succeed(render_inner) ctx = context.WovenContext() ctx.remember(None, inevow.IData) out = [] d = twist.deferflatten(render_outer, ctx, out.append) return self.assertFailure(d, NestedException)
def sanitize(data, d=None): """Nevow JSON serializer is not able to handle some types. We convert those types in proper types: - string to unicode string - PgSQL result set into list - handling of deferreds """ if type(data) in [list, tuple] or \ (PgSQL and isinstance(data, PgSQL.PgResultSet)): return [sanitize(x, d) for x in data] if PgSQL and isinstance(data, PgSQL.PgBooleanType): if data: return u"true" return u"false" if type(data) == str: return unicode(data, errors='ignore') if isinstance(data, rend.Fragment): io = StringIO() writer = io.write finisher = lambda result: io.getvalue() newctx = context.PageContext(parent=ctx, tag=data) data.rememberStuff(newctx) doc = data.docFactory.load() newctx = context.WovenContext(newctx, T.invisible[doc]) fl = self.flattenFactory(doc, newctx, writer, finisher) fl.addCallback(sanitize, None) d.append(fl) return fl if isinstance(data, defer.Deferred): if data.called: return sanitize(data.result) return data if isinstance(data, failure.Failure): return unicode( "<span class='error'>An error occured (%s)</span>" % data.getErrorMessage(), errors='ignore') return data
def test_errorPropogation(self): # A generator that raises an error def gen(ctx, data): yield 1 raise Exception('This is an exception!') yield 2 # Hacky imports from cStringIO import StringIO from nevow.flat import twist # Simple context with None IData ctx = context.WovenContext() ctx.remember(None, inevow.IData) # The actual test notquiteglobals = {} io = StringIO() def finished(spam): print 'FINISHED' def error(failure): notquiteglobals['exception'] = failure.value def checker(result): if not isinstance(notquiteglobals['exception'], Exception): self.fail( 'deferflatten did not errback with the correct failure') return result d = twist.deferflatten(gen, ctx, io.write) d.addCallback(finished) d.addErrback(error) d.addBoth(checker) return d
def _withAndWithout(self, loader): ctx = context.WovenContext() self.assertEquals(loader.load(), ['<p>hello</p>']) self.assertEquals(loader.load(ctx), ['<p>hello</p>'])
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))