def test_url(self): """ An L{URL} object is flattened to the appropriate representation of itself, whether it is the child of a tag or the value of a tag attribute. """ link = URL.fromString("http://foo/fu?bar=baz&bar=baz#quux%2f") self.assertStringEqual(self.flatten(link), "http://foo/fu?bar=baz&bar=baz#quux%2F") self.assertStringEqual( self.flatten(div[link]), '<div>http://foo/fu?bar=baz&bar=baz#quux%2F</div>') self.assertStringEqual( self.flatten(div(foo=link)), '<div foo="http://foo/fu?bar=baz&bar=baz#quux%2F"></div>') self.assertStringEqual( self.flatten(div[div(foo=link)]), '<div><div foo="http://foo/fu?bar=baz&bar=baz#quux%2F"></div>' '</div>') link = URL.fromString("http://foo/fu?%2f=%7f") self.assertStringEqual(self.flatten(link), "http://foo/fu?%2F=%7F") self.assertStringEqual(self.flatten(div[link]), '<div>http://foo/fu?%2F=%7F</div>') self.assertStringEqual(self.flatten(div(foo=link)), '<div foo="http://foo/fu?%2F=%7F"></div>')
def test_url(self): """ An L{URL} object is flattened to the appropriate representation of itself, whether it is the child of a tag or the value of a tag attribute. """ link = URL.fromString("http://foo/fu?bar=baz&bar=baz#quux%2f") self.assertStringEqual( self.flatten(link), "http://foo/fu?bar=baz&bar=baz#quux%2F") self.assertStringEqual( self.flatten(div[link]), '<div>http://foo/fu?bar=baz&bar=baz#quux%2F</div>') self.assertStringEqual( self.flatten(div(foo=link)), '<div foo="http://foo/fu?bar=baz&bar=baz#quux%2F"></div>') self.assertStringEqual( self.flatten(div[div(foo=link)]), '<div><div foo="http://foo/fu?bar=baz&bar=baz#quux%2F"></div>' '</div>') link = URL.fromString("http://foo/fu?%2f=%7f") self.assertStringEqual( self.flatten(link), "http://foo/fu?%2F=%7F") self.assertStringEqual( self.flatten(div[link]), '<div>http://foo/fu?%2F=%7F</div>') self.assertStringEqual( self.flatten(div(foo=link)), '<div foo="http://foo/fu?%2F=%7F"></div>')
def test_getSelectedTabExactMatch(self): """ Check that L{webnav.getSelectedTab} returns the tab whose C{linkURL} attribute exactly matches the path of the L{nevow.url.URL} it is passed """ tabs = list(webnav.Tab(str(i), None, 0, linkURL="/" + str(i)) for i in xrange(5)) for (i, tab) in enumerate(tabs): selected = webnav.getSelectedTab(tabs, URL.fromString(tab.linkURL)) self.assertIdentical(selected, tab) selected = webnav.getSelectedTab(tabs, URL.fromString("/XYZ")) self.failIf(selected)
def test_getSelectedTabExactMatch(self): """ Check that L{webnav.getSelectedTab} returns the tab whose C{linkURL} attribute exactly matches the path of the L{nevow.url.URL} it is passed """ tabs = list(webnav.Tab(str(i), None, 0, linkURL='/' + str(i)) for i in xrange(5)) for (i, tab) in enumerate(tabs): selected = webnav.getSelectedTab(tabs, URL.fromString(tab.linkURL)) self.assertIdentical(selected, tab) selected = webnav.getSelectedTab(tabs, URL.fromString('/XYZ')) self.failIf(selected)
def _root(self, scheme, hostname, portObj, standardPort): # TODO - real unicode support (but punycode is so bad) if portObj is None: return None portNumber = portObj.portNumber port = portObj.listeningPort if hostname is None: hostname = self.hostname else: hostname = hostname.split(':')[0].encode('ascii') if portNumber == 0: if port is None: return None else: portNumber = port.getHost().port # At some future point, we may want to make pathsegs persistently # configurable - perhaps scheme and hostname as well - in order to # easily support reverse proxying configurations, particularly where # Mantissa is being "mounted" somewhere other than /. See also rootURL # which has some overlap with this method (the difference being # universal vs absolute URLs - rootURL may want to call cleartextRoot # or encryptedRoot in the future). See #417 and #2309. pathsegs = [''] if portNumber != standardPort: hostname = '%s:%d' % (hostname, portNumber) return URL(scheme, hostname, pathsegs)
def rendered(request): if request.redirected_to is None: result.callback(request) else: visited.append(request.redirected_to) if visited.index(request.redirected_to) != len(visited) - 1: visited.append(request.redirected_to) result.errback(Exception("Redirect loop: %r" % (visited,))) elif len(visited) > redirectLimit: result.errback(Exception("Too many redirects: %r" % (visited,))) else: newHeaders = headers.copy() # Respect redirects location = URL.fromString(request.redirected_to) newHeaders['host'] = location.netloc # Respect cookies cookies.update(request.cookies) # str(URL) shouldn't really do what it does. page = getResource( site, str(location), newHeaders, cookies) page.addCallbacks(rendered, result.errback)
def locateChild(self, ctx, segments): """ Look up children in the normal manner, but then customize them for the authenticated user if they support the L{ICustomizable} interface. If the user is attempting to access a private URL, redirect them. """ result = self._getAppStoreResource(ctx, segments[0]) if result is not None: child, segments = result, segments[1:] return child, segments if segments[0] == '': result = self.child_(ctx) if result is not None: child, segments = result, segments[1:] return child, segments # If the user is trying to access /private/*, then his session has # expired or he is otherwise not logged in. Redirect him to /login, # preserving the URL segments, rather than giving him an obscure 404. if segments[0] == 'private': u = URL.fromContext(ctx).click('/').child('login') for seg in segments: u = u.child(seg) return u, () return rend.NotFound
def rendered(request): if request.redirected_to is None: result.callback(request) else: visited.append(request.redirected_to) if visited.index(request.redirected_to) != len(visited) - 1: visited.append(request.redirected_to) result.errback(Exception("Redirect loop: %r" % (visited, ))) elif len(visited) > redirectLimit: result.errback( Exception("Too many redirects: %r" % (visited, ))) else: newHeaders = headers.copy() # Respect redirects location = URL.fromString(request.redirected_to) newHeaders['host'] = location.netloc # Respect cookies cookies.update(request.cookies) # str(URL) shouldn't really do what it does. page = getResource(site, str(location), newHeaders, cookies) page.addCallbacks(rendered, result.errback)
def __init__(self, url, tries=10, timeout=defaultTimeout, *a, **kw): """ Prepare the download information. Any additional positional or keyword arguments are passed on to C{twisted.web.client.HTTPPageGetter}. @type url: C{nevow.url.URL} or C{unicode} or C{str} @param url: The HTTP URL to attempt to download @type tries: C{int} @param tries: The maximum number of retry attempts before giving up @type timeout: C{float} @param timeout: Timeout value, in seconds, for the page fetch; defaults to L{defaultTimeout} """ if isinstance(url, unicode): url = url.encode('utf-8') if isinstance(url, str): url = URL.fromString(url) self.url = url.anchor(None) self.args = a self.kwargs = kw self.delay = self.initialDelay self.tries = tries self.timeout = timeout
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 checkid_setup(registry, requestData, user=None): """ This method will validate and redirect a successful request to its return_to param. If the user isn't logged in, or doesn't have an account, we'll redirect to an internal page. @param registry: the current OpenID registry @type registry: L{OpenIDRegistry} @param requestData: the current request data @type requestData: L{OpenIDRequest} @param user: the current user @type user: L{txopenid.user.User} @return: association response @rtype: L{nevow.url.URL} """ if(user is not None): def _identity_state(): return user.hasIdentity(requestData['openid.identity']) def _trust_state(): return user.trustsRoot(requestData['openid.trust_root']) if not(yield maybeDeferred(_identity_state)): return_to = util.appendQuery(OPENID_IDENTITY_URL, requestData) elif not(yield maybeDeferred(_trust_state)): return_to = util.appendQuery(OPENID_TRUST_URL, requestData) else: return_to = get_login_response(registry, requestData) else: return_to = util.appendQuery(OPENID_LOGIN_URL, requestData) returnValue(URL.fromString(return_to))
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_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 test_getJSModuleURL(self): """ L{MantissaLivePage.getJSModuleURL} should return a child of its C{_moduleRoot} attribute of the form:: _moduleRoot/<SHA1 digest of module contents>/Package.ModuleName """ module = 'Mantissa' url = URL(scheme='https', netloc='example.com', pathsegs=['foo']) page = MantissaLivePage(None) page._moduleRoot = url jsDir = FilePath(__file__).parent().parent().child("js") modulePath = jsDir.child(module).child("__init__.js") moduleContents = modulePath.open().read() expect = sha.new(moduleContents).hexdigest() self.assertEqual(page.getJSModuleURL(module), url.child(expect).child(module))
def test_getJSModuleURL(self): """ L{MantissaLivePage.getJSModuleURL} should return a child of its C{_moduleRoot} attribute of the form:: _moduleRoot/<SHA1 digest of module contents>/Package.ModuleName """ module = 'Mantissa' url = URL(scheme='https', netloc='example.com', pathsegs=['foo']) page = MantissaLivePage(None) page._moduleRoot = url jsDir = FilePath(__file__).parent().parent().child("js") modulePath = jsDir.child(module).child("__init__.js") moduleContents = modulePath.open().read() expect = sha1(moduleContents).hexdigest() self.assertEqual(page.getJSModuleURL(module), url.child(expect).child(module))
def test_beforeRenderSetsModuleRoot(self): """ L{MantissaLivePage.beforeRender} should set I{_moduleRoot} to the C{__jsmodule__} child of the URL returned by the I{rootURL} method of the L{WebSite} it wraps. """ receivedRequests = [] root = URL(netloc='example.com', pathsegs=['a', 'b']) class FakeWebSite(object): def rootURL(self, request): receivedRequests.append(request) return root request = FakeRequest() page = MantissaLivePage(FakeWebSite()) page.beforeRender(request) self.assertEqual(receivedRequests, [request]) self.assertEqual(page._moduleRoot, root.child('__jsmodule__'))
def test_parseURLs(self): """ L{eridanus.iriparse.parseURL} extracts and parses (as a L{nevow.url.URL}) all URIs in a string. """ self.assertEquals( list(iriparse.parseURLs(u'http://google.com/')), [URL.fromString(u'http://google.com/')])
def renderHTTP(self, ctx): """ Handle the password reset form. The following exchange describes the process: S: Render C{reset} C: POST C{username} or C{email} S: L{handleRequestForUser}, render C{reset-check-email} (User follows the emailed reset link) S: Render C{reset-step-two} C: POST C{password1} S: L{resetPassword}, render C{reset-done} """ req = inevow.IRequest(ctx) if req.method == 'POST': if req.args.get('username', [''])[0]: user = unicode(usernameFromRequest(req), 'ascii') self.handleRequestForUser(user, URL.fromContext(ctx)) self.fragment = self.templateResolver.getDocFactory( 'reset-check-email') elif req.args.get('email', [''])[0]: email = req.args['email'][0].decode('ascii') acct = self.accountByAddress(email) if acct is not None: username = '******'.join( userbase.getAccountNames(acct.avatars.open()).next()) self.handleRequestForUser(username, URL.fromContext(ctx)) self.fragment = self.templateResolver.getDocFactory( 'reset-check-email') elif 'password1' in req.args: (password, ) = req.args['password1'] self.resetPassword(self.attempt, unicode(password)) self.fragment = self.templateResolver.getDocFactory( 'reset-done') else: # Empty submit; redirect back to self return URL.fromContext(ctx) elif self.attempt: self.fragment = self.templateResolver.getDocFactory( 'reset-step-two') return PublicPage.renderHTTP(self, ctx)
def test_parseURL(self): """ L{eridanus.iriparse.parseURL} extracts and parses (as a L{nevow.url.URL}) the first URI in a string. """ self.assertEquals( iriparse.parseURL( u'http://google.com/ http://foo.bar/ world'), URL.fromString(u'http://google.com/'))
def _differentHostnameNonstandardPort(self, portType, isSecure, scheme): portNumber = 12345 request = FakeRequest( isSecure=isSecure, headers={'host': 'alice.' + self.domain.encode('ascii')}) portType(store=self.store, factory=self.site, portNumber=portNumber) self.assertEqual( self.site.rootURL(request), URL(scheme, '%s:%s' % (self.domain.encode('ascii'), portNumber)))
def evaluate(self, expn): """ Evaluate an expression. """ url = URL.fromString('http://www.google.com/search?') url = url.add('q', expn + '=') url = url.add('num', '1') d = self._fetch(url) d.addCallback(self._extractResult, expn) return d
def renderHTTP(self, ctx): """ Handle the password reset form. The following exchange describes the process: S: Render C{reset} C: POST C{username} or C{email} S: L{handleRequestForUser}, render C{reset-check-email} (User follows the emailed reset link) S: Render C{reset-step-two} C: POST C{password1} S: L{resetPassword}, render C{reset-done} """ req = inevow.IRequest(ctx) if req.method == 'POST': if req.args.get('username', [''])[0]: user = unicode(usernameFromRequest(req), 'ascii') self.handleRequestForUser(user, URL.fromContext(ctx)) self.fragment = self.templateResolver.getDocFactory( 'reset-check-email') elif req.args.get('email', [''])[0]: email = req.args['email'][0].decode('ascii') acct = self.accountByAddress(email) if acct is not None: username = '******'.join( userbase.getAccountNames(acct.avatars.open()).next()) self.handleRequestForUser(username, URL.fromContext(ctx)) self.fragment = self.templateResolver.getDocFactory('reset-check-email') elif 'password1' in req.args: (password,) = req.args['password1'] self.resetPassword(self.attempt, unicode(password)) self.fragment = self.templateResolver.getDocFactory('reset-done') else: # Empty submit; redirect back to self return URL.fromContext(ctx) elif self.attempt: self.fragment = self.templateResolver.getDocFactory('reset-step-two') return PublicPage.renderHTTP(self, ctx)
def test_shortURL(self): """ L{StylesheetRewritingRequestWrapper._replace} changes URLs with only one segment so they are beneath the root URL. """ request = object() roots = {request: URL.fromString('/bar/')} wrapper = website.StylesheetRewritingRequestWrapper( request, [], roots.get) self.assertEqual(wrapper._replace('/'), '/bar/')
class Wunderground(object): API_ROOT = URL.fromString('http://api.wunderground.com/auto/wui/geo') @classmethod def current(cls, query): url = cls.API_ROOT.child('WXCurrentObXML').child('index.xml').add( 'query', query) return util.PerseverantDownloader(url).go().addCallback( lambda (data, headers): etree.fromstring(data)).addCallback( WundergroundConditions.fromElement)
def test_rootURLNonstandardRequestPort(self): """ L{SiteConfiguration.rootURL} returns C{/} for a request made onto a non-standard port which is one on which the L{SiteConfiguration} is configured to listen. """ request = FakeRequest( headers={'host': '%s:%s' % (self.domain.encode('ascii'), 54321)}) TCPPort(store=self.store, factory=self.site, portNumber=54321) self.assertEqual(self.site.rootURL(request), URL('', ''))
def test_replaceMantissa(self): """ L{StylesheetRewritingRequestWrapper._replace} changes URLs of the form I{/Mantissa/foo} to I{<rootURL>/static/mantissa-base/foo}. """ request = object() roots = {request: URL.fromString('/bar/')} wrapper = website.StylesheetRewritingRequestWrapper( request, [], roots.get) self.assertEqual(wrapper._replace('/Mantissa/foo.png'), '/bar/static/mantissa-base/foo.png')
def test_replaceMantissa(self): """ L{StylesheetRewritingRequestWrapper._replace} changes URLs of the form I{/Mantissa/foo} to I{<rootURL>/static/mantissa-base/foo}. """ request = object() roots = {request: URL.fromString('/bar/')} wrapper = website.StylesheetRewritingRequestWrapper(request, [], roots.get) self.assertEqual( wrapper._replace('/Mantissa/foo.png'), '/bar/static/mantissa-base/foo.png')
def childFactory(self, ctx, name): for T in self.original.store.query( Ticket, AND(Ticket.booth == self.original, Ticket.nonce == unicode(name, 'ascii'))): something = T.claim() res = IResource(something) lgo = getattr(res, 'logout', lambda : None) ISession(ctx).setDefaultResource(res, lgo) return URL.fromContext(ctx).click("/private") return None
def childFactory(self, ctx, name): for T in self.original.store.query( Ticket, AND(Ticket.booth == self.original, Ticket.nonce == unicode(name, 'ascii'))): something = T.claim() res = IResource(something) lgo = getattr(res, 'logout', lambda: None) ISession(ctx).setDefaultResource(res, lgo) return URL.fromContext(ctx).click("/private") return None
def test_shortURL(self): """ L{StylesheetRewritingRequestWrapper._replace} changes URLs with only one segment so they are beneath the root URL. """ request = object() roots = {request: URL.fromString('/bar/')} wrapper = website.StylesheetRewritingRequestWrapper( request, [], roots.get) self.assertEqual( wrapper._replace('/'), '/bar/')
def _portZero(self, portType, scheme, method): randomPort = 7777 class FakePort(object): def getHost(self): return IPv4Address('TCP', u'example.com', randomPort) port = portType(store=self.store, portNumber=0, factory=self.site) port.listeningPort = FakePort() self.assertEquals( getattr(self.site, method)(), URL(scheme, '%s:%s' % (self.domain, randomPort)))
def rootChild_resetPassword(self, req, webViewer): """ Redirect authenticated users to their settings page (hopefully they have one) when they try to reset their password. This is the wrong way for this functionality to be implemented. See #2524. """ from xmantissa.ixmantissa import IWebTranslator, IPreferenceAggregator return URL.fromString( IWebTranslator(self.store).linkTo( IPreferenceAggregator(self.store).storeID))
def test_replaceOtherOffering(self): """ L{StylesheetRewritingRequestWrapper._replace} changes URLs of the form I{/Something/foo} to I{<rootURL>/static/Something/foo} if C{Something} gives the name of an installed offering with a static content path. """ request = object() roots = {request: URL.fromString('/bar/')} wrapper = website.StylesheetRewritingRequestWrapper( request, ['OfferingName'], roots.get) self.assertEqual(wrapper._replace('/OfferingName/foo.png'), '/bar/static/OfferingName/foo.png')
def test_replaceOtherOffering(self): """ L{StylesheetRewritingRequestWrapper._replace} changes URLs of the form I{/Something/foo} to I{<rootURL>/static/Something/foo} if C{Something} gives the name of an installed offering with a static content path. """ request = object() roots = {request: URL.fromString('/bar/')} wrapper = website.StylesheetRewritingRequestWrapper(request, ['OfferingName'], roots.get) self.assertEqual( wrapper._replace('/OfferingName/foo.png'), '/bar/static/OfferingName/foo.png')
def test_nonOfferingOnlyGivenPrefix(self): """ L{StylesheetRewritingRequestWrapper._replace} only changes URLs of the form I{/Something/foo} so they are beneath the root URL if C{Something} does not give the name of an installed offering. """ request = object() roots = {request: URL.fromString('/bar/')} wrapper = website.StylesheetRewritingRequestWrapper( request, ['Foo'], roots.get) self.assertEqual(wrapper._replace('/OfferingName/foo.png'), '/bar/OfferingName/foo.png')
def renderHTTP(self, ctx): req = inevow.IRequest(ctx) password = req.args.get('password', [None])[0] if password is None: return Page.renderHTTP(self, ctx) self.original.store.transact(self.original.setPassword, unicode(password)) # XXX TODO: select # proper decoding # strategy. return URL.fromString('/')
def test_segments(self): """ L{LoginPage.beforeRender} should fill the I{login-action} slot with an L{URL} which includes all the segments given to the L{LoginPage}. """ segments = ('foo', 'bar') page = LoginPage(self.siteStore, segments) page.beforeRender(self.context) loginAction = self.context.locateSlotData('login-action') expectedLocation = URL.fromString('/') for segment in (LOGIN_AVATAR, ) + segments: expectedLocation = expectedLocation.child(segment) self.assertEqual(loginAction, expectedLocation)
def test_segments(self): """ L{LoginPage.beforeRender} should fill the I{login-action} slot with an L{URL} which includes all the segments given to the L{LoginPage}. """ segments = ('foo', 'bar') page = LoginPage(self.siteStore, segments) page.beforeRender(self.context) loginAction = self.context.locateSlotData('login-action') expectedLocation = URL.fromString('/') for segment in (LOGIN_AVATAR,) + segments: expectedLocation = expectedLocation.child(segment) self.assertEqual(loginAction, expectedLocation)
def test_nonOfferingOnlyGivenPrefix(self): """ L{StylesheetRewritingRequestWrapper._replace} only changes URLs of the form I{/Something/foo} so they are beneath the root URL if C{Something} does not give the name of an installed offering. """ request = object() roots = {request: URL.fromString('/bar/')} wrapper = website.StylesheetRewritingRequestWrapper( request, ['Foo'], roots.get) self.assertEqual( wrapper._replace('/OfferingName/foo.png'), '/bar/OfferingName/foo.png')
def render_child_base_href(ctx, data): """ Render a URL that acts as a base for constructing links to child resources. In essence, this is url.here with any slashes removed from the end, giving it consistent for root and non-root URLs. An example of how one might use this to render a link to a child resource is: <a href="#"><n:attr name="href"><n:invisible n:render="child_base_href" />/<n:slot name="id" /><n:attr>more ...</a> """ url = str(URL.fromContext(ctx)) url = url.rstrip('/') return url
def test_rootURLAlternateSubdomain(self): """ L{SiteConfiguration.rootURL} returns C{/} for a request made onto a subdomain known as an internal domain. """ userbase.LoginMethod(store=self.store, localpart=u'username', domain=u'example.org', internal=True, protocol=u'*', verified=True, account=self.store) request = FakeRequest(headers={'host': 'example.org'}) self.assertEqual(self.site.rootURL(request), URL('', ''))
def test_queryArguments(self): """ L{LoginPage.beforeRender} should fill the I{login-action} slot with an L{URL} which includes all the query arguments given to the L{LoginPage}. """ args = {'foo': ['bar']} page = LoginPage(self.siteStore, (), args) page.beforeRender(self.context) loginAction = self.context.locateSlotData('login-action') expectedLocation = URL.fromString('/') expectedLocation = expectedLocation.child(LOGIN_AVATAR) expectedLocation = expectedLocation.add('foo', 'bar') self.assertEqual(loginAction, expectedLocation)
def test_adminRedirect(self): """ When the admin redirect is installed on a store, it should return an URL which should redirect to /private. """ s = Store(self.mktemp()) s.powerUp(self.adminpage.RedirectPlugin(store=s)) m = Mantissa() m.installSite(s, u'localhost', u'', False) root = IMantissaSite(s) viewer = StubViewer() result, segments = root.siteProduceResource(FakeRequest(), tuple(['admin.php']), viewer) self.assertEquals(result, URL.fromString("http://localhost/private"))
def returnedFromProvider(request, sessionDict, here): argsSingle = dict((k, v[0]) for k,v in request.args.items()) c = openid.consumer.consumer.Consumer(sessionDict, store) resp = c.complete(argsSingle, here) if resp.status != 'success': request.setResponseCode(http.UNAUTHORIZED) return "login failed: %s" % resp.message sessionDict['identity'] = resp.identity_url print "returned" pprint.pprint(vars()) redir = dict(URL.fromString(here).queryList()).get('redir') if redir is not None: request.redirect('http://%s%s' % (request.getHeader('host'), redir)) # waiting... else: # todo: clear query params request.redirect(here) return ""
def fromRequest(cls, store, request): """ Return a L{LoginPage} which will present the user with a login prompt. @type store: L{Store} @param store: A I{site} store. @type request: L{nevow.inevow.IRequest} @param request: The HTTP request which encountered a need for authentication. This will be effectively re-issued after login succeeds. @return: A L{LoginPage} and the remaining segments to be processed. """ location = URL.fromRequest(request) segments = location.pathList(unquote=True, copy=False) segments.append(request.postpath[0]) return cls(store, segments, request.args)
def getResource(site, uri, headers={}, cookies={}): """ Retrieve the resource at the given URI from C{site}. Return a L{Deferred} which is called back with the request after resource traversal and rendering has finished. @type site: L{NevowSite} @param site: The site object from which to retrieve the resource. @type uri: C{str} @param uri: The absolute path to the resource to retrieve, eg I{/private/12345}. @type headers: C{dict} @param headers: HTTP headers to include in the request. """ headers = headers.copy() cookies = cookies.copy() url = URL.fromString(uri) path = '/' + url.path args = {} for (k, v) in url.queryList(): args.setdefault(k, []).append(v) remainingSegments = tuple(url.pathList()) request = FakeRequest( isSecure=url.scheme == 'https', uri=path, args=args, headers=headers, cookies=cookies, currentSegments=()) requestContext = RequestContext(parent=site.context, tag=request) requestContext.remember((), ICurrentSegments) requestContext.remember(remainingSegments, IRemainingSegments) page = site.getPageContextForRequestContext(requestContext) page.addCallback( renderPage, topLevelContext=lambda tag: tag, reqFactory=lambda: request) page.addCallback(lambda ignored: request) return page
def checkid_immediate(registry, requestData, user=None): """ Validate the provided request. @param registry: the current OpenID registry @type registry: L{OpenIDRegistry} @param requestData: the current request data @type requestData: L{OpenIDRequest} @param user: the current user @type user: L{txopenid.user.User} @return: checkid response @rtype: L{nevow.url.URL} """ if(user is not None): def _identity_state(): return user.hasIdentity(requestData['openid.identity']) def _trust_state(): return user.trustsRoot(requestData['openid.trust_root']) if not(yield maybeDeferred(_identity_state)): return_to = util.appendQuery(requestData['openid.return_to'], { 'openid.mode':'id_res', 'openid.user_setup_url':util.appendQuery(OPENID_IDENTITY_URL, requestData), }) elif not(yield maybeDeferred(_trust_state)): return_to = util.appendQuery(requestData['openid.return_to'], { 'openid.mode':'id_res', 'openid.user_setup_url':util.appendQuery(OPENID_TRUST_URL, requestData), }) else: return_to = get_login_response(registry, requestData) else: return_to = util.appendQuery(requestData['openid.return_to'], { 'openid.mode':'id_res', 'openid.user_setup_url':util.appendQuery(OPENID_LOGIN_URL, requestData), }) returnValue(URL.fromString(return_to))
def test_extractStatusIDFromURL(self): """ Status identifiers are extracted from known valid forms of Twitter status URLs, C{None} is extracted for unknown forms. """ expected = [ ('http://twitter.com/bob/status/514431337', '514431337'), ('http://www.twitter.com/bob/status/514431337', '514431337'), ('http://twitter.com/bob/statuses/514431337', '514431337'), ('http://twitter.com/#!/bob/statuses/514431337', '514431337'), ('http://www.twitter.com/#!/bob/statuses/514431337', '514431337'), ('http://www.twitter.com/bob/statuses/hello', None), ('http://www.twitter.com/bob/statuses', None), ('http://somethingnottwitter.com/bob/statuses/514431337', None)] for url, result in expected: assertFn = self.assertEquals if result is None: assertFn = self.assertIdentical assertFn(twitter.extractStatusIDFromURL(URL.fromString(url)), result)
def test_sendEmail(self): """ L{PasswordResetResource.sendEmail} should format a meaningful password reset email. """ resetAddress = '*****@*****.**' resetURI = URL.fromString('http://example.org/resetPassword') userAddress = '*****@*****.**' resetAttempt = self.reset.newAttemptForUser(userAddress.decode('ascii')) _sentEmail = [] self.reset.sendEmail(resetURI, resetAttempt, userAddress, _sendEmail=lambda *args: _sentEmail.append(args)) self.assertEquals(len(_sentEmail), 1) [(sentFrom, sentTo, sentText)] = _sentEmail self.assertEquals(sentFrom, resetAddress) self.assertEquals(sentTo, userAddress) msg = email.message_from_string(sentText) [headerFrom] = msg.get_all('from') [headerTo] = msg.get_all('to') [headerDate] = msg.get_all('date') # Python < 2.5 compatibility try: from email import utils except ImportError: from email import Utils as utils self.assertEquals(utils.parseaddr(headerFrom)[1], resetAddress) self.assertEquals(utils.parseaddr(headerTo)[1], userAddress) self.assertTrue(utils.parsedate_tz(headerDate) is not None, '%r is not a RFC 2822 date' % headerDate) self.assertTrue(not msg.is_multipart()) self.assertIn(flatten(resetURI.child(resetAttempt.key)), msg.get_payload())