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

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg 2023-07-21 15:34:11 -07:00 committed by Tim Abbott
parent 4e645c8ff9
commit 3b09197fdf
21 changed files with 55 additions and 63 deletions

View File

@ -155,7 +155,7 @@ class Command(BaseCommand):
table: Type[BaseCount], table: Type[BaseCount],
) -> None: ) -> None:
end_times = time_range( 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: if table == InstallationCount:
id_args: Dict[str, Any] = {} id_args: Dict[str, Any] = {}

View File

@ -126,6 +126,11 @@ def communities_view(request: HttpRequest) -> HttpResponse:
for realm in want_to_be_advertised_realms: for realm in want_to_be_advertised_realms:
open_to_public = not realm.invite_required and not realm.emails_restricted_to_domains 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: 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( eligible_realms.append(
{ {
"id": realm.id, "id": realm.id,
@ -133,11 +138,7 @@ def communities_view(request: HttpRequest) -> HttpResponse:
"realm_url": realm.uri, "realm_url": realm.uri,
"logo_url": get_realm_icon_url(realm), "logo_url": get_realm_icon_url(realm),
"description": get_realm_text_description(realm), "description": get_realm_text_description(realm),
"org_type_key": [ "org_type_key": org_type,
org_type
for org_type in Realm.ORG_TYPES
if Realm.ORG_TYPES[org_type]["id"] == realm.org_type
][0],
} }
) )
unique_org_type_ids.add(realm.org_type) unique_org_type_ids.add(realm.org_type)

View File

@ -55,11 +55,11 @@ class TestRuleList(TestCase):
) )
for line in rule.get("bad_lines", []): for line in rule.get("bad_lines", []):
with patch( for filename in rule.get("include_only", {"foo.bar"}):
"builtins.open", return_value=StringIO(line + "\n\n"), autospec=True with patch(
), patch("builtins.print"): "builtins.open", return_value=StringIO(line + "\n\n"), autospec=True
filename = list(rule.get("include_only", {"foo.bar"}))[0] ), patch("builtins.print"):
self.assertTrue( self.assertTrue(
RuleList([], [rule]).custom_check_file(filename, "baz", ""), RuleList([], [rule]).custom_check_file(filename, "baz", ""),
f"The pattern '{pattern}' didn't match the line '{line}' while it should.", f"The pattern '{pattern}' didn't match the line '{line}' while it should.",
) )

View File

@ -453,11 +453,9 @@ def check_presence(
assert isinstance(event["presence"], dict) assert isinstance(event["presence"], dict)
# Our tests only have one presence value. # Our tests only have one presence value.
assert len(event["presence"]) == 1 [(event_presence_key, event_presence_value)] = event["presence"].items()
assert event_presence_key == presence_key
assert list(event["presence"].keys())[0] == presence_key assert event_presence_value["status"] == status
assert list(event["presence"].values())[0]["status"] == status
# Type for the legacy user field; the `user_id` field is intended to # Type for the legacy user field; the `user_id` field is intended to

View File

@ -1152,8 +1152,9 @@ class InlineInterestingLinkProcessor(markdown.treeprocessors.Treeprocessor):
): ):
return insertion_index return insertion_index
uncle_link = list(uncle.iter(tag="a"))[0].attrib["href"] uncle_link = uncle.find("a")
if uncle_link not in parent_links: assert uncle_link is not None
if uncle_link.attrib["href"] not in parent_links:
return insertion_index return insertion_index
def run(self, root: Element) -> None: def run(self, root: Element) -> None:

View File

@ -1542,7 +1542,8 @@ Output:
return values return values
def find_by_id(self, data: List[Dict[str, Any]], db_id: int) -> Dict[str, Any]: 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: def init_default_ldap_database(self) -> None:
""" """

View File

@ -623,10 +623,10 @@ def get_user_groups(client: Client) -> int:
# {code_example|end} # {code_example|end}
validate_against_openapi_schema(result, "/user_groups", "get", "200") 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" 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"] return marketing_user_group["id"]

View File

@ -3698,7 +3698,7 @@ class GenericOpenIdConnectTest(SocialAuthBase):
account_data_dict = self.get_account_data_dict(email=email, name=name) account_data_dict = self.get_account_data_dict(email=email, name=name)
oidc_setting_dict = copy.deepcopy(settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS) 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 idp_settings_dict["auto_signup"] = True
with mock.patch.object(GenericOpenIdConnectBackend, "settings_dict", new=idp_settings_dict): with mock.patch.object(GenericOpenIdConnectBackend, "settings_dict", new=idp_settings_dict):
result = self.social_auth_test( 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) 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) 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"] del idp_config_dict["client_id"]
with self.settings(SOCIAL_AUTH_OIDC_ENABLED_IDPS=mock_oidc_setting_dict): with self.settings(SOCIAL_AUTH_OIDC_ENABLED_IDPS=mock_oidc_setting_dict):
result = self.social_auth_test( 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) 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) 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 mock_oidc_setting_dict["secondprovider"] = idp_config_dict
with self.settings(SOCIAL_AUTH_OIDC_ENABLED_IDPS=mock_oidc_setting_dict): with self.settings(SOCIAL_AUTH_OIDC_ENABLED_IDPS=mock_oidc_setting_dict):
result = self.social_auth_test( result = self.social_auth_test(

View File

@ -585,9 +585,9 @@ class GetEventsTest(ZulipTestCase):
self.assert_json_success(result) self.assert_json_success(result)
self.assert_length(events, 1) self.assert_length(events, 1)
pronouns_field = [ [pronouns_field] = (
field for field in events[0]["fields"] if field["id"] == profile_field.id field for field in events[0]["fields"] if field["id"] == profile_field.id
][0] )
if pronouns_field_type_supported: if pronouns_field_type_supported:
expected_type = CustomProfileField.PRONOUNS expected_type = CustomProfileField.PRONOUNS
else: else:
@ -794,9 +794,7 @@ class FetchInitialStateDataTest(ZulipTestCase):
) )
self.assertIn("custom_profile_fields", result) self.assertIn("custom_profile_fields", result)
custom_profile_fields = result["custom_profile_fields"] custom_profile_fields = result["custom_profile_fields"]
pronouns_field = [field for field in custom_profile_fields if field["name"] == "Pronouns"][ [pronouns_field] = (field for field in custom_profile_fields if field["name"] == "Pronouns")
0
]
self.assertEqual(pronouns_field["type"], CustomProfileField.SHORT_TEXT) self.assertEqual(pronouns_field["type"], CustomProfileField.SHORT_TEXT)
result = fetch_initial_state_data( result = fetch_initial_state_data(
@ -805,9 +803,7 @@ class FetchInitialStateDataTest(ZulipTestCase):
) )
self.assertIn("custom_profile_fields", result) self.assertIn("custom_profile_fields", result)
custom_profile_fields = result["custom_profile_fields"] custom_profile_fields = result["custom_profile_fields"]
pronouns_field = [field for field in custom_profile_fields if field["name"] == "Pronouns"][ [pronouns_field] = (field for field in custom_profile_fields if field["name"] == "Pronouns")
0
]
self.assertEqual(pronouns_field["type"], CustomProfileField.PRONOUNS) self.assertEqual(pronouns_field["type"], CustomProfileField.PRONOUNS)

View File

@ -1080,9 +1080,9 @@ class NormalActionsTest(BaseAction):
pronouns_field_type_supported=True, pronouns_field_type_supported=True,
) )
check_custom_profile_fields("events[0]", events[0]) 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 field_obj for field_obj in events[0]["fields"] if field_obj["id"] == field.id
][0] )
self.assertEqual(pronouns_field["type"], CustomProfileField.PRONOUNS) self.assertEqual(pronouns_field["type"], CustomProfileField.PRONOUNS)
hint = "What pronouns should people use to refer you?" hint = "What pronouns should people use to refer you?"
@ -1091,9 +1091,9 @@ class NormalActionsTest(BaseAction):
pronouns_field_type_supported=False, pronouns_field_type_supported=False,
) )
check_custom_profile_fields("events[0]", events[0]) 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 field_obj for field_obj in events[0]["fields"] if field_obj["id"] == field.id
][0] )
self.assertEqual(pronouns_field["type"], CustomProfileField.SHORT_TEXT) self.assertEqual(pronouns_field["type"], CustomProfileField.SHORT_TEXT)
def test_custom_profile_field_data_events(self) -> None: def test_custom_profile_field_data_events(self) -> None:

View File

@ -95,16 +95,16 @@ class GitterImporter(ZulipTestCase):
self.assertIn(messages["zerver_message"][0]["content"], "test message") self.assertIn(messages["zerver_message"][0]["content"], "test message")
# test usermessages and soft-deactivation of users # test usermessages and soft-deactivation of users
user_should_be_long_term_idle = [ [user_should_be_long_term_idle] = (
user user
for user in realm["zerver_userprofile"] for user in realm["zerver_userprofile"]
if user["delivery_email"] == "username1@users.noreply.github.com" if user["delivery_email"] == "username1@users.noreply.github.com"
][0] )
user_should_not_be_long_term_idle = [ [user_should_not_be_long_term_idle] = (
user user
for user in realm["zerver_userprofile"] for user in realm["zerver_userprofile"]
if user["delivery_email"] == "username2@users.noreply.github.com" if user["delivery_email"] == "username2@users.noreply.github.com"
][0] )
self.assertEqual(user_should_be_long_term_idle["long_term_idle"], True) self.assertEqual(user_should_be_long_term_idle["long_term_idle"], True)
# Only the user who's not soft-deactivated gets UserMessages. # Only the user who's not soft-deactivated gets UserMessages.

View File

@ -2812,7 +2812,7 @@ class GetOldMessagesTest(ZulipTestCase):
'<p>昨日、<span class="highlight">日本</span>のお菓子を送りました。</p>', '<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_TOPIC], "english")
self.assertEqual( self.assertEqual(
english_message["match_content"], english_message["match_content"],

View File

@ -586,9 +586,7 @@ class MessagePOSTTest(ZulipTestCase):
message_id = orjson.loads(result.content)["id"] message_id = orjson.loads(result.content)["id"]
recent_conversations = get_recent_private_conversations(user_profile) recent_conversations = get_recent_private_conversations(user_profile)
self.assert_length(recent_conversations, 1) [(recipient_id, recent_conversation)] = recent_conversations.items()
recent_conversation = list(recent_conversations.values())[0]
recipient_id = list(recent_conversations.keys())[0]
self.assertEqual(set(recent_conversation["user_ids"]), {othello.id}) self.assertEqual(set(recent_conversation["user_ids"]), {othello.id})
self.assertEqual(recent_conversation["max_message_id"], message_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 # Now verify we have the appropriate self-pm data structure
del recent_conversations[recipient_id] del recent_conversations[recipient_id]
recent_conversation = list(recent_conversations.values())[0] [(recipient_id, recent_conversation)] = recent_conversations.items()
recipient_id = list(recent_conversations.keys())[0]
self.assertEqual(set(recent_conversation["user_ids"]), set()) self.assertEqual(set(recent_conversation["user_ids"]), set())
self.assertEqual(recent_conversation["max_message_id"], self_message_id) 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) self.assert_length(msg_data["huddle_dict"].keys(), 2)
recent_conversations = get_recent_private_conversations(users[1]) recent_conversations = get_recent_private_conversations(users[1])
self.assert_length(recent_conversations, 1) [recent_conversation] = recent_conversations.values()
recent_conversation = list(recent_conversations.values())[0]
self.assertEqual( self.assertEqual(
set(recent_conversation["user_ids"]), {user.id for user in users if user != users[1]} set(recent_conversation["user_ids"]), {user.id for user in users if user != users[1]}
) )

View File

@ -2158,7 +2158,7 @@ class BulkUsersTest(ZulipTestCase):
data = dict(client_gravatar=orjson.dumps(client_gravatar).decode()) data = dict(client_gravatar=orjson.dumps(client_gravatar).decode())
result = self.client_get("/json/users", data) result = self.client_get("/json/users", data)
rows = self.assert_json_success(result)["members"] 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"] return hamlet_data["avatar_url"]
self.assertEqual( self.assertEqual(

View File

@ -40,7 +40,7 @@ def upload_emoji(
raise JsonableError(_("You must upload exactly one file.")) raise JsonableError(_("You must upload exactly one file."))
if emoji_name in valid_built_in_emoji and not user_profile.is_realm_admin: if emoji_name in valid_built_in_emoji and not user_profile.is_realm_admin:
raise JsonableError(_("Only administrators can override default emoji.")) 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 isinstance(emoji_file, UploadedFile)
assert emoji_file.size is not None assert emoji_file.size is not None
if (settings.MAX_EMOJI_FILE_SIZE_MIB * 1024 * 1024) < emoji_file.size: if (settings.MAX_EMOJI_FILE_SIZE_MIB * 1024 * 1024) < emoji_file.size:

View File

@ -19,7 +19,7 @@ def upload_icon(request: HttpRequest, user_profile: UserProfile) -> HttpResponse
if len(request.FILES) != 1: if len(request.FILES) != 1:
raise JsonableError(_("You must upload exactly one icon.")) 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 isinstance(icon_file, UploadedFile)
assert icon_file.size is not None assert icon_file.size is not None
if (settings.MAX_ICON_FILE_SIZE_MIB * 1024 * 1024) < icon_file.size: if (settings.MAX_ICON_FILE_SIZE_MIB * 1024 * 1024) < icon_file.size:

View File

@ -25,7 +25,7 @@ def upload_logo(
if len(request.FILES) != 1: if len(request.FILES) != 1:
raise JsonableError(_("You must upload exactly one logo.")) 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 isinstance(logo_file, UploadedFile)
assert logo_file.size is not None assert logo_file.size is not None
if (settings.MAX_LOGO_FILE_SIZE_MIB * 1024 * 1024) < logo_file.size: if (settings.MAX_LOGO_FILE_SIZE_MIB * 1024 * 1024) < logo_file.size:

View File

@ -269,7 +269,7 @@ def upload_file_backend(request: HttpRequest, user_profile: UserProfile) -> Http
if len(request.FILES) != 1: if len(request.FILES) != 1:
raise JsonableError(_("You may only upload one file at a time")) 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) assert isinstance(user_file, UploadedFile)
file_size = user_file.size file_size = user_file.size
assert file_size is not None assert file_size is not None

View File

@ -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: if avatar_changes_disabled(user_profile.realm) and not user_profile.is_realm_admin:
raise JsonableError(str(AVATAR_CHANGES_DISABLED_ERROR)) 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 isinstance(user_file, UploadedFile)
assert user_file.size is not None assert user_file.size is not None
if (settings.MAX_AVATAR_FILE_SIZE_MIB * 1024 * 1024) < user_file.size: if (settings.MAX_AVATAR_FILE_SIZE_MIB * 1024 * 1024) < user_file.size:

View File

@ -414,7 +414,7 @@ def patch_bot_backend(
if len(request.FILES) == 0: if len(request.FILES) == 0:
pass pass
elif len(request.FILES) == 1: elif len(request.FILES) == 1:
user_file = list(request.FILES.values())[0] [user_file] = request.FILES.values()
assert isinstance(user_file, UploadedFile) assert isinstance(user_file, UploadedFile)
assert user_file.size is not None assert user_file.size is not None
upload_avatar_image(user_file, user_profile, bot) upload_avatar_image(user_file, user_profile, bot)
@ -556,7 +556,7 @@ def add_bot_backend(
acting_user=user_profile, acting_user=user_profile,
) )
if len(request.FILES) == 1: if len(request.FILES) == 1:
user_file = list(request.FILES.values())[0] [user_file] = request.FILES.values()
assert isinstance(user_file, UploadedFile) assert isinstance(user_file, UploadedFile)
assert user_file.size is not None assert user_file.size is not None
upload_avatar_image(user_file, user_profile, bot_profile) upload_avatar_image(user_file, user_profile, bot_profile)

View File

@ -2844,9 +2844,8 @@ class GenericOpenIdConnectBackend(SocialAuthMixin, OpenIdConnectAuth):
# Hack: We don't yet support multiple IdPs, but we want this # Hack: We don't yet support multiple IdPs, but we want this
# module to import if nothing has been configured yet. # module to import if nothing has been configured yet.
settings_dict: OIDCIdPConfigDict = list( settings_dict: OIDCIdPConfigDict
settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS.values() or [OIDCIdPConfigDict()] [settings_dict] = settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS.values() or [OIDCIdPConfigDict()]
)[0]
display_icon: Optional[str] = settings_dict.get("display_icon", None) display_icon: Optional[str] = settings_dict.get("display_icon", None)
display_name: str = settings_dict.get("display_name", "OIDC") display_name: str = settings_dict.get("display_name", "OIDC")
@ -2871,7 +2870,7 @@ class GenericOpenIdConnectBackend(SocialAuthMixin, OpenIdConnectAuth):
return False return False
mandatory_config_keys = ["oidc_url", "client_id", "secret"] 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): if not all(idp_config_dict.get(key) for key in mandatory_config_keys):
return False return False