]> git.ipfire.org Git - thirdparty/tornado.git/commitdiff
Add type: ignore comments to make mypy happy
authorBen Darnell <ben@bendarnell.com>
Mon, 11 Apr 2016 00:59:58 +0000 (20:59 -0400)
committerBen Darnell <ben@bendarnell.com>
Mon, 11 Apr 2016 00:59:58 +0000 (20:59 -0400)
30 files changed:
tornado/auth.py
tornado/autoreload.py
tornado/curl_httpclient.py
tornado/gen.py
tornado/httpclient.py
tornado/httputil.py
tornado/iostream.py
tornado/locale.py
tornado/netutil.py
tornado/platform/asyncio.py
tornado/platform/caresresolver.py
tornado/platform/interface.py
tornado/platform/twisted.py
tornado/platform/windows.py
tornado/process.py
tornado/template.py
tornado/test/concurrent_test.py
tornado/test/curl_httpclient_test.py
tornado/test/httpserver_test.py
tornado/test/import_test.py
tornado/test/iostream_test.py
tornado/test/netutil_test.py
tornado/test/options_test.py
tornado/test/twisted_test.py
tornado/test/util.py
tornado/test/util_test.py
tornado/test/web_test.py
tornado/test/wsgi_test.py
tornado/testing.py
tornado/web.py

index 5b7657bcebabb8e477e2996700c39d9cdc922714..44144061e644a69c403712c191dad0e81d420a11 100644 (file)
@@ -92,11 +92,6 @@ else:
     import urlparse
     import urllib as urllib_parse
 
-try:
-    long  # py2
-except NameError:
-    long = int  # py3
-
 
 class AuthError(Exception):
     pass
index 1cbf26c6cb091327d2f481ce1380d42bf6701cc4..5e0d00d1ffaa2ca797b2e0b4e9ecef1024d71c09 100644 (file)
@@ -83,7 +83,7 @@ if __name__ == "__main__":
 import functools
 import logging
 import os
-import pkgutil
+import pkgutil  # type: ignore
 import sys
 import traceback
 import types
@@ -112,7 +112,7 @@ _has_execv = sys.platform != 'win32'
 _watched_files = set()
 _reload_hooks = []
 _reload_attempted = False
-_io_loops = weakref.WeakKeyDictionary()
+_io_loops = weakref.WeakKeyDictionary()  # type: ignore
 
 
 def start(io_loop=None, check_time=500):
index 664cb492c0f4fab04956df37b91c09648faa0327..fa317b2da9491bb1dad3cbeb67340895d4e18bef 100644 (file)
@@ -21,7 +21,7 @@ from __future__ import absolute_import, division, print_function, with_statement
 import collections
 import functools
 import logging
-import pycurl
+import pycurl  # type: ignore
 import threading
 import time
 from io import BytesIO
index 29e8cb50b53861893522b5482e16c13a0dad260f..8cffcc0bf0faa8745ffe17133bfd046bddb9de45 100644 (file)
@@ -92,7 +92,8 @@ from tornado.util import PY3, raise_exc_info
 
 try:
     try:
-        from functools import singledispatch  # py34+
+        # py34+
+        from functools import singledispatch  # type: ignore
     except ImportError:
         from singledispatch import singledispatch  # backport
 except ImportError:
@@ -108,9 +109,10 @@ except ImportError:
 
 try:
     try:
-        from collections.abc import Generator as GeneratorType  # py35+
+        # py35+
+        from collections.abc import Generator as GeneratorType  # type: ignore
     except ImportError:
-        from backports_abc import Generator as GeneratorType
+        from backports_abc import Generator as GeneratorType  # type: ignore
 
     try:
         from inspect import isawaitable  # py35+
@@ -121,7 +123,7 @@ except ImportError:
         raise
     from types import GeneratorType
 
-    def isawaitable(x):
+    def isawaitable(x):  # type: ignore
         return False
 
 if PY3:
index c80172160891e11e1461d2a7df5e62b8f2bc45f8..c62b6207cf6379c9423d83b705b92a73d675e504 100644 (file)
@@ -572,7 +572,8 @@ class HTTPResponse(object):
         self.request_time = request_time
         self.time_info = time_info or {}
 
-    def _get_body(self):
+    @property
+    def body(self):
         if self.buffer is None:
             return None
         elif self._body is None:
@@ -580,8 +581,6 @@ class HTTPResponse(object):
 
         return self._body
 
-    body = property(_get_body)
-
     def rethrow(self):
         """If there was an error on the request, raise an `HTTPError`."""
         if self.error:
index 061e71078c245992340e9fe8d3eba897465f12e5..d0901565a3c9a40a753bb5d53280eca7f83371fe 100644 (file)
@@ -53,9 +53,11 @@ try:
     from ssl import SSLError
 except ImportError:
     # ssl is unavailable on app engine.
-    class SSLError(Exception):
+    class _SSLError(Exception):
         pass
-
+    # Hack around a mypy limitation. We can't simply put "type: ignore"
+    # on the class definition itself; must go through an assignment.
+    SSLError = _SSLError  # type: ignore
 
 # RFC 7230 section 3.5: a recipient MAY recognize a single LF as a line
 # terminator and ignore any preceding CR.
@@ -738,7 +740,7 @@ def parse_multipart_form_data(boundary, data, arguments, files):
         name = disp_params["name"]
         if disp_params.get("filename"):
             ctype = headers.get("Content-Type", "application/unknown")
-            files.setdefault(name, []).append(HTTPFile(
+            files.setdefault(name, []).append(HTTPFile(  # type: ignore
                 filename=disp_params["filename"], body=value,
                 content_type=ctype))
         else:
index 4e304f890073e19f8da8264c9dd10e126e0c2b35..bcf444148c0ff2b639571ccb8796d569d8c7bf53 100644 (file)
@@ -58,7 +58,7 @@ except ImportError:
 _ERRNO_WOULDBLOCK = (errno.EWOULDBLOCK, errno.EAGAIN)
 
 if hasattr(errno, "WSAEWOULDBLOCK"):
-    _ERRNO_WOULDBLOCK += (errno.WSAEWOULDBLOCK,)
+    _ERRNO_WOULDBLOCK += (errno.WSAEWOULDBLOCK,)  # type: ignore
 
 # These errnos indicate that a connection has been abruptly terminated.
 # They should be caught and handled less noisily than other errors.
@@ -66,7 +66,7 @@ _ERRNO_CONNRESET = (errno.ECONNRESET, errno.ECONNABORTED, errno.EPIPE,
                     errno.ETIMEDOUT)
 
 if hasattr(errno, "WSAECONNRESET"):
-    _ERRNO_CONNRESET += (errno.WSAECONNRESET, errno.WSAECONNABORTED, errno.WSAETIMEDOUT)
+    _ERRNO_CONNRESET += (errno.WSAECONNRESET, errno.WSAECONNABORTED, errno.WSAETIMEDOUT)  # type: ignore
 
 if sys.platform == 'darwin':
     # OSX appears to have a race condition that causes send(2) to return
@@ -74,13 +74,13 @@ if sys.platform == 'darwin':
     # http://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/
     # Since the socket is being closed anyway, treat this as an ECONNRESET
     # instead of an unexpected error.
-    _ERRNO_CONNRESET += (errno.EPROTOTYPE,)
+    _ERRNO_CONNRESET += (errno.EPROTOTYPE,)  # type: ignore
 
 # More non-portable errnos:
 _ERRNO_INPROGRESS = (errno.EINPROGRESS,)
 
 if hasattr(errno, "WSAEINPROGRESS"):
-    _ERRNO_INPROGRESS += (errno.WSAEINPROGRESS,)
+    _ERRNO_INPROGRESS += (errno.WSAEINPROGRESS,)  # type: ignore
 
 
 class StreamClosedError(IOError):
index 0a1b077095415be3e037b70a062af84f6a678e3e..db7411431682a230a886414f5de4f0ce9321b3ec 100644 (file)
@@ -55,7 +55,7 @@ from tornado.log import gen_log
 from tornado._locale_data import LOCALE_NAMES
 
 _default_locale = "en_US"
-_translations = {}
+_translations = {}  # type: dict
 _supported_locales = frozenset([_default_locale])
 _use_gettext = False
 CONTEXT_SEPARATOR = "\x04"
index b249945e8f3a7b130fc3598da028f4fd5b4f9bb8..348f3519c134df389cf963331a3e93a9641b9581 100644 (file)
@@ -51,11 +51,11 @@ if hasattr(ssl, 'match_hostname') and hasattr(ssl, 'CertificateError'):  # pytho
     ssl_match_hostname = ssl.match_hostname
     SSLCertificateError = ssl.CertificateError
 elif ssl is None:
-    ssl_match_hostname = SSLCertificateError = None
+    ssl_match_hostname = SSLCertificateError = None  # type: ignore
 else:
     import backports.ssl_match_hostname
     ssl_match_hostname = backports.ssl_match_hostname.match_hostname
-    SSLCertificateError = backports.ssl_match_hostname.CertificateError
+    SSLCertificateError = backports.ssl_match_hostname.CertificateError  # type: ignore
 
 if hasattr(ssl, 'SSLContext'):
     if hasattr(ssl, 'create_default_context'):
@@ -102,7 +102,7 @@ u'foo'.encode('idna')
 _ERRNO_WOULDBLOCK = (errno.EWOULDBLOCK, errno.EAGAIN)
 
 if hasattr(errno, "WSAEWOULDBLOCK"):
-    _ERRNO_WOULDBLOCK += (errno.WSAEWOULDBLOCK,)
+    _ERRNO_WOULDBLOCK += (errno.WSAEWOULDBLOCK,)  # type: ignore
 
 # Default backlog used when calling sock.listen()
 _DEFAULT_BACKLOG = 128
@@ -411,8 +411,8 @@ class ThreadedResolver(ExecutorResolver):
        All ``ThreadedResolvers`` share a single thread pool, whose
        size is set by the first one to be created.
     """
-    _threadpool = None
-    _threadpool_pid = None
+    _threadpool = None  # type: ignore
+    _threadpool_pid = None  # type: int
 
     def initialize(self, io_loop=None, num_threads=10):
         threadpool = ThreadedResolver._create_threadpool(num_threads)
@@ -516,4 +516,4 @@ def ssl_wrap_socket(socket, ssl_options, server_hostname=None, **kwargs):
         else:
             return context.wrap_socket(socket, **kwargs)
     else:
-        return ssl.wrap_socket(socket, **dict(context, **kwargs))
+        return ssl.wrap_socket(socket, **dict(context, **kwargs))  # type: ignore
index bf0428ec511c3fbed7b7d236571ae78a10394cc0..d5a4899633cf93cf54bd0388fcc845685fc82088 100644 (file)
@@ -34,7 +34,7 @@ try:
 except ImportError as e:
     # Asyncio itself isn't available; see if trollius is (backport to py26+).
     try:
-        import trollius as asyncio
+        import trollius as asyncio  # type: ignore
     except ImportError:
         # Re-raise the original asyncio error, not the trollius one.
         raise e
@@ -213,4 +213,4 @@ def to_asyncio_future(tornado_future):
     return af
 
 if hasattr(convert_yielded, 'register'):
-    convert_yielded.register(asyncio.Future, to_tornado_future)
+    convert_yielded.register(asyncio.Future, to_tornado_future)  # type: ignore
index 5559614f596b8316d684cee4d71e223235a2a14e..d68b3fcc4b48aec43656d3c0c6fc25439990a4eb 100644 (file)
@@ -1,5 +1,5 @@
 from __future__ import absolute_import, division, print_function, with_statement
-import pycares
+import pycares  # type: ignore
 import socket
 
 from tornado import gen
index 07da6babdbdcc929037401252ce2c613b77d5dd5..cc062391175fee2e0346a868eecf3b8b0c248066 100644 (file)
@@ -61,3 +61,6 @@ class Waker(object):
     def close(self):
         """Closes the waker's file descriptor(s)."""
         raise NotImplementedError()
+
+def monotonic_time():
+    raise NotImplementedError()
index d3a4e75d1c95bd8e8df8fc2a08babfcb99759734..91a335832bcc23221e9e0daab27f4cf9deb7da8d 100644 (file)
@@ -29,19 +29,18 @@ import numbers
 import socket
 import sys
 
-import twisted.internet.abstract
-from twisted.internet.defer import Deferred
-from twisted.internet.posixbase import PosixReactorBase
-from twisted.internet.interfaces import \
-    IReactorFDSet, IDelayedCall, IReactorTime, IReadDescriptor, IWriteDescriptor
-from twisted.python import failure, log
-from twisted.internet import error
-import twisted.names.cache
-import twisted.names.client
-import twisted.names.hosts
-import twisted.names.resolve
-
-from zope.interface import implementer
+import twisted.internet.abstract  # type: ignore
+from twisted.internet.defer import Deferred  # type: ignore
+from twisted.internet.posixbase import PosixReactorBase  # type: ignore
+from twisted.internet.interfaces import IReactorFDSet, IDelayedCall, IReactorTime, IReadDescriptor, IWriteDescriptor  # type: ignore
+from twisted.python import failure, log  # type: ignore
+from twisted.internet import error  # type: ignore
+import twisted.names.cache  # type: ignore
+import twisted.names.client  # type: ignore
+import twisted.names.hosts  # type: ignore
+import twisted.names.resolve  # type: ignore
+
+from zope.interface import implementer  # type: ignore
 
 from tornado.concurrent import Future
 from tornado.escape import utf8
@@ -354,7 +353,7 @@ def install(io_loop=None):
     if not io_loop:
         io_loop = tornado.ioloop.IOLoop.current()
     reactor = TornadoReactor(io_loop)
-    from twisted.internet.main import installReactor
+    from twisted.internet.main import installReactor  # type: ignore
     installReactor(reactor)
     return reactor
 
@@ -412,7 +411,7 @@ class TwistedIOLoop(tornado.ioloop.IOLoop):
     def initialize(self, reactor=None, **kwargs):
         super(TwistedIOLoop, self).initialize(**kwargs)
         if reactor is None:
-            import twisted.internet.reactor
+            import twisted.internet.reactor  # type: ignore
             reactor = twisted.internet.reactor
         self.reactor = reactor
         self.fds = {}
@@ -570,7 +569,7 @@ class TwistedResolver(Resolver):
         raise gen.Return(result)
 
 if hasattr(gen.convert_yielded, 'register'):
-    @gen.convert_yielded.register(Deferred)
+    @gen.convert_yielded.register(Deferred)  # type: ignore
     def _(d):
         f = Future()
 
index 817bdca13e367ea3ad7ba767bea2b3f913720380..92295fc6cf4ed75ebe3d8ab4b80db04f7ab26878 100644 (file)
@@ -3,8 +3,8 @@
 
 
 from __future__ import absolute_import, division, print_function, with_statement
-import ctypes
-import ctypes.wintypes
+import ctypes  # type: ignore
+import ctypes.wintypes  # type: ignore
 
 # See: http://msdn.microsoft.com/en-us/library/ms724935(VS.85).aspx
 SetHandleInformation = ctypes.windll.kernel32.SetHandleInformation
index e18ebbf05f3ac3b53aeb6d3af8325258dc43250e..64e77c72d17da12e9f47caeb33cce244c0d0bb65 100644 (file)
@@ -207,7 +207,7 @@ class Subprocess(object):
     STREAM = object()
 
     _initialized = False
-    _waiting = {}
+    _waiting = {}  # type: ignore
 
     def __init__(self, *args, **kwargs):
         self.io_loop = kwargs.pop('io_loop', None) or ioloop.IOLoop.current()
index 499cc242ca339624dbe0be8ecfff3678c52b5784..e64b0296f79aacd1a8f119a81851f66a4fc573a3 100644 (file)
@@ -207,12 +207,12 @@ import threading
 
 from tornado import escape
 from tornado.log import app_log
-from tornado.util import ObjectDict, exec_in, unicode_type
+from tornado.util import ObjectDict, exec_in, unicode_type, PY3
 
-try:
-    from cStringIO import StringIO  # py2
-except ImportError:
-    from io import StringIO  # py3
+if PY3:
+    from io import StringIO
+else:
+    from cStringIO import StringIO
 
 _DEFAULT_AUTOESCAPE = "xhtml_escape"
 _UNSET = object()
@@ -335,7 +335,7 @@ class Template(object):
             # __name__ and __loader__ allow the traceback mechanism to find
             # the generated source code.
             "__name__": self.name.replace('.', '_'),
-            "__loader__": ObjectDict(get_source=lambda name: self.code),
+            "__loader__": ObjectDict(get_source=lambda name: self.code),  # type: ignore
         }
         namespace.update(self.namespace)
         namespace.update(kwargs)
index bf90ad0ec92cd829f0084941258dc239ebbc54c5..8ce095ec1b3118e2d49a99b168c844d9399d139e 100644 (file)
@@ -275,7 +275,7 @@ class GeneratorCapClient(BaseCapClient):
 
 class ClientTestMixin(object):
     def setUp(self):
-        super(ClientTestMixin, self).setUp()
+        super(ClientTestMixin, self).setUp()  # type: ignore
         self.server = CapServer(io_loop=self.io_loop)
         sock, port = bind_unused_port()
         self.server.add_sockets([sock])
@@ -283,7 +283,7 @@ class ClientTestMixin(object):
 
     def tearDown(self):
         self.server.stop()
-        super(ClientTestMixin, self).tearDown()
+        super(ClientTestMixin, self).tearDown()  # type: ignore
 
     def test_callback(self):
         self.client.capitalize("hello", callback=self.stop)
index 097aec3e7cfcc9038a371a36e63da02460786000..b115454276234485b05025135c4e8ba043620bde 100644 (file)
@@ -13,7 +13,7 @@ from tornado.web import Application, RequestHandler
 
 
 try:
-    import pycurl
+    import pycurl  # type: ignore
 except ImportError:
     pycurl = None
 
index 942bc4cb0d905940e57465055b20fcdc13a6966c..900c2c354f7523ddf6a332e8f0befc098b021dc9 100644 (file)
@@ -86,7 +86,7 @@ class BaseSSLTest(AsyncHTTPSTestCase):
 
 class SSLTestMixin(object):
     def get_ssl_options(self):
-        return dict(ssl_version=self.get_ssl_version(),
+        return dict(ssl_version=self.get_ssl_version(),  # type: ignore
                     **AsyncHTTPSTestCase.get_ssl_options())
 
     def get_ssl_version(self):
index 1be6427f19aa7d52d814c0fc045d4f057e011855..a50566d0d2dfee86c761b715d57e2ace15d49c7f 100644 (file)
@@ -40,7 +40,7 @@ class ImportTest(unittest.TestCase):
 
     def test_import_pycurl(self):
         try:
-            import pycurl
+            import pycurl  # type: ignore
         except ImportError:
             pass
         else:
index 060f7a454f12296518d9499c85a5e79062149e48..6e15136c3b751da4948811d95eb0cd9004bdb9ee 100644 (file)
@@ -20,10 +20,10 @@ import ssl
 import sys
 
 try:
-    from unittest import mock  # python 3.3
+    from unittest import mock  # type: ignore
 except ImportError:
     try:
-        import mock  # third-party mock package
+        import mock  # type: ignore
     except ImportError:
         mock = None
 
@@ -258,7 +258,7 @@ class TestIOStreamMixin(object):
         stream = IOStream(s, io_loop=self.io_loop)
         stream.set_close_callback(self.stop)
         with mock.patch('socket.socket.connect',
-                        side_effect=socket.gaierror('boom')):
+                        side_effect=socket.gaierror(errno.EIO, 'boom')):
             with ExpectLog(gen_log, "Connect error"):
                 stream.connect(('localhost', 80), callback=self.stop)
                 self.wait()
index 9ef5f7cfe13e36a0c4ba811d6262574ef5f08f77..70d969499fa433a13c27cad5475dad0fe10ed605 100644 (file)
@@ -1,5 +1,6 @@
 from __future__ import absolute_import, division, print_function, with_statement
 
+import errno
 import os
 import signal
 import socket
@@ -18,15 +19,15 @@ except ImportError:
     futures = None
 
 try:
-    import pycares
+    import pycares  # type: ignore
 except ImportError:
     pycares = None
 else:
     from tornado.platform.caresresolver import CaresResolver
 
 try:
-    import twisted
-    import twisted.names
+    import twisted  # type: ignore
+    import twisted.names  # type: ignore
 except ImportError:
     twisted = None
 else:
@@ -70,7 +71,7 @@ class _ResolverErrorTestMixin(object):
 
 def _failing_getaddrinfo(*args):
     """Dummy implementation of getaddrinfo for use in mocks"""
-    raise socket.gaierror("mock: lookup failed")
+    raise socket.gaierror(errno.EIO, "mock: lookup failed")
 
 
 @skipIfNoNetwork
index fd2798fcdba70c248367b11deeff0d4a472ff79b..f7b215c5a5629d0c35e541f1c99e930f464e6abc 100644 (file)
@@ -15,10 +15,11 @@ else:
     from cStringIO import StringIO
 
 try:
-    from unittest import mock  # python 3.3
+    # py33+
+    from unittest import mock  # type: ignore
 except ImportError:
     try:
-        import mock  # third-party mock package
+        import mock  # type: ignore
     except ImportError:
         mock = None
 
index f1df06a6a1ceff055348bbab2e1f5d8bc2599d26..298da6c9cf7a5e879761d7d4e5b2b6b8a7952466 100644 (file)
@@ -42,12 +42,12 @@ from tornado.web import RequestHandler, Application
 
 try:
     import fcntl
-    from twisted.internet.defer import Deferred, inlineCallbacks, returnValue
-    from twisted.internet.interfaces import IReadDescriptor, IWriteDescriptor
-    from twisted.internet.protocol import Protocol
-    from twisted.python import log
+    from twisted.internet.defer import Deferred, inlineCallbacks, returnValue  # type: ignore
+    from twisted.internet.interfaces import IReadDescriptor, IWriteDescriptor  # type: ignore
+    from twisted.internet.protocol import Protocol  # type: ignore
+    from twisted.python import log  # type: ignore
     from tornado.platform.twisted import TornadoReactor, TwistedIOLoop
-    from zope.interface import implementer
+    from zope.interface import implementer  # type: ignore
     have_twisted = True
 except ImportError:
     have_twisted = False
@@ -55,9 +55,9 @@ except ImportError:
 # The core of Twisted 12.3.0 is available on python 3, but twisted.web is not
 # so test for it separately.
 try:
-    from twisted.web.client import Agent, readBody
-    from twisted.web.resource import Resource
-    from twisted.web.server import Site
+    from twisted.web.client import Agent, readBody  # type: ignore
+    from twisted.web.resource import Resource  # type: ignore
+    from twisted.web.server import Site  # type: ignore
     # As of Twisted 15.0.0, twisted.web is present but fails our
     # tests due to internal str/bytes errors.
     have_twisted_web = sys.version_info < (3,)
@@ -220,53 +220,51 @@ class ReactorCallInThread(ReactorTestCase):
         self._reactor.run()
 
 
-class Reader(object):
-    def __init__(self, fd, callback):
-        self._fd = fd
-        self._callback = callback
-
-    def logPrefix(self):
-        return "Reader"
+if have_twisted:
+    @implementer(IReadDescriptor)
+    class Reader(object):
+        def __init__(self, fd, callback):
+            self._fd = fd
+            self._callback = callback
 
-    def close(self):
-        self._fd.close()
+        def logPrefix(self):
+            return "Reader"
 
-    def fileno(self):
-        return self._fd.fileno()
+        def close(self):
+            self._fd.close()
 
-    def readConnectionLost(self, reason):
-        self.close()
+        def fileno(self):
+            return self._fd.fileno()
 
-    def connectionLost(self, reason):
-        self.close()
+        def readConnectionLost(self, reason):
+            self.close()
 
-    def doRead(self):
-        self._callback(self._fd)
-if have_twisted:
-    Reader = implementer(IReadDescriptor)(Reader)
+        def connectionLost(self, reason):
+            self.close()
 
+        def doRead(self):
+            self._callback(self._fd)
 
-class Writer(object):
-    def __init__(self, fd, callback):
-        self._fd = fd
-        self._callback = callback
+    @implementer(IWriteDescriptor)
+    class Writer(object):
+        def __init__(self, fd, callback):
+            self._fd = fd
+            self._callback = callback
 
-    def logPrefix(self):
-        return "Writer"
+        def logPrefix(self):
+            return "Writer"
 
-    def close(self):
-        self._fd.close()
+        def close(self):
+            self._fd.close()
 
-    def fileno(self):
-        return self._fd.fileno()
+        def fileno(self):
+            return self._fd.fileno()
 
-    def connectionLost(self, reason):
-        self.close()
+        def connectionLost(self, reason):
+            self.close()
 
-    def doWrite(self):
-        self._callback(self._fd)
-if have_twisted:
-    Writer = implementer(IWriteDescriptor)(Writer)
+        def doWrite(self):
+            self._callback(self._fd)
 
 
 @skipIfNoTwisted
@@ -611,14 +609,14 @@ if have_twisted:
             test_class = import_object(test_name)
         except (ImportError, AttributeError):
             continue
-        for test_func in blacklist:
+        for test_func in blacklist:  # type: ignore
             if hasattr(test_class, test_func):
                 # The test_func may be defined in a mixin, so clobber
                 # it instead of delattr()
                 setattr(test_class, test_func, lambda self: None)
 
         def make_test_subclass(test_class):
-            class TornadoTest(test_class):
+            class TornadoTest(test_class):  # type: ignore
                 _reactors = ["tornado.platform.twisted._TestReactor"]
 
                 def setUp(self):
@@ -628,10 +626,10 @@ if have_twisted:
                     self.__curdir = os.getcwd()
                     self.__tempdir = tempfile.mkdtemp()
                     os.chdir(self.__tempdir)
-                    super(TornadoTest, self).setUp()
+                    super(TornadoTest, self).setUp()  # type: ignore
 
                 def tearDown(self):
-                    super(TornadoTest, self).tearDown()
+                    super(TornadoTest, self).tearDown()  # type: ignore
                     os.chdir(self.__curdir)
                     shutil.rmtree(self.__tempdir)
 
@@ -646,7 +644,7 @@ if have_twisted:
                     # enabled) but without our filter rules to ignore those
                     # warnings from Twisted code.
                     filtered = []
-                    for w in super(TornadoTest, self).flushWarnings(
+                    for w in super(TornadoTest, self).flushWarnings(  # type: ignore
                             *args, **kwargs):
                         if w['category'] in (BytesWarning, ResourceWarning):
                             continue
@@ -683,7 +681,7 @@ if have_twisted:
 
     # Twisted recently introduced a new logger; disable that one too.
     try:
-        from twisted.logger import globalLogBeginner
+        from twisted.logger import globalLogBeginner  # type: ignore
     except ImportError:
         pass
     else:
@@ -702,7 +700,7 @@ if have_twisted:
             # When configured to use LayeredTwistedIOLoop we can't easily
             # get the next-best IOLoop implementation, so use the lowest common
             # denominator.
-            self.real_io_loop = SelectIOLoop(make_current=False)
+            self.real_io_loop = SelectIOLoop(make_current=False)  # type: ignore
             reactor = TornadoReactor(io_loop=self.real_io_loop)
             super(LayeredTwistedIOLoop, self).initialize(reactor=reactor, **kwargs)
             self.add_callback(self.make_current)
index cfa7c81d21cb6b8d6433167a935e214f82067677..2e3d779fd1f6dfc8ede702c04cc8f44b8a300fe2 100644 (file)
@@ -12,7 +12,7 @@ from tornado.testing import bind_unused_port
 # To be used as 'from tornado.test.util import unittest'.
 if sys.version_info < (2, 7):
     # In py26, we must always use unittest2.
-    import unittest2 as unittest
+    import unittest2 as unittest  # type: ignore
 else:
     # Otherwise, use whichever version of unittest was imported in
     # tornado.testing.
@@ -72,7 +72,7 @@ def exec_test(caller_globals, caller_locals, s):
     # Flatten the real global and local namespace into our fake
     # globals: it's all global from the perspective of code defined
     # in s.
-    global_namespace = dict(caller_globals, **caller_locals)
+    global_namespace = dict(caller_globals, **caller_locals)  # type: ignore
     local_namespace = {}
     exec(textwrap.dedent(s), global_namespace, local_namespace)
     return local_namespace
index 70b6e7a1e299e3d279949c4765254f7831f6ade0..48b16f89e697276e3d445984050821e7a98b389f 100644 (file)
@@ -6,13 +6,13 @@ import datetime
 
 import tornado.escape
 from tornado.escape import utf8
-from tornado.util import raise_exc_info, Configurable, exec_in, ArgReplacer, timedelta_to_seconds, import_object, re_unescape
+from tornado.util import raise_exc_info, Configurable, exec_in, ArgReplacer, timedelta_to_seconds, import_object, re_unescape, PY3
 from tornado.test.util import unittest
 
-try:
-    from cStringIO import StringIO  # py2
-except ImportError:
-    from io import StringIO  # py3
+if PY3:
+    from io import StringIO
+else:
+    from cStringIO import StringIO
 
 
 class RaiseExcInfoTest(unittest.TestCase):
index 49049ad8616f8683c6de8ebbf1c2a816d5441a51..fac23a21fd82ec9e65062312bd29c3f74b40a3a6 100644 (file)
@@ -81,9 +81,9 @@ class CookieTestRequestHandler(RequestHandler):
         # don't call super.__init__
         self._cookies = {}
         if key_version is None:
-            self.application = ObjectDict(settings=dict(cookie_secret=cookie_secret))
+            self.application = ObjectDict(settings=dict(cookie_secret=cookie_secret))  # type: ignore
         else:
-            self.application = ObjectDict(settings=dict(cookie_secret=cookie_secret,
+            self.application = ObjectDict(settings=dict(cookie_secret=cookie_secret,  # type: ignore
                                                         key_version=key_version))
 
     def get_cookie(self, name):
@@ -2527,7 +2527,7 @@ class XSRFTest(SimpleHandlerTestCase):
 
     def test_xsrf_success_header(self):
         response = self.fetch("/", method="POST", body=b"",
-                              headers=dict({"X-Xsrftoken": self.xsrf_token},
+                              headers=dict({"X-Xsrftoken": self.xsrf_token},  # type: ignore
                                            **self.cookie_headers()))
         self.assertEqual(response.code, 200)
 
index 125d42aae6a039090c9f80d39069f2cc6b7bbfd1..5b19aad7edcbeeac12f1a3735b35b8d0d0956940 100644 (file)
@@ -76,7 +76,7 @@ class WSGIConnectionTest(httpserver_test.HTTPConnectionTest):
 def wrap_web_tests_application():
     result = {}
     for cls in web_test.wsgi_safe_tests:
-        class WSGIApplicationWrappedTest(cls):
+        class WSGIApplicationWrappedTest(cls):  # type: ignore
             def get_app(self):
                 self.app = WSGIApplication(self.get_handlers(),
                                            **self.get_app_kwargs())
@@ -89,7 +89,7 @@ globals().update(wrap_web_tests_application())
 def wrap_web_tests_adapter():
     result = {}
     for cls in web_test.wsgi_safe_tests:
-        class WSGIAdapterWrappedTest(cls):
+        class WSGIAdapterWrappedTest(cls):  # type: ignore
             def get_app(self):
                 self.app = Application(self.get_handlers(),
                                        **self.get_app_kwargs())
index e3f7ea60866fd071668d80dd406030f7d41988bc..625334220b2dd37cf65ccb9ff2e6cf020c629855 100644 (file)
@@ -23,13 +23,13 @@ try:
 except ImportError:
     # These modules are not importable on app engine.  Parts of this module
     # won't work, but e.g. LogTrapTestCase and main() will.
-    AsyncHTTPClient = None
-    gen = None
-    HTTPServer = None
-    IOLoop = None
-    netutil = None
-    SimpleAsyncHTTPClient = None
-    Subprocess = None
+    AsyncHTTPClient = None  # type: ignore
+    gen = None  # type: ignore
+    HTTPServer = None  # type: ignore
+    IOLoop = None  # type: ignore
+    netutil = None  # type: ignore
+    SimpleAsyncHTTPClient = None  # type: ignore
+    Subprocess = None  # type: ignore
 from tornado.log import gen_log, app_log
 from tornado.stack_context import ExceptionStackContext
 from tornado.util import raise_exc_info, basestring_type, PY3
@@ -48,9 +48,9 @@ else:
     from cStringIO import StringIO
 
 try:
-    from collections.abc import Generator as GeneratorType  # py35+
+    from collections.abc import Generator as GeneratorType  # type: ignore
 except ImportError:
-    from types import GeneratorType
+    from types import GeneratorType  # type: ignore
 
 if sys.version_info >= (3, 5):
     iscoroutine = inspect.iscoroutine
@@ -208,8 +208,8 @@ class AsyncTestCase(unittest.TestCase):
                 self.assertIn("FriendFeed", response.body)
                 self.stop()
     """
-    def __init__(self, methodName='runTest', **kwargs):
-        super(AsyncTestCase, self).__init__(methodName, **kwargs)
+    def __init__(self, methodName='runTest'):
+        super(AsyncTestCase, self).__init__(methodName)
         self.__stopped = False
         self.__running = False
         self.__failure = None
@@ -547,7 +547,7 @@ def gen_test(func=None, timeout=None):
 
 # Without this attribute, nosetests will try to run gen_test as a test
 # anywhere it is imported.
-gen_test.__test__ = False
+gen_test.__test__ = False  # type: ignore
 
 
 class LogTrapTestCase(unittest.TestCase):
index 54a369877dbb63cd1796aeb1ad48b90e6b002f6a..8f2acfcc93f23c235489191a0a1b4f987b647109 100644 (file)
@@ -102,6 +102,11 @@ else:
     import urlparse
     from urllib import urlencode
 
+try:
+    import typing  # noqa
+except ImportError:
+    pass
+
 
 MIN_SUPPORTED_SIGNED_VALUE_VERSION = 1
 """The oldest signed value version supported by this version of Tornado.
@@ -145,7 +150,7 @@ class RequestHandler(object):
     SUPPORTED_METHODS = ("GET", "HEAD", "POST", "DELETE", "PATCH", "PUT",
                          "OPTIONS")
 
-    _template_loaders = {}  # {path: template.BaseLoader}
+    _template_loaders = {}  # type: typing.Dict[str, template.BaseLoader]
     _template_loader_lock = threading.Lock()
     _remove_control_chars_regex = re.compile(r"[\x00-\x08\x0e-\x1f]")
 
@@ -358,7 +363,7 @@ class RequestHandler(object):
             raise ValueError("Unsafe header value %r", value)
         return value
 
-    _ARG_DEFAULT = []
+    _ARG_DEFAULT = object()
 
     def get_argument(self, name, default=_ARG_DEFAULT, strip=True):
         """Returns the value of the argument with the given name.
@@ -2238,7 +2243,7 @@ class StaticFileHandler(RequestHandler):
     """
     CACHE_MAX_AGE = 86400 * 365 * 10  # 10 years
 
-    _static_hashes = {}
+    _static_hashes = {}  # type: typing.Dict
     _lock = threading.Lock()  # protects _static_hashes
 
     def initialize(self, path, default_filename=None):