def test_produceRedirect(self): """ L{_PrivateRootPage.produceResource} should return a redirect to '/private/<default-private-id>' when asked for '/'. This is a bad way to do it, because it isn't optional; all logged-in users are instantly redirected to their private page, even if the application has something interesting to display. See ticket #2708 for details. """ item = FakeModelItem(store=self.userStore) class TabThingy(object): implements(INavigableElement) def getTabs(self): return [Tab("supertab", item.storeID, 1.0)] tt = TabThingy() self.userStore.inMemoryPowerUp(tt, INavigableElement) rsrc, segments = self.privapp.produceResource( FakeRequest(), tuple(['']), None) self.assertIsInstance(rsrc, _PrivateRootPage) self.assertEqual(segments, tuple([''])) url, newSegs = rsrc.locateChild(FakeRequest(), ('',)) self.assertEqual(newSegs, ()) req = FakeRequest() target = self.privapp.linkTo(item.storeID) self.assertEqual('/'+url.path, target)
def test_userAgentDetection(self): """ C{LivePage._supportedBrowser} should return True for User-Agent strings which are not known to be supported and False for those which are known to be unsupported. """ page = athena.LivePage() supported = [ "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.3)" " Gecko/20061201 Firefox/2.0.0.3 (Ubuntu-feisty)", "Mozilla/5.0 (Windows; U; Windows NT 5.2; sv-SE;" " rv:1.8.0.8) Gecko/20061025 Firefox 1.5.0.8", "Opera/9.20 (Windows NT 6.0; U; en)" ] unsupported = [ "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en)" " AppleWebKit/418.9.1 (KHTML, like Gecko) Safari/419.3", "Opera/8.5 (Windows NT 6.0; U; en)", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US;" " rv:1.7.10) Gecko/20050716 Firefox/1.0.6", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)" ] for ua in supported: req = FakeRequest() req.received_headers['user-agent'] = ua self.assertTrue(page._supportedBrowser(req)) for ua in unsupported: req = FakeRequest() req.received_headers['user-agent'] = ua self.assertFalse(page._supportedBrowser(req))
def test_fromContext(self): r = FakeRequest(uri='/a/b/c') urlpath = url.URL.fromContext(context.RequestContext(tag=r)) self.assertEqual('http://localhost/', str(urlpath)) r.prepath = ['a'] urlpath = url.URL.fromContext(context.RequestContext(tag=r)) self.assertEqual('http://localhost/a', str(urlpath)) r = FakeRequest(uri='/a/b/c?foo=bar') r.prepath = ['a','b'] urlpath = url.URL.fromContext(context.RequestContext(tag=r)) self.assertEqual('http://localhost/a/b?foo=bar', str(urlpath))
def doRendering(self, fragmentClass): """ Verify that the given fragment class will render without raising an exception. """ siteStore = Store() loginSystem = LoginSystem(store=siteStore) installOn(loginSystem, siteStore) p = Product(store=siteStore, types=["xmantissa.webadmin.LocalUserBrowser", "xmantissa.signup.SignupConfiguration"]) account = loginSystem.addAccount(u'testuser', u'localhost', None) p.installProductOn(account.avatars.open()) f = fragmentClass(None, u'testuser', account) p = LivePage( docFactory=stan( html[ head(render=directive('liveglue')), body(render=lambda ctx, data: f)])) f.setFragmentParent(p) ctx = WovenContext() req = FakeRequest() ctx.remember(req, IRequest) d = p.renderHTTP(ctx) def rendered(ign): p.action_close(None) d.addCallback(rendered) return d
def render(resource, query_args): """ Render (in the manner of the Nevow appserver) a Nevow ``Page`` or a Twisted ``Resource`` against a request with the given query arguments . :param resource: The page or resource to render. :param query_args: The query arguments to put into the request being rendered. A mapping from ``bytes`` to ``list`` of ``bytes``. :return Deferred: A Deferred that fires with the rendered response body as ``bytes``. """ ctx = WebContext(tag=resource) req = FakeRequest(args=query_args) ctx.remember(DefaultExceptionHandler(), ICanHandleException) ctx.remember(req, IRequest) ctx.remember(None, IData) def maybe_concat(res): if isinstance(res, bytes): return req.v + res return req.v resource = INevowResource(resource) d = maybeDeferred(resource.renderHTTP, ctx) d.addErrback(processingFailed, req, ctx) d.addCallback(maybe_concat) return d
def test_authenticatedApplicationNavigation(self): """ The I{applicationNavigation} renderer should add primary navigation elements to the tag it is passed if it is called on a L{_PublicPageMixin} being rendered for an authenticated user. """ navigable = FakeNavigableElement(store=self.userStore) installOn(navigable, self.userStore) navigable.tabs = [Tab('foo', 123, 0, [Tab('bar', 432, 0)])] request = FakeRequest() page = self.createPage(self.username) navigationPattern = div[ span(id='app-tab', pattern='app-tab'), span(id='tab-contents', pattern='tab-contents')] ctx = context.WebContext(tag=navigationPattern) ctx.remember(request) tag = page.render_applicationNavigation(ctx, None) self.assertEqual(tag.tagName, 'div') self.assertEqual(tag.attributes, {}) children = [child for child in tag.children if child.pattern is None] self.assertEqual(children, []) self.assertEqual(len(tag.slotData['tabs']), 1) fooTab = tag.slotData['tabs'][0] self.assertEqual(fooTab.attributes, {'id': 'app-tab'}) self.assertEqual(fooTab.slotData['name'], 'foo') fooContent = fooTab.slotData['tab-contents'] self.assertEqual(fooContent.attributes, {'id': 'tab-contents'}) self.assertEqual(fooContent.slotData['href'], self.privateApp.linkTo(123))
def test_bootstraps(self): """ L{LivePage._bootstraps} should return a list of 2-tuples of (initialization method, arguments) of methods to call in JavaScript. Specifically, it should invoke Divmod.bootstrap with the page's own URL, and Nevow.Athena.bootstrap with the name of the client-side Page class to instantiate and the URL to instantiate it with. """ SEG = "'" + '"' URI = "http://localhost/" + SEG req = FakeRequest(uri='/' + SEG, currentSegments=[SEG]) ctx = WovenContext() ctx.remember(req, IRequest) self.page.clientID = 'asdf' self.assertEqual( self.page._bootstraps(ctx), [ ( "Divmod.bootstrap", # Nevow's URL quoting rules are weird, but this is the URL # flattener's fault, not mine. Adjust to taste if that changes # (it won't) -glyph [u"http://localhost/'%22"]), ("Nevow.Athena.bootstrap", [u'Nevow.Athena.PageWidget', u'asdf']) ])
def test_setResponseCode(self): """ Test that the response code of a fake request can be set. """ req = FakeRequest() req.setResponseCode(BAD_REQUEST) self.assertEqual(req.code, BAD_REQUEST)
def test_quality_invalid_notFloat(self): request = FakeRequest(headers={ 'accept-language': 'fo;q=0.4,ba;q=junk', }) ctx = context.RequestContext(tag=request) r = inevow.ILanguages(ctx) self.assertEquals(r, ['ba', 'fo'])
def test_quality_simple(self): request = FakeRequest(headers={ 'accept-language': 'fo;q=0.4', }) ctx = context.RequestContext(tag=request) r = inevow.ILanguages(ctx) self.assertEquals(r, ['fo'])
def test_confusedNewPlugin(self): """ If L{UnguardedWrapper.locateChild} discovers a plugin that implements both C{sessionlessProduceResource} and C{resourceFactory}, it should prefer the new C{sessionlessProduceResource} method and return that resource. """ wrapper = UnguardedWrapper(self.store, None) req = FakeRequest() test = self segments = ('foo', 'bar') result = object() calledWith = [] class SiteRootPlugin(object): def resourceFactory(self, segments): test.fail("Don't call this.") def sessionlessProduceResource(self, request, segments): calledWith.append((request, segments)) return result, segments[1:] self.store.inMemoryPowerUp(SiteRootPlugin(), ISessionlessSiteRootPlugin) resource, resultSegments = wrapper.locateChild(req, segments) self.assertEqual(calledWith, [(req, segments)]) self.assertIdentical(resource, result) self.assertEqual(resultSegments, ('bar', ))
def test_multipleLanguages(self): request = FakeRequest(headers={ 'accept-language': 'fo,ba,th', }) ctx = context.RequestContext(tag=request) r = inevow.ILanguages(ctx) self.assertEquals(r, ['fo', 'ba', 'th'])
def test_confusedNewPlugin(self): """ When L{SiteRootMixin.locateChild} finds a L{ISiteRootPlugin} that implements both C{produceResource} and C{resourceFactory}, it should prefer the new-style C{produceResource} method. """ navthing = object() result = object() calledWith = [] test = self class ConfusedSiteRootPlugin(object): implements(ISiteRootPlugin) def produceResource(self, req, segs, webViewer): calledWith.append((req, segs, webViewer)) return result def resourceFactory(self, segs): test.fail("resourceFactory called.") self.store.inMemoryPowerUp(ConfusedSiteRootPlugin(), ISiteRootPlugin) self.store.inMemoryPowerUp(navthing, IWebViewer) req = FakeRequest(headers={'host': 'localhost'}) self.resource.locateChild(req, ("foo", "bar")) self.assertEqual(calledWith, [(req, ("foo", "bar"), navthing)])
def test_rootURL(self): """ L{SiteConfiguration.rootURL} returns C{/} for a request made onto the hostname with which the L{SiteConfiguration} is configured. """ request = FakeRequest(headers={'host': self.domain.encode('ascii')}) self.assertEqual(self.site.rootURL(request), URL('', ''))
def test_finish(self): """ L{StylesheetRewritingRequestWrapper.finish} causes all written bytes to be translated with C{_replace} written to the wrapped request. """ stylesheetFormat = """ .foo { background-image: url(%s) } """ originalStylesheet = stylesheetFormat % ("/Foo/bar", ) expectedStylesheet = stylesheetFormat % ("/bar/Foo/bar", ) request = FakeRequest() roots = {request: URL.fromString('/bar/')} wrapper = website.StylesheetRewritingRequestWrapper( request, [], roots.get) wrapper.write(originalStylesheet) wrapper.finish() # Parse and serialize both versions to normalize whitespace so we can # make a comparison. parser = CSSParser() self.assertEqual( parser.parseString(request.accumulator).cssText, parser.parseString(expectedStylesheet).cssText)
def test_rootURLWithoutHost(self): """ L{SiteConfiguration.rootURL} returns C{/} for a request made without a I{Host} header. """ request = FakeRequest() self.assertEqual(self.site.rootURL(request), URL('', ''))
def test_prePathURL(self): """ Verify that L{FakeRequest.prePathURL} returns the prepath of the requested URL. """ req = FakeRequest(currentSegments=['a'], uri='/a/b') self.assertEqual(req.prePathURL(), 'http://localhost/a')
def _getRenderViewScroller(self): """ Get a L{hyperbola_view.ShareScrollingElement} by way of L{hyperbola_view.BlogBlurbViewer.view}. """ fragment = hyperbola_view.BlogBlurbViewer(self.publicBlogShare) return fragment.view(FakeRequest(), tags.invisible())
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 test_oneLanguage(self): request = FakeRequest(headers={ 'accept-language': 'fo', }) ctx = context.RequestContext(tag=request) r = inevow.ILanguages(ctx) self.assertEqual(r, ['fo'])
def test_oldFlattenableOverriddenRend(self): """ Flattening L{Element} instances with an overridden C{rend} method flattened with the old flatten function results in the flattened version of whatever their C{rend} method returns. """ renders = [] class OldStyleElement(Element): docFactory = stan("Hello, world") def rend(self, ctx, data): return invisible(render=directive("foo"))[Element.rend( self, ctx, data)] def foo(self, request, tag): renders.append((self, request)) return p[tag] renderer(foo) result = [] element = OldStyleElement() request = FakeRequest() context = WovenContext() context.remember(request) finished = oldFlatten(element, context, result.append, lambda ign: ign) def cbFinished(ignored): self.assertEqual("".join(result), "<p>Hello, world</p>") self.assertEqual(renders, [(element, request)]) finished.addCallback(cbFinished) return finished
def test_quality_sort(self): request = FakeRequest(headers={ 'accept-language': 'fo;q=0.4,ba;q=0.2,xy;q=0.9', }) ctx = context.RequestContext(tag=request) r = inevow.ILanguages(ctx) self.assertEquals(r, ['xy', 'fo', 'ba'])
def test_postWithoutPrivileges(self): """ Attempting to post to a blog should result in a L{LoginPage} which remembers the parameters of the attempted post. """ class StubBlurb(object): """ L{Blurb}-alike for testing purposes. """ def __init__(self, store, flavor): self.store = store self.flavor = flavor currentSegments = ['foo', 'bar'] postSegments = ['post', 'baz'] arguments = {'quux': ['1', '2']} request = FakeRequest( uri='/'.join([''] + currentSegments + postSegments), currentSegments=currentSegments, args=arguments) blurb = StubBlurb(self.userStore, FLAVOR.BLOG) sharedBlurb = SharedProxy(blurb, (IViewable,), 'abc') view = BlurbViewer(sharedBlurb) child, segments = view.locateChild(request, postSegments) self.assertTrue(isinstance(child, LoginPage)) self.assertEqual(child.segments, currentSegments + postSegments[:1]) self.assertEqual(child.arguments, arguments) self.assertEqual(segments, postSegments[1:])
def test_notFound(self): """ L{AnonymousSite.locateChild} returns L{NotFound} for requests it cannot find another response for. """ result = self.resource.locateChild( FakeRequest(headers={"host": "example.com"}), ("foo", "bar")) self.assertIdentical(result, NotFound)
def _render(self, page): """ Test helper which tries to render the given page. """ ctx = WovenContext() req = FakeRequest() ctx.remember(req, IRequest) return page.renderHTTP(ctx).addCallback(lambda ign: req.v)
def test_rootURLWWWSubdomain(self): """ L{SiteConfiguration.rootURL} returns C{/} for a request made onto the I{www} subdomain of the hostname of the L{SiteConfiguration}. """ request = FakeRequest( headers={'host': 'www.' + self.domain.encode('ascii')}) self.assertEqual(self.site.rootURL(request), URL('', ''))
def _render(self, resource): """ Test helper which tries to render the given resource. """ ctx = WovenContext() req = FakeRequest(headers={'host': self.hostname}) ctx.remember(req, IRequest) return req, resource.renderHTTP(ctx)
def _render(self, fragment): """ Test helper which tries to render the given fragment. """ ctx = WovenContext() req = FakeRequest() ctx.remember(req, IRequest) return Page(docFactory=stan(fragment)).renderString(ctx)
def test_smashInitialHeaderCase(self): """ L{FakeRequest.getHeader} will return the value of a header specified to L{FakeRequest.__init__} even if the header names have differing case. """ host = 'example.com' request = FakeRequest(headers={'HoSt': host}) self.assertEqual(request.getHeader('hOsT'), host)
def test_renderHTTPS(self): """ L{SecuringWrapper.renderHTTP} returns the result of the wrapped resource's C{renderHTTP} method if it is called with a secure request. """ request = FakeRequest(isSecure=True) result = self.wrapper.renderHTTP(request) self.assertIdentical(self.resource.renderedWithContext, request) self.assertEqual(result, self.content)