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_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 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_missingContentMD5(self): """ Submitting a request with no Content-MD5 header should succeed. """ req = FakeRequest() req.content = StringIO('wrongdata') return self.creator.handlePUT(req)
def test_prePathURLHost(self): """ Verify that L{FakeRequest.prePathURL} will turn the C{Host} header of the request into the netloc of the returned URL, if it's present. """ req = FakeRequest(currentSegments=["a", "b"], uri="/a/b/c/", headers={"host": "foo.bar"}) self.assertEqual(req.prePathURL(), "http://foo.bar/a/b")
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_domainSpecified(self): """ Test that L{usernameFromRequest} returns the username in the request if that username specifies a domain. """ request = FakeRequest(headers={"host": "divmod.com"}) request.args = {"username": ["*****@*****.**"]} username = usernameFromRequest(request) self.assertEqual(username, "*****@*****.**")
def test_headers(self): """ Check that setting a header with L{FakeRequest.setHeader} actually places it in the headers dictionary. """ host = 'divmod.com' req = FakeRequest() req.setHeader('host', host) self.assertEqual(req.responseHeaders.getRawHeaders('host'), [host])
def test_caseInsensitiveHeaders(self): """ L{FakeRequest.getHeader} will return the value of a header regardless of casing. """ host = 'example.com' request = FakeRequest() request.received_headers['host'] = host self.assertEqual(request.getHeader('hOsT'), host)
def test_domainSpecified(self): """ Test that L{usernameFromRequest} returns the username in the request if that username specifies a domain. """ request = FakeRequest(headers={'host': 'divmod.com'}) request.args = {'username': ['*****@*****.**']} username = usernameFromRequest(request) self.assertEqual(username, '*****@*****.**')
def test_prePathURLHost(self): """ Verify that L{FakeRequest.prePathURL} will turn the C{Host} header of the request into the netloc of the returned URL, if it's present. """ req = FakeRequest(currentSegments=['a', 'b'], uri='/a/b/c/', headers={'host': 'foo.bar'}) self.assertEqual(req.prePathURL(), 'http://foo.bar/a/b')
def test_correctContentMD5(self): """ Submitting a request with a Content-MD5 header that agrees with the uploaded data should succeed. """ req = FakeRequest() req.received_headers['content-md5'] = '72VMQKtPF0f8aZkV1PcJAg==' req.content = StringIO('testdata') return self.creator.handlePUT(req)
def test_headers(self): """ Check that setting a header with L{FakeRequest.setHeader} actually places it in the headers dictionary. """ host = 'divmod.com' req = FakeRequest() req.setHeader(b'host', host) self.assertEqual(req.headers['host'], host)
def test_headers(self): """ Check that one can get headers from L{FakeRequest} after they have been set with L{FakeRequest.setHeader}. """ host = 'divmod.com' req = FakeRequest() req.setHeader('host', host) self.assertEqual(req.getHeader('host'), host)
def render2(self, page, **kwargs): # use this to exercise the normal Nevow docFactory rendering. It # returns a string. If one of the render_* methods returns a # Deferred, this will throw an exception. (note that # page.renderString is the Deferred-returning equivalent) req = FakeRequest(**kwargs) req.fields = None ctx = self.make_context(req) return page.renderSynchronously(ctx)
def test_caseInsensitiveHeaders(self): """ L{FakeRequest.getHeader} will return the value of a header regardless of casing. """ host = "example.com" request = FakeRequest() request.requestHeaders.setRawHeaders("host", [host]) self.assertEqual(request.getHeader("hOsT"), host)
def test_caseInsensitiveHeaders(self): """ L{FakeRequest.getHeader} will return the value of a header regardless of casing. """ host = 'example.com' request = FakeRequest() request.requestHeaders.setRawHeaders('host', [host]) self.assertEqual(request.getHeader('hOsT'), host)
def test_headers(self): """ Check that setting a header with L{FakeRequest.setHeader} actually places it in the headers dictionary. """ host = "divmod.com" req = FakeRequest() req.setHeader("host", host) self.assertEqual(req.responseHeaders.getRawHeaders("host"), [host])
def test_headers(self): """ Check that setting a header with L{FakeRequest.setHeader} actually places it in the headers dictionary. """ host = 'divmod.com' req = FakeRequest() req.setHeader('host', host) self.assertEqual(req.headers['host'], host)
def test_incorrectContentMD5(self): """ Submitting a request with a Content-MD5 header that disagrees with the uploaded data should fail. """ req = FakeRequest() req.received_headers['content-md5'] = '72VMQKtPF0f8aZkV1PcJAg==' req.content = StringIO('wrongdata') self.assertRaises(ValueError, self.creator.handlePUT, req)
def test_savorSessionCookie(self): """ L{PersistentSessionWrapper.savorSessionCookie} adds a cookie with a large maximum age and a request-appropriate domain to the request. """ request = FakeRequest(headers={"host": "example.com"}) resource = PersistentSessionWrapper(None, None, domains=["example.org", "example.com"]) resource.savorSessionCookie(request) self.assertEqual(request.cookies, {resource.cookieKey: request.getSession().uid})
def test_domainUnspecified(self): """ Test that L{usernameFromRequest} adds the value of host header to the username in the request if the username doesn't already specify a domain. """ request = FakeRequest(headers={'host': 'divmod.com'}) request.args = {'username': ['joe']} username = usernameFromRequest(request) self.assertEqual(username, '*****@*****.**')
def test_domainUnspecified(self): """ Test that L{usernameFromRequest} adds the value of host header to the username in the request if the username doesn't already specify a domain. """ request = FakeRequest(headers={"host": "divmod.com"}) request.args = {"username": ["joe"]} username = usernameFromRequest(request) self.assertEqual(username, "*****@*****.**")
def test_getRootURL(self): """ L{FakeRequest.getRootURL} returns C{None} when L{FakeRequest.rememberRootURL} has not yet been called. After L{FakeRequest.rememberRootURL} has been called, L{FakeRequest.getRootURL} returns the value which was passed to it. """ request = FakeRequest() self.assertIdentical(request.getRootURL(), None) request.rememberRootURL("foo/bar") self.assertEqual(request.getRootURL(), "foo/bar")
def test_rendering(self): """ L{AddBlogPostDialogFragment} can be rendered as part of a Mantissa public Athena page. """ page = PublicAthenaLivePage(self.store, self.fragment, None, None) request = FakeRequest() request.args = {'title': ['foo'], 'body': ['bar'], 'url': ['baz']} return renderLivePage(page, reqFactory=lambda: request)
def test_savorSessionCookie(self): """ L{PersistentSessionWrapper.savorSessionCookie} adds a cookie with a large maximum age and a request-appropriate domain to the request. """ request = FakeRequest(headers={'host': 'example.com'}) resource = PersistentSessionWrapper( None, None, domains=['example.org', 'example.com']) resource.savorSessionCookie(request) self.assertEqual(request.cookies, {resource.cookieKey: request.getSession().uid})
def test_headerSeparation(self): """ Request headers and response headers are different things. Test that they are handled separately. """ req = FakeRequest() req.setHeader("foo", "bar") self.assertFalse(req.requestHeaders.hasHeader("foo")) self.assertEqual(req.getHeader("foo"), None) req.requestHeaders.setRawHeaders("foo", ["bar"]) self.assertEqual(req.getHeader("foo"), "bar")
def render1(self, page, **kwargs): # use this to exercise an overridden renderHTTP, usually for # output=json or render_GET. It always returns a Deferred. req = FakeRequest(**kwargs) req.fields = None ctx = self.make_context(req) d = defer.maybeDeferred(page.renderHTTP, ctx) def _done(res): if isinstance(res, str): return res + req.v return req.v d.addCallback(_done) return d
def test_unsupportedBrowserPage(self): """ Test that unsupported browsers get told they're unsupported. """ ctx = WovenContext() page = athena.LivePage() req = FakeRequest() req.received_headers[ 'user-agent'] = "Mozilla/4.0 (compatible; MSIE 2.0; Windows NT 5.1)" ctx.remember(req, IRequest) d = renderPage(page, reqFactory=lambda: req) d.addCallback(self.assertEqual, flat.flatten(page.unsupportedBrowserLoader)) return d
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 test_fromContext(self): r = FakeRequest(uri='/a/b/c') urlpath = url.URL.fromContext(context.RequestContext(tag=r)) self.assertEquals('http://localhost/', str(urlpath)) r.prepath = ['a'] urlpath = url.URL.fromContext(context.RequestContext(tag=r)) self.assertEquals('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.assertEquals('http://localhost/a/b?foo=bar', str(urlpath))
def process(typed, data, configurable=None, ctx=None): if ctx is None: from nevow.testutil import FakeRequest from nevow import context fr = FakeRequest() if type(data) is dict: fr.args = data ctx = context.RequestContext(tag=fr) ctx.remember(fr, inevow.IRequest) ctx.remember(None, inevow.IData) try: return iformless.IInputProcessor(typed).process(ctx, configurable, data, autoConfigure=False) except TypeError: return iformless.IInputProcessor(typed).process(ctx, configurable, data)
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_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 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_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_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_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_oneLanguage(self): request = FakeRequest(headers={ 'accept-language': 'fo', }) ctx = context.RequestContext(tag=request) r = inevow.ILanguages(ctx) self.assertEqual(r, ['fo'])
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_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_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_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_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_nothingSpecified(self): """ Submitting an empty form should redirect the user back to the form. """ self.reset.handleRequestForUser = lambda *args: self.fail(args) _request = FakeRequest( headers={'host': 'example.org'}, uri='/resetPassword', currentSegments=['resetPassword'], args={'username': [''], 'email': ['']}) _request.method = 'POST' d = renderPage(self.reset, reqFactory=lambda: _request) def rendered(_): self.assertEquals(_request.redirected_to, 'http://example.org/resetPassword') d.addCallback(rendered) return d
def test_headerSeparation(self): """ Request headers and response headers are different things. Test that they are handled separately. """ req = FakeRequest() req.setHeader('foo', 'bar') self.assertNotIn('foo', req.received_headers) self.assertEqual(req.getHeader('foo'), None) req.received_headers['foo'] = 'bar' self.assertEqual(req.getHeader('foo'), 'bar')
class RequestWrapperTests(TestCase): """ Tests for L{CompressingRequestWrapper}. """ def setUp(self): """ Wrap a request fake to test the wrapper. """ self.request = FakeRequest() self.wrapper = CompressingRequestWrapper(self.request) def test_attributes(self): """ Attributes on the wrapper should be forwarded to the underlying request. """ attributes = ['method', 'uri', 'path', 'args', 'requestHeaders'] for attrName in attributes: self.assertIdentical(getattr(self.wrapper, attrName), getattr(self.request, attrName)) def test_missingAttributes(self): """ Attributes that are not part of the interfaces being proxied should not be proxied. """ self.assertRaises(AttributeError, getattr, self.wrapper, 'doesntexist') self.request._privateTestAttribute = 42 self.assertRaises(AttributeError, getattr, self.wrapper, '_privateTestAttribute') def test_contentLength(self): """ Content-Length header should be discarded when compression is in use. """ self.assertFalse( self.request.responseHeaders.hasHeader('content-length')) self.wrapper.setHeader('content-length', 1234) self.assertFalse( self.request.responseHeaders.hasHeader('content-length')) self.request.setHeader('content-length', 1234) self.wrapper = CompressingRequestWrapper(self.request) self.assertFalse( self.request.responseHeaders.hasHeader('content-length')) def test_responseHeaders(self): """ Content-Encoding header should be set appropriately. """ self.assertEqual( self.request.responseHeaders.getRawHeaders('content-encoding'), ['gzip']) def test_lazySetup(self): """ The gzip prelude should only be written once real data is written. This is necessary to avoid terminating the header too quickly. """ self.assertEqual(self.request.accumulator, '') self.wrapper.write('foo') self.assertNotEqual(self.request.accumulator, '') def _ungzip(self, data): """ Un-gzip some data. """ s = StringIO(data) return GzipFile(fileobj=s, mode='rb').read() def test_encoding(self): """ Response content should be written out in compressed format. """ self.wrapper.write('foo') self.wrapper.write('bar') self.wrapper.finishRequest(True) self.assertEqual(self._ungzip(self.request.accumulator), 'foobar') def test_finish(self): """ Calling C{finishRequest()} on the wrapper should cause the underlying implementation to be called. """ self.wrapper.finishRequest(True) self.assertTrue(self.request.finished)
def __init__(self, *a, **k): FakeRequest.__init__(self, *a, **k) self.args = {'username': [''], 'email': [bogusEmail]}
def setUp(self): """ Wrap a request fake to test the wrapper. """ self.request = FakeRequest() self.wrapper = CompressingRequestWrapper(self.request)