From ed049da34f663de4c1b4d9cc0654f958923eaf13 Mon Sep 17 00:00:00 2001 From: Jean-Paul Calderone Date: Wed, 23 Sep 2020 16:24:40 -0400 Subject: [PATCH] Add a helper that can render a Page or a Resource --- src/allmydata/test/common_web.py | 60 ++++++++++++++++++++++++++++++-- 1 file changed, 57 insertions(+), 3 deletions(-) diff --git a/src/allmydata/test/common_web.py b/src/allmydata/test/common_web.py index 1c9312689..d11e39383 100644 --- a/src/allmydata/test/common_web.py +++ b/src/allmydata/test/common_web.py @@ -1,9 +1,33 @@ import treq -from twisted.internet import defer +from twisted.internet.defer import ( + maybeDeferred, + inlineCallbacks, + returnValue, + succeed, +) from twisted.web.error import Error +from twisted.web.resource import ( + IResource as ITwistedResource, +) +from twisted.web.test.requesthelper import ( + DummyRequest, +) -@defer.inlineCallbacks +from nevow.context import WebContext +from nevow.testutil import FakeRequest +from nevow.appserver import ( + processingFailed, + DefaultExceptionHandler, +) +from nevow.inevow import ( + ICanHandleException, + IRequest, + IResource as INevowResource, + IData, +) + +@inlineCallbacks def do_http(method, url, **kwargs): response = yield treq.request(method, url, persistent=False, **kwargs) body = yield treq.content(response) @@ -11,4 +35,34 @@ def do_http(method, url, **kwargs): # https://github.com/twisted/treq/pull/159 has landed if 400 <= response.code < 600: raise Error(response.code, response=body) - defer.returnValue(body) + returnValue(body) + + +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.addCallback(maybe_concat) + return d