From: Ben Darnell Date: Mon, 11 Apr 2016 00:59:58 +0000 (-0400) Subject: Add type: ignore comments to make mypy happy X-Git-Tag: v4.4.0b1~30 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=b6998247702a960f0c73004a6b5f8ae775607c03;p=thirdparty%2Ftornado.git Add type: ignore comments to make mypy happy --- diff --git a/tornado/auth.py b/tornado/auth.py index 5b7657bce..44144061e 100644 --- a/tornado/auth.py +++ b/tornado/auth.py @@ -92,11 +92,6 @@ else: import urlparse import urllib as urllib_parse -try: - long # py2 -except NameError: - long = int # py3 - class AuthError(Exception): pass diff --git a/tornado/autoreload.py b/tornado/autoreload.py index 1cbf26c6c..5e0d00d1f 100644 --- a/tornado/autoreload.py +++ b/tornado/autoreload.py @@ -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): diff --git a/tornado/curl_httpclient.py b/tornado/curl_httpclient.py index 664cb492c..fa317b2da 100644 --- a/tornado/curl_httpclient.py +++ b/tornado/curl_httpclient.py @@ -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 diff --git a/tornado/gen.py b/tornado/gen.py index 29e8cb50b..8cffcc0bf 100644 --- a/tornado/gen.py +++ b/tornado/gen.py @@ -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: diff --git a/tornado/httpclient.py b/tornado/httpclient.py index c80172160..c62b6207c 100644 --- a/tornado/httpclient.py +++ b/tornado/httpclient.py @@ -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: diff --git a/tornado/httputil.py b/tornado/httputil.py index 061e71078..d0901565a 100644 --- a/tornado/httputil.py +++ b/tornado/httputil.py @@ -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: diff --git a/tornado/iostream.py b/tornado/iostream.py index 4e304f890..bcf444148 100644 --- a/tornado/iostream.py +++ b/tornado/iostream.py @@ -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): diff --git a/tornado/locale.py b/tornado/locale.py index 0a1b07709..db7411431 100644 --- a/tornado/locale.py +++ b/tornado/locale.py @@ -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" diff --git a/tornado/netutil.py b/tornado/netutil.py index b249945e8..348f3519c 100644 --- a/tornado/netutil.py +++ b/tornado/netutil.py @@ -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 diff --git a/tornado/platform/asyncio.py b/tornado/platform/asyncio.py index bf0428ec5..d5a489963 100644 --- a/tornado/platform/asyncio.py +++ b/tornado/platform/asyncio.py @@ -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 diff --git a/tornado/platform/caresresolver.py b/tornado/platform/caresresolver.py index 5559614f5..d68b3fcc4 100644 --- a/tornado/platform/caresresolver.py +++ b/tornado/platform/caresresolver.py @@ -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 diff --git a/tornado/platform/interface.py b/tornado/platform/interface.py index 07da6babd..cc0623911 100644 --- a/tornado/platform/interface.py +++ b/tornado/platform/interface.py @@ -61,3 +61,6 @@ class Waker(object): def close(self): """Closes the waker's file descriptor(s).""" raise NotImplementedError() + +def monotonic_time(): + raise NotImplementedError() diff --git a/tornado/platform/twisted.py b/tornado/platform/twisted.py index d3a4e75d1..91a335832 100644 --- a/tornado/platform/twisted.py +++ b/tornado/platform/twisted.py @@ -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() diff --git a/tornado/platform/windows.py b/tornado/platform/windows.py index 817bdca13..92295fc6c 100644 --- a/tornado/platform/windows.py +++ b/tornado/platform/windows.py @@ -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 diff --git a/tornado/process.py b/tornado/process.py index e18ebbf05..64e77c72d 100644 --- a/tornado/process.py +++ b/tornado/process.py @@ -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() diff --git a/tornado/template.py b/tornado/template.py index 499cc242c..e64b0296f 100644 --- a/tornado/template.py +++ b/tornado/template.py @@ -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) diff --git a/tornado/test/concurrent_test.py b/tornado/test/concurrent_test.py index bf90ad0ec..8ce095ec1 100644 --- a/tornado/test/concurrent_test.py +++ b/tornado/test/concurrent_test.py @@ -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) diff --git a/tornado/test/curl_httpclient_test.py b/tornado/test/curl_httpclient_test.py index 097aec3e7..b11545427 100644 --- a/tornado/test/curl_httpclient_test.py +++ b/tornado/test/curl_httpclient_test.py @@ -13,7 +13,7 @@ from tornado.web import Application, RequestHandler try: - import pycurl + import pycurl # type: ignore except ImportError: pycurl = None diff --git a/tornado/test/httpserver_test.py b/tornado/test/httpserver_test.py index 942bc4cb0..900c2c354 100644 --- a/tornado/test/httpserver_test.py +++ b/tornado/test/httpserver_test.py @@ -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): diff --git a/tornado/test/import_test.py b/tornado/test/import_test.py index 1be6427f1..a50566d0d 100644 --- a/tornado/test/import_test.py +++ b/tornado/test/import_test.py @@ -40,7 +40,7 @@ class ImportTest(unittest.TestCase): def test_import_pycurl(self): try: - import pycurl + import pycurl # type: ignore except ImportError: pass else: diff --git a/tornado/test/iostream_test.py b/tornado/test/iostream_test.py index 060f7a454..6e15136c3 100644 --- a/tornado/test/iostream_test.py +++ b/tornado/test/iostream_test.py @@ -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() diff --git a/tornado/test/netutil_test.py b/tornado/test/netutil_test.py index 9ef5f7cfe..70d969499 100644 --- a/tornado/test/netutil_test.py +++ b/tornado/test/netutil_test.py @@ -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 diff --git a/tornado/test/options_test.py b/tornado/test/options_test.py index fd2798fcd..f7b215c5a 100644 --- a/tornado/test/options_test.py +++ b/tornado/test/options_test.py @@ -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 diff --git a/tornado/test/twisted_test.py b/tornado/test/twisted_test.py index f1df06a6a..298da6c9c 100644 --- a/tornado/test/twisted_test.py +++ b/tornado/test/twisted_test.py @@ -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) diff --git a/tornado/test/util.py b/tornado/test/util.py index cfa7c81d2..2e3d779fd 100644 --- a/tornado/test/util.py +++ b/tornado/test/util.py @@ -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 diff --git a/tornado/test/util_test.py b/tornado/test/util_test.py index 70b6e7a1e..48b16f89e 100644 --- a/tornado/test/util_test.py +++ b/tornado/test/util_test.py @@ -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): diff --git a/tornado/test/web_test.py b/tornado/test/web_test.py index 49049ad86..fac23a21f 100644 --- a/tornado/test/web_test.py +++ b/tornado/test/web_test.py @@ -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) diff --git a/tornado/test/wsgi_test.py b/tornado/test/wsgi_test.py index 125d42aae..5b19aad7e 100644 --- a/tornado/test/wsgi_test.py +++ b/tornado/test/wsgi_test.py @@ -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()) diff --git a/tornado/testing.py b/tornado/testing.py index e3f7ea608..625334220 100644 --- a/tornado/testing.py +++ b/tornado/testing.py @@ -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): diff --git a/tornado/web.py b/tornado/web.py index 54a369877..8f2acfcc9 100644 --- a/tornado/web.py +++ b/tornado/web.py @@ -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):