Python tornado.escape.json_decode() Examples

The following are 30 code examples of tornado.escape.json_decode(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tornado.escape , or try the search function .
Example #1
Source File: web_test.py    From tornado-zh with MIT License 6 votes vote down vote up
def test_decode_argument(self):
        # These urls all decode to the same thing
        urls = ["/decode_arg/%C3%A9?foo=%C3%A9&encoding=utf-8",
                "/decode_arg/%E9?foo=%E9&encoding=latin1",
                "/decode_arg_kw/%E9?foo=%E9&encoding=latin1",
                ]
        for req_url in urls:
            response = self.fetch(req_url)
            response.rethrow()
            data = json_decode(response.body)
            self.assertEqual(data, {u('path'): [u('unicode'), u('\u00e9')],
                                    u('query'): [u('unicode'), u('\u00e9')],
                                    })

        response = self.fetch("/decode_arg/%C3%A9?foo=%C3%A9")
        response.rethrow()
        data = json_decode(response.body)
        self.assertEqual(data, {u('path'): [u('bytes'), u('c3a9')],
                                u('query'): [u('bytes'), u('c3a9')],
                                }) 
Example #2
Source File: web_test.py    From tornado-zh with MIT License 6 votes vote down vote up
def test_get_argument(self):
        response = self.fetch("/get_argument?foo=bar")
        self.assertEqual(response.body, b"bar")
        response = self.fetch("/get_argument?foo=")
        self.assertEqual(response.body, b"")
        response = self.fetch("/get_argument")
        self.assertEqual(response.body, b"default")

        # Test merging of query and body arguments.
        # In singular form, body arguments take precedence over query arguments.
        body = urllib_parse.urlencode(dict(foo="hello"))
        response = self.fetch("/get_argument?foo=bar", method="POST", body=body)
        self.assertEqual(response.body, b"hello")
        # In plural methods they are merged.
        response = self.fetch("/get_arguments?foo=bar",
                              method="POST", body=body)
        self.assertEqual(json_decode(response.body),
                         dict(default=['bar', 'hello'],
                              query=['bar'],
                              body=['hello'])) 
Example #3
Source File: httpserver_test.py    From tornado-zh with MIT License 6 votes vote down vote up
def test_chunked_request_body(self):
        # Chunked requests are not widely supported and we don't have a way
        # to generate them in AsyncHTTPClient, but HTTPServer will read them.
        self.stream.write(b"""\
POST /echo HTTP/1.1
Transfer-Encoding: chunked
Content-Type: application/x-www-form-urlencoded

4
foo=
3
bar
0

""".replace(b"\n", b"\r\n"))
        read_stream_body(self.stream, self.stop)
        headers, response = self.wait()
        self.assertEqual(json_decode(response), {u('foo'): [u('bar')]}) 
Example #4
Source File: httpserver_test.py    From tornado-zh with MIT License 6 votes vote down vote up
def test_multipart_form(self):
        # Encodings here are tricky:  Headers are latin1, bodies can be
        # anything (we use utf8 by default).
        response = self.raw_fetch([
            b"POST /multipart HTTP/1.0",
            b"Content-Type: multipart/form-data; boundary=1234567890",
            b"X-Header-encoding-test: \xe9",
        ],
            b"\r\n".join([
                b"Content-Disposition: form-data; name=argument",
                b"",
                u("\u00e1").encode("utf-8"),
                b"--1234567890",
                u('Content-Disposition: form-data; name="files"; filename="\u00f3"').encode("utf8"),
                b"",
                u("\u00fa").encode("utf-8"),
                b"--1234567890--",
                b"",
            ]))
        data = json_decode(response)
        self.assertEqual(u("\u00e9"), data["header"])
        self.assertEqual(u("\u00e1"), data["argument"])
        self.assertEqual(u("\u00f3"), data["filename"])
        self.assertEqual(u("\u00fa"), data["filebody"]) 
Example #5
Source File: web_test.py    From tornado-zh with MIT License 6 votes vote down vote up
def test_get_argument(self):
        response = self.fetch("/get_argument?foo=bar")
        self.assertEqual(response.body, b"bar")
        response = self.fetch("/get_argument?foo=")
        self.assertEqual(response.body, b"")
        response = self.fetch("/get_argument")
        self.assertEqual(response.body, b"default")

        # Test merging of query and body arguments.
        # In singular form, body arguments take precedence over query arguments.
        body = urllib_parse.urlencode(dict(foo="hello"))
        response = self.fetch("/get_argument?foo=bar", method="POST", body=body)
        self.assertEqual(response.body, b"hello")
        # In plural methods they are merged.
        response = self.fetch("/get_arguments?foo=bar",
                              method="POST", body=body)
        self.assertEqual(json_decode(response.body),
                         dict(default=['bar', 'hello'],
                              query=['bar'],
                              body=['hello'])) 
Example #6
Source File: auth_test.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
def test_twitter_get_user(self):
        response = self.fetch(
            "/twitter/client/login?oauth_token=zxcv",
            headers={"Cookie": "_oauth_request_token=enhjdg==|MTIzNA=="},
        )
        response.rethrow()
        parsed = json_decode(response.body)
        self.assertEqual(
            parsed,
            {
                u"access_token": {
                    u"key": u"hjkl",
                    u"screen_name": u"foo",
                    u"secret": u"vbnm",
                },
                u"name": u"Foo",
                u"screen_name": u"foo",
                u"username": u"foo",
            },
        ) 
Example #7
Source File: auth_test.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def test_facebook_login(self):
        response = self.fetch("/facebook/client/login", follow_redirects=False)
        self.assertEqual(response.code, 302)
        self.assertTrue("/facebook/server/authorize?" in response.headers["Location"])
        response = self.fetch(
            "/facebook/client/login?code=1234", follow_redirects=False
        )
        self.assertEqual(response.code, 200)
        user = json_decode(response.body)
        self.assertEqual(user["access_token"], "asdf")
        self.assertEqual(user["session_expires"], "3600") 
Example #8
Source File: auth_test.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def test_twitter_show_user(self):
        response = self.fetch("/twitter/client/show_user?name=somebody")
        response.rethrow()
        self.assertEqual(
            json_decode(response.body), {"name": "Somebody", "screen_name": "somebody"}
        ) 
Example #9
Source File: auth_test.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def test_oauth10a_get_user(self):
        response = self.fetch(
            "/oauth10a/client/login?oauth_token=zxcv",
            headers={"Cookie": "_oauth_request_token=enhjdg==|MTIzNA=="},
        )
        response.rethrow()
        parsed = json_decode(response.body)
        self.assertEqual(parsed["email"], "foo@example.com")
        self.assertEqual(parsed["access_token"], dict(key="uiop", secret="5678")) 
Example #10
Source File: web_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_flow_control_chunked_body(self):
        chunks = [b'abcd', b'efgh', b'ijkl']
        @gen.coroutine
        def body_producer(write):
            for i in chunks:
                yield write(i)
        response = self.fetch('/', body_producer=body_producer, method='POST')
        response.rethrow()
        self.assertEqual(json_decode(response.body),
                         dict(methods=['prepare', 'data_received',
                                       'data_received', 'data_received',
                                       'post'])) 
Example #11
Source File: flash_message.py    From torngas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def messages(self):
        messages = self.get_secure_cookie(self._flash_name)
        messages = json_decode(messages) if messages else []
        return messages 
Example #12
Source File: auth_test.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def test_google_login(self):
        response = self.fetch("/client/login")
        self.assertDictEqual(
            {
                u"name": u"Foo",
                u"email": u"foo@example.com",
                u"access_token": u"fake-access-token",
            },
            json_decode(response.body),
        ) 
Example #13
Source File: auth.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def _on_twitter_request(self, future, response):
        if response.error:
            future.set_exception(AuthError(
                "Error response %s fetching %s" % (response.error,
                                                   response.request.url)))
            return
        future.set_result(escape.json_decode(response.body)) 
Example #14
Source File: httpserver_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def fetch_json(self, *args, **kwargs):
        response = self.fetch(*args, **kwargs)
        response.rethrow()
        return json_decode(response.body) 
Example #15
Source File: escape_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_json_encode(self):
        # json deals with strings, not bytes.  On python 2 byte strings will
        # convert automatically if they are utf8; on python 3 byte strings
        # are not allowed.
        self.assertEqual(json_decode(json_encode(u("\u00e9"))), u("\u00e9"))
        if bytes is str:
            self.assertEqual(json_decode(json_encode(utf8(u("\u00e9")))), u("\u00e9"))
            self.assertRaises(UnicodeDecodeError, json_encode, b"\xe9") 
Example #16
Source File: web_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_flow_control_compressed_body(self):
        bytesio = BytesIO()
        gzip_file = gzip.GzipFile(mode='w', fileobj=bytesio)
        gzip_file.write(b'abcdefghijklmnopqrstuvwxyz')
        gzip_file.close()
        compressed_body = bytesio.getvalue()
        response = self.fetch('/', body=compressed_body, method='POST',
                              headers={'Content-Encoding': 'gzip'})
        response.rethrow()
        self.assertEqual(json_decode(response.body),
                         dict(methods=['prepare', 'data_received',
                                       'data_received', 'data_received',
                                       'post'])) 
Example #17
Source File: auth.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def _on_friendfeed_request(self, future, response):
        if response.error:
            future.set_exception(AuthError(
                "Error response %s fetching %s" % (response.error,
                                                   response.request.url)))
            return
        future.set_result(escape.json_decode(response.body)) 
Example #18
Source File: auth_test.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def test_oauth10_request_parameters(self):
        response = self.fetch("/oauth10/client/request_params")
        response.rethrow()
        parsed = json_decode(response.body)
        self.assertEqual(parsed["oauth_consumer_key"], "asdf")
        self.assertEqual(parsed["oauth_token"], "uiop")
        self.assertTrue("oauth_nonce" in parsed)
        self.assertTrue("oauth_signature" in parsed) 
Example #19
Source File: httpserver_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_empty_query_string(self):
        response = self.fetch("/echo?foo=&foo=")
        data = json_decode(response.body)
        self.assertEqual(data, {u("foo"): [u(""), u("")]}) 
Example #20
Source File: web_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_flow_control_fixed_body(self):
        response = self.fetch('/', body='abcdefghijklmnopqrstuvwxyz',
                              method='POST')
        response.rethrow()
        self.assertEqual(json_decode(response.body),
                         dict(methods=['prepare', 'data_received',
                                       'data_received', 'data_received',
                                       'post'])) 
Example #21
Source File: web_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_catch_error(self):
        response = self.fetch('/')
        self.assertEqual(json_decode(response.body),
                         {'arg_name': 'foo',
                          'log_message': 'Missing argument foo'}) 
Example #22
Source File: web_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_kw(self):
        response = self.fetch('/kw/foo')
        response.rethrow()
        data = json_decode(response.body)
        self.assertEqual(data, {'args': [], 'kwargs': {'path': 'foo'}}) 
Example #23
Source File: web_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_decode_argument_plus(self):
        # These urls are all equivalent.
        urls = ["/decode_arg/1%20%2B%201?foo=1%20%2B%201&encoding=utf-8",
                "/decode_arg/1%20+%201?foo=1+%2B+1&encoding=utf-8"]
        for req_url in urls:
            response = self.fetch(req_url)
            response.rethrow()
            data = json_decode(response.body)
            self.assertEqual(data, {u('path'): [u('unicode'), u('1 + 1')],
                                    u('query'): [u('unicode'), u('1 + 1')],
                                    }) 
Example #24
Source File: web_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_types(self):
        cookie_value = to_unicode(create_signed_value(self.COOKIE_SECRET,
                                                      "asdf", "qwer"))
        response = self.fetch("/typecheck/asdf?foo=bar",
                              headers={"Cookie": "asdf=" + cookie_value})
        data = json_decode(response.body)
        self.assertEqual(data, {})

        response = self.fetch("/typecheck/asdf?foo=bar", method="POST",
                              headers={"Cookie": "asdf=" + cookie_value},
                              body="foo=bar") 
Example #25
Source File: web_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def fetch_json(self, *args, **kwargs):
        response = self.fetch(*args, **kwargs)
        response.rethrow()
        return json_decode(response.body) 
Example #26
Source File: wsgi_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_types(self):
        headers = {"Cookie": "foo=bar"}
        response = self.fetch("/typecheck?foo=bar", headers=headers)
        data = json_decode(response.body)
        self.assertEqual(data, {})

        response = self.fetch("/typecheck", method="POST", body="foo=bar", headers=headers)
        data = json_decode(response.body)
        self.assertEqual(data, {})

# This is kind of hacky, but run some of the HTTPServer tests through
# WSGIContainer and WSGIApplication to make sure everything survives
# repeated disassembly and reassembly. 
Example #27
Source File: auth_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_google_login(self):
        response = self.fetch('/client/login')
        self.assertDictEqual({
            u('name'): u('Foo'),
            u('email'): u('foo@example.com'),
            u('access_token'): u('fake-access-token'),
        }, json_decode(response.body)) 
Example #28
Source File: auth_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_twitter_show_user_future(self):
        response = self.fetch('/twitter/client/show_user_future?name=somebody')
        response.rethrow()
        self.assertEqual(json_decode(response.body),
                         {'name': 'Somebody', 'screen_name': 'somebody'}) 
Example #29
Source File: auth_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_twitter_show_user(self):
        response = self.fetch('/twitter/client/show_user?name=somebody')
        response.rethrow()
        self.assertEqual(json_decode(response.body),
                         {'name': 'Somebody', 'screen_name': 'somebody'}) 
Example #30
Source File: auth_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_twitter_get_user(self):
        response = self.fetch(
            '/twitter/client/login?oauth_token=zxcv',
            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})
        response.rethrow()
        parsed = json_decode(response.body)
        self.assertEqual(parsed,
                         {u('access_token'): {u('key'): u('hjkl'),
                                              u('screen_name'): u('foo'),
                                              u('secret'): u('vbnm')},
                          u('name'): u('Foo'),
                          u('screen_name'): u('foo'),
                          u('username'): u('foo')})