Example #1
0
    def test_json_decode(self):
        # json_decode accepts both bytes and unicode, but strings it returns
        # are always unicode.
        self.assertEqual(json_decode(b'"foo"'), u"foo")
        self.assertEqual(json_decode(u'"foo"'), u"foo")

        # Non-ascii bytes are interpreted as utf8
        self.assertEqual(json_decode(utf8(u'"\u00e9"')), u"\u00e9")
Example #2
0
 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 #3
0
    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, {})
Example #4
0
 def test_double_slash(self):
     # urlparse.urlsplit (which tornado.httpserver used to use
     # incorrectly) would parse paths beginning with "//" as
     # protocol-relative urls.
     response = self.fetch("//doubleslash")
     self.assertEqual(200, response.code)
     self.assertEqual(json_decode(response.body), {})
Example #5
0
 def test_openid_get_user(self):
     response = self.fetch(
         '/openid/client/login?openid.mode=blah&openid.ns.ax=http://openid.net/srv/ax/1.0&openid.ax.type.email=http://axschema.org/contact/email&[email protected]'
     )
     response.rethrow()
     parsed = json_decode(response.body)
     self.assertEqual(parsed["email"], "*****@*****.**")
Example #6
0
 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 #7
0
 def test_gzip_unsupported(self):
     # Gzip support is opt-in; without it the server fails to parse
     # the body (but parsing form bodies is currently just a log message,
     # not a fatal error).
     with ExpectLog(gen_log, "Unsupported Content-Encoding"):
         response = self.post_gzip('foo=bar')
     self.assertEquals(json_decode(response.body), {})
Example #8
0
 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 #9
0
 def test_oauth10a_request_parameters(self):
     response = self.fetch('/oauth10a/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 #10
0
 def test_google_login(self):
     response = self.fetch('/client/login')
     self.assertDictEqual(
         {
             u'name': u'Foo',
             u'email': u'*****@*****.**',
             u'access_token': u'fake-access-token',
         }, json_decode(response.body))
Example #11
0
 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'], '*****@*****.**')
     self.assertEqual(parsed['access_token'], dict(key='uiop',
                                                   secret='5678'))
Example #12
0
    def _on_access_token(self, future, response):
        """Callback function for the exchange to the access token."""
        if response.error:
            future.set_exception(
                AuthError('Google auth error: %s' % str(response)))
            return

        args = escape.json_decode(response.body)
        future.set_result(args)
Example #13
0
 def fetch_chunk_sizes(self, **kwargs):
     response = self.fetch('/', method='POST', **kwargs)
     response.rethrow()
     chunks = json_decode(response.body)
     self.assertEqual(len(self.BODY), sum(chunks))
     for chunk_size in chunks:
         self.assertLessEqual(chunk_size, self.CHUNK_SIZE,
                              'oversized chunk: ' + str(chunks))
         self.assertGreater(chunk_size, 0, 'empty chunk: ' + str(chunks))
     return chunks
Example #14
0
 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 #15
0
 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 #16
0
    def test_chunked_request_uppercase(self):
        # As per RFC 2616 section 3.6, "Transfer-Encoding" header's value is
        # case-insensitive.
        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 #17
0
    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 #18
0
    def _on_access_token(self, redirect_uri, client_id, client_secret, future,
                         fields, response):
        if response.error:
            future.set_exception(
                AuthError('Facebook auth error: %s' % str(response)))
            return

        args = escape.json_decode(response.body)
        session = {
            "access_token": args.get("access_token"),
            "expires_in": args.get("expires_in")
        }

        self.facebook_request(path="/me",
                              callback=functools.partial(
                                  self._on_get_user_info, future, session,
                                  fields),
                              access_token=session["access_token"],
                              appsecret_proof=hmac.new(
                                  key=client_secret.encode('utf8'),
                                  msg=session["access_token"].encode('utf8'),
                                  digestmod=hashlib.sha256).hexdigest(),
                              fields=",".join(fields))
Example #19
0
 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 #20
0
 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 #21
0
 def fetch_json(self, *args, **kwargs):
     response = self.fetch(*args, **kwargs)
     response.rethrow()
     return json_decode(response.body)
Example #22
0
 def test_uncompressed(self):
     response = self.fetch('/', method='POST', body='foo=bar')
     self.assertEquals(json_decode(response.body), {u'foo': [u'bar']})
Example #23
0
 def test_empty_post_parameters(self):
     response = self.fetch("/echo", method="POST", body="foo=&bar=")
     data = json_decode(response.body)
     self.assertEqual(data, {u"foo": [u""], u"bar": [u""]})
Example #24
0
 def test_gzip(self):
     response = self.post_gzip('foo=bar')
     self.assertEquals(json_decode(response.body), {u'foo': [u'bar']})
Example #25
0
 def test_query_string_encoding(self):
     response = self.fetch("/echo?foo=%C3%A9")
     data = json_decode(response.body)
     self.assertEqual(data, {u"foo": [u"\u00e9"]})