From 6e14149f245839e7a2ce4ba3a517aee0ef26dbc4 Mon Sep 17 00:00:00 2001 From: Sean Hammond Date: Thu, 23 Jan 2025 12:19:44 +0000 Subject: [PATCH] Update code formatting This commit is just the result of running `make format` after moving from Pylint to Ruff and first running `make fix` and `make noqa`. --- h/accounts/schemas.py | 7 +++--- h/cli/commands/authclient.py | 4 +--- h/db/__init__.py | 1 + h/db/types.py | 8 ++----- h/migrations/env.py | 2 +- h/models/user.py | 8 ++----- h/realtime.py | 4 +--- h/schemas/base.py | 4 +--- h/schemas/forms/accounts/util.py | 2 +- h/scripts/init_elasticsearch.py | 1 + h/security/predicates.py | 10 ++++---- h/services/bulk_api/lms_stats.py | 2 +- h/services/bulk_executor/_actions.py | 4 +++- h/services/user_delete.py | 1 - h/session.py | 2 +- h/streamer/metrics.py | 5 +++- h/tasks/mailer.py | 1 + h/views/api/exceptions.py | 4 +--- tests/unit/h/accounts/schemas_test.py | 4 ++-- tests/unit/h/activity/query_test.py | 12 +++++----- tests/unit/h/models/document/_meta_test.py | 10 ++++---- tests/unit/h/models/document/_uri_test.py | 6 ++--- tests/unit/h/schemas/annotation_test.py | 10 ++++---- .../forms/accounts/reset_password_test.py | 4 +--- tests/unit/h/services/group_list_test.py | 1 - tests/unit/h/services/nipsa_test.py | 6 ++--- tests/unit/h/streamer/messages_speed_test.py | 2 +- tests/unit/h/util/test_logging_filters.py | 24 +++++++++---------- tests/unit/h/views/activity_test.py | 5 +++- tests/unit/h/views/api/config_test.py | 2 +- 30 files changed, 73 insertions(+), 83 deletions(-) diff --git a/h/accounts/schemas.py b/h/accounts/schemas.py index 8d71774bd40..a598fb39951 100644 --- a/h/accounts/schemas.py +++ b/h/accounts/schemas.py @@ -61,7 +61,8 @@ def unique_username(node, value): # account with the same username to be registered. # Otherwise new accounts could inherit dating belonging to deleted accounts. if request.db.scalars( - select(models.UserDeletion.id).where( + select(models.UserDeletion.id) + .where( models.UserDeletion.userid == format_userid(value, request.default_authority) ) @@ -82,7 +83,7 @@ def email_node(**kwargs): widget=deform.widget.TextInputWidget( template="emailinput", autocomplete="username" ), - **kwargs + **kwargs, ) @@ -123,7 +124,7 @@ def new_password_node(**kwargs): return colander.SchemaNode( colander.String(), validator=validators.Length(min=PASSWORD_MIN_LENGTH), - **kwargs + **kwargs, ) diff --git a/h/cli/commands/authclient.py b/h/cli/commands/authclient.py index b85c5fbe5cd..ae1db3e2d61 100644 --- a/h/cli/commands/authclient.py +++ b/h/cli/commands/authclient.py @@ -36,9 +36,7 @@ def authclient(): help="An allowable grant type", ) @click.pass_context -def add( - ctx, name, authority, type_, redirect_uri, grant_type -): # pylint:disable=too-many-arguments, too-many-positional-arguments +def add(ctx, name, authority, type_, redirect_uri, grant_type): # pylint:disable=too-many-arguments, too-many-positional-arguments """Create a new OAuth client.""" request = ctx.obj["bootstrap"]() diff --git a/h/db/__init__.py b/h/db/__init__.py index 631477ceb49..68a3c477074 100644 --- a/h/db/__init__.py +++ b/h/db/__init__.py @@ -11,6 +11,7 @@ Most application code should access the database session using the request property `request.db` which is provided by this module. """ + import logging from os import environ diff --git a/h/db/types.py b/h/db/types.py index 21807dcd1c1..189dd0948b3 100644 --- a/h/db/types.py +++ b/h/db/types.py @@ -13,9 +13,7 @@ class InvalidUUID(Exception, DontWrapMixin): # noqa: N818 pass -class URLSafeUUID( - types.TypeDecorator -): # pylint:disable=abstract-method,too-many-ancestors +class URLSafeUUID(types.TypeDecorator): # pylint:disable=abstract-method,too-many-ancestors """ Expose UUIDs as URL-safe base64-encoded strings. @@ -133,9 +131,7 @@ def _remove_magic_byte(cls, hex_str): return hex_str[0:12] + hex_str[13:16] + hex_str[17:32] -class AnnotationSelectorJSONB( - types.TypeDecorator -): # pylint:disable=abstract-method, too-many-ancestors +class AnnotationSelectorJSONB(types.TypeDecorator): # pylint:disable=abstract-method, too-many-ancestors r""" Special type for the Annotation selector column. diff --git a/h/migrations/env.py b/h/migrations/env.py index e64810c0ede..32885a9db89 100644 --- a/h/migrations/env.py +++ b/h/migrations/env.py @@ -14,7 +14,7 @@ def configure_logging(): logging.basicConfig( - format="%(asctime)s %(process)d %(name)s [%(levelname)s] " "%(message)s", + format="%(asctime)s %(process)d %(name)s [%(levelname)s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO, ) diff --git a/h/models/user.py b/h/models/user.py index 622d9ae2d86..c717f97e1a6 100644 --- a/h/models/user.py +++ b/h/models/user.py @@ -31,9 +31,7 @@ def _normalise_username(username): return sa.func.lower(sa.func.replace(username, sa.text("'.'"), sa.text("''"))) -class UsernameComparator( - Comparator -): # pylint: disable=abstract-method,too-many-ancestors +class UsernameComparator(Comparator): # pylint: disable=abstract-method,too-many-ancestors """ Custom comparator for :py:attr:`~h.models.user.User.username`. @@ -60,9 +58,7 @@ def in_(self, other): return _normalise_username(self.__clause_element__()).in_(usernames) -class UserIDComparator( - Comparator -): # pylint: disable=abstract-method,too-many-ancestors +class UserIDComparator(Comparator): # pylint: disable=abstract-method,too-many-ancestors """ Custom comparator for :py:attr:`~h.models.user.User.userid`. diff --git a/h/realtime.py b/h/realtime.py index b8dfa062ae0..1869c178d90 100644 --- a/h/realtime.py +++ b/h/realtime.py @@ -31,9 +31,7 @@ def __init__(self, connection, routing_key, handler): self.handler = handler self.exchange = get_exchange() - def get_consumers( - self, consumer_factory, channel - ): # pylint: disable=arguments-renamed + def get_consumers(self, consumer_factory, channel): # pylint: disable=arguments-renamed name = self.generate_queue_name() queue = kombu.Queue( name, diff --git a/h/schemas/base.py b/h/schemas/base.py index 741c9d75cfd..c7fc3f5edb1 100644 --- a/h/schemas/base.py +++ b/h/schemas/base.py @@ -15,9 +15,7 @@ def deferred_csrf_token(_node, kwargs): return get_csrf_token(request) -class ValidationError( - httpexceptions.HTTPBadRequest -): # pylint: disable=too-many-ancestors +class ValidationError(httpexceptions.HTTPBadRequest): # pylint: disable=too-many-ancestors pass diff --git a/h/schemas/forms/accounts/util.py b/h/schemas/forms/accounts/util.py index 838043d9264..d69e7c5467b 100644 --- a/h/schemas/forms/accounts/util.py +++ b/h/schemas/forms/accounts/util.py @@ -12,5 +12,5 @@ def new_password_node(**kwargs): return colander.SchemaNode( colander.String(), validator=validators.Length(min=PASSWORD_MIN_LENGTH), - **kwargs + **kwargs, ) diff --git a/h/scripts/init_elasticsearch.py b/h/scripts/init_elasticsearch.py index 3bdaf2fae30..1f5e1389bff 100755 --- a/h/scripts/init_elasticsearch.py +++ b/h/scripts/init_elasticsearch.py @@ -7,6 +7,7 @@ python3 -m h.scripts.init_elasticsearch conf/development.ini """ + import argparse import os diff --git a/h/security/predicates.py b/h/security/predicates.py index 858f48612c6..b0bf4835971 100644 --- a/h/security/predicates.py +++ b/h/security/predicates.py @@ -209,12 +209,10 @@ def group_member_remove(identity, context: GroupMembershipContext): @requires(authenticated_user, group_found) -def group_member_edit( - identity, context: EditGroupMembershipContext -): # pylint:disable=too-many-return-statements - assert ( - context.new_roles is not None - ), "new_roles must be set before checking permissions" +def group_member_edit(identity, context: EditGroupMembershipContext): # pylint:disable=too-many-return-statements + assert context.new_roles is not None, ( + "new_roles must be set before checking permissions" + ) old_roles = context.membership.roles new_roles = context.new_roles diff --git a/h/services/bulk_api/lms_stats.py b/h/services/bulk_api/lms_stats.py index 6004684e07d..5e4e7afa622 100644 --- a/h/services/bulk_api/lms_stats.py +++ b/h/services/bulk_api/lms_stats.py @@ -157,7 +157,7 @@ def get_annotation_counts( # Include the relevant columnns based on group_by *group_by_select_columns[group_by], # Always include the counts column - *self._count_columns(annos_query) + *self._count_columns(annos_query), ) # Apply relevant joins diff --git a/h/services/bulk_executor/_actions.py b/h/services/bulk_executor/_actions.py index d89d09fa55d..7b96fa14223 100644 --- a/h/services/bulk_executor/_actions.py +++ b/h/services/bulk_executor/_actions.py @@ -246,7 +246,9 @@ def _upsert_user_table(self, users): ], upsert=["display_name"], ).returning( - User.id, User.authority, User._username # pylint: disable=protected-access # noqa: SLF001 + User.id, + User.authority, + User._username, # pylint: disable=protected-access # noqa: SLF001 ) return self._execute_statement(stmt).fetchall() diff --git a/h/services/user_delete.py b/h/services/user_delete.py index 8ed2e15e886..0a15cf3009f 100644 --- a/h/services/user_delete.py +++ b/h/services/user_delete.py @@ -54,7 +54,6 @@ def log_deleted_rows(user, model_class, deleted_ids, log_ids=True): class UserDeleteService: - def __init__(self, db, job_queue, user_svc): self.db = db self.job_queue = job_queue diff --git a/h/session.py b/h/session.py index 23e8f0170e0..e02f482abb3 100644 --- a/h/session.py +++ b/h/session.py @@ -42,7 +42,7 @@ def profile(request, authority=None): "features": request.feature.all(), "preferences": _user_preferences(user), }, - **user_info(user) + **user_info(user), ) diff --git a/h/streamer/metrics.py b/h/streamer/metrics.py index 78ccaaa00fd..74eb13b9560 100644 --- a/h/streamer/metrics.py +++ b/h/streamer/metrics.py @@ -25,7 +25,10 @@ def websocket_metrics(queue): yield f"{PREFIX}/Alive", 1 yield f"{PREFIX}/Connections/Active", connections_active - yield f"{PREFIX}/Connections/Authenticated", connections_active - connections_anonymous + yield ( + f"{PREFIX}/Connections/Authenticated", + connections_active - connections_anonymous, + ) yield f"{PREFIX}/Connections/Anonymous", connections_anonymous yield f"{PREFIX}/WorkQueueSize", queue.qsize() diff --git a/h/tasks/mailer.py b/h/tasks/mailer.py index de7cf42f61c..ab374b2eb07 100644 --- a/h/tasks/mailer.py +++ b/h/tasks/mailer.py @@ -4,6 +4,7 @@ This module defines a Celery task for sending emails in a worker process. """ + import smtplib import pyramid_mailer diff --git a/h/views/api/exceptions.py b/h/views/api/exceptions.py index df432323878..c90b32fbdee 100644 --- a/h/views/api/exceptions.py +++ b/h/views/api/exceptions.py @@ -11,9 +11,7 @@ class OAuthAuthorizeError( # pylint: disable=too-many-ancestors """An OAuth authorization request failure.""" -class OAuthTokenError( - httpexceptions.HTTPUnauthorized -): # pylint: disable=too-many-ancestors +class OAuthTokenError(httpexceptions.HTTPUnauthorized): # pylint: disable=too-many-ancestors """ An OAuth token request failure. diff --git a/tests/unit/h/accounts/schemas_test.py b/tests/unit/h/accounts/schemas_test.py index 5f6ad9aef3b..2e62dbe2bf1 100644 --- a/tests/unit/h/accounts/schemas_test.py +++ b/tests/unit/h/accounts/schemas_test.py @@ -102,7 +102,7 @@ def test_it_is_invalid_with_invalid_characters_in_username(self, pyramid_request with pytest.raises(colander.Invalid) as exc: schema.deserialize({"username": "Fred Flintstone"}) assert exc.value.asdict()["username"] == ( - "Must have only letters, " "numbers, periods, and " "underscores." + "Must have only letters, numbers, periods, and underscores." ) def test_it_is_invalid_with_false_privacy_accepted(self, pyramid_request): @@ -259,7 +259,7 @@ def test_it_is_invalid_if_email_already_taken(self, models, schema): schema.deserialize({"email": "foo@bar.com", "password": "flibble"}) assert exc.value.asdict() == { - "email": "Sorry, an account with this " "email address already exists." + "email": "Sorry, an account with this email address already exists." } @pytest.fixture diff --git a/tests/unit/h/activity/query_test.py b/tests/unit/h/activity/query_test.py index bcfc3057d21..a146f8c21b6 100644 --- a/tests/unit/h/activity/query_test.py +++ b/tests/unit/h/activity/query_test.py @@ -409,9 +409,9 @@ def test_it_returns_each_annotations_group(self, _fetch_groups, pyramid_request) def test_it_returns_each_annotations_incontext_link(self, links, pyramid_request): def incontext_link(request, annotation): - assert ( - request == pyramid_request - ), "It should always pass the request to incontext_link" + assert request == pyramid_request, ( + "It should always pass the request to incontext_link" + ) # Return a predictable per-annotation value for the incontext link. return f"incontext_link_for_annotation_{annotation.id}" @@ -431,9 +431,9 @@ def incontext_link(request, annotation): def test_it_returns_each_annotations_html_link(self, links, pyramid_request): def html_link(request, annotation): - assert ( - request == pyramid_request - ), "It should always pass the request to html_link" + assert request == pyramid_request, ( + "It should always pass the request to html_link" + ) # Return a predictable per-annotation value for the html link. return f"html_link_for_annotation_{annotation.id}" diff --git a/tests/unit/h/models/document/_meta_test.py b/tests/unit/h/models/document/_meta_test.py index c486a302b3e..dd83b7e301f 100644 --- a/tests/unit/h/models/document/_meta_test.py +++ b/tests/unit/h/models/document/_meta_test.py @@ -53,9 +53,9 @@ def test_it_updates_an_existing_DocumentMeta_if_there_is_one( assert document_meta.updated == updated_attrs["updated"] assert document_meta.created == original_attrs["created"] assert document_meta.document == original_attrs["document"] - assert ( - len(db_session.query(DocumentMeta).all()) == 1 - ), "It shouldn't have added any new objects to the db" + assert len(db_session.query(DocumentMeta).all()) == 1, ( + "It shouldn't have added any new objects to the db" + ) @pytest.mark.parametrize( "doc_title,final_title", @@ -80,9 +80,7 @@ def test_it_logs_a_warning_with_existing_meta_on_a_different_doc( document_one = factories.Document() document_two = factories.Document() existing_document_meta = factories.DocumentMeta(document=document_one) - mock_db_session.query.return_value.filter.return_value.one_or_none.return_value = ( - existing_document_meta - ) + mock_db_session.query.return_value.filter.return_value.one_or_none.return_value = existing_document_meta create_or_update_document_meta( session=mock_db_session, **dict(meta_attrs, document=document_two) diff --git a/tests/unit/h/models/document/_uri_test.py b/tests/unit/h/models/document/_uri_test.py index 9af137fb10d..97b1bc65bca 100644 --- a/tests/unit/h/models/document/_uri_test.py +++ b/tests/unit/h/models/document/_uri_test.py @@ -96,9 +96,9 @@ def test_it_updates_the_existing_DocumentURI_if_there_is_one( assert document_uri.created == original_attrs["created"] assert document_uri.updated == updated_attrs["updated"] - assert ( - len(db_session.query(DocumentURI).all()) == 1 - ), "It shouldn't have added any new objects to the db" + assert len(db_session.query(DocumentURI).all()) == 1, ( + "It shouldn't have added any new objects to the db" + ) def test_it_creates_a_new_DocumentURI_if_there_is_no_existing_one( self, db_session, doc_uri_attrs diff --git a/tests/unit/h/schemas/annotation_test.py b/tests/unit/h/schemas/annotation_test.py index 2e8c9f2c6bc..2055de361fc 100644 --- a/tests/unit/h/schemas/annotation_test.py +++ b/tests/unit/h/schemas/annotation_test.py @@ -125,10 +125,10 @@ def test_it_does_not_raise_for_full_valid_data(self, pyramid_request, validate): ( { "document": { - "link": [{"href": f"https://example.com?{'LONG'*3000}"}] + "link": [{"href": f"https://example.com?{'LONG' * 3000}"}] } }, - f"document.link.0.href: 'https://example.com?{'LONG'*3000}' is too long", + f"document.link.0.href: 'https://example.com?{'LONG' * 3000}' is too long", ), ( {"document": {"link": [{"href": "http://example.com", "type": False}]}}, @@ -341,7 +341,8 @@ def test_it_does_not_pass_modified_dict_to_document_metas_from_data( } def document_uris_from_data( - document, claimant # pylint:disable=unused-argument + document, + claimant, # pylint:disable=unused-argument ): document["new_key"] = "new_value" document["top_level_key"] = "new_value" @@ -371,7 +372,8 @@ def test_it_clears_existing_keys_from_document(self, pyramid_request, validate): """ appstruct = validate( - pyramid_request, {"document": {"foo": "bar"}} # This should be deleted. + pyramid_request, + {"document": {"foo": "bar"}}, # This should be deleted. ) assert "foo" not in appstruct["document"] diff --git a/tests/unit/h/schemas/forms/accounts/reset_password_test.py b/tests/unit/h/schemas/forms/accounts/reset_password_test.py index 9135e5e5ccf..2eb3160feb7 100644 --- a/tests/unit/h/schemas/forms/accounts/reset_password_test.py +++ b/tests/unit/h/schemas/forms/accounts/reset_password_test.py @@ -101,9 +101,7 @@ def schema(self, pyramid_csrf_request): return ResetPasswordSchema().bind(request=pyramid_csrf_request) @pytest.fixture(autouse=True) - def serializer( - self, pyramid_csrf_request, pyramid_config - ): # pylint:disable=unused-argument + def serializer(self, pyramid_csrf_request, pyramid_config): # pylint:disable=unused-argument # We must be after `pyramid_config` in the queue, as it replaces the # registry object with another one which undoes our changes here diff --git a/tests/unit/h/services/group_list_test.py b/tests/unit/h/services/group_list_test.py index 92f3f494480..c16b428bab0 100644 --- a/tests/unit/h/services/group_list_test.py +++ b/tests/unit/h/services/group_list_test.py @@ -158,7 +158,6 @@ class TestUserGroups: def test_it_returns_all_user_groups_sorted_by_group_name( self, db_session, svc, user, user_groups ): - with db_session.no_autoflush: user.memberships = [GroupMembership(group=group) for group in user_groups] diff --git a/tests/unit/h/services/nipsa_test.py b/tests/unit/h/services/nipsa_test.py index b1c35005da9..ad2b795fe84 100644 --- a/tests/unit/h/services/nipsa_test.py +++ b/tests/unit/h/services/nipsa_test.py @@ -67,9 +67,9 @@ def test_fetch_all_flagged_userids_caches_lookup(self, svc, users): def test_flag_updates_cache(self, svc, users): svc.fetch_all_flagged_userids() svc.flag(users["unflagged_user"]) - users["unflagged_user"].nipsa = ( - False # Make sure result below comes from cache. - ) + users[ + "unflagged_user" + ].nipsa = False # Make sure result below comes from cache. assert svc.is_flagged(users["unflagged_user"].userid) diff --git a/tests/unit/h/streamer/messages_speed_test.py b/tests/unit/h/streamer/messages_speed_test.py index 33e7e7d534d..d9d82b56a87 100644 --- a/tests/unit/h/streamer/messages_speed_test.py +++ b/tests/unit/h/streamer/messages_speed_test.py @@ -38,7 +38,7 @@ def test_speed( # pylint: disable=too-many-arguments millis = diff.seconds * 1000 + diff.microseconds / 1000 print( - f"{action} x {reps}: {millis} ms, {millis/reps} ms/item, {reps/millis*1000} items/sec" + f"{action} x {reps}: {millis} ms, {millis / reps} ms/item, {reps / millis * 1000} items/sec" ) @pytest.fixture diff --git a/tests/unit/h/util/test_logging_filters.py b/tests/unit/h/util/test_logging_filters.py index 25ef3c0fc94..56f017acf42 100644 --- a/tests/unit/h/util/test_logging_filters.py +++ b/tests/unit/h/util/test_logging_filters.py @@ -19,36 +19,36 @@ def test_does_not_log_specified_exceptions(self, logger, read_timeout_exception) raise read_timeout_exception except ReadTimeoutError: logger.warning("warning", exc_info=True) - assert not logger.handlers[ - 0 - ].handler_called, "Didn't filter out log message when it should have!!" + assert not logger.handlers[0].handler_called, ( + "Didn't filter out log message when it should have!!" + ) def test_does_log_if_log_level_mismatch(self, logger, read_timeout_exception): try: raise read_timeout_exception except ReadTimeoutError: logger.critical("critical", exc_info=True) - assert logger.handlers[ - 0 - ].handler_called, "Filtered out log message when it shouldn't have!!" + assert logger.handlers[0].handler_called, ( + "Filtered out log message when it shouldn't have!!" + ) def test_does_log_if_exception_mismatch(self, logger): try: raise ValueError("Not a read timeout") except ValueError: logger.warning("warning", exc_info=True) - assert logger.handlers[ - 0 - ].handler_called, "Filtered out log message when it shouldn't have!!" + assert logger.handlers[0].handler_called, ( + "Filtered out log message when it shouldn't have!!" + ) def test_does_log_if_no_exc_info_is_recorded(self, logger, read_timeout_exception): try: raise read_timeout_exception except ReadTimeoutError: logger.warning("warning") - assert logger.handlers[ - 0 - ].handler_called, "Filtered out log message when it shouldn't have!!" + assert logger.handlers[0].handler_called, ( + "Filtered out log message when it shouldn't have!!" + ) @pytest.fixture def read_timeout_exception(self): diff --git a/tests/unit/h/views/activity_test.py b/tests/unit/h/views/activity_test.py index 06c701d3f56..773974c84da 100644 --- a/tests/unit/h/views/activity_test.py +++ b/tests/unit/h/views/activity_test.py @@ -1028,7 +1028,10 @@ def test_back_removes_empty_query(self, controller, user, pyramid_request, q): @pytest.fixture def controller( - self, user, pyramid_request, query # pylint:disable=unused-argument + self, + user, + pyramid_request, + query, # pylint:disable=unused-argument ): return activity.UserSearchController(UserContext(user), pyramid_request) diff --git a/tests/unit/h/views/api/config_test.py b/tests/unit/h/views/api/config_test.py index d3d4d148e0c..50b37b3937d 100644 --- a/tests/unit/h/views/api/config_test.py +++ b/tests/unit/h/views/api/config_test.py @@ -148,7 +148,7 @@ def test_it_adds_api_links_to_registry( link_name=link_name, description=description, route_name=route_name, - **kwargs + **kwargs, ) if link_name: