Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

ruff: Fix RUF015 Prefer `next(...)` over single element slice.

Anders Kaseorg3b09197fdfb2
diff --git a/analytics/management/commands/populate_analytics_db.py b/analytics/management/commands/populate_analytics_db.py
index 57cdd9715c3..3abc148e076 100644
--- a/analytics/management/commands/populate_analytics_db.py
+++ b/analytics/management/commands/populate_analytics_db.py
@@ -155,7 +155,7 @@ class Command(BaseCommand):
table: Type[BaseCount],
) -> None:
end_times = time_range(
- last_end_time, last_end_time, stat.frequency, len(list(fixture_data.values())[0])
+ last_end_time, last_end_time, stat.frequency, len(next(iter(fixture_data.values())))
)
if table == InstallationCount:
id_args: Dict[str, Any] = {}
diff --git a/corporate/views/portico.py b/corporate/views/portico.py
index b05b705894d..dd7b06221ee 100644
--- a/corporate/views/portico.py
+++ b/corporate/views/portico.py
@@ -126,6 +126,11 @@ def communities_view(request: HttpRequest) -> HttpResponse:
for realm in want_to_be_advertised_realms:
open_to_public = not realm.invite_required and not realm.emails_restricted_to_domains
if realm.allow_web_public_streams_access() or open_to_public:
+ [org_type] = (
+ org_type
+ for org_type in Realm.ORG_TYPES
+ if Realm.ORG_TYPES[org_type]["id"] == realm.org_type
+ )
eligible_realms.append(
{
"id": realm.id,
@@ -133,11 +138,7 @@ def communities_view(request: HttpRequest) -> HttpResponse:
"realm_url": realm.uri,
"logo_url": get_realm_icon_url(realm),
"description": get_realm_text_description(realm),
- "org_type_key": [
- org_type
- for org_type in Realm.ORG_TYPES
- if Realm.ORG_TYPES[org_type]["id"] == realm.org_type
- ][0],
+ "org_type_key": org_type,
}
)
unique_org_type_ids.add(realm.org_type)
diff --git a/tools/tests/test_zulint_custom_rules.py b/tools/tests/test_zulint_custom_rules.py
index f1fa147ada9..8deb85dbbd0 100644
--- a/tools/tests/test_zulint_custom_rules.py
+++ b/tools/tests/test_zulint_custom_rules.py
@@ -55,11 +55,11 @@ class TestRuleList(TestCase):
)
for line in rule.get("bad_lines", []):
- with patch(
- "builtins.open", return_value=StringIO(line + "\n\n"), autospec=True
- ), patch("builtins.print"):
- filename = list(rule.get("include_only", {"foo.bar"}))[0]
- self.assertTrue(
- RuleList([], [rule]).custom_check_file(filename, "baz", ""),
- f"The pattern '{pattern}' didn't match the line '{line}' while it should.",
- )
+ for filename in rule.get("include_only", {"foo.bar"}):
+ with patch(
+ "builtins.open", return_value=StringIO(line + "\n\n"), autospec=True
+ ), patch("builtins.print"):
+ self.assertTrue(
+ RuleList([], [rule]).custom_check_file(filename, "baz", ""),
+ f"The pattern '{pattern}' didn't match the line '{line}' while it should.",
+ )
diff --git a/zerver/lib/event_schema.py b/zerver/lib/event_schema.py
index 0d0fe81fb2c..731d30d23a4 100644
--- a/zerver/lib/event_schema.py
+++ b/zerver/lib/event_schema.py
@@ -453,11 +453,9 @@ def check_presence(
assert isinstance(event["presence"], dict)
# Our tests only have one presence value.
- assert len(event["presence"]) == 1
-
- assert list(event["presence"].keys())[0] == presence_key
-
- assert list(event["presence"].values())[0]["status"] == status
+ [(event_presence_key, event_presence_value)] = event["presence"].items()
+ assert event_presence_key == presence_key
+ assert event_presence_value["status"] == status
# Type for the legacy user field; the `user_id` field is intended to
diff --git a/zerver/lib/markdown/__init__.py b/zerver/lib/markdown/__init__.py
index 8d7892728d7..69b475e9b99 100644
--- a/zerver/lib/markdown/__init__.py
+++ b/zerver/lib/markdown/__init__.py
@@ -1152,8 +1152,9 @@ class InlineInterestingLinkProcessor(markdown.treeprocessors.Treeprocessor):
):
return insertion_index
- uncle_link = list(uncle.iter(tag="a"))[0].attrib["href"]
- if uncle_link not in parent_links:
+ uncle_link = uncle.find("a")
+ assert uncle_link is not None
+ if uncle_link.attrib["href"] not in parent_links:
return insertion_index
def run(self, root: Element) -> None:
diff --git a/zerver/lib/test_classes.py b/zerver/lib/test_classes.py
index d5bd5715e7b..62a3b88fd81 100644
--- a/zerver/lib/test_classes.py
+++ b/zerver/lib/test_classes.py
@@ -1542,7 +1542,8 @@ Output:
return values
def find_by_id(self, data: List[Dict[str, Any]], db_id: int) -> Dict[str, Any]:
- return [r for r in data if r["id"] == db_id][0]
+ [r] = (r for r in data if r["id"] == db_id)
+ return r
def init_default_ldap_database(self) -> None:
"""
diff --git a/zerver/openapi/python_examples.py b/zerver/openapi/python_examples.py
index 48163b1b0c2..66fb61a18d5 100644
--- a/zerver/openapi/python_examples.py
+++ b/zerver/openapi/python_examples.py
@@ -623,10 +623,10 @@ def get_user_groups(client: Client) -> int:
# {code_example|end}
validate_against_openapi_schema(result, "/user_groups", "get", "200")
- hamlet_user_group = [u for u in result["user_groups"] if u["name"] == "hamletcharacters"][0]
+ [hamlet_user_group] = (u for u in result["user_groups"] if u["name"] == "hamletcharacters")
assert hamlet_user_group["description"] == "Characters of Hamlet"
- marketing_user_group = [u for u in result["user_groups"] if u["name"] == "marketing"][0]
+ [marketing_user_group] = (u for u in result["user_groups"] if u["name"] == "marketing")
return marketing_user_group["id"]
diff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.py
index f8525b26cc7..c6c37a2d5f6 100644
--- a/zerver/tests/test_auth_backends.py
+++ b/zerver/tests/test_auth_backends.py
@@ -3698,7 +3698,7 @@ class GenericOpenIdConnectTest(SocialAuthBase):
account_data_dict = self.get_account_data_dict(email=email, name=name)
oidc_setting_dict = copy.deepcopy(settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS)
- idp_settings_dict = list(oidc_setting_dict.values())[0]
+ [idp_settings_dict] = oidc_setting_dict.values()
idp_settings_dict["auto_signup"] = True
with mock.patch.object(GenericOpenIdConnectBackend, "settings_dict", new=idp_settings_dict):
result = self.social_auth_test(
@@ -3748,7 +3748,7 @@ class GenericOpenIdConnectTest(SocialAuthBase):
account_data_dict = self.get_account_data_dict(email=self.email, name=self.name)
mock_oidc_setting_dict = copy.deepcopy(settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS)
- idp_config_dict = list(mock_oidc_setting_dict.values())[0]
+ [idp_config_dict] = mock_oidc_setting_dict.values()
del idp_config_dict["client_id"]
with self.settings(SOCIAL_AUTH_OIDC_ENABLED_IDPS=mock_oidc_setting_dict):
result = self.social_auth_test(
@@ -3763,7 +3763,7 @@ class GenericOpenIdConnectTest(SocialAuthBase):
account_data_dict = self.get_account_data_dict(email=self.email, name=self.name)
mock_oidc_setting_dict = copy.deepcopy(settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS)
- idp_config_dict = list(mock_oidc_setting_dict.values())[0]
+ [idp_config_dict] = mock_oidc_setting_dict.values()
mock_oidc_setting_dict["secondprovider"] = idp_config_dict
with self.settings(SOCIAL_AUTH_OIDC_ENABLED_IDPS=mock_oidc_setting_dict):
result = self.social_auth_test(
diff --git a/zerver/tests/test_event_system.py b/zerver/tests/test_event_system.py
index aaeb051a1ef..cbe9d11d1f2 100644
--- a/zerver/tests/test_event_system.py
+++ b/zerver/tests/test_event_system.py
@@ -585,9 +585,9 @@ class GetEventsTest(ZulipTestCase):
self.assert_json_success(result)
self.assert_length(events, 1)
- pronouns_field = [
+ [pronouns_field] = (
field for field in events[0]["fields"] if field["id"] == profile_field.id
- ][0]
+ )
if pronouns_field_type_supported:
expected_type = CustomProfileField.PRONOUNS
else:
@@ -794,9 +794,7 @@ class FetchInitialStateDataTest(ZulipTestCase):
)
self.assertIn("custom_profile_fields", result)
custom_profile_fields = result["custom_profile_fields"]
- pronouns_field = [field for field in custom_profile_fields if field["name"] == "Pronouns"][
- 0
- ]
+ [pronouns_field] = (field for field in custom_profile_fields if field["name"] == "Pronouns")
self.assertEqual(pronouns_field["type"], CustomProfileField.SHORT_TEXT)
result = fetch_initial_state_data(
@@ -805,9 +803,7 @@ class FetchInitialStateDataTest(ZulipTestCase):
)
self.assertIn("custom_profile_fields", result)
custom_profile_fields = result["custom_profile_fields"]
- pronouns_field = [field for field in custom_profile_fields if field["name"] == "Pronouns"][
- 0
- ]
+ [pronouns_field] = (field for field in custom_profile_fields if field["name"] == "Pronouns")
self.assertEqual(pronouns_field["type"], CustomProfileField.PRONOUNS)
diff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.py
index 43ec086b0c0..78f9d26ace1 100644
--- a/zerver/tests/test_events.py
+++ b/zerver/tests/test_events.py
@@ -1080,9 +1080,9 @@ class NormalActionsTest(BaseAction):
pronouns_field_type_supported=True,
)
check_custom_profile_fields("events[0]", events[0])
- pronouns_field = [
+ [pronouns_field] = (
field_obj for field_obj in events[0]["fields"] if field_obj["id"] == field.id
- ][0]
+ )
self.assertEqual(pronouns_field["type"], CustomProfileField.PRONOUNS)
hint = "What pronouns should people use to refer you?"
@@ -1091,9 +1091,9 @@ class NormalActionsTest(BaseAction):
pronouns_field_type_supported=False,
)
check_custom_profile_fields("events[0]", events[0])
- pronouns_field = [
+ [pronouns_field] = (
field_obj for field_obj in events[0]["fields"] if field_obj["id"] == field.id
- ][0]
+ )
self.assertEqual(pronouns_field["type"], CustomProfileField.SHORT_TEXT)
def test_custom_profile_field_data_events(self) -> None:
diff --git a/zerver/tests/test_gitter_importer.py b/zerver/tests/test_gitter_importer.py
index 09aeb1ffac7..e09f9976171 100644
--- a/zerver/tests/test_gitter_importer.py
+++ b/zerver/tests/test_gitter_importer.py
@@ -95,16 +95,16 @@ class GitterImporter(ZulipTestCase):
self.assertIn(messages["zerver_message"][0]["content"], "test message")
# test usermessages and soft-deactivation of users
- user_should_be_long_term_idle = [
+ [user_should_be_long_term_idle] = (
user
for user in realm["zerver_userprofile"]
if user["delivery_email"] == "[email protected]"
- ][0]
- user_should_not_be_long_term_idle = [
+ )
+ [user_should_not_be_long_term_idle] = (
user
for user in realm["zerver_userprofile"]
if user["delivery_email"] == "[email protected]"
- ][0]
+ )
self.assertEqual(user_should_be_long_term_idle["long_term_idle"], True)
# Only the user who's not soft-deactivated gets UserMessages.
diff --git a/zerver/tests/test_message_fetch.py b/zerver/tests/test_message_fetch.py
index 23acc64e052..ecbf55f58d3 100644
--- a/zerver/tests/test_message_fetch.py
+++ b/zerver/tests/test_message_fetch.py
@@ -2812,7 +2812,7 @@ class GetOldMessagesTest(ZulipTestCase):
'<p>昨日、<span class="highlight">日本</span>のお菓子を送りました。</p>',
)
- english_message = [m for m in messages if m[TOPIC_NAME] == "english"][0]
+ [english_message] = (m for m in messages if m[TOPIC_NAME] == "english")
self.assertEqual(english_message[MATCH_TOPIC], "english")
self.assertEqual(
english_message["match_content"],
diff --git a/zerver/tests/test_message_send.py b/zerver/tests/test_message_send.py
index dfd25d4fac5..d4ffd76c788 100644
--- a/zerver/tests/test_message_send.py
+++ b/zerver/tests/test_message_send.py
@@ -586,9 +586,7 @@ class MessagePOSTTest(ZulipTestCase):
message_id = orjson.loads(result.content)["id"]
recent_conversations = get_recent_private_conversations(user_profile)
- self.assert_length(recent_conversations, 1)
- recent_conversation = list(recent_conversations.values())[0]
- recipient_id = list(recent_conversations.keys())[0]
+ [(recipient_id, recent_conversation)] = recent_conversations.items()
self.assertEqual(set(recent_conversation["user_ids"]), {othello.id})
self.assertEqual(recent_conversation["max_message_id"], message_id)
@@ -612,8 +610,7 @@ class MessagePOSTTest(ZulipTestCase):
# Now verify we have the appropriate self-pm data structure
del recent_conversations[recipient_id]
- recent_conversation = list(recent_conversations.values())[0]
- recipient_id = list(recent_conversations.keys())[0]
+ [(recipient_id, recent_conversation)] = recent_conversations.items()
self.assertEqual(set(recent_conversation["user_ids"]), set())
self.assertEqual(recent_conversation["max_message_id"], self_message_id)
@@ -1997,8 +1994,7 @@ class StreamMessagesTest(ZulipTestCase):
self.assert_length(msg_data["huddle_dict"].keys(), 2)
recent_conversations = get_recent_private_conversations(users[1])
- self.assert_length(recent_conversations, 1)
- recent_conversation = list(recent_conversations.values())[0]
+ [recent_conversation] = recent_conversations.values()
self.assertEqual(
set(recent_conversation["user_ids"]), {user.id for user in users if user != users[1]}
)
diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.py
index bec20d2329a..fa05467c31f 100644
--- a/zerver/tests/test_users.py
+++ b/zerver/tests/test_users.py
@@ -2158,7 +2158,7 @@ class BulkUsersTest(ZulipTestCase):
data = dict(client_gravatar=orjson.dumps(client_gravatar).decode())
result = self.client_get("/json/users", data)
rows = self.assert_json_success(result)["members"]
- hamlet_data = [row for row in rows if row["user_id"] == hamlet.id][0]
+ [hamlet_data] = (row for row in rows if row["user_id"] == hamlet.id)
return hamlet_data["avatar_url"]
self.assertEqual(
diff --git a/zerver/views/realm_emoji.py b/zerver/views/realm_emoji.py
index c0bc66b0a70..35bf25932c1 100644
--- a/zerver/views/realm_emoji.py
+++ b/zerver/views/realm_emoji.py
@@ -40,7 +40,7 @@ def upload_emoji(
raise JsonableError(_("You must upload exactly one file."))
if emoji_name in valid_built_in_emoji and not user_profile.is_realm_admin:
raise JsonableError(_("Only administrators can override default emoji."))
- emoji_file = list(request.FILES.values())[0]
+ [emoji_file] = request.FILES.values()
assert isinstance(emoji_file, UploadedFile)
assert emoji_file.size is not None
if (settings.MAX_EMOJI_FILE_SIZE_MIB * 1024 * 1024) < emoji_file.size:
diff --git a/zerver/views/realm_icon.py b/zerver/views/realm_icon.py
index 683dde730ca..bff6d2346b6 100644
--- a/zerver/views/realm_icon.py
+++ b/zerver/views/realm_icon.py
@@ -19,7 +19,7 @@ def upload_icon(request: HttpRequest, user_profile: UserProfile) -> HttpResponse
if len(request.FILES) != 1:
raise JsonableError(_("You must upload exactly one icon."))
- icon_file = list(request.FILES.values())[0]
+ [icon_file] = request.FILES.values()
assert isinstance(icon_file, UploadedFile)
assert icon_file.size is not None
if (settings.MAX_ICON_FILE_SIZE_MIB * 1024 * 1024) < icon_file.size:
diff --git a/zerver/views/realm_logo.py b/zerver/views/realm_logo.py
index 0a712ab172b..88a9e1402de 100644
--- a/zerver/views/realm_logo.py
+++ b/zerver/views/realm_logo.py
@@ -25,7 +25,7 @@ def upload_logo(
if len(request.FILES) != 1:
raise JsonableError(_("You must upload exactly one logo."))
- logo_file = list(request.FILES.values())[0]
+ [logo_file] = request.FILES.values()
assert isinstance(logo_file, UploadedFile)
assert logo_file.size is not None
if (settings.MAX_LOGO_FILE_SIZE_MIB * 1024 * 1024) < logo_file.size:
diff --git a/zerver/views/upload.py b/zerver/views/upload.py
index fbe5caaf25e..9c01f343be1 100644
--- a/zerver/views/upload.py
+++ b/zerver/views/upload.py
@@ -269,7 +269,7 @@ def upload_file_backend(request: HttpRequest, user_profile: UserProfile) -> Http
if len(request.FILES) != 1:
raise JsonableError(_("You may only upload one file at a time"))
- user_file = list(request.FILES.values())[0]
+ [user_file] = request.FILES.values()
assert isinstance(user_file, UploadedFile)
file_size = user_file.size
assert file_size is not None
diff --git a/zerver/views/user_settings.py b/zerver/views/user_settings.py
index 90bb7244c33..a9ac8fd2a98 100644
--- a/zerver/views/user_settings.py
+++ b/zerver/views/user_settings.py
@@ -363,7 +363,7 @@ def set_avatar_backend(request: HttpRequest, user_profile: UserProfile) -> HttpR
if avatar_changes_disabled(user_profile.realm) and not user_profile.is_realm_admin:
raise JsonableError(str(AVATAR_CHANGES_DISABLED_ERROR))
- user_file = list(request.FILES.values())[0]
+ [user_file] = request.FILES.values()
assert isinstance(user_file, UploadedFile)
assert user_file.size is not None
if (settings.MAX_AVATAR_FILE_SIZE_MIB * 1024 * 1024) < user_file.size:
diff --git a/zerver/views/users.py b/zerver/views/users.py
index 1bbc4893b5c..7416e26e072 100644
--- a/zerver/views/users.py
+++ b/zerver/views/users.py
@@ -414,7 +414,7 @@ def patch_bot_backend(
if len(request.FILES) == 0:
pass
elif len(request.FILES) == 1:
- user_file = list(request.FILES.values())[0]
+ [user_file] = request.FILES.values()
assert isinstance(user_file, UploadedFile)
assert user_file.size is not None
upload_avatar_image(user_file, user_profile, bot)
@@ -556,7 +556,7 @@ def add_bot_backend(
acting_user=user_profile,
)
if len(request.FILES) == 1:
- user_file = list(request.FILES.values())[0]
+ [user_file] = request.FILES.values()
assert isinstance(user_file, UploadedFile)
assert user_file.size is not None
upload_avatar_image(user_file, user_profile, bot_profile)
diff --git a/zproject/backends.py b/zproject/backends.py
index f0060bb2576..d5c3100a48b 100644
--- a/zproject/backends.py
+++ b/zproject/backends.py
@@ -2844,9 +2844,8 @@ class GenericOpenIdConnectBackend(SocialAuthMixin, OpenIdConnectAuth):
# Hack: We don't yet support multiple IdPs, but we want this
# module to import if nothing has been configured yet.
- settings_dict: OIDCIdPConfigDict = list(
- settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS.values() or [OIDCIdPConfigDict()]
- )[0]
+ settings_dict: OIDCIdPConfigDict
+ [settings_dict] = settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS.values() or [OIDCIdPConfigDict()]
display_icon: Optional[str] = settings_dict.get("display_icon", None)
display_name: str = settings_dict.get("display_name", "OIDC")
@@ -2871,7 +2870,7 @@ class GenericOpenIdConnectBackend(SocialAuthMixin, OpenIdConnectAuth):
return False
mandatory_config_keys = ["oidc_url", "client_id", "secret"]
- idp_config_dict = list(settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS.values())[0]
+ [idp_config_dict] = settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS.values()
if not all(idp_config_dict.get(key) for key in mandatory_config_keys):
return False