def testDeferredResource(self): r = resource.Resource() r.isLeaf = 1 s = SDResource(r) d = DummyRequest(['foo', 'bar', 'baz']) resource.getChildForRequest(s, d) self.assertEqual(d.postpath, ['bar', 'baz'])
def test_putNamedChild_django_static_override(self): "check that overridden resources work" with mock.patch('hendrix.facilities.resources.WSGIResource') as wsgi: static_dir = os.path.join(os.path.dirname(__file__),'testproject','static') # Django finders import in order of INSTALLED_APPS so overrides must happen first overridden_media = DjangoStaticResource(static_dir+'/override/css','/static/base/css') # Same rel_url -> overrides self.hr.putNamedChild(overridden_media) base_media = DjangoStaticResource(static_dir+'/base/css','/static/base/css') self.hr.putNamedChild(base_media) # main.css file should be the same as it is not overridden request = DummyRequest(['static', 'base', 'css','main.css']) actual_res = getChildForRequest(self.hr, request) with actual_res.open() as f: actual_content = f.read() with open(static_dir+'/base/css/main.css') as f: expected_content = f.read() self.assertEqual(expected_content,actual_content) # form.css should be the same as the overridden folder request = DummyRequest(['static', 'base', 'css','form.css']) actual_res = getChildForRequest(self.hr, request) with actual_res.open() as f: actual_content = f.read() with open(static_dir+'/override/css/form.css') as f: expected_content = f.read() self.assertEqual(expected_content,actual_content)
def testDeferredResource(self): r = resource.Resource() r.isLeaf = 1 s = SDResource(r) d = DummyRequest(["foo", "bar", "baz"]) resource.getChildForRequest(s, d) self.assertEqual(d.postpath, ["bar", "baz"])
def test_putNamedChild_duplicate(self): "check that duplicate resources work" with mock.patch('hendrix.facilities.resources.WSGIResource') as wsgi: request = DummyRequest(['path', 'to', 'child']) actual_res = getChildForRequest(self.hr, request) self.assertEqual(self.res, actual_res) # Before duplicate duplicate = NamedResource(self.res.namespace) self.hr.putNamedChild(duplicate) request = DummyRequest(['path', 'to', 'child']) actual_duplicate_res = getChildForRequest(self.hr, request) self.assertEqual(duplicate, actual_duplicate_res) # After duplicate
def test_putNamedChild_duplicate(self): "check that duplicate resources work" with mock.patch('hendrix.facilities.resources.WSGIResource') as wsgi: request = DummyRequest(['path', 'to', 'child']) actual_res = getChildForRequest(self.hr, request) self.assertEqual(actual_res, self.res) # Before duplicate duplicate = NamedResource(self.res.namespace) self.hr.putNamedChild(duplicate) request = DummyRequest(['path', 'to', 'child']) actual_duplicate_res = getChildForRequest(self.hr, request) self.assertEqual(duplicate, actual_duplicate_res) # After duplicate
def test_get_blobs_enabled(self): blobs_resource = BlobsResource("filesystem", '/tmp') streaming_resource = StreamingResource("filesystem", '/tmp') resource = PublicResource( blobs_resource=blobs_resource, streaming_resource=streaming_resource, sync_pool=_pool) request = DummyRequest(['blobs']) child = getChildForRequest(resource, request) self.assertIsInstance(child, BlobsResource) request = DummyRequest(['stream']) child = getChildForRequest(resource, request) self.assertIsInstance(child, StreamingResource)
def test_get_root(self): blobs_resource = None # doesn't matter resource = PublicResource( blobs_resource=blobs_resource, sync_pool=_pool) request = DummyRequest(['']) child = getChildForRequest(resource, request) self.assertIsInstance(child, ServerInfo)
def test_getChallengeCalledWithRequest(self): """ When L{HTTPAuthSessionWrapper} finds an L{ICredentialFactory} to issue a challenge, it calls the C{getChallenge} method with the request as an argument. """ class DumbCredentialFactory(object): implements(ICredentialFactory) scheme = 'dumb' def __init__(self): self.requests = [] def getChallenge(self, request): self.requests.append(request) return {} factory = DumbCredentialFactory() self.credentialFactories.append(factory) request = self.makeRequest([self.childName]) child = getChildForRequest(self.wrapper, request) d = request.notifyFinish() def cbFinished(ignored): self.assertEqual(factory.requests, [request]) d.addCallback(cbFinished) request.render(child) return d
def test_get_sync(self): enable_blobs = None # doesn't matter resource = SoledadResource(enable_blobs=enable_blobs, sync_pool=_pool) request = DummyRequest(['user-db', 'sync-from', 'source-id']) child = getChildForRequest(resource, request) self.assertIsInstance(child, WSGIResource) self.assertIsInstance(child._application, GzipMiddleware)
def test_unexpectedDecodeError(self): """ Any unexpected exception raised by the credential factory's C{decode} method results in a 500 response code and causes the exception to be logged. """ class UnexpectedException(Exception): pass class BadFactory(object): scheme = 'bad' def getChallenge(self, client): return {} def decode(self, response, request): raise UnexpectedException() self.credentialFactories.append(BadFactory()) request = self.makeRequest([self.childName]) request.headers['authorization'] = 'Bad abc' child = getChildForRequest(self.wrapper, request) request.render(child) self.assertEqual(request.responseCode, 500) self.assertEqual(len(self.flushLoggedErrors(UnexpectedException)), 1)
def test_get_root(self): blobs_resource = None # doesn't matter resource = PublicResource(blobs_resource=blobs_resource, sync_pool=_pool) request = DummyRequest(['']) child = getChildForRequest(resource, request) self.assertIsInstance(child, ServerInfo)
def test_locateChildSpinneretResource(self): """ If ``locateChild`` returns something adaptable to `ISpinneretResource` it is adapted to an `IResource`. """ @implementer(ISpinneretResource) class _ResultingResource(object): def render_GET(zelf, request): request.setResponseCode(http.OK) return b'hello world' @implementer(ISpinneretResource) class _TestResource(object): def locateChild(zelf, request, segments): return _ResultingResource(), [] resource = SpinneretResource(_TestResource()) request = InMemoryRequest(['']) request.method = b'GET' result = getChildForRequest(resource, request) request.render(result) self.assertThat( b''.join(request.written), Equals(b'hello world')) self.assertThat( http.OK, Equals(request.responseCode)) self.assertThat( request.postpath, Equals([]))
def test_getChallengeCalledWithRequest(self): """ When L{HTTPAuthSessionWrapper} finds an L{ICredentialFactory} to issue a challenge, it calls the C{getChallenge} method with the request as an argument. """ @implementer(ICredentialFactory) class DumbCredentialFactory: scheme = b'dumb' def __init__(self): self.requests = [] def getChallenge(self, request): self.requests.append(request) return {} factory = DumbCredentialFactory() self.credentialFactories.append(factory) request = self.makeRequest([self.childName]) child = getChildForRequest(self.wrapper, request) d = request.notifyFinish() def cbFinished(ignored): self.assertEqual(factory.requests, [request]) d.addCallback(cbFinished) request.render(child) return d
def test_locateChildRenderable(self): """ If ``locateChild`` returns something adaptable to `IRenderable` it is rendered. """ class _TestElement(Element): loader = TagLoader(tags.span(u'Hello ', tags.em(u'World'))) @implementer(ISpinneretResource) class _TestResource(object): def locateChild(zelf, request, segments): return _TestElement(), [] resource = SpinneretResource(_TestResource()) request = InMemoryRequest(['']) result = getChildForRequest(resource, request) request.render(result) self.assertThat( b''.join(request.written), Equals(b'<!DOCTYPE html>\n<span>Hello <em>World</em></span>')) self.assertThat( http.OK, Equals(request.responseCode)) self.assertThat( request.postpath, Equals([]))
def test_unexpectedDecodeError(self): """ Any unexpected exception raised by the credential factory's C{decode} method results in a 500 response code and causes the exception to be logged. """ logObserver = EventLoggingObserver.createWithCleanup( self, globalLogPublisher) class UnexpectedException(Exception): pass class BadFactory: scheme = b'bad' def getChallenge(self, client): return {} def decode(self, response, request): raise UnexpectedException() self.credentialFactories.append(BadFactory()) request = self.makeRequest([self.childName]) request.requestHeaders.addRawHeader(b'authorization', b'Bad abc') child = getChildForRequest(self.wrapper, request) request.render(child) self.assertEqual(request.responseCode, 500) self.assertEquals(1, len(logObserver)) self.assertIsInstance(logObserver[0]["log_failure"].value, UnexpectedException) self.assertEqual(len(self.flushLoggedErrors(UnexpectedException)), 1)
def test_processors(self): """ If a request is made which encounters a L{File} before a final segment which names a file with an extension which is in the L{File}'s C{processors} mapping, the processor associated with that extension is used to serve the response to the request. """ base = FilePath(self.mktemp()) base.makedirs() base.child("foo.bar").setContent( "from twisted.web.static import Data\n" "resource = Data('dynamic world','text/plain')\n") file = static.File(base.path) file.processors = {'.bar': script.ResourceScript} request = DummyRequest(["foo.bar"]) child = resource.getChildForRequest(file, request) d = self._render(child, request) def cbRendered(ignored): self.assertEqual(''.join(request.written), 'dynamic world') self.assertEqual(request.outgoingHeaders['content-length'], '13') d.addCallback(cbRendered) return d
def test_locateChildResource(self): """ If ``locateChild`` returns something adaptable to `IResource` it is returned. """ class _ResultingResource(Resource): isLeaf = True def render(zelf, request): request.setResponseCode(http.OK) return b'hello world' class _TestResource(SpinneretResource): def locateChild(zelf, request, segments): return _ResultingResource(), segments resource = _TestResource() request = InMemoryRequest(['']) result = getChildForRequest(resource, request) request.render(result) self.assertThat( b''.join(request.written), Equals(b'hello world')) self.assertThat( http.OK, Equals(request.responseCode))
def test_get_blobs_enabled(self): blobs_resource = BlobsResource('/tmp') resource = SoledadResource( blobs_resource=blobs_resource, sync_pool=_pool) request = DummyRequest(['blobs']) child = getChildForRequest(resource, request) self.assertIsInstance(child, BlobsResource)
def test_info(self): '''The Info resource must be accessible as the "info" child of the TxDarn resource. ''' self.request.postpath = [b'info'] resrc = getChildForRequest(self.txdarn, self.request) self.assertIs(resrc, self.txdarn.info)
def render_GET(self, request): try: index = request.args["code"][0] self.main.removeMessage(index) request.render(getChildForRequest(Index(self.main), request)) return NOT_DONE_YET except: return "Error"
def test_get_sync(self): blobs_resource = None # doesn't matter resource = PublicResource( blobs_resource=blobs_resource, sync_pool=_pool) request = DummyRequest(['user-db', 'sync-from', 'source-id']) child = getChildForRequest(resource, request) self.assertIsInstance(child, WSGIResource) self.assertIsInstance(child._application, GzipMiddleware)
def test_get_blobs_disabled(self): enable_blobs = False resource = SoledadResource(enable_blobs=enable_blobs, sync_pool=_pool) request = DummyRequest(['blobs']) child = getChildForRequest(resource, request) # if blobs is disabled, the request should be routed to sync self.assertIsInstance(child, WSGIResource) self.assertIsInstance(child._application, GzipMiddleware)
def process(r): if IResource.providedBy(r): return request.render(getChildForRequest(r, request)) if IRenderable.providedBy(r): return flattenString(request, r).addCallback(process) return r
def test_locateChildSetPostpath(self): """ The second elements in ``locateChild`` return value is the new request postpath. """ class _TestResource(SpinneretResource): def locateChild(zelf, request, segments): return None, [b'quux'] resource = _TestResource() request = InMemoryRequest([b'foo', b'bar']) self.assertThat( request.postpath, Equals([b'foo', b'bar'])) getChildForRequest(resource, request) self.assertThat( request.postpath, Equals([b'quux']))
def test_exhaustedPostPath(self): """ L{getChildForRequest} returns whatever resource has been reached by the time the request's C{postpath} is empty. """ request = DummyRequest([]) resource = Resource() result = getChildForRequest(resource, request) self.assertIdentical(resource, result)
def getChild(self, child, request ): if not self.static: return self.prepareWSGI(child, request) else: resource = getChildForRequest(self.static, request) if not hasattr(resource, "isdir") or resource.isdir() or not resource.exists(): return self.prepareWSGI(child, request) else: return resource
def _authorizedBasicLogin(self, request): """ Add an I{basic authorization} header to the given request and then dispatch it, starting from C{self.wrapper} and returning the resulting L{IResource}. """ authorization = b64encode(self.username + ':' + self.password) request.headers['authorization'] = 'Basic ' + authorization return getChildForRequest(self.wrapper, request)
def getChild(self, path, request): if path == 'account-app': self.putChild('checkmsg', AccountApp('checkmsg')) self.putChild('new', AccountApp('new')) self.putChild('find', AccountApp('find')) self.putChild('delete', AccountApp('delete')) return resource.getChildForRequest(self, request) elif path == 'account-profile': self.putChild('new', AccountProfile('new')) self.putChild('find', AccountProfile('find')) return resource.getChildForRequest(self, request) elif path == 'account-dev': self.putChild('register', AccountDev('register')) self.putChild('subscribe', AccountDev('subscribe')) self.putChild('device_ids', AccountDev('device_ids')) return resource.getChildForRequest(self, request) else: return ErrorPage(ErrNo.NO_RESOURCE)
def test_get_blobs_disabled(self): blobs_resource = None resource = PublicResource( blobs_resource=blobs_resource, sync_pool=_pool) request = DummyRequest(['blobs']) child = getChildForRequest(resource, request) # if blobs is disabled, the request should be routed to sync self.assertIsInstance(child, WSGIResource) self.assertIsInstance(child._application, GzipMiddleware)
def process(r): if IResource.providedBy(r): request.render(getChildForRequest(r, request)) return _StandInResource if IRenderable.providedBy(r): return flattenString(request, r).addCallback(process) return r
def test_greeting_trailing_slash(self): '''The Greeting resource must be accessible as the direct child of the TxDarn resource (i.e., with a trailing slash). ''' # a trailing slash -- empty string in postpath self.request.postpath = [b''] resrc = getChildForRequest(self.txdarn, self.request) self.assertIs(resrc, self.txdarn.greeting)
def _authorizedBasicLogin(self, request): """ Add an I{basic authorization} header to the given request and then dispatch it, starting from C{self.wrapper} and returning the resulting L{IResource}. """ authorization = b64encode(self.username + b":" + self.password) request.requestHeaders.addRawHeader(b"authorization", b"Basic " + authorization) return getChildForRequest(self.wrapper, request)
def test_getStaticChild(self): """ When attempting to get a statically registered child resource, that child is returned. """ request = _FakeRequest(["a", "b"], ["c", "d"]) child = resource.getChildForRequest(self.resource, request) self.assertIdentical(child, self.child) self.assertEqual(request.prepath, ["a", "b", "c"]) self.assertEqual(request.postpath, ["d"])
def test_leafResource(self): """ L{getChildForRequest} returns the first resource it encounters with a C{isLeaf} attribute set to C{True}. """ request = DummyRequest([b"foo", b"bar"]) resource = Resource() resource.isLeaf = True result = getChildForRequest(resource, request) self.assertIdentical(resource, result)
def test00_render(self): tree = CardstoriesTree(self.service) request = DummyRequest(['agpl']) child = resource.getChildForRequest(tree, request) self.assertTrue(isinstance(child, AGPLResource)) d = _render(child, request) def finish(result): self.assertEquals('PK', request.written[0][:2]) d.addCallback(finish) return d
def getResourceFor(self, request): if request.uri.startswith('/json') or request.uri.startswith('/dump'): request.site = self request.sitepath = copy.copy(request.prepath) result = resource.getChildForRequest(self.resource, request) else: pathParts = request.uri.split('/') version = pathParts[1] if pathParts[2].startswith('index.'): contentType = 'text/html' absoluteFilePath = os.path.join(projectTargetDir(), 'dev', version, pathParts[2]) result = static.File(absoluteFilePath, contentType) else: # http://homer.local:8888/beta/css/clipperz/images/loginInfoBackground.png # pathParts: ['', 'beta', 'css', 'clipperz', 'images', 'loginInfoBackground.png'] try: imagePathIndex = pathParts.index('images') resourceType = 'images' for _ in range(2, imagePathIndex): del pathParts[2] except: resourceType = pathParts[2] basePath = projectBaseDir() + '/frontend' if resourceType == 'images': fileExtension = os.path.splitext(request.uri)[1] if fileExtension == '.png': contentType = 'image/png' elif fileExtension == '.jpg': contentType = 'image/jpeg' elif fileExtension == '.gif': contentType = 'image/gif' else: print "ERROR - unknown image extension: " + fileExtension absoluteFilePath = basePath + '/'.join(pathParts) else: resourceType = pathParts[2] if resourceType == 'css': contentType = 'text/css' elif resourceType == 'js': contentType = 'text/javascript' else: contentType = 'text/html' absoluteFilePath = basePath + request.uri result = static.File(absoluteFilePath, contentType) return result
def getResourceForPath(site, path): """ @param site: a L{server.Site}. @param path: a C{str} URL-encoded path that starts with C{"/"}. @return: a resource from C{site}'s resource tree that corresponds to C{path}. """ rootResource = site.resource dummyRequest = makeRequestForPath(site, path) return getChildForRequest(rootResource, dummyRequest)
def test_getChildWithDefault(self): request = self.makeRequest([self.childName]) child = getChildForRequest(self.wrapper, request) d = request.notifyFinish() def cbFinished(result): self.assertEqual(request.responseCode, 401) d.addCallback(cbFinished) request.render(child) return d
def test_decodeRaises(self): """ Resource traversal which enouncters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} when the request has a I{Basic Authorization} header which cannot be decoded using base64. """ self.credentialFactories.append(BasicCredentialFactory('example.com')) request = self.makeRequest([self.childName]) request.headers['authorization'] = 'Basic decode should fail' child = getChildForRequest(self.wrapper, request) self.assertIsInstance(child, UnauthorizedResource)
def hackGetResourceFor(self, request): """ Hack the getResourceFor function to log the site visit info. """ request.site = self if (not request.uri.startswith('/static')) and ( not request.uri.endswith('/')): _LOGGER.info('Request for uri: {0} from {1}'.format( request.uri, request.client.host)) request.sitepath = copy.copy(request.prepath) return resource.getChildForRequest(self.resource, request)
def test_reachable(self, get_config, request): """ A resource is reachable at a child of the resource returned by ``from_configuration``. """ tempdir = self.useFixture(TempDir()) config = get_config(tempdir.join(b"tahoe"), b"tub.port") root = root_from_config(config, datetime.now) self.assertThat( getChildForRequest(root, request), Provides([IResource]), )
def _invalidAuthorizationTest(self, response): request = self.makeRequest([self.childName]) request.requestHeaders.addRawHeader(b'authorization', response) child = getChildForRequest(self.wrapper, request) d = request.notifyFinish() def cbFinished(result): self.assertEqual(request.responseCode, 401) d.addCallback(cbFinished) request.render(child) return d
def test_postPathToPrePath(self): """ As path segments from the request are traversed, they are taken from C{postpath} and put into C{prepath}. """ request = DummyRequest([b"foo", b"bar"]) root = Resource() child = Resource() child.isLeaf = True root.putChild(b"foo", child) self.assertIdentical(child, getChildForRequest(root, request)) self.assertEqual(request.prepath, [b"foo"]) self.assertEqual(request.postpath, [b"bar"])
def getResourceFor(self, request): """ Get a resource for a request. This iterates through the resource heirarchy, calling getChildWithDefault on each resource it finds for a path element, stopping when it hits an element where isLeaf is true. """ request.site = self # Sitepath is used to determine cookie names between distributed # servers and disconnected sites. request.sitepath = copy.copy(request.prepath) return resource.getChildForRequest(self.resource, request)
def test_emptyChild(self): """ The C{''} child of a L{File} which corresponds to a directory in the filesystem is a L{DirectoryLister}. """ base = FilePath(self.mktemp()) base.makedirs() file = static.File(base.path) request = DummyRequest(['']) child = resource.getChildForRequest(file, request) self.assertIsInstance(child, static.DirectoryLister) self.assertEqual(child.path, base.path)
def test_getChildWithDefault(self): """ Resource traversal which encounters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} instance when the request does not have the required I{Authorization} headers. """ request = self.makeRequest([self.childName]) child = getChildForRequest(self.wrapper, request) d = request.notifyFinish() def cbFinished(result): self.assertEquals(request.responseCode, 401) d.addCallback(cbFinished) render(child, request) return d
def render(root, request): resource = getChildForRequest(root, request) result = resource.render(request) if isinstance(result, str): request.write(result) request.finish() return succeed(None) elif result is server.NOT_DONE_YET: if request.finished: return succeed(None) else: return request.notifyFinish() else: raise ValueError("Unexpected return value: %r" % (result, ))