mypy: Remove type: ignores not needed in Python 3.

This commit is contained in:
Tim Abbott 2017-08-25 11:01:20 -07:00
parent 55f0555c8d
commit b8e7369dee
18 changed files with 31 additions and 64 deletions

View File

@ -61,7 +61,7 @@ def get_old_conf(output_filename):
secrets_file = six.moves.configparser.RawConfigParser() secrets_file = six.moves.configparser.RawConfigParser()
secrets_file.read(output_filename) secrets_file.read(output_filename)
return dict(secrets_file.items("secrets")) # type: ignore # likely typeshed issue return dict(secrets_file.items("secrets"))
def generate_secrets(development=False): def generate_secrets(development=False):
# type: (bool) -> None # type: (bool) -> None

View File

@ -19,6 +19,6 @@ except IndexError:
''') ''')
sys.exit(1) sys.exit(1)
p = pstats.Stats(fn) # type: ignore # stats stubs are broken p = pstats.Stats(fn)
p.strip_dirs().sort_stats('cumulative').print_stats(25) # type: ignore # stats stubs are broken p.strip_dirs().sort_stats('cumulative').print_stats(25) # type: ignore # stats stubs are broken
p.strip_dirs().sort_stats('time').print_stats(25) # type: ignore # stats stubs are broken p.strip_dirs().sort_stats('time').print_stats(25) # type: ignore # stats stubs are broken

View File

@ -150,7 +150,7 @@ def block_internet():
"https://zulip.readthedocs.io/en/latest/testing.html#internet-access-inside-test-suits") "https://zulip.readthedocs.io/en/latest/testing.html#internet-access-inside-test-suits")
httplib2.Http.request = internet_guard httplib2.Http.request = internet_guard
requests.request = internet_guard # type: ignore # mypy bug; see our #6017 requests.request = internet_guard
if __name__ == "__main__": if __name__ == "__main__":
block_internet() block_internet()

View File

@ -38,7 +38,7 @@ if __name__ == '__main__':
suite = loader.discover(start_dir=tools_test_dir, top_level_dir=root_dir) suite = loader.discover(start_dir=tools_test_dir, top_level_dir=root_dir)
runner = unittest.TextTestRunner(verbosity=2) runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(suite) # type: ignore # https://github.com/python/typeshed/issues/372 result = runner.run(suite)
if result.errors or result.failures: if result.errors or result.failures:
raise Exception('Test failed!') raise Exception('Test failed!')

View File

@ -19,14 +19,6 @@ except ImportError:
sys.exit(1) sys.exit(1)
class ParserTestHappyPath(unittest.TestCase): class ParserTestHappyPath(unittest.TestCase):
def __init__(self, *args, **kwargs):
# type: (*Any, **Any) -> None
# This method should be removed when we migrate to version 3 of Python
import six
if six.PY2:
self.assertRaisesRegex = self.assertRaisesRegexp # type: ignore
super(ParserTestHappyPath, self).__init__(*args, **kwargs)
def test_basic_parse(self): def test_basic_parse(self):
# type: () -> None # type: () -> None
my_selector = 'li.foo' my_selector = 'li.foo'
@ -170,14 +162,6 @@ class ParserTestSadPath(unittest.TestCase):
of selectors. Some of this is just for expediency; of selectors. Some of this is just for expediency;
some of this is to enforce consistent formatting. some of this is to enforce consistent formatting.
''' '''
def __init__(self, *args, **kwargs):
# type: (*Any, **Any) -> None
# This method should be removed when we migrate to version 3 of Python
import six
if six.PY2:
self.assertRaisesRegex = self.assertRaisesRegexp # type: ignore
super(ParserTestSadPath, self).__init__(*args, **kwargs)
def _assert_error(self, my_css, error): def _assert_error(self, my_css, error):
# type: (str, str) -> None # type: (str, str) -> None
with self.assertRaisesRegex(CssParserException, error): with self.assertRaisesRegex(CssParserException, error):

View File

@ -18,14 +18,6 @@ except ImportError:
sys.exit(1) sys.exit(1)
class ParserTest(unittest.TestCase): class ParserTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
# type: (*Any, **Any) -> None
# This method should be removed when we migrate to version 3 of Python
import six
if six.PY2:
self.assertRaisesRegex = self.assertRaisesRegexp # type: ignore
super(ParserTest, self).__init__(*args, **kwargs)
def _assert_validate_error(self, error, fn=None, text=None, check_indent=True): def _assert_validate_error(self, error, fn=None, text=None, check_indent=True):
# type: (str, Optional[str], Optional[str], bool) -> None # type: (str, Optional[str], Optional[str], bool) -> None
with self.assertRaisesRegex(TemplateParserException, error): with self.assertRaisesRegex(TemplateParserException, error):

View File

@ -287,7 +287,7 @@ def cache(func):
Uses a key based on the function's name, filename, and Uses a key based on the function's name, filename, and
the repr() of its arguments.""" the repr() of its arguments."""
func_uniqifier = '%s-%s' % (func.__code__.co_filename, func.__name__) # type: ignore # https://github.com/python/mypy/issues/1923 func_uniqifier = '%s-%s' % (func.__code__.co_filename, func.__name__)
@wraps(func) @wraps(func)
def keyfunc(*args, **kwargs): def keyfunc(*args, **kwargs):

View File

@ -10,7 +10,7 @@ class AbstractEnum(Enum):
def __new__(cls): def __new__(cls):
# type: (Type[AbstractEnum]) -> AbstractEnum # type: (Type[AbstractEnum]) -> AbstractEnum
obj = object.__new__(cls) obj = object.__new__(cls)
obj._value_ = len(cls.__members__) + 1 # type: ignore # typeshed enum missing Enum.__members__ obj._value_ = len(cls.__members__) + 1
return obj return obj
# Override all the `Enum` methods that use `_value_`. # Override all the `Enum` methods that use `_value_`.
@ -144,7 +144,7 @@ class JsonableError(Exception):
def __str__(self): def __str__(self):
# type: () -> str # type: () -> str
return self.msg # type: ignore # remove once py3-only return self.msg
class RateLimited(PermissionDenied): class RateLimited(PermissionDenied):
def __init__(self, msg=""): def __init__(self, msg=""):

View File

@ -180,7 +180,7 @@ def stdout_suppressed():
"""Redirect stdout to /dev/null.""" """Redirect stdout to /dev/null."""
with open(os.devnull, 'a') as devnull: with open(os.devnull, 'a') as devnull:
stdout, sys.stdout = sys.stdout, devnull # type: ignore # monkey-patching stdout, sys.stdout = sys.stdout, devnull
yield stdout yield stdout
sys.stdout = stdout sys.stdout = stdout

View File

@ -256,7 +256,7 @@ def run_subsuite(args):
# type of Partial is different from Callable. All the methods of # type of Partial is different from Callable. All the methods of
# TestResult are passed TestCase as the first argument but # TestResult are passed TestCase as the first argument but
# addInstrumentation does not need it. # addInstrumentation does not need it.
process_instrumented_calls(partial(result.addInstrumentation, None)) # type: ignore process_instrumented_calls(partial(result.addInstrumentation, None))
return subsuite_index, result.events return subsuite_index, result.events
# Monkey-patch database creation to fix unnecessary sleep(1) # Monkey-patch database creation to fix unnecessary sleep(1)
@ -365,7 +365,7 @@ class TestSuite(unittest.TestSuite):
if getattr(result, '_testRunEntered', False) is False: if getattr(result, '_testRunEntered', False) is False:
result._testRunEntered = topLevel = True result._testRunEntered = topLevel = True
for test in self: # type: ignore # Mypy cannot recognize this for test in self:
# but this is correct. Taken from unittest. # but this is correct. Taken from unittest.
if result.shouldStop: if result.shouldStop:
break break
@ -503,7 +503,7 @@ def get_test_names(suite):
def get_tests_from_suite(suite): def get_tests_from_suite(suite):
# type: (TestSuite) -> TestCase # type: (TestSuite) -> TestCase
for test in suite: # type: ignore for test in suite:
if isinstance(test, TestSuite): if isinstance(test, TestSuite):
for child in get_tests_from_suite(test): for child in get_tests_from_suite(test):
yield child yield child

View File

@ -43,7 +43,7 @@ class AddHeaderMixin(object):
ret_dict[path] = (path, path, True) ret_dict[path] = (path, path, True)
super_class = super(AddHeaderMixin, self) # type: ignore # https://github.com/JukkaL/mypy/issues/857 super_class = super(AddHeaderMixin, self)
if hasattr(super_class, 'post_process'): if hasattr(super_class, 'post_process'):
super_ret = super_class.post_process(paths, dry_run, **kwargs) # type: ignore # https://github.com/python/mypy/issues/2956 super_ret = super_class.post_process(paths, dry_run, **kwargs) # type: ignore # https://github.com/python/mypy/issues/2956
else: else:
@ -73,7 +73,7 @@ class RemoveUnminifiedFilesMixin(object):
is_valid = lambda p: all([not p.startswith(k) for k in to_remove]) is_valid = lambda p: all([not p.startswith(k) for k in to_remove])
paths = {k: v for k, v in paths.items() if is_valid(k)} paths = {k: v for k, v in paths.items() if is_valid(k)}
super_class = super(RemoveUnminifiedFilesMixin, self) # type: ignore # https://github.com/JukkaL/mypy/issues/857 super_class = super(RemoveUnminifiedFilesMixin, self)
if hasattr(super_class, 'post_process'): if hasattr(super_class, 'post_process'):
return super_class.post_process(paths, dry_run, **kwargs) # type: ignore # https://github.com/python/mypy/issues/2956 return super_class.post_process(paths, dry_run, **kwargs) # type: ignore # https://github.com/python/mypy/issues/2956

View File

@ -8,7 +8,7 @@ from django.test import override_settings
from sqlalchemy.sql import ( from sqlalchemy.sql import (
and_, select, column, table, and_, select, column, table,
) )
from sqlalchemy.sql import compiler # type: ignore from sqlalchemy.sql import compiler
from zerver.models import ( from zerver.models import (
Realm, Recipient, Stream, Subscription, UserProfile, Attachment, Realm, Recipient, Stream, Subscription, UserProfile, Attachment,
@ -50,7 +50,7 @@ import ujson
def get_sqlalchemy_query_params(query): def get_sqlalchemy_query_params(query):
# type: (Text) -> Dict[Text, Text] # type: (Text) -> Dict[Text, Text]
dialect = get_sqlalchemy_connection().dialect # type: ignore dialect = get_sqlalchemy_connection().dialect
comp = compiler.SQLCompiler(dialect, query) comp = compiler.SQLCompiler(dialect, query)
return comp.params return comp.params

View File

@ -256,7 +256,7 @@ class PushNotificationTest(BouncerTestCase):
super(PushNotificationTest, self).setUp() super(PushNotificationTest, self).setUp()
self.user_profile = self.example_user('hamlet') self.user_profile = self.example_user('hamlet')
apn.connection = apn.get_connection('fake-cert', 'fake-key') apn.connection = apn.get_connection('fake-cert', 'fake-key')
self.redis_client = apn.redis_client = MockRedis() # type: ignore self.redis_client = apn.redis_client = MockRedis()
self.tokens = [u'aaaa', u'bbbb'] self.tokens = [u'aaaa', u'bbbb']
for token in self.tokens: for token in self.tokens:
PushDeviceToken.objects.create( PushDeviceToken.objects.create(

View File

@ -49,7 +49,7 @@ class TypesPrintTest(TestCase):
def empty_func(): def empty_func():
# type: () -> None # type: () -> None
pass pass
self.check_signature("empty_func() -> None", None, empty_func) # type: ignore # https://github.com/python/mypy/issues/1932 self.check_signature("empty_func() -> None", None, empty_func)
self.check_signature("<lambda>() -> None", None, (lambda: None)) # type: ignore # https://github.com/python/mypy/issues/1932 self.check_signature("<lambda>() -> None", None, (lambda: None)) # type: ignore # https://github.com/python/mypy/issues/1932
def test_basic(self): def test_basic(self):

View File

@ -18,7 +18,7 @@ def setup_tornado_rabbitmq():
if settings.USING_RABBITMQ: if settings.USING_RABBITMQ:
queue_client = get_queue_client() queue_client = get_queue_client()
atexit.register(lambda: queue_client.close()) atexit.register(lambda: queue_client.close())
tornado.autoreload.add_reload_hook(lambda: queue_client.close()) # type: ignore # TODO: Fix missing tornado.autoreload stub tornado.autoreload.add_reload_hook(lambda: queue_client.close())
def create_tornado_application(): def create_tornado_application():
# type: () -> tornado.web.Application # type: () -> tornado.web.Application

View File

@ -473,7 +473,7 @@ def setup_event_queue():
atexit.register(dump_event_queues) atexit.register(dump_event_queues)
# Make sure we dump event queues even if we exit via signal # Make sure we dump event queues even if we exit via signal
signal.signal(signal.SIGTERM, lambda signum, stack: sys.exit(1)) signal.signal(signal.SIGTERM, lambda signum, stack: sys.exit(1))
tornado.autoreload.add_reload_hook(dump_event_queues) # type: ignore # TODO: Fix missing tornado.autoreload stub tornado.autoreload.add_reload_hook(dump_event_queues)
try: try:
os.rename(settings.JSON_PERSISTENT_QUEUE_FILENAME, "/var/tmp/event_queues.json.last") os.rename(settings.JSON_PERSISTENT_QUEUE_FILENAME, "/var/tmp/event_queues.json.last")

View File

@ -8,28 +8,19 @@ import select
from tornado import ioloop from tornado import ioloop
from django.conf import settings from django.conf import settings
try: from tornado.ioloop import IOLoop, PollIOLoop
# Tornado 2.4 # There isn't a good way to get at what the underlying poll implementation
orig_poll_impl = ioloop._poll # type: ignore # cross-version type variation is hard for mypy # will be without actually constructing an IOLoop, so we just assume it will
# be epoll.
orig_poll_impl = select.epoll
def instrument_tornado_ioloop(): class InstrumentedPollIOLoop(PollIOLoop):
# type: () -> None def initialize(self, **kwargs): # type: ignore # TODO investigate likely buggy monkey patching here
ioloop._poll = InstrumentedPoll # type: ignore # cross-version type variation is hard for mypy super(InstrumentedPollIOLoop, self).initialize(impl=InstrumentedPoll(), **kwargs)
except Exception:
# Tornado 3
from tornado.ioloop import IOLoop, PollIOLoop
# There isn't a good way to get at what the underlying poll implementation
# will be without actually constructing an IOLoop, so we just assume it will
# be epoll.
orig_poll_impl = select.epoll
class InstrumentedPollIOLoop(PollIOLoop): def instrument_tornado_ioloop():
def initialize(self, **kwargs): # type: ignore # TODO investigate likely buggy monkey patching here # type: () -> None
super(InstrumentedPollIOLoop, self).initialize(impl=InstrumentedPoll(), **kwargs) IOLoop.configure(InstrumentedPollIOLoop)
def instrument_tornado_ioloop():
# type: () -> None
IOLoop.configure(InstrumentedPollIOLoop)
# A hack to keep track of how much time we spend working, versus sleeping in # A hack to keep track of how much time we spend working, versus sleeping in
# the event loop. # the event loop.

View File

@ -24,7 +24,7 @@ def environment(**options):
'minified_js': minified_js, 'minified_js': minified_js,
}) })
env.install_gettext_translations(translation, True) # type: ignore # https://github.com/python/typeshed/issues/927 env.install_gettext_translations(translation, True)
env.filters['slugify'] = slugify env.filters['slugify'] = slugify
env.filters['pluralize'] = pluralize env.filters['pluralize'] = pluralize