]> git.ipfire.org Git - thirdparty/tornado.git/commitdiff
Run autopep8
authorBen Darnell <ben@bendarnell.com>
Sun, 8 Feb 2015 19:40:04 +0000 (14:40 -0500)
committerBen Darnell <ben@bendarnell.com>
Sun, 8 Feb 2015 19:40:04 +0000 (14:40 -0500)
26 files changed:
tornado/auth.py
tornado/concurrent.py
tornado/curl_httpclient.py
tornado/gen.py
tornado/http1connection.py
tornado/httputil.py
tornado/iostream.py
tornado/netutil.py
tornado/platform/asyncio.py
tornado/platform/select.py
tornado/simple_httpclient.py
tornado/test/asyncio_test.py
tornado/test/escape_test.py
tornado/test/gen_test.py
tornado/test/httpclient_test.py
tornado/test/httputil_test.py
tornado/test/ioloop_test.py
tornado/test/iostream_test.py
tornado/test/locale_test.py
tornado/test/netutil_test.py
tornado/test/twisted_test.py
tornado/test/util.py
tornado/test/web_test.py
tornado/test/websocket_test.py
tornado/util.py
tornado/websocket.py

index ac2fd0d198af06bac288c64421fc099a634fdde1..f28b1ee25a8d992a0731063ad2fa0901118a6022 100644 (file)
@@ -1307,7 +1307,7 @@ class FacebookGraphMixin(OAuth2Mixin):
 
         http.fetch(self._oauth_request_token_url(**args),
                    functools.partial(self._on_access_token, redirect_uri, client_id,
-                                       client_secret, callback, fields))
+                                     client_secret, callback, fields))
 
     def _on_access_token(self, redirect_uri, client_id, client_secret,
                          future, fields, response):
index acfbcd83e820dfd1ff1e6eb9be8af961d5ae0084..a3f15dcde99beee04faf3d5cd2639f4a54ce93f5 100644 (file)
@@ -44,12 +44,14 @@ except ImportError:
 _GC_CYCLE_FINALIZERS = (platform.python_implementation() == 'CPython' and
                         sys.version_info >= (3, 4))
 
+
 class ReturnValueIgnoredError(Exception):
     pass
 
 # This class and associated code in the future object is derived
 # from the Trollius project, a backport of asyncio to Python 2.x - 3.x
 
+
 class _TracebackLogger(object):
     """Helper to log a traceback upon destruction if not cleared.
 
index ebbe0e84b9300485d1acae2ed405b4cf512b0e21..87d2ba488996bb2fb8dce3b5802d5f801def82a4 100644 (file)
@@ -35,6 +35,7 @@ from tornado.httpclient import HTTPResponse, HTTPError, AsyncHTTPClient, main
 
 curl_log = logging.getLogger('tornado.curl_httpclient')
 
+
 class CurlAsyncHTTPClient(AsyncHTTPClient):
     def initialize(self, io_loop, max_clients=10, defaults=None):
         super(CurlAsyncHTTPClient, self).initialize(io_loop, defaults=defaults)
@@ -286,7 +287,7 @@ class CurlAsyncHTTPClient(AsyncHTTPClient):
 
         curl.setopt(pycurl.HEADERFUNCTION,
                     functools.partial(self._curl_header_callback,
-                        headers, request.header_callback))
+                                      headers, request.header_callback))
         if request.streaming_callback:
             write_function = lambda chunk: self.io_loop.add_callback(
                 request.streaming_callback, chunk)
@@ -404,7 +405,7 @@ class CurlAsyncHTTPClient(AsyncHTTPClient):
 
             curl.setopt(pycurl.USERPWD, native_str(userpwd))
             curl_log.debug("%s %s (username: %r)", request.method, request.url,
-                          request.auth_username)
+                           request.auth_username)
         else:
             curl.unsetopt(pycurl.USERPWD)
             curl_log.debug("%s %s", request.method, request.url)
index 86fe2f19596ea77267af838b65c7faa03541b16a..5c40c6ed6468e48640f6e48a6353699e7035406d 100644 (file)
@@ -263,6 +263,7 @@ class Return(Exception):
         super(Return, self).__init__()
         self.value = value
 
+
 class WaitIterator(object):
     """Provides an iterator to yield the results of futures as they finish.
 
@@ -846,10 +847,10 @@ class Runner(object):
         # Lists containing YieldPoints require stack contexts;
         # other lists are handled via multi_future in convert_yielded.
         if (isinstance(yielded, list) and
-            any(isinstance(f, YieldPoint) for f in yielded)):
+                any(isinstance(f, YieldPoint) for f in yielded)):
             yielded = Multi(yielded)
         elif (isinstance(yielded, dict) and
-            any(isinstance(f, YieldPoint) for f in yielded.values())):
+              any(isinstance(f, YieldPoint) for f in yielded.values())):
             yielded = Multi(yielded)
 
         if isinstance(yielded, YieldPoint):
index 181319c42e4e192c74cc4bb20dc80d51b3bbc86a..6226ef7af2c85d4489598bd1b9a48a3652a6afea 100644 (file)
@@ -37,6 +37,7 @@ class _QuietException(Exception):
     def __init__(self):
         pass
 
+
 class _ExceptionLoggingContext(object):
     """Used with the ``with`` statement when calling delegate methods to
     log any exceptions with the given logger.  Any exceptions caught are
@@ -53,6 +54,7 @@ class _ExceptionLoggingContext(object):
             self.logger.error("Uncaught exception", exc_info=(typ, value, tb))
             raise _QuietException
 
+
 class HTTP1ConnectionParameters(object):
     """Parameters for `.HTTP1Connection` and `.HTTP1ServerConnection`.
     """
@@ -202,7 +204,7 @@ class HTTP1Connection(httputil.HTTPConnection):
                     # 1xx responses should never indicate the presence of
                     # a body.
                     if ('Content-Length' in headers or
-                        'Transfer-Encoding' in headers):
+                            'Transfer-Encoding' in headers):
                         raise httputil.HTTPInputError(
                             "Response code %d cannot have body" % code)
                     # TODO: client delegates will get headers_received twice
index 9c99b3efa8ec820669dc7198825d295b693ce578..21b170919b9030d750db447809b7548f67ff3273 100644 (file)
@@ -884,6 +884,7 @@ def doctests():
     import doctest
     return doctest.DocTestSuite()
 
+
 def split_host_and_port(netloc):
     """Returns ``(host, port)`` tuple from ``netloc``.
 
index cdb6250b9055fed5bb86fab08f3eb87b82b00cf1..1bd33b42a6004d1647647f40d778390cd8c93d82 100644 (file)
@@ -83,6 +83,8 @@ if hasattr(errno, "WSAEINPROGRESS"):
     _ERRNO_INPROGRESS += (errno.WSAEINPROGRESS,)
 
 #######################################################
+
+
 class StreamClosedError(IOError):
     """Exception raised by `IOStream` methods when the stream is closed.
 
@@ -1222,7 +1224,7 @@ class SSLIOStream(IOStream):
             # quiet as well.
             # https://groups.google.com/forum/?fromgroups#!topic/python-tornado/ApucKJat1_0
             if (err.args[0] in _ERRNO_CONNRESET or
-                err.args[0] == errno.EBADF):
+                    err.args[0] == errno.EBADF):
                 return self.close(exc_info=True)
             raise
         except AttributeError:
index 17e9580405d664b7e9d4cc0b13ac30c405fa63f4..06923b2af4edc5d55216069dfc670e502060af05 100644 (file)
@@ -68,6 +68,7 @@ if hasattr(errno, "WSAEWOULDBLOCK"):
 # Default backlog used when calling sock.listen()
 _DEFAULT_BACKLOG = 128
 
+
 def bind_sockets(port, address=None, family=socket.AF_UNSPEC,
                  backlog=_DEFAULT_BACKLOG, flags=None):
     """Creates listening sockets bound to the given port and address.
index bc6851750ac119e8e22de79e9a5ffa3bc000dde5..cf1bf7a4480549ba954891111979592f9006b668 100644 (file)
@@ -29,6 +29,7 @@ except ImportError as e:
         # Re-raise the original asyncio error, not the trollius one.
         raise e
 
+
 class BaseAsyncIOLoop(IOLoop):
     def initialize(self, asyncio_loop, close_loop=False):
         self.asyncio_loop = asyncio_loop
@@ -141,12 +142,14 @@ class AsyncIOLoop(BaseAsyncIOLoop):
         super(AsyncIOLoop, self).initialize(asyncio.new_event_loop(),
                                             close_loop=True)
 
+
 def to_tornado_future(asyncio_future):
     """Convert an ``asyncio.Future`` to a `tornado.concurrent.Future`."""
     tf = tornado.concurrent.Future()
     tornado.concurrent.chain_future(asyncio_future, tf)
     return tf
 
+
 def to_asyncio_future(tornado_future):
     """Convert a `tornado.concurrent.Future` to an ``asyncio.Future``."""
     af = asyncio.Future()
index 1e1265547ce7f396f070e1125ec171dcb51c1b80..db52ef91063bf813f8ed39f5fe2ef4d803429e72 100644 (file)
@@ -47,7 +47,7 @@ class _Select(object):
             # Closed connections are reported as errors by epoll and kqueue,
             # but as zero-byte reads by select, so when errors are requested
             # we need to listen for both read and error.
-            #self.read_fds.add(fd)
+            # self.read_fds.add(fd)
 
     def modify(self, fd, events):
         self.unregister(fd)
index 31d076e2d114d0840dcf586410aee11eebcaf43f..13400207a3d48934c5d01e197b235da25d301b22 100644 (file)
@@ -317,7 +317,7 @@ class _HTTPConnection(httputil.HTTPMessageDelegate):
             body_present = (self.request.body is not None or
                             self.request.body_producer is not None)
             if ((body_expected and not body_present) or
-                (body_present and not body_expected)):
+                    (body_present and not body_expected)):
                 raise ValueError(
                     'Body must %sbe None for method %s (unelss '
                     'allow_nonstandard_methods is true)' %
index cb990748f6f45173b982e9d7c0dce4ccbd35fb95..1be0e54f35529da7a0a6671992f0b279d74cffdb 100644 (file)
@@ -27,6 +27,7 @@ except ImportError:
 skipIfNoSingleDispatch = unittest.skipIf(
     gen.singledispatch is None, "singledispatch module not present")
 
+
 @unittest.skipIf(asyncio is None, "asyncio module not present")
 class AsyncIOLoopTest(AsyncTestCase):
     def get_new_ioloop(self):
index f640428881522e869875dcd6d079a1bf01b3e5a9..98a23463890c0b8633bc966075253196df8ecadd 100644 (file)
@@ -217,9 +217,8 @@ class EscapeTestCase(unittest.TestCase):
             self.assertRaises(UnicodeDecodeError, json_encode, b"\xe9")
 
     def test_squeeze(self):
-        self.assertEqual(squeeze(u('sequences     of    whitespace   chars'))
-            , u('sequences of whitespace chars'))
-    
+        self.assertEqual(squeeze(u('sequences     of    whitespace   chars')), u('sequences of whitespace chars'))
+
     def test_recursive_unicode(self):
         tests = {
             'dict': {b"foo": b"bar"},
index 5d646d15007a0b100d5f9fa0c00623ba48690372..a5d78b5a9b16fad78f0e27d2e3e43ea239b8ee82 100644 (file)
@@ -1072,6 +1072,7 @@ class WithTimeoutTest(AsyncTestCase):
             yield gen.with_timeout(datetime.timedelta(seconds=3600),
                                    executor.submit(lambda: None))
 
+
 class WaitIteratorTest(AsyncTestCase):
     @gen_test
     def test_empty_iterator(self):
@@ -1121,10 +1122,10 @@ class WaitIteratorTest(AsyncTestCase):
         while not dg.done():
             dr = yield dg.next()
             if dg.current_index == "f1":
-                self.assertTrue(dg.current_future==f1 and dr==24,
+                self.assertTrue(dg.current_future == f1 and dr == 24,
                                 "WaitIterator dict status incorrect")
             elif dg.current_index == "f2":
-                self.assertTrue(dg.current_future==f2 and dr==42,
+                self.assertTrue(dg.current_future == f2 and dr == 42,
                                 "WaitIterator dict status incorrect")
             else:
                 self.fail("got bad WaitIterator index {}".format(
@@ -1145,7 +1146,7 @@ class WaitIteratorTest(AsyncTestCase):
             futures[3].set_result(84)
 
         if iteration < 8:
-            self.io_loop.add_callback(self.finish_coroutines, iteration+1, futures)
+            self.io_loop.add_callback(self.finish_coroutines, iteration + 1, futures)
 
     @gen_test
     def test_iterator(self):
index 875864ac69ff66ab851a8b95819ba6f62e1fc607..f62cb5ca1906e725c69e4b46d7b19df7a20f90dc 100644 (file)
@@ -459,7 +459,7 @@ Transfer-Encoding: chunked
     # Twisted's reactor does not.  The removeReader call fails and so
     # do all future removeAll calls (which our tests do at cleanup).
     #
-    #def test_post_307(self):
+    # def test_post_307(self):
     #    response = self.fetch("/redirect?status=307&url=/post",
     #                          method="POST", body=b"arg1=foo&arg2=bar")
     #    self.assertEqual(response.body, b"Post arg1: foo, arg2: bar")
@@ -589,5 +589,5 @@ class HTTPRequestTestCase(unittest.TestCase):
     def test_if_modified_since(self):
         http_date = datetime.datetime.utcnow()
         request = HTTPRequest('http://example.com', if_modified_since=http_date)
-        self.assertEqual(request.headers, 
-            {'If-Modified-Since': format_timestamp(http_date)})
+        self.assertEqual(request.headers,
+                         {'If-Modified-Since': format_timestamp(http_date)})
index 3995abe8b94ab9166e0ed43205b12cf4ef578e3d..2ddc15fab0d5af5cf0c41257f4b303cbef70a6b5 100644 (file)
@@ -237,14 +237,14 @@ Foo: even
         # and cpython's unicodeobject.c (which defines the implementation
         # of unicode_type.splitlines(), and uses a different list than TR13).
         newlines = [
-            u('\u001b'), # VERTICAL TAB
-            u('\u001c'), # FILE SEPARATOR
-            u('\u001d'), # GROUP SEPARATOR
-            u('\u001e'), # RECORD SEPARATOR
-            u('\u0085'), # NEXT LINE
-            u('\u2028'), # LINE SEPARATOR
-            u('\u2029'), # PARAGRAPH SEPARATOR
-            ]
+            u('\u001b'),  # VERTICAL TAB
+            u('\u001c'),  # FILE SEPARATOR
+            u('\u001d'),  # GROUP SEPARATOR
+            u('\u001e'),  # RECORD SEPARATOR
+            u('\u0085'),  # NEXT LINE
+            u('\u2028'),  # LINE SEPARATOR
+            u('\u2029'),  # PARAGRAPH SEPARATOR
+        ]
         for newline in newlines:
             # Try the utf8 and latin1 representations of each newline
             for encoding in ['utf8', 'latin1']:
@@ -278,7 +278,7 @@ Foo: even
                          [('Cr', 'cr\rMore: more'),
                           ('Crlf', 'crlf'),
                           ('Lf', 'lf'),
-                         ])
+                          ])
 
 
 class FormatTimestampTest(unittest.TestCase):
index 7eb7594fd32448c27bca7ab0c29ca979177be827..15f8a2cdbbcedf3df77c75b47346f08f21c0d8ec 100644 (file)
@@ -305,7 +305,7 @@ class TestIOLoop(AsyncTestCase):
         # Use a NullContext to keep the exception from being caught by
         # AsyncTestCase.
         with NullContext():
-            self.io_loop.add_callback(lambda: 1/0)
+            self.io_loop.add_callback(lambda: 1 / 0)
             self.io_loop.add_callback(self.stop)
             with ExpectLog(app_log, "Exception in callback"):
                 self.wait()
@@ -316,7 +316,7 @@ class TestIOLoop(AsyncTestCase):
             @gen.coroutine
             def callback():
                 self.io_loop.add_callback(self.stop)
-                1/0
+                1 / 0
             self.io_loop.add_callback(callback)
             with ExpectLog(app_log, "Exception in callback"):
                 self.wait()
@@ -324,12 +324,12 @@ class TestIOLoop(AsyncTestCase):
     def test_spawn_callback(self):
         # An added callback runs in the test's stack_context, so will be
         # re-arised in wait().
-        self.io_loop.add_callback(lambda: 1/0)
+        self.io_loop.add_callback(lambda: 1 / 0)
         with self.assertRaises(ZeroDivisionError):
             self.wait()
         # A spawned callback is run directly on the IOLoop, so it will be
         # logged without stopping the test.
-        self.io_loop.spawn_callback(lambda: 1/0)
+        self.io_loop.spawn_callback(lambda: 1 / 0)
         self.io_loop.add_callback(self.stop)
         with ExpectLog(app_log, "Exception in callback"):
             self.wait()
index ca35de69bbae0b48467642c4b157e17f3878cab1..9d0bd4f69c9c338359c9464e02fb29df3e35799b 100644 (file)
@@ -884,7 +884,6 @@ class TestIOStreamStartTLS(AsyncTestCase):
         with self.assertRaises((ssl.SSLError, socket.error)):
             yield server_future
 
-
     @unittest.skipIf(not hasattr(ssl, 'create_default_context'),
                      'ssl.create_default_context not present')
     @gen_test
index d12ad52ffa810e7d809b53c71bb94a399eeba4e3..2c3dae910ff32dd3b5ed70e9657c4e8aef4e85e6 100644 (file)
@@ -58,7 +58,7 @@ class EnglishTest(unittest.TestCase):
         self.assertEqual(locale.format_date(date, full_format=True),
                          'April 28, 2013 at 6:35 pm')
 
-        self.assertEqual(locale.format_date(datetime.datetime.utcnow() - datetime.timedelta(seconds=2), full_format=False), 
+        self.assertEqual(locale.format_date(datetime.datetime.utcnow() - datetime.timedelta(seconds=2), full_format=False),
                          '2 seconds ago')
         self.assertEqual(locale.format_date(datetime.datetime.utcnow() - datetime.timedelta(minutes=2), full_format=False),
                          '2 minutes ago')
index 1df1e32042f3711e70d1cbf6867baee153401a37..7d9cad34a0491b579813dff135b7d8db560a86a0 100644 (file)
@@ -67,10 +67,12 @@ class _ResolverErrorTestMixin(object):
             yield self.resolver.resolve('an invalid domain', 80,
                                         socket.AF_UNSPEC)
 
+
 def _failing_getaddrinfo(*args):
     """Dummy implementation of getaddrinfo for use in mocks"""
     raise socket.gaierror("mock: lookup failed")
 
+
 @skipIfNoNetwork
 class BlockingResolverTest(AsyncTestCase, _ResolverTestMixin):
     def setUp(self):
index b31ae94cb90e5e4f01be1a005291bac36adb5f53..315b3b758d3cd2288458a5c040cc9c5ceb7888d4 100644 (file)
@@ -75,6 +75,7 @@ skipIfNoTwisted = unittest.skipUnless(have_twisted,
 skipIfNoSingleDispatch = unittest.skipIf(
     gen.singledispatch is None, "singledispatch module not present")
 
+
 def save_signal_handlers():
     saved = {}
     for sig in [signal.SIGINT, signal.SIGTERM, signal.SIGCHLD]:
index 358809f216e247014b2401089c9744a5cde336cc..9dd9c0ce12d42b099b708fe1033c9edcfda70829 100644 (file)
@@ -31,6 +31,7 @@ skipIfNoNetwork = unittest.skipIf('NO_NETWORK' in os.environ,
 
 skipIfNoIPv6 = unittest.skipIf(not socket.has_ipv6, 'ipv6 support not present')
 
+
 def refusing_port():
     """Returns a local port number that will refuse all connections.
 
index adf6be97448c51dc42ab571164d0521cafab52a2..3c470428b991faf889aefb72c0365177fb723364 100644 (file)
@@ -245,7 +245,7 @@ class CookieTest(WebTestCase):
         headers = response.headers.get_list("Set-Cookie")
         self.assertEqual(sorted(headers),
                          ["foo=bar; Max-Age=10; Path=/"])
-    
+
     def test_set_cookie_expires_days(self):
         response = self.fetch("/set_expires_days")
         header = response.headers.get("Set-Cookie")
@@ -2312,7 +2312,7 @@ class XSRFTest(SimpleHandlerTestCase):
         token2 = self.get_token()
         # Each token can be used to authenticate its own request.
         for token in (self.xsrf_token, token2):
-            response  = self.fetch(
+            response = self.fetch(
                 "/", method="POST",
                 body=urllib_parse.urlencode(dict(_xsrf=token)),
                 headers=self.cookie_headers(token))
index 7e93d17141a886a9cb06a5f840a11f7e723b9dae..42599382d8c2c0392b17d748a47a1775cd253746 100644 (file)
@@ -53,7 +53,7 @@ class EchoHandler(TestWebSocketHandler):
 
 class ErrorInOnMessageHandler(TestWebSocketHandler):
     def on_message(self, message):
-        1/0
+        1 / 0
 
 
 class HeaderHandler(TestWebSocketHandler):
@@ -106,6 +106,7 @@ class WebSocketBaseTestCase(AsyncHTTPTestCase):
         ws.close()
         yield self.close_future
 
+
 class WebSocketTest(WebSocketBaseTestCase):
     def get_app(self):
         self.close_future = Future()
@@ -250,7 +251,7 @@ class WebSocketTest(WebSocketBaseTestCase):
         headers = {'Origin': 'http://127.0.0.1:%d' % port}
 
         ws = yield websocket_connect(HTTPRequest(url, headers=headers),
-            io_loop=self.io_loop)
+                                     io_loop=self.io_loop)
         ws.write_message('hello')
         response = yield ws.read_message()
         self.assertEqual(response, 'hello')
@@ -264,7 +265,7 @@ class WebSocketTest(WebSocketBaseTestCase):
         headers = {'Origin': 'http://127.0.0.1:%d/something' % port}
 
         ws = yield websocket_connect(HTTPRequest(url, headers=headers),
-            io_loop=self.io_loop)
+                                     io_loop=self.io_loop)
         ws.write_message('hello')
         response = yield ws.read_message()
         self.assertEqual(response, 'hello')
index cac4e3aaea48addd9d051886bd319efd3b6b282c..bc66beaebfe07e7ad7fbd69c27586239ec93b5ad 100644 (file)
@@ -343,7 +343,7 @@ def _websocket_mask_python(mask, data):
         return unmasked.tostring()
 
 if (os.environ.get('TORNADO_NO_EXTENSION') or
-    os.environ.get('TORNADO_EXTENSION') == '0'):
+        os.environ.get('TORNADO_EXTENSION') == '0'):
     # These environment variables exist to make it easier to do performance
     # comparisons; they are not guaranteed to remain supported in the future.
     _websocket_mask = _websocket_mask_python
index c009225ce51decfd59ea964855648cbe10babe92..7c7866369bc014be14a868a0dace1eff626d1e53 100644 (file)
@@ -39,9 +39,9 @@ from tornado.tcpclient import TCPClient
 from tornado.util import _websocket_mask
 
 try:
-    from urllib.parse import urlparse # py2
+    from urllib.parse import urlparse  # py2
 except ImportError:
-    from urlparse import urlparse # py3
+    from urlparse import urlparse  # py3
 
 try:
     xrange  # py2
@@ -160,7 +160,6 @@ class WebSocketHandler(tornado.web.RequestHandler):
         else:
             origin = self.request.headers.get("Sec-Websocket-Origin", None)
 
-
         # If there was an origin header, check to make sure it matches
         # according to check_origin. When the origin is None, we assume it
         # did not come from a browser and that it can be passed on.
@@ -549,12 +548,12 @@ class WebSocketProtocol13(WebSocketProtocol):
         extensions = self._parse_extensions_header(self.request.headers)
         for ext in extensions:
             if (ext[0] == 'permessage-deflate' and
-                self._compression_options is not None):
+                    self._compression_options is not None):
                 # TODO: negotiate parameters if compression_options
                 # specifies limits.
                 self._create_compressors('server', ext[1])
                 if ('client_max_window_bits' in ext[1] and
-                    ext[1]['client_max_window_bits'] is None):
+                        ext[1]['client_max_window_bits'] is None):
                     # Don't echo an offered client_max_window_bits
                     # parameter with no value.
                     del ext[1]['client_max_window_bits']
@@ -599,7 +598,7 @@ class WebSocketProtocol13(WebSocketProtocol):
         extensions = self._parse_extensions_header(headers)
         for ext in extensions:
             if (ext[0] == 'permessage-deflate' and
-                self._compression_options is not None):
+                    self._compression_options is not None):
                 self._create_compressors('client', ext[1])
             else:
                 raise ValueError("unsupported extension %r", ext)