refactor: Replace super(.*self) with Python 3-specific super().

We change all the instances except for the `test_helpers.py`
TimeTrackingCursor monkey-patching, which actually needs to specify
the base class.
This commit is contained in:
rht 2017-10-27 08:28:23 +02:00 committed by Tim Abbott
parent d140451fb4
commit c4fcff7178
32 changed files with 68 additions and 68 deletions

View File

@ -298,7 +298,7 @@ class TestProcessCountStat(AnalyticsTestCase):
class TestCountStats(AnalyticsTestCase): class TestCountStats(AnalyticsTestCase):
def setUp(self): def setUp(self):
# type: () -> None # type: () -> None
super(TestCountStats, self).setUp() super().setUp()
# This tests two things for each of the queries/CountStats: Handling # This tests two things for each of the queries/CountStats: Handling
# more than 1 realm, and the time bounds (time_start and time_end in # more than 1 realm, and the time bounds (time_start and time_end in
# the queries). # the queries).
@ -812,7 +812,7 @@ class TestDeleteStats(AnalyticsTestCase):
class TestActiveUsersAudit(AnalyticsTestCase): class TestActiveUsersAudit(AnalyticsTestCase):
def setUp(self): def setUp(self):
# type: () -> None # type: () -> None
super(TestActiveUsersAudit, self).setUp() super().setUp()
self.user = self.create_user() self.user = self.create_user()
self.stat = COUNT_STATS['active_users_audit:is_bot:day'] self.stat = COUNT_STATS['active_users_audit:is_bot:day']
self.current_property = self.stat.property self.current_property = self.stat.property
@ -975,7 +975,7 @@ class TestActiveUsersAudit(AnalyticsTestCase):
class TestRealmActiveHumans(AnalyticsTestCase): class TestRealmActiveHumans(AnalyticsTestCase):
def setUp(self): def setUp(self):
# type: () -> None # type: () -> None
super(TestRealmActiveHumans, self).setUp() super().setUp()
self.stat = COUNT_STATS['realm_active_humans::day'] self.stat = COUNT_STATS['realm_active_humans::day']
self.current_property = self.stat.property self.current_property = self.stat.property

View File

@ -30,7 +30,7 @@ class ConfirmationKeyException(Exception):
def __init__(self, error_type): def __init__(self, error_type):
# type: (int) -> None # type: (int) -> None
super(ConfirmationKeyException, self).__init__() super().__init__()
self.error_type = error_type self.error_type = error_type
def render_confirmation_key_error(request, exception): def render_confirmation_key_error(request, exception):

View File

@ -92,7 +92,7 @@ To fix them run './manage.py makemigrations --merge'
<output skipped> <output skipped>
File "/srv/zulip/zerver/lib/db.py", line 33, in execute File "/srv/zulip/zerver/lib/db.py", line 33, in execute
return wrapper_execute(self, super(TimeTrackingCursor, self).execute, query, vars) return wrapper_execute(self, super().execute, query, vars)
File "/srv/zulip/zerver/lib/db.py", line 20, in wrapper_execute File "/srv/zulip/zerver/lib/db.py", line 20, in wrapper_execute
return action(sql, params) return action(sql, params)
django.db.utils.ProgrammingError: relation "zerver_realmfilter" does not exist django.db.utils.ProgrammingError: relation "zerver_realmfilter" does not exist

View File

@ -24,7 +24,7 @@ class HelpDocumentationSpider(BaseDocumentationSpider):
help_images_static_dir = get_help_images_dir(help_images_path) help_images_static_dir = get_help_images_dir(help_images_path)
def __init__(self, *args: Any, **kwargs: Any) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None:
super(HelpDocumentationSpider, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.static_images = set() # type: Set self.static_images = set() # type: Set
def _is_external_url(self, url: str) -> bool: def _is_external_url(self, url: str) -> bool:

View File

@ -30,7 +30,7 @@ class BaseDocumentationSpider(scrapy.Spider):
attrs = ('href', 'src') attrs = ('href', 'src')
def __init__(self, *args: Any, **kwargs: Any) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None:
super(BaseDocumentationSpider, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.has_error = False self.has_error = False
def _set_error_state(self) -> None: def _set_error_state(self) -> None:

View File

@ -199,14 +199,14 @@ class BaseWebsocketHandler(WebSocketHandler):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
# type: (*Any, **Any) -> None # type: (*Any, **Any) -> None
super(BaseWebsocketHandler, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
# define client for target websocket server # define client for target websocket server
self.client = None # type: Any self.client = None # type: Any
def get(self, *args, **kwargs): def get(self, *args, **kwargs):
# type: (*Any, **Any) -> Optional[Callable] # type: (*Any, **Any) -> Optional[Callable]
# use get method from WebsocketHandler # use get method from WebsocketHandler
return super(BaseWebsocketHandler, self).get(*args, **kwargs) return super().get(*args, **kwargs)
def open(self): def open(self):
# type: () -> None # type: () -> None
@ -262,7 +262,7 @@ class CombineHandler(BaseWebsocketHandler):
def get(self, *args, **kwargs): def get(self, *args, **kwargs):
# type: (*Any, **Any) -> Optional[Callable] # type: (*Any, **Any) -> Optional[Callable]
if self.request.headers.get("Upgrade", "").lower() == 'websocket': if self.request.headers.get("Upgrade", "").lower() == 'websocket':
return super(CombineHandler, self).get(*args, **kwargs) return super().get(*args, **kwargs)
return None return None
def head(self): def head(self):
@ -314,7 +314,7 @@ class CombineHandler(BaseWebsocketHandler):
if 'X-REAL-IP' not in self.request.headers: if 'X-REAL-IP' not in self.request.headers:
self.request.headers['X-REAL-IP'] = self.request.remote_ip self.request.headers['X-REAL-IP'] = self.request.remote_ip
if self.request.headers.get("Upgrade", "").lower() == 'websocket': if self.request.headers.get("Upgrade", "").lower() == 'websocket':
return super(CombineHandler, self).prepare() return super().prepare()
url = transform_url( url = transform_url(
self.request.protocol, self.request.protocol,
self.request.path, self.request.path,
@ -363,12 +363,12 @@ class Application(web.Application):
(r"/sockjs.*", TornadoHandler), (r"/sockjs.*", TornadoHandler),
(r"/.*", DjangoHandler) (r"/.*", DjangoHandler)
] ]
super(Application, self).__init__(handlers, enable_logging=enable_logging) super().__init__(handlers, enable_logging=enable_logging)
def log_request(self, handler): def log_request(self, handler):
# type: (BaseWebsocketHandler) -> None # type: (BaseWebsocketHandler) -> None
if self.settings['enable_logging']: if self.settings['enable_logging']:
super(Application, self).log_request(handler) super().log_request(handler)
def on_shutdown(): def on_shutdown():

View File

@ -94,7 +94,7 @@ class RegistrationForm(forms.Form):
self.realm_creation = kwargs['realm_creation'] self.realm_creation = kwargs['realm_creation']
del kwargs['realm_creation'] del kwargs['realm_creation']
super(RegistrationForm, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
if settings.TERMS_OF_SERVICE: if settings.TERMS_OF_SERVICE:
self.fields['terms'] = forms.BooleanField(required=True) self.fields['terms'] = forms.BooleanField(required=True)
self.fields['realm_name'] = forms.CharField( self.fields['realm_name'] = forms.CharField(
@ -131,7 +131,7 @@ class HomepageForm(forms.Form):
# type: (*Any, **Any) -> None # type: (*Any, **Any) -> None
self.realm = kwargs.pop('realm', None) self.realm = kwargs.pop('realm', None)
self.from_multiuse_invite = kwargs.pop('from_multiuse_invite', False) self.from_multiuse_invite = kwargs.pop('from_multiuse_invite', False)
super(HomepageForm, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
def clean_email(self): def clean_email(self):
# type: () -> str # type: () -> str
@ -331,7 +331,7 @@ class MultiEmailField(forms.Field):
def validate(self, emails): def validate(self, emails):
# type: (List[Text]) -> None # type: (List[Text]) -> None
"""Check if value consists only of valid emails.""" """Check if value consists only of valid emails."""
super(MultiEmailField, self).validate(emails) super().validate(emails)
for email in emails: for email in emails:
validate_email(email) validate_email(email)

View File

@ -1034,7 +1034,7 @@ class UListProcessor(markdown.blockprocessors.UListProcessor):
# this class, so that bulleted lists (and only bulleted lists) # this class, so that bulleted lists (and only bulleted lists)
# work off 2-space indentation. # work off 2-space indentation.
parser.markdown.tab_length = 2 parser.markdown.tab_length = 2
super(UListProcessor, self).__init__(parser) super().__init__(parser)
parser.markdown.tab_length = 4 parser.markdown.tab_length = 4
class ListIndentProcessor(markdown.blockprocessors.ListIndentProcessor): class ListIndentProcessor(markdown.blockprocessors.ListIndentProcessor):
@ -1050,7 +1050,7 @@ class ListIndentProcessor(markdown.blockprocessors.ListIndentProcessor):
# this class, so that bulleted lists (and only bulleted lists) # this class, so that bulleted lists (and only bulleted lists)
# work off 2-space indentation. # work off 2-space indentation.
parser.markdown.tab_length = 2 parser.markdown.tab_length = 2
super(ListIndentProcessor, self).__init__(parser) super().__init__(parser)
parser.markdown.tab_length = 4 parser.markdown.tab_length = 4
class BugdownUListPreprocessor(markdown.preprocessors.Preprocessor): class BugdownUListPreprocessor(markdown.preprocessors.Preprocessor):
@ -1260,7 +1260,7 @@ class Bugdown(markdown.Extension):
"realm": [kwargs['realm'], "Realm name"] "realm": [kwargs['realm'], "Realm name"]
} }
super(Bugdown, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
def extendMarkdown(self, md, md_globals): def extendMarkdown(self, md, md_globals):
# type: (markdown.Markdown, Dict[str, Any]) -> None # type: (markdown.Markdown, Dict[str, Any]) -> None

View File

@ -28,11 +28,11 @@ class TimeTrackingCursor(cursor):
def execute(self, query, vars=None): def execute(self, query, vars=None):
# type: (NonBinaryStr, Optional[ParamsT]) -> TimeTrackingCursor # type: (NonBinaryStr, Optional[ParamsT]) -> TimeTrackingCursor
return wrapper_execute(self, super(TimeTrackingCursor, self).execute, query, vars) return wrapper_execute(self, super().execute, query, vars)
def executemany(self, query, vars): def executemany(self, query, vars):
# type: (NonBinaryStr, Iterable[Any]) -> TimeTrackingCursor # type: (NonBinaryStr, Iterable[Any]) -> TimeTrackingCursor
return wrapper_execute(self, super(TimeTrackingCursor, self).executemany, query, vars) return wrapper_execute(self, super().executemany, query, vars)
class TimeTrackingConnection(connection): class TimeTrackingConnection(connection):
"""A psycopg2 connection class that uses TimeTrackingCursors.""" """A psycopg2 connection class that uses TimeTrackingCursors."""
@ -40,7 +40,7 @@ class TimeTrackingConnection(connection):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
# type: (*Any, **Any) -> None # type: (*Any, **Any) -> None
self.queries = [] # type: List[Dict[str, str]] self.queries = [] # type: List[Dict[str, str]]
super(TimeTrackingConnection, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
def cursor(self, *args, **kwargs): def cursor(self, *args, **kwargs):
# type: (*Any, **Any) -> TimeTrackingCursor # type: (*Any, **Any) -> TimeTrackingCursor

View File

@ -149,4 +149,4 @@ class JsonableError(Exception):
class RateLimited(PermissionDenied): class RateLimited(PermissionDenied):
def __init__(self, msg=""): def __init__(self, msg=""):
# type: (str) -> None # type: (str) -> None
super(RateLimited, self).__init__(msg) super().__init__(msg)

View File

@ -118,7 +118,7 @@ class BotIntegration(Integration):
def __init__(self, name, categories, logo=None, secondary_line_text=None, def __init__(self, name, categories, logo=None, secondary_line_text=None,
display_name=None, doc=None): display_name=None, doc=None):
# type: (str, List[str], Optional[str], Optional[str], Optional[str], Optional[str]) -> None # type: (str, List[str], Optional[str], Optional[str], Optional[str], Optional[str]) -> None
super(BotIntegration, self).__init__( super().__init__(
name, name,
client_name=name, client_name=name,
categories=categories, categories=categories,
@ -160,7 +160,7 @@ class WebhookIntegration(Integration):
# type: (str, List[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[bool]) -> None # type: (str, List[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[bool]) -> None
if client_name is None: if client_name is None:
client_name = self.DEFAULT_CLIENT_NAME.format(name=name.title()) client_name = self.DEFAULT_CLIENT_NAME.format(name=name.title())
super(WebhookIntegration, self).__init__( super().__init__(
name, name,
client_name, client_name,
categories, categories,
@ -205,7 +205,7 @@ class HubotLozenge(Integration):
if git_url is None: if git_url is None:
git_url = self.GIT_URL_TEMPLATE.format(name) git_url = self.GIT_URL_TEMPLATE.format(name)
self.git_url = git_url self.git_url = git_url
super(HubotLozenge, self).__init__( super().__init__(
name, name, categories, name, name, categories,
logo=logo, display_name=display_name, logo=logo, display_name=display_name,
legacy=legacy legacy=legacy
@ -221,7 +221,7 @@ class GithubIntegration(WebhookIntegration):
# type: (str, List[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[bool]) -> None # type: (str, List[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[bool]) -> None
url = self.DEFAULT_URL.format(name='github') url = self.DEFAULT_URL.format(name='github')
super(GithubIntegration, self).__init__( super().__init__(
name, name,
categories, categories,
client_name=client_name, client_name=client_name,
@ -251,7 +251,7 @@ class EmbeddedBotIntegration(Integration):
# type: (str, *Any, **Any) -> None # type: (str, *Any, **Any) -> None
assert kwargs.get("client_name") is None assert kwargs.get("client_name") is None
client_name = self.DEFAULT_CLIENT_NAME.format(name=name.title()) client_name = self.DEFAULT_CLIENT_NAME.format(name=name.title())
super(EmbeddedBotIntegration, self).__init__( super().__init__(
name, client_name, *args, **kwargs) name, client_name, *args, **kwargs)
EMBEDDED_BOTS = [ EMBEDDED_BOTS = [

View File

@ -177,7 +177,7 @@ class ExceptionFreeTornadoConnection(pika.adapters.TornadoConnection):
def _adapter_disconnect(self): def _adapter_disconnect(self):
# type: () -> None # type: () -> None
try: try:
super(ExceptionFreeTornadoConnection, self)._adapter_disconnect() super()._adapter_disconnect()
except (pika.exceptions.ProbableAuthenticationError, except (pika.exceptions.ProbableAuthenticationError,
pika.exceptions.ProbableAccessDeniedError, pika.exceptions.ProbableAccessDeniedError,
pika.exceptions.IncompatibleProtocolError) as e: pika.exceptions.IncompatibleProtocolError) as e:
@ -190,7 +190,7 @@ class TornadoQueueClient(SimpleQueueClient):
# https://pika.readthedocs.io/en/0.9.8/examples/asynchronous_consumer_example.html # https://pika.readthedocs.io/en/0.9.8/examples/asynchronous_consumer_example.html
def __init__(self): def __init__(self):
# type: () -> None # type: () -> None
super(TornadoQueueClient, self).__init__() super().__init__()
# Enable rabbitmq heartbeat since TornadoConection can process them # Enable rabbitmq heartbeat since TornadoConection can process them
self.rabbitmq_heartbeat = None self.rabbitmq_heartbeat = None
self._on_open_cbs = [] # type: List[Callable[[], None]] self._on_open_cbs = [] # type: List[Callable[[], None]]

View File

@ -175,7 +175,7 @@ class TextTestResult(runner.TextTestResult):
""" """
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
# type: (*Any, **Any) -> None # type: (*Any, **Any) -> None
super(TextTestResult, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.failed_tests = [] # type: List[str] self.failed_tests = [] # type: List[str]
def addInfo(self, test, msg): def addInfo(self, test, msg):
@ -400,7 +400,7 @@ class ParallelTestSuite(django_runner.ParallelTestSuite):
def __init__(self, suite, processes, failfast): def __init__(self, suite, processes, failfast):
# type: (TestSuite, int, bool) -> None # type: (TestSuite, int, bool) -> None
super(ParallelTestSuite, self).__init__(suite, processes, failfast) super().__init__(suite, processes, failfast)
self.subsuites = SubSuiteList(self.subsuites) # type: SubSuiteList self.subsuites = SubSuiteList(self.subsuites) # type: SubSuiteList
class Runner(DiscoverRunner): class Runner(DiscoverRunner):
@ -445,7 +445,7 @@ class Runner(DiscoverRunner):
settings.DATABASES['default']['NAME'] = settings.BACKEND_DATABASE_TEMPLATE settings.DATABASES['default']['NAME'] = settings.BACKEND_DATABASE_TEMPLATE
# We create/destroy the test databases in run_tests to avoid # We create/destroy the test databases in run_tests to avoid
# duplicate work when running in parallel mode. # duplicate work when running in parallel mode.
return super(Runner, self).setup_test_environment(*args, **kwargs) return super().setup_test_environment(*args, **kwargs)
def teardown_test_environment(self, *args, **kwargs): def teardown_test_environment(self, *args, **kwargs):
# type: (*Any, **Any) -> Any # type: (*Any, **Any) -> Any
@ -456,7 +456,7 @@ class Runner(DiscoverRunner):
# destroy settings.BACKEND_DATABASE_TEMPLATE; we don't want that. # destroy settings.BACKEND_DATABASE_TEMPLATE; we don't want that.
# So run this only in serial mode. # So run this only in serial mode.
destroy_test_databases() destroy_test_databases()
return super(Runner, self).teardown_test_environment(*args, **kwargs) return super().teardown_test_environment(*args, **kwargs)
def run_tests(self, test_labels, extra_tests=None, def run_tests(self, test_labels, extra_tests=None,
full_suite=False, **kwargs): full_suite=False, **kwargs):
@ -533,9 +533,9 @@ class SubSuiteList(list):
def __init__(self, suites): def __init__(self, suites):
# type: (List[TestSuite]) -> None # type: (List[TestSuite]) -> None
serialized_suites = [serialize_suite(s) for s in suites] serialized_suites = [serialize_suite(s) for s in suites]
super(SubSuiteList, self).__init__(serialized_suites) super().__init__(serialized_suites)
def __getitem__(self, index): def __getitem__(self, index):
# type: (Any) -> Any # type: (Any) -> Any
suite = super(SubSuiteList, self).__getitem__(index) suite = super().__getitem__(index)
return deserialize_suite(suite) return deserialize_suite(suite)

View File

@ -25,7 +25,7 @@ class Command(compilemessages.Command):
# version # version
settings.STATIC_ROOT = os.path.join(settings.DEPLOY_ROOT, "static") settings.STATIC_ROOT = os.path.join(settings.DEPLOY_ROOT, "static")
settings.LOCALE_PATHS = (os.path.join(settings.DEPLOY_ROOT, 'static/locale'),) settings.LOCALE_PATHS = (os.path.join(settings.DEPLOY_ROOT, 'static/locale'),)
super(Command, self).handle(*args, **options) super().handle(*args, **options)
self.extract_language_options() self.extract_language_options()
self.create_language_name_map() self.create_language_name_map()

View File

@ -84,7 +84,7 @@ class Command(ZulipBaseCommand):
# Fix support for multi-line usage # Fix support for multi-line usage
def create_parser(self, *args: Any, **kwargs: Any) -> ArgumentParser: def create_parser(self, *args: Any, **kwargs: Any) -> ArgumentParser:
parser = super(Command, self).create_parser(*args, **kwargs) parser = super().create_parser(*args, **kwargs)
parser.formatter_class = RawTextHelpFormatter parser.formatter_class = RawTextHelpFormatter
return parser return parser

View File

@ -19,7 +19,7 @@ class Command(BaseCommand):
# Fix support for multi-line usage # Fix support for multi-line usage
def create_parser(self, *args: Any, **kwargs: Any) -> ArgumentParser: def create_parser(self, *args: Any, **kwargs: Any) -> ArgumentParser:
parser = super(Command, self).create_parser(*args, **kwargs) parser = super().create_parser(*args, **kwargs)
parser.formatter_class = RawTextHelpFormatter parser.formatter_class = RawTextHelpFormatter
return parser return parser

View File

@ -71,7 +71,7 @@ def strip_whitespaces(src: Text) -> Text:
class Command(makemessages.Command): class Command(makemessages.Command):
def add_arguments(self, parser: ArgumentParser) -> None: def add_arguments(self, parser: ArgumentParser) -> None:
super(Command, self).add_arguments(parser) super().add_arguments(parser)
parser.add_argument('--frontend-source', type=str, parser.add_argument('--frontend-source', type=str,
default='static/templates', default='static/templates',
help='Name of the Handlebars template directory') help='Name of the Handlebars template directory')
@ -123,7 +123,7 @@ class Command(makemessages.Command):
ignore_patterns = options.get('ignore_patterns', []) ignore_patterns = options.get('ignore_patterns', [])
ignore_patterns.append('docs/*') ignore_patterns.append('docs/*')
options['ignore_patterns'] = ignore_patterns options['ignore_patterns'] = ignore_patterns
super(Command, self).handle(*args, **options) super().handle(*args, **options)
finally: finally:
template.endblock_re = old_endblock_re template.endblock_re = old_endblock_re
template.block_re = old_block_re template.block_re = old_block_re

View File

@ -19,7 +19,7 @@ Example: ./manage.py realm_emoji --realm=zulip.com --op=show
# Fix support for multi-line usage # Fix support for multi-line usage
def create_parser(self, *args: Any, **kwargs: Any) -> CommandParser: def create_parser(self, *args: Any, **kwargs: Any) -> CommandParser:
parser = super(Command, self).create_parser(*args, **kwargs) parser = super().create_parser(*args, **kwargs)
parser.formatter_class = RawTextHelpFormatter parser.formatter_class = RawTextHelpFormatter
return parser return parser

View File

@ -24,7 +24,7 @@ For example:
# Fix support for multi-line usage # Fix support for multi-line usage
def create_parser(self, *args: Any, **kwargs: Any) -> ArgumentParser: def create_parser(self, *args: Any, **kwargs: Any) -> ArgumentParser:
parser = super(Command, self).create_parser(*args, **kwargs) parser = super().create_parser(*args, **kwargs)
parser.formatter_class = RawTextHelpFormatter parser.formatter_class = RawTextHelpFormatter
return parser return parser

View File

@ -83,7 +83,7 @@ class Uploader(object):
class LocalUploader(Uploader): class LocalUploader(Uploader):
def __init__(self) -> None: def __init__(self) -> None:
super(LocalUploader, self).__init__() super().__init__()
@staticmethod @staticmethod
def mkdirs(path: Text) -> None: def mkdirs(path: Text) -> None:
@ -108,7 +108,7 @@ class LocalUploader(Uploader):
class S3Uploader(Uploader): class S3Uploader(Uploader):
def __init__(self) -> None: def __init__(self) -> None:
super(S3Uploader, self).__init__() super().__init__()
conn = S3Connection(settings.S3_KEY, settings.S3_SECRET_KEY) conn = S3Connection(settings.S3_KEY, settings.S3_SECRET_KEY)
bucket_name = settings.S3_AVATAR_BUCKET bucket_name = settings.S3_AVATAR_BUCKET
self.bucket = conn.get_bucket(bucket_name, validate=False) self.bucket = conn.get_bucket(bucket_name, validate=False)

View File

@ -42,7 +42,7 @@ class AddHeaderMixin(object):
ret_dict[path] = (path, path, True) ret_dict[path] = (path, path, True)
super_class = super(AddHeaderMixin, self) super_class = super()
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:
@ -72,7 +72,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) super_class = super()
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

@ -403,7 +403,7 @@ class EventsRegisterTest(ZulipTestCase):
def setUp(self): def setUp(self):
# type: () -> None # type: () -> None
super(EventsRegisterTest, self).setUp() super().setUp()
self.user_profile = self.example_user('hamlet') self.user_profile = self.example_user('hamlet')
def create_bot(self, email): def create_bot(self, email):

View File

@ -50,12 +50,12 @@ class BouncerTestCase(ZulipTestCase):
hostname="demo.example.com", hostname="demo.example.com",
last_updated=now()) last_updated=now())
server.save() server.save()
super(BouncerTestCase, self).setUp() super().setUp()
def tearDown(self): def tearDown(self):
# type: () -> None # type: () -> None
RemoteZulipServer.objects.filter(uuid=self.server_uuid).delete() RemoteZulipServer.objects.filter(uuid=self.server_uuid).delete()
super(BouncerTestCase, self).tearDown() super().tearDown()
def bounce_request(self, *args, **kwargs): def bounce_request(self, *args, **kwargs):
# type: (*Any, **Any) -> HttpResponse # type: (*Any, **Any) -> HttpResponse
@ -265,7 +265,7 @@ class PushBouncerNotificationTest(BouncerTestCase):
class PushNotificationTest(BouncerTestCase): class PushNotificationTest(BouncerTestCase):
def setUp(self): def setUp(self):
# type: () -> None # type: () -> None
super(PushNotificationTest, self).setUp() super().setUp()
self.user_profile = self.example_user('hamlet') self.user_profile = self.example_user('hamlet')
self.tokens = [u'aaaa', u'bbbb'] self.tokens = [u'aaaa', u'bbbb']
for token in self.tokens: for token in self.tokens:
@ -921,7 +921,7 @@ class TestPushApi(ZulipTestCase):
class GCMTest(PushNotificationTest): class GCMTest(PushNotificationTest):
def setUp(self): def setUp(self):
# type: () -> None # type: () -> None
super(GCMTest, self).setUp() super().setUp()
apn.gcm = gcm.GCM('fake key') apn.gcm = gcm.GCM('fake key')
self.gcm_tokens = [u'1111', u'2222'] self.gcm_tokens = [u'1111', u'2222']
for token in self.gcm_tokens: for token in self.gcm_tokens:

View File

@ -189,7 +189,7 @@ class WorkerTest(ZulipTestCase):
class TestWorker(queue_processors.QueueProcessingWorker): class TestWorker(queue_processors.QueueProcessingWorker):
def __init__(self): def __init__(self):
# type: () -> None # type: () -> None
super(TestWorker, self).__init__() super().__init__()
def consume(self, data): def consume(self, data):
# type: (Mapping[str, Any]) -> None # type: (Mapping[str, Any]) -> None
@ -203,7 +203,7 @@ class WorkerTest(ZulipTestCase):
class TestWorker(queue_processors.QueueProcessingWorker): class TestWorker(queue_processors.QueueProcessingWorker):
def __init__(self): def __init__(self):
# type: () -> None # type: () -> None
super(TestWorker, self).__init__() super().__init__()
with self.assertRaises(queue_processors.WorkerDeclarationException): with self.assertRaises(queue_processors.WorkerDeclarationException):
worker = TestWorker() worker = TestWorker()

View File

@ -19,7 +19,7 @@ class TestRetentionLib(ZulipTestCase):
def setUp(self): def setUp(self):
# type: () -> None # type: () -> None
super(TestRetentionLib, self).setUp() super().setUp()
self.zulip_realm = self._set_realm_message_retention_value('zulip', 30) self.zulip_realm = self._set_realm_message_retention_value('zulip', 30)
self.mit_realm = self._set_realm_message_retention_value('zephyr', 100) self.mit_realm = self._set_realm_message_retention_value('zephyr', 100)
@ -118,7 +118,7 @@ class TestMoveMessageToArchive(ZulipTestCase):
def setUp(self): def setUp(self):
# type: () -> None # type: () -> None
super(TestMoveMessageToArchive, self).setUp() super().setUp()
self.sender = 'hamlet@zulip.com' self.sender = 'hamlet@zulip.com'
self.recipient = 'cordelia@zulip.com' self.recipient = 'cordelia@zulip.com'

View File

@ -42,14 +42,14 @@ from typing import Any, Callable, Dict, Generator, Optional, Text, List, cast
class TornadoWebTestCase(AsyncHTTPTestCase, ZulipTestCase): class TornadoWebTestCase(AsyncHTTPTestCase, ZulipTestCase):
def setUp(self): def setUp(self):
# type: () -> None # type: () -> None
super(TornadoWebTestCase, self).setUp() super().setUp()
signals.request_started.disconnect(close_old_connections) signals.request_started.disconnect(close_old_connections)
signals.request_finished.disconnect(close_old_connections) signals.request_finished.disconnect(close_old_connections)
self.session_cookie = None # type: Optional[Dict[Text, Text]] self.session_cookie = None # type: Optional[Dict[Text, Text]]
def tearDown(self): def tearDown(self):
# type: () -> None # type: () -> None
super(TornadoWebTestCase, self).tearDown() super().tearDown()
self.session_cookie = None # type: Optional[Dict[Text, Text]] self.session_cookie = None # type: Optional[Dict[Text, Text]]
@override_settings(DEBUG=False) @override_settings(DEBUG=False)
@ -87,7 +87,7 @@ class TornadoWebTestCase(AsyncHTTPTestCase, ZulipTestCase):
def login(self, *args, **kwargs): def login(self, *args, **kwargs):
# type: (*Any, **Any) -> None # type: (*Any, **Any) -> None
super(TornadoWebTestCase, self).login(*args, **kwargs) super().login(*args, **kwargs)
session_cookie = settings.SESSION_COOKIE_NAME session_cookie = settings.SESSION_COOKIE_NAME
session_key = self.client.session.session_key session_key = self.client.session.session_key
self.session_cookie = { self.session_cookie = {
@ -157,11 +157,11 @@ class WebSocketBaseTestCase(AsyncHTTPTestCase, ZulipTestCase):
def setUp(self): def setUp(self):
# type: () -> None # type: () -> None
settings.RUNNING_INSIDE_TORNADO = True settings.RUNNING_INSIDE_TORNADO = True
super(WebSocketBaseTestCase, self).setUp() super().setUp()
def tearDown(self): def tearDown(self):
# type: () -> None # type: () -> None
super(WebSocketBaseTestCase, self).tearDown() super().tearDown()
settings.RUNNING_INSIDE_TORNADO = False settings.RUNNING_INSIDE_TORNADO = False
@gen.coroutine @gen.coroutine

View File

@ -77,7 +77,7 @@ class AsyncDjangoHandler(tornado.web.RequestHandler, base.BaseHandler):
initLock = Lock() initLock = Lock()
def __init__(self, *args: Any, **kwargs: Any) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None:
super(AsyncDjangoHandler, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
# Set up middleware if needed. We couldn't do this earlier, because # Set up middleware if needed. We couldn't do this earlier, because
# settings weren't available. # settings weren't available.

View File

@ -14,7 +14,7 @@ orig_poll_impl = select.epoll
class InstrumentedPollIOLoop(PollIOLoop): class InstrumentedPollIOLoop(PollIOLoop):
def initialize(self, **kwargs): # type: ignore # TODO investigate likely buggy monkey patching here def initialize(self, **kwargs): # type: ignore # TODO investigate likely buggy monkey patching here
super(InstrumentedPollIOLoop, self).initialize(impl=InstrumentedPoll(), **kwargs) super().initialize(impl=InstrumentedPoll(), **kwargs)
def instrument_tornado_ioloop() -> None: def instrument_tornado_ioloop() -> None:
IOLoop.configure(InstrumentedPollIOLoop) IOLoop.configure(InstrumentedPollIOLoop)

View File

@ -42,7 +42,7 @@ def add_api_uri_context(context, request):
class ApiURLView(TemplateView): class ApiURLView(TemplateView):
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
# type: (**Any) -> Dict[str, str] # type: (**Any) -> Dict[str, str]
context = super(ApiURLView, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
add_api_uri_context(context, self.request) add_api_uri_context(context, self.request)
return context return context
@ -122,7 +122,7 @@ class IntegrationView(ApiURLView):
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
# type: (**Any) -> Dict[str, Any] # type: (**Any) -> Dict[str, Any]
context = super(IntegrationView, self).get_context_data(**kwargs) # type: Dict[str, Any] context = super().get_context_data(**kwargs) # type: Dict[str, Any]
add_integrations_context(context) add_integrations_context(context)
return context return context

View File

@ -68,7 +68,7 @@ class LibratoWebhookParser(object):
class LibratoWebhookHandler(LibratoWebhookParser): class LibratoWebhookHandler(LibratoWebhookParser):
def __init__(self, payload, attachments): def __init__(self, payload, attachments):
# type: (Dict[str, Any], List[Dict[str, Any]]) -> None # type: (Dict[str, Any], List[Dict[str, Any]]) -> None
super(LibratoWebhookHandler, self).__init__(payload, attachments) super().__init__(payload, attachments)
self.payload_available_types = { self.payload_available_types = {
ALERT_CLEAR: self.handle_alert_clear_message, ALERT_CLEAR: self.handle_alert_clear_message,
ALERT_VIOLATION: self.handle_alert_violation_message ALERT_VIOLATION: self.handle_alert_violation_message

View File

@ -338,7 +338,7 @@ class SlowQueryWorker(QueueProcessingWorker):
class MessageSenderWorker(QueueProcessingWorker): class MessageSenderWorker(QueueProcessingWorker):
def __init__(self): def __init__(self):
# type: () -> None # type: () -> None
super(MessageSenderWorker, self).__init__() super().__init__()
self.redis_client = get_redis_client() self.redis_client = get_redis_client()
self.handler = BaseHandler() self.handler = BaseHandler()
self.handler.load_middleware() self.handler.load_middleware()

View File

@ -251,7 +251,7 @@ class SocialAuthMixin(ZulipAuthMixin):
""" """
try: try:
# Call the auth_complete method of social_core.backends.oauth.BaseOAuth2 # Call the auth_complete method of social_core.backends.oauth.BaseOAuth2
return super(SocialAuthMixin, self).auth_complete(*args, **kwargs) # type: ignore # monkey-patching return super().auth_complete(*args, **kwargs) # type: ignore # monkey-patching
except AuthFailed: except AuthFailed:
return None return None
except SocialAuthBaseException as e: except SocialAuthBaseException as e: