From 570f3dd44741c8b1c3aaf9fcacc1f083115d7f47 Mon Sep 17 00:00:00 2001 From: Anders Kaseorg Date: Tue, 5 Dec 2023 09:45:07 -0800 Subject: [PATCH] python: Reformat with Ruff formatter. https://docs.astral.sh/ruff/formatter/ Signed-off-by: Anders Kaseorg --- analytics/tests/test_counts.py | 12 ++--- corporate/lib/decorator.py | 6 +-- ...stomerplanoffer_sent_invoice_id_invoice.py | 1 - ...backfill_end_date_for_fixed_price_plans.py | 1 - ...plan_reminder_to_review_plan_email_sent.py | 1 - corporate/views/remote_billing_page.py | 8 ++-- .../check_personal_zephyr_mirrors | 1 + .../check_user_zephyr_mirror_liveness | 1 + .../zulip_zephyr_mirror/check_zephyr_mirror | 1 + .../zulip_app_frontend/check_cron_file | 4 +- .../check_queue_worker_errors | 1 + .../check_send_receive_time | 1 + .../check_postgresql_replication_lag | 1 + pyproject.toml | 1 + scripts/lib/email-mirror-postfix | 2 +- scripts/lib/zulip_tools.py | 2 +- scripts/restart-server | 4 +- tools/fetch-contributor-data | 1 + tools/lint | 7 +-- tools/setup/emoji/emoji_setup_utils.py | 2 +- zerver/actions/presence.py | 4 +- zerver/context_processors.py | 5 +-- zerver/data_import/mattermost.py | 2 +- zerver/decorator.py | 44 +++++++++---------- zerver/lib/cache.py | 5 ++- zerver/lib/dev_ldap_directory.py | 2 +- zerver/lib/drafts.py | 2 +- zerver/lib/events.py | 21 +++++---- zerver/lib/export.py | 4 +- zerver/lib/external_accounts.py | 2 +- zerver/lib/message_cache.py | 2 +- zerver/lib/narrow.py | 3 +- zerver/lib/push_notifications.py | 4 +- zerver/lib/request.py | 2 +- zerver/lib/rest.py | 2 +- zerver/lib/soft_deactivation.py | 2 +- zerver/lib/test_classes.py | 4 +- zerver/lib/test_helpers.py | 2 +- zerver/lib/typed_endpoint.py | 2 +- zerver/lib/users.py | 6 +-- ...l_realmauditlog_extradata_to_json_field.py | 4 +- ...6_alter_scheduledmessage_read_by_sender.py | 4 +- zerver/migrations/0497_resort_edit_history.py | 1 - ...m_realm_new_stream_announcements_stream.py | 1 - ...tream_realm_signup_announcements_stream.py | 1 - ...realm_zulip_update_announcements_stream.py | 1 - zerver/models/users.py | 5 ++- zerver/tests/test_auth_backends.py | 4 +- zerver/tests/test_compatibility.py | 29 +++++------- zerver/tests/test_link_embed.py | 8 +--- zerver/tests/test_markdown.py | 2 +- zerver/tests/test_message_send.py | 2 +- zerver/tests/test_push_notifications.py | 28 +++--------- zerver/tests/test_queue_worker.py | 4 +- zerver/tests/test_retention.py | 8 +--- zerver/tests/test_service_bot_system.py | 4 +- zerver/tests/test_subs.py | 4 +- zerver/views/auth.py | 2 +- zerver/views/upload.py | 3 +- zerver/webhooks/freshdesk/tests.py | 4 +- zerver/webhooks/gitlab/view.py | 2 +- zerver/webhooks/librato/view.py | 4 +- zilencer/auth.py | 2 +- zilencer/management/commands/populate_db.py | 7 +-- ...e_realmauditlog_extradata_to_json_field.py | 4 +- ...count_add_mobile_pushes_forwarded_index.py | 1 - ...log_add_synced_billing_event_type_index.py | 1 - zilencer/models.py | 3 +- 68 files changed, 137 insertions(+), 184 deletions(-) diff --git a/analytics/tests/test_counts.py b/analytics/tests/test_counts.py index 0b161ce2d4..d667bbab00 100644 --- a/analytics/tests/test_counts.py +++ b/analytics/tests/test_counts.py @@ -1461,9 +1461,7 @@ class TestLoggingCountStats(AnalyticsTestCase): ), mock.patch("zilencer.views.send_apple_push_notification", return_value=1), mock.patch( "corporate.lib.stripe.RemoteServerBillingSession.current_count_for_billed_licenses", return_value=10, - ), self.assertLogs( - "zilencer.views", level="INFO" - ): + ), self.assertLogs("zilencer.views", level="INFO"): result = self.uuid_post( self.server_uuid, "/api/v1/remotes/push/notify", @@ -1522,9 +1520,7 @@ class TestLoggingCountStats(AnalyticsTestCase): ), mock.patch("zilencer.views.send_apple_push_notification", return_value=1), mock.patch( "corporate.lib.stripe.RemoteServerBillingSession.current_count_for_billed_licenses", return_value=10, - ), self.assertLogs( - "zilencer.views", level="INFO" - ): + ), self.assertLogs("zilencer.views", level="INFO"): result = self.uuid_post( self.server_uuid, "/api/v1/remotes/push/notify", @@ -1582,9 +1578,7 @@ class TestLoggingCountStats(AnalyticsTestCase): ), mock.patch("zilencer.views.send_apple_push_notification", return_value=1), mock.patch( "corporate.lib.stripe.RemoteRealmBillingSession.current_count_for_billed_licenses", return_value=10, - ), self.assertLogs( - "zilencer.views", level="INFO" - ): + ), self.assertLogs("zilencer.views", level="INFO"): result = self.uuid_post( self.server_uuid, "/api/v1/remotes/push/notify", diff --git a/corporate/lib/decorator.py b/corporate/lib/decorator.py index 94d513b722..49059f79fd 100644 --- a/corporate/lib/decorator.py +++ b/corporate/lib/decorator.py @@ -38,7 +38,7 @@ def is_self_hosting_management_subdomain(request: HttpRequest) -> bool: def self_hosting_management_endpoint( - view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse] + view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]: @wraps(view_func) def _wrapped_view_func( @@ -52,7 +52,7 @@ def self_hosting_management_endpoint( def authenticated_remote_realm_management_endpoint( - view_func: Callable[Concatenate[HttpRequest, RemoteRealmBillingSession, ParamT], HttpResponse] + view_func: Callable[Concatenate[HttpRequest, RemoteRealmBillingSession, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]: @wraps(view_func) def _wrapped_view_func( @@ -152,7 +152,7 @@ def get_next_page_param_from_request_path(request: HttpRequest) -> Optional[str] def authenticated_remote_server_management_endpoint( - view_func: Callable[Concatenate[HttpRequest, RemoteServerBillingSession, ParamT], HttpResponse] + view_func: Callable[Concatenate[HttpRequest, RemoteServerBillingSession, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]: @wraps(view_func) def _wrapped_view_func( diff --git a/corporate/migrations/0038_customerplanoffer_sent_invoice_id_invoice.py b/corporate/migrations/0038_customerplanoffer_sent_invoice_id_invoice.py index 2e40b9832f..0f1f36931a 100644 --- a/corporate/migrations/0038_customerplanoffer_sent_invoice_id_invoice.py +++ b/corporate/migrations/0038_customerplanoffer_sent_invoice_id_invoice.py @@ -5,7 +5,6 @@ from django.db import migrations, models class Migration(migrations.Migration): - dependencies = [ ("corporate", "0037_customerplanoffer"), ] diff --git a/corporate/migrations/0039_backfill_end_date_for_fixed_price_plans.py b/corporate/migrations/0039_backfill_end_date_for_fixed_price_plans.py index db42420dad..495fd6fba1 100644 --- a/corporate/migrations/0039_backfill_end_date_for_fixed_price_plans.py +++ b/corporate/migrations/0039_backfill_end_date_for_fixed_price_plans.py @@ -51,7 +51,6 @@ def backfill_end_date_for_fixed_price_plans( class Migration(migrations.Migration): - dependencies = [ ("corporate", "0038_customerplanoffer_sent_invoice_id_invoice"), ] diff --git a/corporate/migrations/0040_customerplan_reminder_to_review_plan_email_sent.py b/corporate/migrations/0040_customerplan_reminder_to_review_plan_email_sent.py index 0f59baa4d6..5fdf23f5fd 100644 --- a/corporate/migrations/0040_customerplan_reminder_to_review_plan_email_sent.py +++ b/corporate/migrations/0040_customerplan_reminder_to_review_plan_email_sent.py @@ -4,7 +4,6 @@ from django.db import migrations, models class Migration(migrations.Migration): - dependencies = [ ("corporate", "0039_backfill_end_date_for_fixed_price_plans"), ] diff --git a/corporate/views/remote_billing_page.py b/corporate/views/remote_billing_page.py index 1ddcc9aee4..124c70fd67 100644 --- a/corporate/views/remote_billing_page.py +++ b/corporate/views/remote_billing_page.py @@ -143,7 +143,7 @@ def get_identity_dict_from_signed_access_token( def is_tos_consent_needed_for_user( - remote_user: Union[RemoteRealmBillingUser, RemoteServerBillingUser] + remote_user: Union[RemoteRealmBillingUser, RemoteServerBillingUser], ) -> bool: assert settings.TERMS_OF_SERVICE_VERSION is not None return int(settings.TERMS_OF_SERVICE_VERSION.split(".")[0]) > int( @@ -323,9 +323,9 @@ def remote_realm_billing_finalize_login( identity_dict["remote_billing_user_id"] = remote_user.id request.session["remote_billing_identities"] = {} - request.session["remote_billing_identities"][ - f"remote_realm:{remote_realm_uuid}" - ] = identity_dict + request.session["remote_billing_identities"][f"remote_realm:{remote_realm_uuid}"] = ( + identity_dict + ) next_page = identity_dict["next_page"] assert next_page in VALID_NEXT_PAGES diff --git a/puppet/kandra/files/nagios_plugins/zulip_zephyr_mirror/check_personal_zephyr_mirrors b/puppet/kandra/files/nagios_plugins/zulip_zephyr_mirror/check_personal_zephyr_mirrors index 5620324510..df87f86097 100755 --- a/puppet/kandra/files/nagios_plugins/zulip_zephyr_mirror/check_personal_zephyr_mirrors +++ b/puppet/kandra/files/nagios_plugins/zulip_zephyr_mirror/check_personal_zephyr_mirrors @@ -8,6 +8,7 @@ This script works by just monitoring the files under mirrors when they receive the messages sent every minute by /etc/cron.d/test_zephyr_personal_mirrors """ + import os import sys import time diff --git a/puppet/kandra/files/nagios_plugins/zulip_zephyr_mirror/check_user_zephyr_mirror_liveness b/puppet/kandra/files/nagios_plugins/zulip_zephyr_mirror/check_user_zephyr_mirror_liveness index 3d82924b98..685b9fa144 100755 --- a/puppet/kandra/files/nagios_plugins/zulip_zephyr_mirror/check_user_zephyr_mirror_liveness +++ b/puppet/kandra/files/nagios_plugins/zulip_zephyr_mirror/check_user_zephyr_mirror_liveness @@ -6,6 +6,7 @@ Nagios plugin to check that our MIT users' Zephyr mirrors are running. It must be run on a machine that is using the live database for the Django ORM. """ + import os import sys from datetime import timedelta diff --git a/puppet/kandra/files/nagios_plugins/zulip_zephyr_mirror/check_zephyr_mirror b/puppet/kandra/files/nagios_plugins/zulip_zephyr_mirror/check_zephyr_mirror index d918e2471a..ce7ef8f202 100755 --- a/puppet/kandra/files/nagios_plugins/zulip_zephyr_mirror/check_zephyr_mirror +++ b/puppet/kandra/files/nagios_plugins/zulip_zephyr_mirror/check_zephyr_mirror @@ -9,6 +9,7 @@ run out of cron. See puppet/kandra/files/cron.d/zephyr-mirror for the crontab details. """ + import os import sys import time diff --git a/puppet/zulip/files/nagios_plugins/zulip_app_frontend/check_cron_file b/puppet/zulip/files/nagios_plugins/zulip_app_frontend/check_cron_file index 2f3f66f71d..ceddc43564 100755 --- a/puppet/zulip/files/nagios_plugins/zulip_app_frontend/check_cron_file +++ b/puppet/zulip/files/nagios_plugins/zulip_app_frontend/check_cron_file @@ -1,7 +1,9 @@ #!/usr/bin/env python3 -""" Nagios plugin paired with a cron job. This just verifies that the +""" +Nagios plugin paired with a cron job. This just verifies that the file output by the cron job is correct. """ + import sys import time from typing import Tuple diff --git a/puppet/zulip/files/nagios_plugins/zulip_app_frontend/check_queue_worker_errors b/puppet/zulip/files/nagios_plugins/zulip_app_frontend/check_queue_worker_errors index f7b83d6b19..b6eaebd233 100755 --- a/puppet/zulip/files/nagios_plugins/zulip_app_frontend/check_queue_worker_errors +++ b/puppet/zulip/files/nagios_plugins/zulip_app_frontend/check_queue_worker_errors @@ -3,6 +3,7 @@ """ Nagios plugin to check that none of our queue workers have reported errors. """ + import glob import os import sys diff --git a/puppet/zulip/files/nagios_plugins/zulip_app_frontend/check_send_receive_time b/puppet/zulip/files/nagios_plugins/zulip_app_frontend/check_send_receive_time index ed23d5d079..50ef47f1cd 100755 --- a/puppet/zulip/files/nagios_plugins/zulip_app_frontend/check_send_receive_time +++ b/puppet/zulip/files/nagios_plugins/zulip_app_frontend/check_send_receive_time @@ -6,6 +6,7 @@ Script to provide information about send-receive times. It must be run on a machine that is using the live database for the Django ORM. """ + import argparse import os import random diff --git a/puppet/zulip/files/nagios_plugins/zulip_postgresql/check_postgresql_replication_lag b/puppet/zulip/files/nagios_plugins/zulip_postgresql/check_postgresql_replication_lag index 7a98c726e6..443324dc4d 100755 --- a/puppet/zulip/files/nagios_plugins/zulip_postgresql/check_postgresql_replication_lag +++ b/puppet/zulip/files/nagios_plugins/zulip_postgresql/check_postgresql_replication_lag @@ -6,6 +6,7 @@ connects to PostgreSQL as has been granted the `pg_monitor` role. This can only use stdlib modules from python. """ + import configparser import re import subprocess diff --git a/pyproject.toml b/pyproject.toml index 52815cb046..cbe03d829c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -150,6 +150,7 @@ ignore = [ "E402", # Module level import not at top of file "E501", # Line too long "E731", # Do not assign a lambda expression, use a def + "ISC001", # Implicitly concatenated string literals on one line "N802", # Function name should be lowercase "N806", # Variable in function should be lowercase "PERF203", # `try`-`except` within a loop incurs performance overhead diff --git a/scripts/lib/email-mirror-postfix b/scripts/lib/email-mirror-postfix index a5d68676fc..6870ebdfc6 100755 --- a/scripts/lib/email-mirror-postfix +++ b/scripts/lib/email-mirror-postfix @@ -38,8 +38,8 @@ Also you can use optional keys to configure the script and change default values self-signed certificates. Default value: False. -t Disable sending request to the Zulip server. Default value: False. - """ + import argparse import base64 import json diff --git a/scripts/lib/zulip_tools.py b/scripts/lib/zulip_tools.py index 8708428d44..da49ed2806 100755 --- a/scripts/lib/zulip_tools.py +++ b/scripts/lib/zulip_tools.py @@ -31,7 +31,7 @@ FAIL = "\033[91m" ENDC = "\033[0m" BLACKONYELLOW = "\x1b[0;30;43m" WHITEONRED = "\x1b[0;37;41m" -BOLDRED = "\x1B[1;31m" +BOLDRED = "\x1b[1;31m" BOLD = "\x1b[1m" GRAY = "\x1b[90m" diff --git a/scripts/restart-server b/scripts/restart-server index c25bfbfa98..ca8e069a2a 100755 --- a/scripts/restart-server +++ b/scripts/restart-server @@ -239,8 +239,6 @@ if change_symlink and "PWD" in os.environ: which has now changed. Your shell will not see this change until you run: cd {} to traverse the symlink again.{} -""".format( - WARNING, symlink, shlex.quote(os.environ["PWD"]), ENDC - ), +""".format(WARNING, symlink, shlex.quote(os.environ["PWD"]), ENDC), file=sys.stderr, ) diff --git a/tools/fetch-contributor-data b/tools/fetch-contributor-data index 1d2f16991c..df9a62ea4c 100755 --- a/tools/fetch-contributor-data +++ b/tools/fetch-contributor-data @@ -3,6 +3,7 @@ Fetch contributors data from GitHub using their API, convert it to structured JSON data for the /team/ page contributors section. """ + import argparse import json import logging diff --git a/tools/lint b/tools/lint index 34523635fb..89bdc8550a 100755 --- a/tools/lint +++ b/tools/lint @@ -1,7 +1,6 @@ #!/usr/bin/env python3 import argparse import os -import re import sys tools_dir = os.path.dirname(os.path.abspath(__file__)) @@ -168,13 +167,11 @@ def run() -> None: description="Formats CSS, JavaScript, YAML", ) linter_config.external_linter( - "black", - ["black"], + "ruff-format", + ["ruff", "format"], ["py", "pyi"], description="Reformats Python code", check_arg=["--check"], - suppress_line=lambda line: line == "All done! ✨ 🍰 ✨\n" - or re.fullmatch(r"\d+ files? would be left unchanged\.\n", line) is not None, ) semgrep_command = [ diff --git a/tools/setup/emoji/emoji_setup_utils.py b/tools/setup/emoji/emoji_setup_utils.py index d8860da7cc..b0f7281a0c 100644 --- a/tools/setup/emoji/emoji_setup_utils.py +++ b/tools/setup/emoji/emoji_setup_utils.py @@ -107,7 +107,7 @@ def emoji_is_supported(emoji_dict: Dict[str, Any]) -> bool: def generate_codepoint_to_names_map( - emoji_name_maps: Dict[str, Dict[str, Any]] + emoji_name_maps: Dict[str, Dict[str, Any]], ) -> Dict[str, List[str]]: # The first element of the names list is always the canonical name. return { diff --git a/zerver/actions/presence.py b/zerver/actions/presence.py index bfeffa2f60..1a4427304c 100644 --- a/zerver/actions/presence.py +++ b/zerver/actions/presence.py @@ -133,9 +133,7 @@ def do_update_user_presence( # and also is under the risk of being shown by clients as offline before the next regular presence checkin # (so at least `settings.OFFLINE_THRESHOLD_SECS - settings.PRESENCE_PING_INTERVAL_SECS - 10`). # These two values happen to be the same in the default configuration. - seconds=settings.OFFLINE_THRESHOLD_SECS - - settings.PRESENCE_PING_INTERVAL_SECS - - 10 + seconds=settings.OFFLINE_THRESHOLD_SECS - settings.PRESENCE_PING_INTERVAL_SECS - 10 ) became_online = status == UserPresence.LEGACY_STATUS_ACTIVE_INT and now_online diff --git a/zerver/context_processors.py b/zerver/context_processors.py index e64cb57380..a6d1c52c80 100644 --- a/zerver/context_processors.py +++ b/zerver/context_processors.py @@ -93,9 +93,8 @@ def zulip_default_corporate_context(request: HttpRequest) -> Dict[str, Any]: from corporate.lib.decorator import is_self_hosting_management_subdomain # Check if view function is in corporate app. - if ( - request.resolver_match is not None - and not request.resolver_match.func.__module__.startswith("corporate") + if request.resolver_match is not None and not request.resolver_match.func.__module__.startswith( + "corporate" ): return { "is_self_hosting_management_page": False, diff --git a/zerver/data_import/mattermost.py b/zerver/data_import/mattermost.py index a7aa35da75..a47c1b4131 100644 --- a/zerver/data_import/mattermost.py +++ b/zerver/data_import/mattermost.py @@ -806,7 +806,7 @@ def write_emoticon_data( def create_username_to_user_mapping( - user_data_list: List[Dict[str, Any]] + user_data_list: List[Dict[str, Any]], ) -> Dict[str, Dict[str, Any]]: username_to_user = {} for user in user_data_list: diff --git a/zerver/decorator.py b/zerver/decorator.py index 8a2932ec7e..e0375fd9e4 100644 --- a/zerver/decorator.py +++ b/zerver/decorator.py @@ -105,7 +105,7 @@ def update_user_activity( # Based on django.views.decorators.http.require_http_methods def require_post( - func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse] + func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]: # Arguments before ParamT needs to be positional-only as required by Concatenate @wraps(func) @@ -132,7 +132,7 @@ def require_post( def require_realm_owner( - func: Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse] + func: Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse]: @wraps(func) def wrapper( @@ -150,7 +150,7 @@ def require_realm_owner( def require_realm_admin( - func: Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse] + func: Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse]: @wraps(func) def wrapper( @@ -168,7 +168,7 @@ def require_realm_admin( def require_organization_member( - func: Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse] + func: Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse]: @wraps(func) def wrapper( @@ -186,7 +186,7 @@ def require_organization_member( def require_billing_access( - func: Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse] + func: Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse]: @wraps(func) def wrapper( @@ -429,7 +429,7 @@ def user_passes_test( """ def decorator( - view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse] + view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]: @wraps(view_func) def _wrapped_view( @@ -481,9 +481,9 @@ def do_login(request: HttpRequest, user_profile: UserProfile) -> None: assert isinstance(validated_user_profile, UserProfile) django_login(request, validated_user_profile) - RequestNotes.get_notes(request).requester_for_logs = ( - validated_user_profile.format_requester_for_logs() - ) + RequestNotes.get_notes( + request + ).requester_for_logs = validated_user_profile.format_requester_for_logs() process_client(request, validated_user_profile, is_browser_view=True) if settings.TWO_FACTOR_AUTHENTICATION_ENABLED: # Log in with two factor authentication as well. @@ -491,7 +491,7 @@ def do_login(request: HttpRequest, user_profile: UserProfile) -> None: def log_view_func( - view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse] + view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]: @wraps(view_func) def _wrapped_view_func( @@ -504,7 +504,7 @@ def log_view_func( def add_logging_data( - view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse] + view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]: @wraps(view_func) def _wrapped_view_func( @@ -523,7 +523,7 @@ def add_logging_data( def human_users_only( - view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse] + view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]: @wraps(view_func) def _wrapped_view_func( @@ -597,7 +597,7 @@ def web_public_view( def require_server_admin( - view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse] + view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]: @zulip_login_required @wraps(view_func) @@ -613,7 +613,7 @@ def require_server_admin( def require_server_admin_api( - view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse] + view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]: @zulip_login_required @wraps(view_func) @@ -631,7 +631,7 @@ def require_server_admin_api( def require_non_guest_user( - view_func: Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse] + view_func: Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse]: @wraps(view_func) def _wrapped_view_func( @@ -649,7 +649,7 @@ def require_non_guest_user( def require_member_or_admin( - view_func: Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse] + view_func: Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse]: @wraps(view_func) def _wrapped_view_func( @@ -669,7 +669,7 @@ def require_member_or_admin( def require_user_group_edit_permission( - view_func: Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse] + view_func: Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse]: @require_member_or_admin @wraps(view_func) @@ -756,7 +756,7 @@ def authenticated_rest_api_view( allow_webhook_access = True def _wrapped_view_func( - view_func: Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse] + view_func: Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]: @csrf_exempt @wraps(view_func) @@ -809,7 +809,7 @@ def authenticated_rest_api_view( def process_as_post( - view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse] + view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]: @wraps(view_func) def _wrapped_view_func( @@ -938,7 +938,7 @@ def internal_api_view( the server.""" def _wrapped_view_func( - view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse] + view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]: @csrf_exempt @require_post @@ -969,7 +969,7 @@ def to_utc_datetime(var_name: str, timestamp: str) -> datetime: def return_success_on_head_request( - view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse] + view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]: @wraps(view_func) def _wrapped_view_func( @@ -1044,7 +1044,7 @@ def add_google_analytics_context(context: Dict[str, object]) -> None: def add_google_analytics( - view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse] + view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]: @wraps(view_func) def _wrapped_view_func( diff --git a/zerver/lib/cache.py b/zerver/lib/cache.py index 4fbc05c69b..63d20e6044 100644 --- a/zerver/lib/cache.py +++ b/zerver/lib/cache.py @@ -724,7 +724,8 @@ class IgnoreUnhashableLruCacheWrapper(Generic[ParamT, ReturnT]): try: return self.cached_function( - *args, **kwargs # type: ignore[arg-type] # might be unhashable + *args, + **kwargs, # type: ignore[arg-type] # might be unhashable ) except TypeError: # args or kwargs contains an element which is unhashable. In @@ -750,7 +751,7 @@ def ignore_unhashable_lru_cache( internal_decorator = lru_cache(maxsize=maxsize, typed=typed) def decorator( - user_function: Callable[ParamT, ReturnT] + user_function: Callable[ParamT, ReturnT], ) -> IgnoreUnhashableLruCacheWrapper[ParamT, ReturnT]: return IgnoreUnhashableLruCacheWrapper(user_function, internal_decorator(user_function)) diff --git a/zerver/lib/dev_ldap_directory.py b/zerver/lib/dev_ldap_directory.py index 0348bd46d6..d710365d29 100644 --- a/zerver/lib/dev_ldap_directory.py +++ b/zerver/lib/dev_ldap_directory.py @@ -60,7 +60,7 @@ def generate_dev_ldap_dir(mode: str, num_users: int = 8) -> Dict[str, Dict[str, def init_fakeldap( - directory: Optional[Dict[str, Dict[str, List[str]]]] = None + directory: Optional[Dict[str, Dict[str, List[str]]]] = None, ) -> None: # nocoverage # We only use this in development. Importing mock inside # this function is an import time optimization, which diff --git a/zerver/lib/drafts.py b/zerver/lib/drafts.py index 4b75d1073f..be34f7be85 100644 --- a/zerver/lib/drafts.py +++ b/zerver/lib/drafts.py @@ -79,7 +79,7 @@ def further_validated_draft_dict( def draft_endpoint( - view_func: Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse] + view_func: Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse]: @wraps(view_func) def draft_view_func( diff --git a/zerver/lib/events.py b/zerver/lib/events.py index ff07213095..5c5f5fca62 100644 --- a/zerver/lib/events.py +++ b/zerver/lib/events.py @@ -219,8 +219,7 @@ def fetch_initial_state_data( # user_topic and muted_topics, and receive the duplicate # muted_topics data only from older servers that don't yet # support user_topic. - event_types is None - or not want("user_topic") + event_types is None or not want("user_topic") ): state["muted_topics"] = [] if user_profile is None else get_topic_mutes(user_profile) @@ -415,12 +414,12 @@ def fetch_initial_state_data( realm_user_default, property_name ) - state["realm_user_settings_defaults"][ - "emojiset_choices" - ] = RealmUserDefault.emojiset_choices() - state["realm_user_settings_defaults"][ - "available_notification_sounds" - ] = get_available_notification_sounds() + state["realm_user_settings_defaults"]["emojiset_choices"] = ( + RealmUserDefault.emojiset_choices() + ) + state["realm_user_settings_defaults"]["available_notification_sounds"] = ( + get_available_notification_sounds() + ) if want("realm_domains"): state["realm_domains"] = get_realm_domains(realm) @@ -662,9 +661,9 @@ def fetch_initial_state_data( state["user_settings"]["emojiset_choices"] = UserProfile.emojiset_choices() state["user_settings"]["timezone"] = canonicalize_timezone(settings_user.timezone) - state["user_settings"][ - "available_notification_sounds" - ] = get_available_notification_sounds() + state["user_settings"]["available_notification_sounds"] = ( + get_available_notification_sounds() + ) if want("user_status"): # We require creating an account to access statuses. diff --git a/zerver/lib/export.py b/zerver/lib/export.py index d96d37433b..06ec7110b8 100644 --- a/zerver/lib/export.py +++ b/zerver/lib/export.py @@ -565,9 +565,7 @@ def export_from_config( if config.custom_tables: exported_tables = config.custom_tables else: - assert ( - table is not None - ), """ + assert table is not None, """ You must specify config.custom_tables if you are not specifying config.table""" exported_tables = [table] diff --git a/zerver/lib/external_accounts.py b/zerver/lib/external_accounts.py index 842c891663..1f1929eef5 100644 --- a/zerver/lib/external_accounts.py +++ b/zerver/lib/external_accounts.py @@ -1,5 +1,5 @@ """ - This module stores data for "external account" custom profile field. +This module stores data for "external account" custom profile field. """ from dataclasses import dataclass diff --git a/zerver/lib/message_cache.py b/zerver/lib/message_cache.py index c3f5d5f248..06f4b2dff7 100644 --- a/zerver/lib/message_cache.py +++ b/zerver/lib/message_cache.py @@ -262,7 +262,7 @@ class MessageDict: @staticmethod def sew_submessages_and_reactions_to_msgs( - messages: List[Dict[str, Any]] + messages: List[Dict[str, Any]], ) -> List[Dict[str, Any]]: msg_ids = [msg["id"] for msg in messages] submessages = SubMessage.get_raw_db_rows(msg_ids) diff --git a/zerver/lib/narrow.py b/zerver/lib/narrow.py index 33c617625b..e4c6266d8b 100644 --- a/zerver/lib/narrow.py +++ b/zerver/lib/narrow.py @@ -968,7 +968,8 @@ def get_base_query_for_search( # zerver_messages, since the user_profile_id limit in # usermessage is more selective, and the query planner # can't know about that cross-table correlation. - .where(column("user_profile_id", Integer) == literal(user_profile.id)).select_from( + .where(column("user_profile_id", Integer) == literal(user_profile.id)) + .select_from( join( table("zerver_usermessage"), table("zerver_message"), diff --git a/zerver/lib/push_notifications.py b/zerver/lib/push_notifications.py index 01d255d07f..9849f6017d 100644 --- a/zerver/lib/push_notifications.py +++ b/zerver/lib/push_notifications.py @@ -880,7 +880,9 @@ def get_mobile_push_content(rendered_content: str) -> str: def format_as_quote(quote_text: str) -> str: return "".join( - f"> {line}\n" for line in quote_text.splitlines() if line # Remove empty lines + f"> {line}\n" + for line in quote_text.splitlines() + if line # Remove empty lines ) def render_olist(ol: lxml.html.HtmlElement) -> str: diff --git a/zerver/lib/request.py b/zerver/lib/request.py index f1ce679fc1..c3a41ee66a 100644 --- a/zerver/lib/request.py +++ b/zerver/lib/request.py @@ -335,7 +335,7 @@ ReturnT = TypeVar("ReturnT") # expected to call json_success or raise JsonableError, as it uses JsonableError # internally when it encounters an error def has_request_variables( - req_func: Callable[Concatenate[HttpRequest, ParamT], ReturnT] + req_func: Callable[Concatenate[HttpRequest, ParamT], ReturnT], ) -> Callable[Concatenate[HttpRequest, ParamT], ReturnT]: num_params = req_func.__code__.co_argcount default_param_values = cast(FunctionType, req_func).__defaults__ diff --git a/zerver/lib/rest.py b/zerver/lib/rest.py index be4c5e2254..cdd84a7c38 100644 --- a/zerver/lib/rest.py +++ b/zerver/lib/rest.py @@ -24,7 +24,7 @@ METHODS = ("GET", "HEAD", "POST", "PUT", "DELETE", "PATCH") def default_never_cache_responses( - view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse] + view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]: """Patched version of the standard Django never_cache_responses decorator that adds headers to a response so that it will never be diff --git a/zerver/lib/soft_deactivation.py b/zerver/lib/soft_deactivation.py index 73da684937..44409aa2fd 100644 --- a/zerver/lib/soft_deactivation.py +++ b/zerver/lib/soft_deactivation.py @@ -272,7 +272,7 @@ def do_soft_deactivate_user(user_profile: UserProfile) -> None: def do_soft_deactivate_users( - users: Union[Sequence[UserProfile], QuerySet[UserProfile]] + users: Union[Sequence[UserProfile], QuerySet[UserProfile]], ) -> List[UserProfile]: BATCH_SIZE = 100 users_soft_deactivated = [] diff --git a/zerver/lib/test_classes.py b/zerver/lib/test_classes.py index 07126f2b35..922ca64665 100644 --- a/zerver/lib/test_classes.py +++ b/zerver/lib/test_classes.py @@ -1544,9 +1544,7 @@ Output: """ with mock.patch( "zerver.lib.markdown.timeout", side_effect=subprocess.CalledProcessError(1, []) - ), self.assertLogs( - level="ERROR" - ): # For markdown_logger.exception + ), self.assertLogs(level="ERROR"): # For markdown_logger.exception yield def create_default_device( diff --git a/zerver/lib/test_helpers.py b/zerver/lib/test_helpers.py index 65f8553238..ea53031ce4 100644 --- a/zerver/lib/test_helpers.py +++ b/zerver/lib/test_helpers.py @@ -585,7 +585,7 @@ TestCaseT = TypeVar("TestCaseT", bound="MigrationsTestCase") def use_db_models( - method: Callable[[TestCaseT, StateApps], None] + method: Callable[[TestCaseT, StateApps], None], ) -> Callable[[TestCaseT, StateApps], None]: # nocoverage def method_patched_with_mock(self: TestCaseT, apps: StateApps) -> None: ArchivedAttachment = apps.get_model("zerver", "ArchivedAttachment") diff --git a/zerver/lib/typed_endpoint.py b/zerver/lib/typed_endpoint.py index ab511c38a0..3887e32a6c 100644 --- a/zerver/lib/typed_endpoint.py +++ b/zerver/lib/typed_endpoint.py @@ -278,7 +278,7 @@ def parse_single_parameter( def parse_view_func_signature( - view_func: Callable[Concatenate[HttpRequest, ParamT], object] + view_func: Callable[Concatenate[HttpRequest, ParamT], object], ) -> ViewFuncInfo: """This is responsible for inspecting the function signature and getting the metadata from the parameters. We want to keep this function as pure as diff --git a/zerver/lib/users.py b/zerver/lib/users.py index b693d6502c..490c5720df 100644 --- a/zerver/lib/users.py +++ b/zerver/lib/users.py @@ -747,9 +747,9 @@ def get_subscribers_of_target_user_subscriptions( for user_id in target_user_ids: target_user_subbed_recipients = target_user_subscriptions_dict[user_id] for recipient_id in target_user_subbed_recipients: - users_subbed_to_target_user_subscriptions_dict[ - user_id - ] |= subscribers_dict_by_recipient_ids[recipient_id] + users_subbed_to_target_user_subscriptions_dict[user_id] |= ( + subscribers_dict_by_recipient_ids[recipient_id] + ) return users_subbed_to_target_user_subscriptions_dict diff --git a/zerver/migrations/0460_backfill_realmauditlog_extradata_to_json_field.py b/zerver/migrations/0460_backfill_realmauditlog_extradata_to_json_field.py index 89de7b256f..bd6654f3f5 100644 --- a/zerver/migrations/0460_backfill_realmauditlog_extradata_to_json_field.py +++ b/zerver/migrations/0460_backfill_realmauditlog_extradata_to_json_field.py @@ -117,7 +117,9 @@ def do_bulk_backfill_extra_data( continue new_value = ast.literal_eval(audit_log_entry.extra_data) # type: ignore[attr-defined] # Explained above. if old_value not in ({}, new_value): - inconsistent_extra_data_json.append((audit_log_entry.id, audit_log_entry.extra_data, old_value, new_value)) # type: ignore[attr-defined] # Explained above. + inconsistent_extra_data_json.append( + (audit_log_entry.id, audit_log_entry.extra_data, old_value, new_value) # type: ignore[attr-defined] # Explained above. + ) audit_log_entry.extra_data_json = new_value # type: ignore[attr-defined] # Explained above. audit_log_model._default_manager.bulk_update( python_valued_audit_log_entries, fields=["extra_data_json"] diff --git a/zerver/migrations/0496_alter_scheduledmessage_read_by_sender.py b/zerver/migrations/0496_alter_scheduledmessage_read_by_sender.py index 2411325e11..bf49354645 100644 --- a/zerver/migrations/0496_alter_scheduledmessage_read_by_sender.py +++ b/zerver/migrations/0496_alter_scheduledmessage_read_by_sender.py @@ -29,9 +29,7 @@ def populate_read_by_sender(apps: StateApps, schema_editor: BaseDatabaseSchemaEd | Q(sending_client_name_lower__contains="desktop app"), ~Q(recipient=F("sender__recipient")), read_by_sender=None, - ).update( - read_by_sender=True - ) + ).update(read_by_sender=True) ScheduledMessage.objects.filter(read_by_sender=None).update(read_by_sender=False) diff --git a/zerver/migrations/0497_resort_edit_history.py b/zerver/migrations/0497_resort_edit_history.py index 36ca1caa7a..d91186676e 100644 --- a/zerver/migrations/0497_resort_edit_history.py +++ b/zerver/migrations/0497_resort_edit_history.py @@ -2,7 +2,6 @@ from django.db import migrations class Migration(migrations.Migration): - dependencies = [ ("zerver", "0496_alter_scheduledmessage_read_by_sender"), ] diff --git a/zerver/migrations/0498_rename_notifications_stream_realm_new_stream_announcements_stream.py b/zerver/migrations/0498_rename_notifications_stream_realm_new_stream_announcements_stream.py index 384754b493..664a10bc83 100644 --- a/zerver/migrations/0498_rename_notifications_stream_realm_new_stream_announcements_stream.py +++ b/zerver/migrations/0498_rename_notifications_stream_realm_new_stream_announcements_stream.py @@ -4,7 +4,6 @@ from django.db import migrations class Migration(migrations.Migration): - dependencies = [ ("zerver", "0497_resort_edit_history"), ] diff --git a/zerver/migrations/0499_rename_signup_notifications_stream_realm_signup_announcements_stream.py b/zerver/migrations/0499_rename_signup_notifications_stream_realm_signup_announcements_stream.py index 9f32cd6879..f698a689eb 100644 --- a/zerver/migrations/0499_rename_signup_notifications_stream_realm_signup_announcements_stream.py +++ b/zerver/migrations/0499_rename_signup_notifications_stream_realm_signup_announcements_stream.py @@ -4,7 +4,6 @@ from django.db import migrations class Migration(migrations.Migration): - dependencies = [ ("zerver", "0498_rename_notifications_stream_realm_new_stream_announcements_stream"), ] diff --git a/zerver/migrations/0500_realm_zulip_update_announcements_stream.py b/zerver/migrations/0500_realm_zulip_update_announcements_stream.py index 025879d2a1..8113d42b44 100644 --- a/zerver/migrations/0500_realm_zulip_update_announcements_stream.py +++ b/zerver/migrations/0500_realm_zulip_update_announcements_stream.py @@ -17,7 +17,6 @@ def set_initial_value_for_zulip_update_announcements_stream( class Migration(migrations.Migration): - dependencies = [ ("zerver", "0499_rename_signup_notifications_stream_realm_signup_announcements_stream"), ] diff --git a/zerver/models/users.py b/zerver/models/users.py index 577a9679d3..77e461e868 100644 --- a/zerver/models/users.py +++ b/zerver/models/users.py @@ -603,8 +603,9 @@ class UserProfile(AbstractBaseUser, PermissionsMixin, UserBaseSettings): for field in custom_profile_fields_for_realm(self.realm_id): field_values = user_data.get(field.id, None) if field_values: - value, rendered_value = field_values.get("value"), field_values.get( - "rendered_value" + value, rendered_value = ( + field_values.get("value"), + field_values.get("rendered_value"), ) else: value, rendered_value = None, None diff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.py index 86227ffc5e..1eb2bcbee9 100644 --- a/zerver/tests/test_auth_backends.py +++ b/zerver/tests/test_auth_backends.py @@ -7256,9 +7256,7 @@ class LDAPBackendTest(ZulipTestCase): "zproject.backends.ZulipLDAPAuthBackend.get_or_build_user", side_effect=error ), mock.patch("django_auth_ldap.backend._LDAPUser._authenticate_user_dn"), self.assertLogs( "django_auth_ldap", "WARNING" - ) as warn_log, self.assertLogs( - "django.request", level="ERROR" - ): + ) as warn_log, self.assertLogs("django.request", level="ERROR"): response = self.client_post("/login/", data) self.assertEqual(response.status_code, 500) self.assert_in_response("Configuration error", response) diff --git a/zerver/tests/test_compatibility.py b/zerver/tests/test_compatibility.py index 9cb83b907d..f8099a5847 100644 --- a/zerver/tests/test_compatibility.py +++ b/zerver/tests/test_compatibility.py @@ -10,10 +10,9 @@ from zerver.lib.test_classes import ZulipTestCase class VersionTest(ZulipTestCase): - data = ( - [ - case.split() - for case in """ + data = [ + case.split() + for case in """ 1.2.3 < 1.2.4 1.2.3 = 1.2.3 1.4.1 > 1.2.3 @@ -30,15 +29,11 @@ class VersionTest(ZulipTestCase): 15.1.95 < 16.2.96 16.2.96 = 16.2.96 20.0.103 > 16.2.96 - """.strip().split( - "\n" - ) - ] - + [ - ["", "?", "1"], - ["", "?", "a"], - ] - ) + """.strip().split("\n") + ] + [ + ["", "?", "1"], + ["", "?", "a"], + ] def test_version_lt(self) -> None: for ver1, cmp, ver2 in self.data: @@ -65,9 +60,7 @@ class VersionTest(ZulipTestCase): ios ZulipMobile/1.2.3 (iPhone OS 2.1) ios ZulipMobile/1.2.3 (iOS 6) None ZulipMobile/1.2.3 (Windows 8) - """.strip().split( - "\n" - ) + """.strip().split("\n") ] def test_find_mobile_os(self) -> None: @@ -97,9 +90,7 @@ class CompatibilityTest(ZulipTestCase): ok ZulipMobile/1 CFNetwork/974.2.1 Darwin/18.0.0 ok ZulipMobile/20.0.103 (Android 6.0.1) ok ZulipMobile/20.0.103 (iOS 12.1) - """.strip().split( - "\n" - ) + """.strip().split("\n") if case ] diff --git a/zerver/tests/test_link_embed.py b/zerver/tests/test_link_embed.py index 4b57acf8f7..dac6d89484 100644 --- a/zerver/tests/test_link_embed.py +++ b/zerver/tests/test_link_embed.py @@ -196,9 +196,7 @@ class OpenGraphParserTestCase(ZulipTestCase): - """.encode( - "big5" - ) + """.encode("big5") parser = OpenGraphParser(html, "text/html; charset=Big5") result = parser.extract_data() self.assertEqual(result.title, "中文") @@ -209,9 +207,7 @@ class OpenGraphParserTestCase(ZulipTestCase): - """.encode( - "big5" - ) + """.encode("big5") parser = OpenGraphParser(html, "text/html") result = parser.extract_data() self.assertEqual(result.title, "中文") diff --git a/zerver/tests/test_markdown.py b/zerver/tests/test_markdown.py index 11b7c40af5..f1c899614b 100644 --- a/zerver/tests/test_markdown.py +++ b/zerver/tests/test_markdown.py @@ -1302,7 +1302,7 @@ class MarkdownTest(ZulipTestCase): assert_conversion("Hello #123World", False) assert_conversion("Hello#123 World", False) assert_conversion("Hello#123World", False) - assert_conversion("Hello\u00A0#123\u00A0World") + assert_conversion("Hello\u00a0#123\u00a0World") # Ideally, these should be converted, but Markdown doesn't # handle word boundary detection in languages that don't use # whitespace for that correctly yet. diff --git a/zerver/tests/test_message_send.py b/zerver/tests/test_message_send.py index d2ba430c5a..1d170792b0 100644 --- a/zerver/tests/test_message_send.py +++ b/zerver/tests/test_message_send.py @@ -924,7 +924,7 @@ class MessagePOSTTest(ZulipTestCase): { "type": "stream", "to": "Verona", - "topic": "Test\uFFFETopic", + "topic": "Test\ufffeTopic", "content": "Test message", }, ) diff --git a/zerver/tests/test_push_notifications.py b/zerver/tests/test_push_notifications.py index bedf92ff63..c72b247ed0 100644 --- a/zerver/tests/test_push_notifications.py +++ b/zerver/tests/test_push_notifications.py @@ -256,9 +256,7 @@ class SendTestPushNotificationEndpointTest(BouncerTestCase): "zerver.lib.push_notifications.send_apple_push_notification" ) as mock_send_apple_push_notification, mock.patch( "zerver.lib.push_notifications.send_android_push_notification" - ) as mock_send_android_push_notification, time_machine.travel( - time_now, tick=False - ): + ) as mock_send_android_push_notification, time_machine.travel(time_now, tick=False): result = self.api_post(user, endpoint, subdomain="zulip") mock_send_android_push_notification.assert_called_once_with( @@ -595,9 +593,7 @@ class PushBouncerNotificationTest(BouncerTestCase): ), mock.patch("zilencer.views.send_apple_push_notification", return_value=1), mock.patch( "corporate.lib.stripe.RemoteRealmBillingSession.current_count_for_billed_licenses", return_value=10, - ), self.assertLogs( - "zilencer.views", level="INFO" - ): + ), self.assertLogs("zilencer.views", level="INFO"): result = self.uuid_post( self.server_uuid, "/api/v1/remotes/push/notify", @@ -669,9 +665,7 @@ class PushBouncerNotificationTest(BouncerTestCase): ) as apple_push, mock.patch( "corporate.lib.stripe.RemoteRealmBillingSession.current_count_for_billed_licenses", return_value=10, - ), time_machine.travel( - time_sent, tick=False - ), self.assertLogs( + ), time_machine.travel(time_sent, tick=False), self.assertLogs( "zilencer.views", level="INFO" ) as logger: result = self.uuid_post( @@ -989,9 +983,7 @@ class PushBouncerNotificationTest(BouncerTestCase): ), mock.patch("zilencer.views.send_apple_push_notification", return_value=1), mock.patch( "corporate.lib.stripe.RemoteServerBillingSession.current_count_for_billed_licenses", return_value=10, - ), self.assertLogs( - "zilencer.views", level="INFO" - ) as logger: + ), self.assertLogs("zilencer.views", level="INFO") as logger: result = self.uuid_post( self.server_uuid, "/api/v1/remotes/push/notify", @@ -2774,9 +2766,7 @@ class HandlePushNotificationTest(PushNotificationTest): return_value=10, ), self.assertLogs( "zerver.lib.push_notifications", level="INFO" - ) as pn_logger, self.assertLogs( - "zilencer.views", level="INFO" - ) as views_logger: + ) as pn_logger, self.assertLogs("zilencer.views", level="INFO") as views_logger: apns_devices = [ (b64_to_hex(device.token), device.ios_app_id, device.token) for device in RemotePushDeviceToken.objects.filter(kind=PushDeviceToken.APNS) @@ -2867,9 +2857,7 @@ class HandlePushNotificationTest(PushNotificationTest): return_value=100, ) as mock_current_count, self.assertLogs( "zerver.lib.push_notifications", level="INFO" - ) as pn_logger, self.assertLogs( - "zilencer.views", level="INFO" - ): + ) as pn_logger, self.assertLogs("zilencer.views", level="INFO"): handle_push_notification(self.user_profile.id, missed_message) self.assertEqual( @@ -2938,9 +2926,7 @@ class HandlePushNotificationTest(PushNotificationTest): return_value=10, ), self.assertLogs( "zerver.lib.push_notifications", level="INFO" - ) as pn_logger, self.assertLogs( - "zilencer.views", level="INFO" - ) as views_logger: + ) as pn_logger, self.assertLogs("zilencer.views", level="INFO") as views_logger: apns_devices = [ (b64_to_hex(device.token), device.ios_app_id, device.token) for device in RemotePushDeviceToken.objects.filter(kind=PushDeviceToken.APNS) diff --git a/zerver/tests/test_queue_worker.py b/zerver/tests/test_queue_worker.py index 5e9f03dca8..18f6e0d1f6 100644 --- a/zerver/tests/test_queue_worker.py +++ b/zerver/tests/test_queue_worker.py @@ -676,9 +676,7 @@ class WorkerTest(ZulipTestCase): "zerver.lib.send_email.build_email", side_effect=EmailNotDeliveredError ), mock_queue_publish( "zerver.lib.queue.queue_json_publish", side_effect=fake_publish - ), self.assertLogs( - level="ERROR" - ) as m: + ), self.assertLogs(level="ERROR") as m: worker.start() self.assertIn("failed due to exception EmailNotDeliveredError", m.output[0]) diff --git a/zerver/tests/test_retention.py b/zerver/tests/test_retention.py index f4c2b5b329..86cc15f0c0 100644 --- a/zerver/tests/test_retention.py +++ b/zerver/tests/test_retention.py @@ -760,9 +760,7 @@ class MoveMessageToArchiveGeneral(MoveMessageToArchiveBase): Some more.... http://{host}/user_uploads/{id}/31/4CBjtTLYZhk66pZrF8hnYGwc/abc.py ... http://{host}/user_uploads/{id}/31/4CBjtTLYZhk66pZrF8hnYGwc/new.py .... http://{host}/user_uploads/{id}/31/4CBjtTLYZhk66pZrF8hnYGwc/hello.txt .... - """.format( - id=realm_id, host=host - ) + """.format(id=realm_id, host=host) msg_id = self.send_personal_message(self.sender, self.recipient, body) # Simulate a reply with the same contents. @@ -821,9 +819,7 @@ class MoveMessageToArchiveGeneral(MoveMessageToArchiveBase): Some more.... http://{host}/user_uploads/{id}/31/4CBjtTLYZhk66pZrF8hnYGwc/abc.py ... http://{host}/user_uploads/{id}/31/4CBjtTLYZhk66pZrF8hnYGwc/new.py .... http://{host}/user_uploads/{id}/31/4CBjtTLYZhk66pZrF8hnYGwc/hello.txt .... - """.format( - id=realm_id, host=host - ) + """.format(id=realm_id, host=host) msg_id = self.send_personal_message(self.sender, self.recipient, body) diff --git a/zerver/tests/test_service_bot_system.py b/zerver/tests/test_service_bot_system.py index ce1a0805fb..e0e3516df0 100644 --- a/zerver/tests/test_service_bot_system.py +++ b/zerver/tests/test_service_bot_system.py @@ -422,7 +422,7 @@ ParamT = ParamSpec("ParamT") def for_all_bot_types( - test_func: Callable[Concatenate["TestServiceBotEventTriggers", ParamT], None] + test_func: Callable[Concatenate["TestServiceBotEventTriggers", ParamT], None], ) -> Callable[Concatenate["TestServiceBotEventTriggers", ParamT], None]: @wraps(test_func) def _wrapped( @@ -443,7 +443,7 @@ def patch_queue_publish( Callable[["TestServiceBotEventTriggers"], None], ]: def inner( - func: Callable[["TestServiceBotEventTriggers", mock.Mock], None] + func: Callable[["TestServiceBotEventTriggers", mock.Mock], None], ) -> Callable[["TestServiceBotEventTriggers"], None]: @wraps(func) def _wrapped(self: "TestServiceBotEventTriggers") -> None: diff --git a/zerver/tests/test_subs.py b/zerver/tests/test_subs.py index 8ac5e2eecf..4457db2d1e 100644 --- a/zerver/tests/test_subs.py +++ b/zerver/tests/test_subs.py @@ -3996,7 +3996,7 @@ class SubscriptionAPITest(ZulipTestCase): # For Cn category post_data_cn = { "subscriptions": orjson.dumps( - [{"name": "new\uFFFEstream", "description": "this is description"}] + [{"name": "new\ufffestream", "description": "this is description"}] ).decode(), "invite_only": orjson.dumps(False).decode(), } @@ -4023,7 +4023,7 @@ class SubscriptionAPITest(ZulipTestCase): result = self.client_patch(f"/json/streams/{stream.id}", {"new_name": "test\n\rname"}) self.assert_json_error(result, "Invalid character in stream name, at position 5!") # Check for Cn characters - result = self.client_patch(f"/json/streams/{stream.id}", {"new_name": "test\uFFFEame"}) + result = self.client_patch(f"/json/streams/{stream.id}", {"new_name": "test\ufffeame"}) self.assert_json_error(result, "Invalid character in stream name, at position 5!") def test_successful_subscriptions_list(self) -> None: diff --git a/zerver/views/auth.py b/zerver/views/auth.py index 16e98a82a9..2bdf732790 100644 --- a/zerver/views/auth.py +++ b/zerver/views/auth.py @@ -631,7 +631,7 @@ def oauth_redirect_to_root( def handle_desktop_flow( - func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse] + func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]: @wraps(func) def wrapper( diff --git a/zerver/views/upload.py b/zerver/views/upload.py index 7b1fc3e93f..07230e0d9f 100644 --- a/zerver/views/upload.py +++ b/zerver/views/upload.py @@ -120,7 +120,8 @@ def serve_local( # the response to; serve it directly ourselves. FileResponse # handles setting Content-Type, Content-Disposition, etc. response: HttpResponseBase = FileResponse( - open(local_path, "rb"), as_attachment=download # noqa: SIM115 + open(local_path, "rb"), # noqa: SIM115 + as_attachment=download, ) patch_cache_control(response, private=True, immutable=True) return response diff --git a/zerver/webhooks/freshdesk/tests.py b/zerver/webhooks/freshdesk/tests.py index c754ca0829..1189bd33f8 100644 --- a/zerver/webhooks/freshdesk/tests.py +++ b/zerver/webhooks/freshdesk/tests.py @@ -98,9 +98,7 @@ Requester Bob updated [ticket #11](http://test1234zz expected_message = """ Requester Bob added a {} note to \ [ticket #11](http://test1234zzz.freshdesk.com/helpdesk/tickets/11). -""".strip().format( - note_type - ) +""".strip().format(note_type) self.api_stream_message( self.test_user, fixture, diff --git a/zerver/webhooks/gitlab/view.py b/zerver/webhooks/gitlab/view.py index 355ea4ddd2..1665d7e183 100644 --- a/zerver/webhooks/gitlab/view.py +++ b/zerver/webhooks/gitlab/view.py @@ -189,7 +189,7 @@ def get_assignees(payload: WildValue) -> Union[List[WildValue], WildValue]: def replace_assignees_username_with_name( - assignees: Union[List[WildValue], WildValue] + assignees: Union[List[WildValue], WildValue], ) -> List[Dict[str, str]]: """Replace the username of each assignee with their (full) name. diff --git a/zerver/webhooks/librato/view.py b/zerver/webhooks/librato/view.py index 4b0e9981c1..dbc95102bd 100644 --- a/zerver/webhooks/librato/view.py +++ b/zerver/webhooks/librato/view.py @@ -164,9 +164,7 @@ def api_librato_webhook( request: HttpRequest, user_profile: UserProfile, *, - payload: Json[ - Mapping[str, Any] - ] = {}, # noqa: B006 # Mapping is indeed immutable, but Json's type annotation drops that information + payload: Json[Mapping[str, Any]] = {}, # noqa: B006 # Mapping is indeed immutable, but Json's type annotation drops that information ) -> HttpResponse: try: attachments = orjson.loads(request.body).get("attachments", []) diff --git a/zilencer/auth.py b/zilencer/auth.py index e69e90a32b..35b4d57934 100644 --- a/zilencer/auth.py +++ b/zilencer/auth.py @@ -103,7 +103,7 @@ def validate_remote_server( def authenticated_remote_server_view( - view_func: Callable[Concatenate[HttpRequest, RemoteZulipServer, ParamT], HttpResponse] + view_func: Callable[Concatenate[HttpRequest, RemoteZulipServer, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]: @wraps(view_func) def _wrapped_view_func( diff --git a/zilencer/management/commands/populate_db.py b/zilencer/management/commands/populate_db.py index d9a75bbab3..f12197bba6 100644 --- a/zilencer/management/commands/populate_db.py +++ b/zilencer/management/commands/populate_db.py @@ -979,8 +979,9 @@ class Command(BaseCommand): "test": {"description": "For testing `code`"}, "errors": {"description": "For errors"}, # 조리법 - Recipes (Korean), Пельмени - Dumplings (Russian) - "조리법 " - + raw_emojis[0]: {"description": "Everything cooking, from pasta to Пельмени"}, + "조리법 " + raw_emojis[0]: { + "description": "Everything cooking, from pasta to Пельмени" + }, } extra_stream_names = [ @@ -1122,7 +1123,7 @@ def get_recipient_by_id(rid: int) -> Recipient: # - multiple messages per subject # - both single and multi-line content def generate_and_send_messages( - data: Tuple[int, Sequence[Sequence[int]], Mapping[str, Any], int] + data: Tuple[int, Sequence[Sequence[int]], Mapping[str, Any], int], ) -> int: realm = get_realm("zulip") (tot_messages, personals_pairs, options, random_seed) = data diff --git a/zilencer/migrations/0027_backfill_remote_realmauditlog_extradata_to_json_field.py b/zilencer/migrations/0027_backfill_remote_realmauditlog_extradata_to_json_field.py index c31689e912..218dedc529 100644 --- a/zilencer/migrations/0027_backfill_remote_realmauditlog_extradata_to_json_field.py +++ b/zilencer/migrations/0027_backfill_remote_realmauditlog_extradata_to_json_field.py @@ -72,7 +72,9 @@ def do_bulk_backfill_extra_data( old_value = audit_log_entry.extra_data_json # type: ignore[attr-defined] # The migration cannot depend on zerver.models, which contains the real type of the RealmAuditLog model, so it cannot be properly typed. new_value = ast.literal_eval(audit_log_entry.extra_data) # type: ignore[attr-defined] # Explained above. if old_value not in ({}, new_value): - inconsistent_extra_data_json.append((audit_log_entry.id, audit_log_entry.extra_data, old_value, new_value)) # type: ignore[attr-defined] # Explained above. + inconsistent_extra_data_json.append( + (audit_log_entry.id, audit_log_entry.extra_data, old_value, new_value) # type: ignore[attr-defined] # Explained above. + ) audit_log_entry.extra_data_json = new_value # type: ignore[attr-defined] # Explained above. audit_log_model._default_manager.bulk_update( python_valued_audit_log_entries, fields=["extra_data_json"] diff --git a/zilencer/migrations/0058_remoteinstallationcount_add_mobile_pushes_forwarded_index.py b/zilencer/migrations/0058_remoteinstallationcount_add_mobile_pushes_forwarded_index.py index 0424c8ffe0..f8b7ecdcc9 100644 --- a/zilencer/migrations/0058_remoteinstallationcount_add_mobile_pushes_forwarded_index.py +++ b/zilencer/migrations/0058_remoteinstallationcount_add_mobile_pushes_forwarded_index.py @@ -4,7 +4,6 @@ from django.db import migrations, models class Migration(migrations.Migration): - dependencies = [ ("zilencer", "0057_remoterealm_last_request_timestamp_and_more"), ] diff --git a/zilencer/migrations/0059_remoterealmauditlog_add_synced_billing_event_type_index.py b/zilencer/migrations/0059_remoterealmauditlog_add_synced_billing_event_type_index.py index 9cbeceb513..86857e9daa 100644 --- a/zilencer/migrations/0059_remoterealmauditlog_add_synced_billing_event_type_index.py +++ b/zilencer/migrations/0059_remoterealmauditlog_add_synced_billing_event_type_index.py @@ -4,7 +4,6 @@ from django.db import migrations, models class Migration(migrations.Migration): - dependencies = [ ("zilencer", "0058_remoteinstallationcount_add_mobile_pushes_forwarded_index"), ] diff --git a/zilencer/models.py b/zilencer/models.py index 75870a6e08..19023018db 100644 --- a/zilencer/models.py +++ b/zilencer/models.py @@ -552,7 +552,8 @@ def get_remote_realm_guest_and_non_guest_count( # bulk_create_users to create the users in the system bot # realm also generate such audit logs. Such audit logs should # never be the latest in a normal realm. - .exclude(extra_data={}).last() + .exclude(extra_data={}) + .last() ) if latest_audit_log is not None: