Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
python: Reformat with Ruff formatter.
Anders Kaseorg570f3dd44741
diff --git a/analytics/tests/test_counts.py b/analytics/tests/test_counts.pyindex 0b161ce2d41..d667bbab005 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.pyindex 94d513b7223..49059f79fd9 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.pyindex 2e40b9832fc..0f1f36931a6 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, modelsclass 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.pyindex db42420dad0..495fd6fba1e 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.pyindex 0f59baa4d64..5fdf23f5fd0 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, modelsclass 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.pyindex 1ddcc9aee48..124c70fd671 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 Nonereturn 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.idrequest.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_PAGESdiff --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_mirrorsindex 56203245101..df87f860976 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 undermirrors when they receive the messages sent every minute by/etc/cron.d/test_zephyr_personal_mirrors"""+import osimport sysimport timediff --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_livenessindex 3d82924b98b..685b9fa1448 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 theDjango ORM."""+import osimport sysfrom datetime import timedeltadiff --git a/puppet/kandra/files/nagios_plugins/zulip_zephyr_mirror/check_zephyr_mirror b/puppet/kandra/files/nagios_plugins/zulip_zephyr_mirror/check_zephyr_mirrorindex d918e2471ab..ce7ef8f2021 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 osimport sysimport timediff --git a/puppet/zulip/files/nagios_plugins/zulip_app_frontend/check_cron_file b/puppet/zulip/files/nagios_plugins/zulip_app_frontend/check_cron_fileindex 2f3f66f71df..ceddc435646 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 thefile output by the cron job is correct."""+import sysimport timefrom typing import Tuplediff --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_errorsindex f7b83d6b194..b6eaebd233f 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 globimport osimport sysdiff --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_timeindex ed23d5d0797..50ef47f1cd4 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 theDjango ORM."""+import argparseimport osimport randomdiff --git a/puppet/zulip/files/nagios_plugins/zulip_postgresql/check_postgresql_replication_lag b/puppet/zulip/files/nagios_plugins/zulip_postgresql/check_postgresql_replication_lagindex 7a98c726e63..443324dc4d8 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 configparserimport reimport subprocessdiff --git a/pyproject.toml b/pyproject.tomlindex 52815cb0469..cbe03d829c3 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 overheaddiff --git a/scripts/lib/email-mirror-postfix b/scripts/lib/email-mirror-postfixindex a5d68676fcf..6870ebdfc6c 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 valuesself-signed certificates. Default value: False.-t Disable sending request to the Zulip server. Default value: False.-"""+import argparseimport base64import jsondiff --git a/scripts/lib/zulip_tools.py b/scripts/lib/zulip_tools.pyindex 8708428d443..da49ed2806b 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-serverindex c25bfbfa98b..ca8e069a2a9 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-dataindex 1d2f16991c1..df9a62ea4cf 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 structuredJSON data for the /team/ page contributors section."""+import argparseimport jsonimport loggingdiff --git a/tools/lint b/tools/lintindex 34523635fb2..89bdc8550a5 100755--- a/tools/lint+++ b/tools/lint@@ -1,7 +1,6 @@#!/usr/bin/env python3import argparseimport os-import reimport systools_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.pyindex d8860da7cc5..b0f7281a0cb 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.pyindex bfeffa2f60b..1a4427304c1 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_onlinediff --git a/zerver/context_processors.py b/zerver/context_processors.pyindex e64cb57380d..a6d1c52c804 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.pyindex a7aa35da756..a47c1b4131f 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.pyindex 8a2932ec7e4..e0375fd9e47 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_methodsdef 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 = Truedef _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.pyindex 4fbc05c69b8..63d20e6044f 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.pyindex 0348bd46d6c..d710365d295 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, whichdiff --git a/zerver/lib/drafts.py b/zerver/lib/drafts.pyindex 4b75d1073f4..be34f7be856 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.pyindex ff07213095d..5c5f5fca629 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.pyindex d96d37433b5..06ec7110b8f 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_tableselse:- assert (- table is not None- ), """+ assert table is not None, """You must specify config.custom_tables if youare not specifying config.table"""exported_tables = [table]diff --git a/zerver/lib/external_accounts.py b/zerver/lib/external_accounts.pyindex 842c8916638..1f1929eef5d 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 dataclassdiff --git a/zerver/lib/message_cache.py b/zerver/lib/message_cache.pyindex c3f5d5f2486..06f4b2dff7c 100644--- a/zerver/lib/message_cache.py+++ b/zerver/lib/message_cache.py@@ -262,7 +262,7 @@ class MessageDict:@staticmethoddef 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.pyindex 33c617625b7..e4c6266d8b3 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.pyindex 01d255d07f2..9849f6017d8 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.pyindex f1ce679fc19..c3a41ee66ad 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 errordef 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_argcountdefault_param_values = cast(FunctionType, req_func).__defaults__diff --git a/zerver/lib/rest.py b/zerver/lib/rest.pyindex be4c5e2254a..cdd84a7c388 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_responsesdecorator that adds headers to a response so that it will never bediff --git a/zerver/lib/soft_deactivation.py b/zerver/lib/soft_deactivation.pyindex 73da6849372..44409aa2fd7 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 = 100users_soft_deactivated = []diff --git a/zerver/lib/test_classes.py b/zerver/lib/test_classes.pyindex 07126f2b35b..922ca646652 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.exceptionyielddef create_default_device(diff --git a/zerver/lib/test_helpers.py b/zerver/lib/test_helpers.pyindex 65f85532380..ea53031ce42 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]: # nocoveragedef 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.pyindex ab511c38a00..3887e32a6cf 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 themetadata from the parameters. We want to keep this function as pure asdiff --git a/zerver/lib/users.py b/zerver/lib/users.pyindex b693d6502c1..490c5720df0 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_dictdiff --git a/zerver/migrations/0460_backfill_realmauditlog_extradata_to_json_field.py b/zerver/migrations/0460_backfill_realmauditlog_extradata_to_json_field.pyindex 89de7b256fb..bd6654f3f5e 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(continuenew_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.pyindex 2411325e111..bf493546456 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.pyindex 36ca1caa7ac..d91186676e6 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 migrationsclass 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.pyindex 384754b493f..664a10bc834 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 migrationsclass 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.pyindex 9f32cd6879f..f698a689eb0 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 migrationsclass 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.pyindex 025879d2a14..8113d42b446 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.pyindex 577a9679d3c..77e461e8687 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, Nonediff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.pyindex 86227ffc5e9..1eb2bcbee99 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.pyindex 9cb83b907d7..f8099a58473 100644--- a/zerver/tests/test_compatibility.py+++ b/zerver/tests/test_compatibility.py@@ -10,10 +10,9 @@ from zerver.lib.test_classes import ZulipTestCaseclass VersionTest(ZulipTestCase):- data = (- [- case.split()- for case in """+ data = [+ case.split()+ for case in """1.2.3 < 1.2.41.2.3 = 1.2.31.4.1 > 1.2.3@@ -30,15 +29,11 @@ class VersionTest(ZulipTestCase):15.1.95 < 16.2.9616.2.96 = 16.2.9620.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.0ok 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.pyindex 4b57acf8f7a..dac6d89484e 100644--- a/zerver/tests/test_link_embed.py+++ b/zerver/tests/test_link_embed.py@@ -196,9 +196,7 @@ class OpenGraphParserTestCase(ZulipTestCase):<head><meta property="og:title" content="中文" /></head>- </html>""".encode(- "big5"- )+ </html>""".encode("big5")parser = OpenGraphParser(html, "text/html; charset=Big5")result = parser.extract_data()self.assertEqual(result.title, "中文")@@ -209,9 +207,7 @@ class OpenGraphParserTestCase(ZulipTestCase):<meta content-type="text/html; charset=Big5" /><meta property="og:title" content="中文" /></head>- </html>""".encode(- "big5"- )+ </html>""".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.pyindex 11b7c40af5e..f1c899614b3 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.pyindex d2ba430c5a0..1d170792b05 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.pyindex bedf92ff63f..c72b247ed03 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.pyindex 5e9f03dca8a..18f6e0d1f61 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.pyindex f4c2b5b3295..86cc15f0c01 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.pyindex ce1a0805fbc..e0e3516df0a 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.pyindex 8ac5e2eecf6..4457db2d1e3 100644--- a/zerver/tests/test_subs.py+++ b/zerver/tests/test_subs.py@@ -3996,7 +3996,7 @@ class SubscriptionAPITest(ZulipTestCase):# For Cn categorypost_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.pyindex 16e98a82a9e..2bdf732790d 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.pyindex 7b1fc3e93f4..07230e0d9f8 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 responsediff --git a/zerver/webhooks/freshdesk/tests.py b/zerver/webhooks/freshdesk/tests.pyindex c754ca0829f..1189bd33f89 100644--- a/zerver/webhooks/freshdesk/tests.py+++ b/zerver/webhooks/freshdesk/tests.py@@ -98,9 +98,7 @@ Requester Bob <[email protected]> updated [ticket #11](http://test1234zzexpected_message = """Requester Bob <[email protected]> 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.pyindex 355ea4ddd24..1665d7e1831 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.pyindex 4b0e9981c1a..dbc95102bdb 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.pyindex e69e90a32be..35b4d579348 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.pyindex d9a75bbab3f..f12197bba6d 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 contentdef 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) = datadiff --git a/zilencer/migrations/0027_backfill_remote_realmauditlog_extradata_to_json_field.py b/zilencer/migrations/0027_backfill_remote_realmauditlog_extradata_to_json_field.pyindex c31689e912c..218dedc529f 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.pyindex 0424c8ffe0f..f8b7ecdcc9c 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, modelsclass 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.pyindex 9cbeceb5130..86857e9daae 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, modelsclass Migration(migrations.Migration):-dependencies = [("zilencer", "0058_remoteinstallationcount_add_mobile_pushes_forwarded_index"),]diff --git a/zilencer/models.py b/zilencer/models.pyindex 75870a6e087..19023018db4 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: