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):
def setUp(self):
# type: () -> None
super(TestCountStats, self).setUp()
super().setUp()
# 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
# the queries).
@ -812,7 +812,7 @@ class TestDeleteStats(AnalyticsTestCase):
class TestActiveUsersAudit(AnalyticsTestCase):
def setUp(self):
# type: () -> None
super(TestActiveUsersAudit, self).setUp()
super().setUp()
self.user = self.create_user()
self.stat = COUNT_STATS['active_users_audit:is_bot:day']
self.current_property = self.stat.property
@ -975,7 +975,7 @@ class TestActiveUsersAudit(AnalyticsTestCase):
class TestRealmActiveHumans(AnalyticsTestCase):
def setUp(self):
# type: () -> None
super(TestRealmActiveHumans, self).setUp()
super().setUp()
self.stat = COUNT_STATS['realm_active_humans::day']
self.current_property = self.stat.property

View File

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

View File

@ -92,7 +92,7 @@ To fix them run './manage.py makemigrations --merge'
<output skipped>
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
return action(sql, params)
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)
def __init__(self, *args: Any, **kwargs: Any) -> None:
super(HelpDocumentationSpider, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.static_images = set() # type: Set
def _is_external_url(self, url: str) -> bool:

View File

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

View File

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

View File

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

View File

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

View File

@ -28,11 +28,11 @@ class TimeTrackingCursor(cursor):
def execute(self, query, vars=None):
# 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):
# 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):
"""A psycopg2 connection class that uses TimeTrackingCursors."""
@ -40,7 +40,7 @@ class TimeTrackingConnection(connection):
def __init__(self, *args, **kwargs):
# type: (*Any, **Any) -> None
self.queries = [] # type: List[Dict[str, str]]
super(TimeTrackingConnection, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
def cursor(self, *args, **kwargs):
# type: (*Any, **Any) -> TimeTrackingCursor

View File

@ -149,4 +149,4 @@ class JsonableError(Exception):
class RateLimited(PermissionDenied):
def __init__(self, msg=""):
# 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,
display_name=None, doc=None):
# type: (str, List[str], Optional[str], Optional[str], Optional[str], Optional[str]) -> None
super(BotIntegration, self).__init__(
super().__init__(
name,
client_name=name,
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
if client_name is None:
client_name = self.DEFAULT_CLIENT_NAME.format(name=name.title())
super(WebhookIntegration, self).__init__(
super().__init__(
name,
client_name,
categories,
@ -205,7 +205,7 @@ class HubotLozenge(Integration):
if git_url is None:
git_url = self.GIT_URL_TEMPLATE.format(name)
self.git_url = git_url
super(HubotLozenge, self).__init__(
super().__init__(
name, name, categories,
logo=logo, display_name=display_name,
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
url = self.DEFAULT_URL.format(name='github')
super(GithubIntegration, self).__init__(
super().__init__(
name,
categories,
client_name=client_name,
@ -251,7 +251,7 @@ class EmbeddedBotIntegration(Integration):
# type: (str, *Any, **Any) -> None
assert kwargs.get("client_name") is None
client_name = self.DEFAULT_CLIENT_NAME.format(name=name.title())
super(EmbeddedBotIntegration, self).__init__(
super().__init__(
name, client_name, *args, **kwargs)
EMBEDDED_BOTS = [

View File

@ -177,7 +177,7 @@ class ExceptionFreeTornadoConnection(pika.adapters.TornadoConnection):
def _adapter_disconnect(self):
# type: () -> None
try:
super(ExceptionFreeTornadoConnection, self)._adapter_disconnect()
super()._adapter_disconnect()
except (pika.exceptions.ProbableAuthenticationError,
pika.exceptions.ProbableAccessDeniedError,
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
def __init__(self):
# type: () -> None
super(TornadoQueueClient, self).__init__()
super().__init__()
# Enable rabbitmq heartbeat since TornadoConection can process them
self.rabbitmq_heartbeat = None
self._on_open_cbs = [] # type: List[Callable[[], None]]

View File

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

View File

@ -25,7 +25,7 @@ class Command(compilemessages.Command):
# version
settings.STATIC_ROOT = os.path.join(settings.DEPLOY_ROOT, "static")
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.create_language_name_map()

View File

@ -84,7 +84,7 @@ class Command(ZulipBaseCommand):
# Fix support for multi-line usage
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
return parser

View File

@ -19,7 +19,7 @@ class Command(BaseCommand):
# Fix support for multi-line usage
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
return parser

View File

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

View File

@ -24,7 +24,7 @@ For example:
# Fix support for multi-line usage
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
return parser

View File

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

View File

@ -42,7 +42,7 @@ class AddHeaderMixin(object):
ret_dict[path] = (path, path, True)
super_class = super(AddHeaderMixin, self)
super_class = super()
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
else:
@ -72,7 +72,7 @@ class RemoveUnminifiedFilesMixin(object):
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)}
super_class = super(RemoveUnminifiedFilesMixin, self)
super_class = super()
if hasattr(super_class, 'post_process'):
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):
# type: () -> None
super(EventsRegisterTest, self).setUp()
super().setUp()
self.user_profile = self.example_user('hamlet')
def create_bot(self, email):

View File

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

View File

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

View File

@ -19,7 +19,7 @@ class TestRetentionLib(ZulipTestCase):
def setUp(self):
# type: () -> None
super(TestRetentionLib, self).setUp()
super().setUp()
self.zulip_realm = self._set_realm_message_retention_value('zulip', 30)
self.mit_realm = self._set_realm_message_retention_value('zephyr', 100)
@ -118,7 +118,7 @@ class TestMoveMessageToArchive(ZulipTestCase):
def setUp(self):
# type: () -> None
super(TestMoveMessageToArchive, self).setUp()
super().setUp()
self.sender = 'hamlet@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):
def setUp(self):
# type: () -> None
super(TornadoWebTestCase, self).setUp()
super().setUp()
signals.request_started.disconnect(close_old_connections)
signals.request_finished.disconnect(close_old_connections)
self.session_cookie = None # type: Optional[Dict[Text, Text]]
def tearDown(self):
# type: () -> None
super(TornadoWebTestCase, self).tearDown()
super().tearDown()
self.session_cookie = None # type: Optional[Dict[Text, Text]]
@override_settings(DEBUG=False)
@ -87,7 +87,7 @@ class TornadoWebTestCase(AsyncHTTPTestCase, ZulipTestCase):
def login(self, *args, **kwargs):
# type: (*Any, **Any) -> None
super(TornadoWebTestCase, self).login(*args, **kwargs)
super().login(*args, **kwargs)
session_cookie = settings.SESSION_COOKIE_NAME
session_key = self.client.session.session_key
self.session_cookie = {
@ -157,11 +157,11 @@ class WebSocketBaseTestCase(AsyncHTTPTestCase, ZulipTestCase):
def setUp(self):
# type: () -> None
settings.RUNNING_INSIDE_TORNADO = True
super(WebSocketBaseTestCase, self).setUp()
super().setUp()
def tearDown(self):
# type: () -> None
super(WebSocketBaseTestCase, self).tearDown()
super().tearDown()
settings.RUNNING_INSIDE_TORNADO = False
@gen.coroutine

View File

@ -77,7 +77,7 @@ class AsyncDjangoHandler(tornado.web.RequestHandler, base.BaseHandler):
initLock = Lock()
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
# settings weren't available.

View File

@ -14,7 +14,7 @@ orig_poll_impl = select.epoll
class InstrumentedPollIOLoop(PollIOLoop):
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:
IOLoop.configure(InstrumentedPollIOLoop)

View File

@ -42,7 +42,7 @@ def add_api_uri_context(context, request):
class ApiURLView(TemplateView):
def get_context_data(self, **kwargs):
# 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)
return context
@ -122,7 +122,7 @@ class IntegrationView(ApiURLView):
def get_context_data(self, **kwargs):
# 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)
return context

View File

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

View File

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

View File

@ -251,7 +251,7 @@ class SocialAuthMixin(ZulipAuthMixin):
"""
try:
# 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:
return None
except SocialAuthBaseException as e: