Skip to content

Commit

Permalink
Update code formatting
Browse files Browse the repository at this point in the history
This commit is just the result of running `make format` after moving
from Pylint to Ruff and first running `make fix` and `make noqa`.
  • Loading branch information
seanh committed Jan 23, 2025
1 parent ecf4bf5 commit 6e14149
Show file tree
Hide file tree
Showing 30 changed files with 73 additions and 83 deletions.
7 changes: 4 additions & 3 deletions h/accounts/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
)
Expand All @@ -82,7 +83,7 @@ def email_node(**kwargs):
widget=deform.widget.TextInputWidget(
template="emailinput", autocomplete="username"
),
**kwargs
**kwargs,
)


Expand Down Expand Up @@ -123,7 +124,7 @@ def new_password_node(**kwargs):
return colander.SchemaNode(
colander.String(),
validator=validators.Length(min=PASSWORD_MIN_LENGTH),
**kwargs
**kwargs,
)


Expand Down
4 changes: 1 addition & 3 deletions h/cli/commands/authclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]()

Expand Down
1 change: 1 addition & 0 deletions h/db/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
8 changes: 2 additions & 6 deletions h/db/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion h/migrations/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand Down
8 changes: 2 additions & 6 deletions h/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand All @@ -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`.
Expand Down
4 changes: 1 addition & 3 deletions h/realtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 1 addition & 3 deletions h/schemas/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
2 changes: 1 addition & 1 deletion h/schemas/forms/accounts/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ def new_password_node(**kwargs):
return colander.SchemaNode(
colander.String(),
validator=validators.Length(min=PASSWORD_MIN_LENGTH),
**kwargs
**kwargs,
)
1 change: 1 addition & 0 deletions h/scripts/init_elasticsearch.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
python3 -m h.scripts.init_elasticsearch conf/development.ini
"""

import argparse
import os

Expand Down
10 changes: 4 additions & 6 deletions h/security/predicates.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion h/services/bulk_api/lms_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion h/services/bulk_executor/_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
1 change: 0 additions & 1 deletion h/services/user_delete.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion h/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def profile(request, authority=None):
"features": request.feature.all(),
"preferences": _user_preferences(user),
},
**user_info(user)
**user_info(user),
)


Expand Down
5 changes: 4 additions & 1 deletion h/streamer/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
1 change: 1 addition & 0 deletions h/tasks/mailer.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
This module defines a Celery task for sending emails in a worker process.
"""

import smtplib

import pyramid_mailer
Expand Down
4 changes: 1 addition & 3 deletions h/views/api/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions tests/unit/h/accounts/schemas_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -259,7 +259,7 @@ def test_it_is_invalid_if_email_already_taken(self, models, schema):
schema.deserialize({"email": "[email protected]", "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
Expand Down
12 changes: 6 additions & 6 deletions tests/unit/h/activity/query_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"

Expand All @@ -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}"

Expand Down
10 changes: 4 additions & 6 deletions tests/unit/h/models/document/_meta_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions tests/unit/h/models/document/_uri_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 6 additions & 4 deletions tests/unit/h/schemas/annotation_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}]}},
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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"]
Expand Down
4 changes: 1 addition & 3 deletions tests/unit/h/schemas/forms/accounts/reset_password_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 0 additions & 1 deletion tests/unit/h/services/group_list_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand Down
6 changes: 3 additions & 3 deletions tests/unit/h/services/nipsa_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
2 changes: 1 addition & 1 deletion tests/unit/h/streamer/messages_speed_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading

0 comments on commit 6e14149

Please sign in to comment.