def test_customized_dumps(self): """ A customized dumps applies to both pretty and non-pretty responses. """ renderer = renderers.JSON(default=lambda obj: 23) render = renderers.bind(renderer, to=lambda _: {"foo": object()}) request = Request( url=URL(path=b"/"), headers=Headers([("Accept", ["application/json"])]), ) self.assertEqual( render(request), Response( content=b'{"foo":23}', headers=Headers([("Content-Type", ["application/json"])]), ), ) self.assertEqual( render(Request(url=URL(path=b"/"))), Response( content=b'{\n "foo": 23\n}', headers=Headers([("Content-Type", ["application/json"])]), ), )
def assertNotPretty(self, content, response): self.assertEqual( response, Response( headers=Headers([("Content-Type", ["application/json"])]), content=json.dumps(content, separators=",:"), ), ) self.assertNotEqual( response, Response(headers=Headers([("Content-Type", ["application/json"])]), content=json.dumps(content, indent=2, sort_keys=True)), )
def test_separators(self): render = renderers.bind(renderers.JSON(), to=lambda _: dict(a=1, b=2)) request = Request( url=URL(path=b"/"), headers=Headers([("Accept", ["application/json"])]), ) self.assertEqual( render(request), Response( content=b'{"a":1,"b":2}', headers=Headers([("Content-Type", ["application/json"])]), ), )
def test_separators(self): render = renderers.bind(renderers.JSON(), to=lambda _: dict(a=1, b=2)) request = Request( url=URL(path=[u""]), headers=Headers([("Accept", ["application/json"])]), ) response = render(request) self.assertEqual( response, Response( content=response.content, headers=Headers([("Content-Type", ["application/json"])]), ), ) self.assertNotIn(response.content, " ") self.assertEqual(json.loads(response.content), {"a": 1, "b": 2})
def fooBar(request): self.assertEqual(request.headers.get(b"X-Foo"), [b"Hello"]) return Response( code=302, content=request.url.path, headers=Headers([(b"Location", [b"http://example.com"])]), )
def render(self, twistedRequest): path = twistedRequest.uri.lstrip("/").decode("ascii").split(u"/") request = Request( content=twistedRequest.content, headers=Headers(twistedRequest.requestHeaders.getAllRawHeaders()), method=twistedRequest.method, url=URL( scheme=u"https" if twistedRequest.isSecure() else u"http", host=twistedRequest.getRequestHostname().decode("ascii"), path=path, query=[(k.decode("ascii"), each.decode("ascii")) for k, v in twistedRequest.args.items() for each in v], ), ) response = self.application.serve( request=request, path=b"/" + b"/".join(twistedRequest.postpath), ) twistedRequest.setResponseCode(response.code) for k, v in response.headers.canonicalized(): twistedRequest.responseHeaders.setRawHeaders(k, v) return response.content
def test_dict_sort_keys(self): content = OrderedDict([("foo", "bar"), ("baz", "quux")]) render = renderers.bind(renderers.JSON(), to=lambda _: content) request = Request( url=URL(path=b"/"), headers=Headers([("Accept", ["*/*"])]), ) self.assertPretty(content, render(request))
def test_it_dumps_practical_json_for_machines(self): content = ["a", "b", "c"] render = renderers.bind(renderers.JSON(), to=lambda _: content) request = Request( url=URL(path=b"/"), headers=Headers([("Accept", ["application/json"])]), ) self.assertNotPretty(content, render(request))
def test_it_dumps_pretty_json_for_humans(self): content = ["a", "b", "c"] render = renderers.bind(renderers.JSON(), to=lambda _: content) request = Request( url=URL(path=b"/"), headers=Headers([("Accept", ["*/*"])]), ) self.assertPretty(content, render(request))
def render(self, request, jsonable): machine_json = request.accept.media_types[-1] == MediaRange( type="application", subtype="json", ) if machine_json: content = self._dumps(jsonable, separators=",:") else: content = self._dumps(jsonable, indent=2, sort_keys=True) return Response( content=content, headers=Headers([("Content-Type", ["application/json"])]), )
def test_it_parses_the_url(self): request = self.get_request( b"/respond?foo=bar#baz", headers=Headers([(b"Host", [b"example.com"])]), ) self.assertEqual( request.url, URL( scheme=b"http", host=b"example.com", path=b"/respond", query={b"foo" : [b"bar"]}, fragment=b"", # Fragments should be ignored by servers. ), )
def render(self, twistedRequest): request = Request( content=twistedRequest.content, headers=Headers(twistedRequest.requestHeaders.getAllRawHeaders()), method=twistedRequest.method, url=URL( scheme=b"https" if twistedRequest.isSecure() else b"http", host=twistedRequest.getRequestHostname(), path=twistedRequest.uri, query=twistedRequest.args, ), ) response = self.application.serve( request=request, path=b"/" + b"/".join(twistedRequest.postpath), ) twistedRequest.setResponseCode(response.code) for k, v in response.headers.canonicalized(): twistedRequest.responseHeaders.setRawHeaders(k, v) return response.content
def test_accept_is_calculated_once(self): accept = "application/json" request = self.make_request(headers=Headers([("accept", [accept])])) self.assertIs(request.accept, request.accept)
def test_accept_no_header(self): request = self.make_request(headers=Headers()) self.assertEqual(request.accept, Accept.ALL)
def test_accept(self): accept = "application/json" request = self.make_request(headers=Headers([("accept", [accept])])) self.assertEqual(request.accept, Accept.from_header(accept))
def get_request(self, *args, **kwargs): kwargs.setdefault("headers", Headers()) response = json.loads(self.get(*args, **kwargs)) response["url"] = URL.from_text(response["url"].decode("utf-8")) return Request(**response)
def headers(self): return Headers((name[5:].replace("_", "-"), [value]) for name, value in iteritems(self.environ) if name.startswith("HTTP_"))
def respond(request): return Response( b"{}", headers=Headers([(b"Content-Type", [b"application/json"])]), )
def get_request(self, *args, **kwargs): kwargs.setdefault("headers", Headers()) response = json.loads(self.get(*args, **kwargs)) response["url"] = URL(**response["url"]) return Request(**response)