Merge pull request #34162 from akhilnarang/bump-ruff

refactor(treewide): bump ruff
This commit is contained in:
Akhil Narang 2025-09-26 17:44:11 +05:30 committed by GitHub
commit 355d218f8e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
37 changed files with 60 additions and 60 deletions

View file

@ -61,3 +61,6 @@ e9bbe03354079cfcef65a77b0c33f57b047a7c93
# replace `frappe.flags.in_test` with `frappe.in_test`
653c80b8483cc41aef25cd7d66b9b6bb188bf5f8
# another ruff update
6ca4d4d167a1a009d99062747711de7a994aa633

View file

@ -21,7 +21,7 @@ repos:
exclude: ^frappe/tests/classes/context_managers\.py$
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.1
rev: v0.13.2
hooks:
- id: ruff
name: "Run ruff import sorter"

View file

@ -669,7 +669,7 @@ def validate_oauth(authorization_header):
required_scopes = frappe.db.get_value("OAuth Bearer Token", token, "scopes").split(
get_url_delimiter()
)
valid, oauthlib_request = get_oauth_server().verify_request(
valid, _oauthlib_request = get_oauth_server().verify_request(
uri, http_method, body, headers, required_scopes
)
if valid:

View file

@ -61,7 +61,7 @@ def create_rq_users(set_admin_password=False, use_rq_auth=False):
)
click.secho(f"`export {env_key}={user_credentials['default'][1]}`")
click.secho(
"NOTE: Please save the admin password as you " "can not access redis server without the password",
"NOTE: Please save the admin password as you can not access redis server without the password",
fg="yellow",
)

View file

@ -336,7 +336,7 @@ def restore_backup(
# Check if the backup is of an older version of frappe and the user hasn't specified force
if is_downgrade(sql_file_path, verbose=True) and not force:
warn_message = (
"This is not recommended and may lead to unexpected behaviour. " "Do you want to continue anyway?"
"This is not recommended and may lead to unexpected behaviour. Do you want to continue anyway?"
)
click.confirm(warn_message, abort=True)

View file

@ -297,7 +297,7 @@ class TestCommands(BaseTestCommands):
self.execute("bench --site {test_site} backup --exclude 'ToDo'", site_data)
site_data.update({"kw": "\"{'partial':True}\""})
self.execute(
"bench --site {test_site} execute" " frappe.utils.backups.fetch_latest_backups --kwargs {kw}",
"bench --site {test_site} execute frappe.utils.backups.fetch_latest_backups --kwargs {kw}",
site_data,
)
site_data.update({"database": json.loads(self.stdout)["database"]})

View file

@ -435,8 +435,7 @@ def import_doc(context: CliCtxObj, path, force=False):
type=click.Path(exists=True, dir_okay=False, resolve_path=True),
required=True,
help=(
"Path to import file (.csv, .xlsx)."
"Consider that relative paths will resolve from 'sites' directory"
"Path to import file (.csv, .xlsx). Consider that relative paths will resolve from 'sites' directory"
),
)
@click.option("--doctype", type=str, required=True)

View file

@ -25,7 +25,7 @@ class TestAuditTrail(IntegrationTestCase):
re_amended_doc = amend_document(amended_doc, changed_fields, {}, 1)
comparator = create_comparator_doc("Test Custom Doctype for Doc Comparator", re_amended_doc.name)
documents, results = comparator.compare_document()
_documents, results = comparator.compare_document()
test_field_values = results["changed"]["Field"]
self.check_expected_values(test_field_values, ["first value", "second value", "third value"])
@ -41,7 +41,7 @@ class TestAuditTrail(IntegrationTestCase):
amended_doc = amend_document(doc, {}, rows_updated, 1)
comparator = create_comparator_doc("Test Custom Doctype for Doc Comparator", amended_doc.name)
documents, results = comparator.compare_document()
_documents, results = comparator.compare_document()
results = frappe._dict(results)
self.check_rows_updated(results.row_changed)

View file

@ -565,11 +565,11 @@ def parse_email(email_strings):
for email in email_string.split(","):
local_part = email.split("@", 1)[0].strip('"')
user, detail = None, None
_user, detail = None, None
if "+" in local_part:
user, detail = local_part.split("+", 1)
_user, detail = local_part.split("+", 1)
elif "--" in local_part:
detail, user = local_part.rsplit("--", 1)
detail, _user = local_part.rsplit("--", 1)
if not detail:
continue

View file

@ -147,7 +147,7 @@ class PostgresTable(DBTable):
if isinstance(default, str):
default = frappe.db.escape(default)
change_nullability.append(
f"ALTER COLUMN \"{col.fieldname}\" {'SET' if col.not_nullable else 'DROP'} NOT NULL"
f'ALTER COLUMN "{col.fieldname}" {"SET" if col.not_nullable else "DROP"} NOT NULL'
)
change_nullability.append(f'ALTER COLUMN "{col.fieldname}" SET DEFAULT {default}')

View file

@ -899,7 +899,7 @@ def tests_utils_get_dependencies(doctype):
import frappe
from frappe.tests.utils.generators import get_modules
module, test_module = get_modules(doctype)
_module, test_module = get_modules(doctype)
meta = frappe.get_meta(doctype)
link_fields = meta.get_link_fields()

View file

@ -622,8 +622,7 @@ def get_linked_fields(doctype, without_ignore_user_permissions_enabled=False):
"DocField", fields=["parent", "options"], filters=child_filters, as_list=1
):
ret[parent] = {"child_doctype": options, "fieldname": links_dict[options]}
if options in ret:
del ret[options]
ret.pop(options, None)
virtual_doctypes = frappe.get_all("DocType", {"is_virtual": 1}, pluck="name")
for dt in virtual_doctypes:

View file

@ -83,7 +83,7 @@ def get_group_by_count(doctype: str, current_filters: str, field: str) -> list[d
break
if owner_idx:
data = [data.pop(owner_idx)] + data[0:49]
data = [data.pop(owner_idx), *data[0:49]]
else:
data = data[0:50]
else:

View file

@ -547,7 +547,7 @@ def get_field_info(fields, doctype):
if parenttype != doctype:
# If the column is from a child table, append the child doctype.
# For example, "Item Code (Sales Invoice Item)".
label += f" ({ _(parenttype) })"
label += f" ({_(parenttype)})"
field_info.append(
{"name": name, "label": label, "fieldtype": fieldtype, "translatable": translatable}

View file

@ -9,8 +9,7 @@ from frappe import _
def get_all_nodes(doctype, label, parent, tree_method, **filters):
"""Recursively gets all data from tree nodes"""
if "cmd" in filters:
del filters["cmd"]
filters.pop("cmd", None)
filters.pop("data", None)
tree_method = frappe.get_attr(tree_method)
@ -20,8 +19,7 @@ def get_all_nodes(doctype, label, parent, tree_method, **filters):
data = tree_method(doctype, parent, **filters)
out = [dict(parent=label, data=data)]
if "is_root" in filters:
del filters["is_root"]
filters.pop("is_root", None)
to_check = [d.get("value") for d in data if d.get("expandable")]
while to_check:

View file

@ -54,7 +54,7 @@ class TestEmailQueue(IntegrationTestCase):
Subject: {subject}
From: Test <test@example.com>
To: <!--recipient-->
Date: {frappe.utils.now_datetime().strftime('%a, %d %b %Y %H:%M:%S %z')}
Date: {frappe.utils.now_datetime().strftime("%a, %d %b %Y %H:%M:%S %z")}
Reply-To: test@example.com
X-Frappe-Site: {frappe.local.site}
"""

View file

@ -352,7 +352,9 @@ def get_context(context):
To queue a notification from a server script:
```python
notification = frappe.get_doc("Notification", "My Notification", ignore_permissions=True)
notification = frappe.get_doc(
"Notification", "My Notification", ignore_permissions=True
)
notification.queue_send(customer)
```

View file

@ -237,7 +237,7 @@ class EMail:
"""Append the message with MIME content to the root node (as attachment)"""
from email.mime.text import MIMEText
maintype, subtype = mime_type.split("/")
_maintype, subtype = mime_type.split("/")
part = MIMEText(message, _subtype=subtype, policy=policy.SMTP)
if as_attachment:
@ -445,7 +445,7 @@ def add_attachment(fname, fcontent, content_type=None, parent=None, content_id=N
from email.mime.text import MIMEText
if not content_type:
content_type, encoding = mimetypes.guess_type(fname)
content_type, _encoding = mimetypes.guess_type(fname)
if not parent:
return
@ -597,7 +597,7 @@ def get_header(header=None):
if not title:
title = frappe.get_hooks("app_title")[-1]
email_header, text = get_email_from_template(
email_header, _text = get_email_from_template(
"email_header", {"header_title": title, "indicator": indicator}
)

View file

@ -205,7 +205,7 @@ class EmailServer:
readonly = self.settings.email_sync_rule != "UNSEEN"
self.imap.select(folder, readonly=readonly)
response, message = self.imap.uid("search", None, self.settings.email_sync_rule)
_response, message = self.imap.uid("search", None, self.settings.email_sync_rule)
if message[0]:
email_list = message[0].split()
else:
@ -217,7 +217,7 @@ class EmailServer:
# compare the UIDVALIDITY of email account and imap server
uid_validity = self.settings.uid_validity
response, message = self.imap.status(folder, "(UIDVALIDITY UIDNEXT)")
_response, message = self.imap.status(folder, "(UIDVALIDITY UIDNEXT)")
current_uid_validity = self.parse_imap_response("UIDVALIDITY", message[0]) or 0
uidnext = int(self.parse_imap_response("UIDNEXT", message[0]) or "1")
@ -270,7 +270,7 @@ class EmailServer:
def retrieve_message(self, uid, msg_num, folder):
try:
if cint(self.settings.use_imap):
status, message = self.imap.uid("fetch", uid, "(BODY.PEEK[] BODY.PEEK[HEADER] FLAGS)")
_status, message = self.imap.uid("fetch", uid, "(BODY.PEEK[] BODY.PEEK[HEADER] FLAGS)")
raw = message[0]
self.get_email_seen_status(uid, raw[0])

View file

@ -34,7 +34,7 @@ class Here:
"label": address["label"],
"value": json.dumps(
{
"address_line1": f'{address.get("street", "")} {address.get("houseNumber", "")}'.strip(),
"address_line1": f"{address.get('street', '')} {address.get('houseNumber', '')}".strip(),
"city": address.get("city", ""),
"state": address.get("state", ""),
"pincode": address.get("postalCode", ""),

View file

@ -37,7 +37,7 @@ class Nomatim:
"label": result["display_name"],
"value": json.dumps(
{
"address_line1": f'{address.get("road")} {address.get("house_number", "")}'.strip(),
"address_line1": f"{address.get('road')} {address.get('house_number', '')}".strip(),
"city": address.get("city") or address.get("town") or address.get("village"),
"state": address.get("state"),
"pincode": address.get("postcode"),

View file

@ -240,7 +240,7 @@ class LDAP_TestCase:
function_return = self.test_class.connect_to_ldap(
base_dn=self.base_dn, password=self.base_password
)
args, kwargs = ldap3_connection_method.call_args
_args, kwargs = ldap3_connection_method.call_args
for connection_arg in kwargs:
if (
@ -305,7 +305,7 @@ class LDAP_TestCase:
base_dn=self.base_dn, password=self.base_password, read_only=False
)
args, kwargs = ldap3_connection_method.call_args
_args, kwargs = ldap3_connection_method.call_args
self.assertFalse(
kwargs["read_only"],

View file

@ -72,7 +72,7 @@ def approve(*args, **kwargs):
frappe.flags.oauth_credentials,
) = get_oauth_server().validate_authorization_request(r.url, r.method, r.get_data(), r.headers)
headers, body, status = get_oauth_server().create_authorization_response(
headers, _body, _status = get_oauth_server().create_authorization_response(
uri=frappe.flags.oauth_credentials["redirect_uri"],
body=r.get_data(),
headers=r.headers,
@ -144,7 +144,7 @@ def authorize(**kwargs):
def get_token(*args, **kwargs):
try:
r = frappe.request
headers, body, status = get_oauth_server().create_token_response(
_headers, body, _status = get_oauth_server().create_token_response(
r.url, r.method, r.form, r.headers, frappe.flags.oauth_credentials
)
body = frappe._dict(json.loads(body))
@ -165,7 +165,7 @@ def get_token(*args, **kwargs):
def revoke_token(*args, **kwargs):
try:
r = frappe.request
headers, body, status = get_oauth_server().create_revocation_response(
_headers, _body, status = get_oauth_server().create_revocation_response(
r.url,
headers=r.headers,
body=r.form,
@ -184,7 +184,7 @@ def revoke_token(*args, **kwargs):
def openid_profile(*args, **kwargs):
try:
r = frappe.request
headers, body, status = get_oauth_server().create_userinfo_response(
_headers, body, _status = get_oauth_server().create_userinfo_response(
r.url,
headers=r.headers,
body=r.form,

View file

@ -471,7 +471,7 @@ class TestResponse(FrappeAPITestCase):
}
for redirect, expected_redirect in expected_redirects.items():
response = self.get(f"/login?{urlencode({'redirect-to':redirect})}", {"sid": self.sid})
response = self.get(f"/login?{urlencode({'redirect-to': redirect})}", {"sid": self.sid})
self.assertEqual(response.location, expected_redirect)

View file

@ -205,7 +205,7 @@ def custom_has_permission(doc, ptype, user):
def custom_auth():
auth_type, token = frappe.get_request_header("Authorization", "Bearer ").split(" ")
_auth_type, token = frappe.get_request_header("Authorization", "Bearer ").split(" ")
if token == "set_test_example_user":
frappe.set_user("test@example.com")

View file

@ -121,7 +121,7 @@ class TestPatchReader(IntegrationTestCase):
@patch("builtins.open", new_callable=mock_open, read_data=EDGE_CASES)
def test_new_style_edge_cases(self, _file):
all, pre, post = self.get_patches()
_all, pre, _post = self.get_patches()
self.assertEqual(
pre,
[
@ -134,7 +134,7 @@ class TestPatchReader(IntegrationTestCase):
@patch("builtins.open", new_callable=mock_open, read_data=COMMENTED_OUT)
def test_ignore_comments(self, _file):
all, pre, post = self.get_patches()
_all, pre, _post = self.get_patches()
self.assertEqual(pre, ["app.module.patch1", "app.module.patch3"])
def test_verify_patch_txt(self):

View file

@ -53,7 +53,7 @@ class TestQueryReport(IntegrationTestCase):
visible_idx = [0, 2, 3]
# Build the result
xlsx_data, column_widths = build_xlsx_data(
xlsx_data, _column_widths = build_xlsx_data(
data, visible_idx, include_indentation=False, include_filters=True
)

View file

@ -468,7 +468,7 @@ class TestMathUtils(IntegrationTestCase):
self.assertEqual(floor(22.7330), 22)
self.assertEqual(floor("24.7"), 24)
self.assertEqual(floor("26.7"), 26)
self.assertEqual(floor(Decimal(29.45)), 29)
self.assertEqual(floor(Decimal("29.45")), 29)
def test_ceil(self):
from decimal import Decimal
@ -478,7 +478,7 @@ class TestMathUtils(IntegrationTestCase):
self.assertEqual(ceil(22.7330), 23)
self.assertEqual(ceil("24.7"), 25)
self.assertEqual(ceil("26.7"), 27)
self.assertEqual(ceil(Decimal(29.45)), 30)
self.assertEqual(ceil(Decimal("29.45")), 30)
class TestHTMLUtils(IntegrationTestCase):
@ -906,7 +906,7 @@ class TestResponse(IntegrationTestCase):
timedelta(days=10, hours=12, minutes=120, seconds=10),
],
"float": [
Decimal(29.21),
Decimal("29.21"),
],
"doc": [
frappe.get_doc("System Settings"),
@ -1177,7 +1177,7 @@ class TestMiscUtils(IntegrationTestCase):
self.assertIsInstance(get_file_timestamp(__file__), str)
def test_execute_in_shell(self):
err, out = execute_in_shell("ls")
_err, out = execute_in_shell("ls")
self.assertIn("apps", cstr(out))
def test_get_all_sites(self):

View file

@ -63,7 +63,7 @@ def get_missing_records_doctypes(doctype, visited=None) -> list[str]:
# Mark as visited
visited.add(doctype)
module, test_module = get_modules(doctype)
_module, test_module = get_modules(doctype)
meta = frappe.get_meta(doctype)
link_fields = meta.get_link_fields()
@ -158,12 +158,11 @@ def _generate_records_for(
index_doctype: str, reset: bool = False, commit: bool = False, initial_doctype: str | None = None
) -> Generator[tuple[str, "Document"], None, None]:
"""Create and yield test records for a specific doctype."""
module: str
test_module: ModuleType
logstr = f" {index_doctype} via {initial_doctype}"
module, test_module = get_modules(index_doctype)
_module, test_module = get_modules(index_doctype)
# First prioriry: module's _make_test_records as an escape hatch
# to completely bypass the standard loading and create test records

View file

@ -695,9 +695,9 @@ def write_csv_file(path, app_messages, lang_dict):
if len(app_message) == 2:
path, message = app_message
elif len(app_message) == 3:
path, message, lineno = app_message
path, message, _lineno = app_message
elif len(app_message) == 4:
path, message, context, lineno = app_message
path, message, context, _lineno = app_message
else:
continue

View file

@ -610,7 +610,7 @@ def get_disk_usage():
files_path = get_files_path()
if not os.path.exists(files_path):
return 0
err, out = execute_in_shell(f"du -hsm {files_path}")
_err, out = execute_in_shell(f"du -hsm {files_path}")
return cint(out.split("\n")[-2].split("\t")[0])

View file

@ -592,7 +592,7 @@ def get_redis_conn(username=None, password=None):
return RedisQueue.get_connection(**cred)
except redis.exceptions.AuthenticationError:
log(
f'Wrong credentials used for {cred.username or "default user"}. '
f"Wrong credentials used for {cred.username or 'default user'}. "
"You can reset credentials using `bench create-rq-users` CLI and restart the server",
colour="red",
)

View file

@ -298,7 +298,7 @@ class BackupGenerator:
def zip_files(self):
# For backwards compatibility - pre v13
click.secho(
"BackupGenerator.zip_files has been deprecated in favour of" " BackupGenerator.backup_files",
"BackupGenerator.zip_files has been deprecated in favour of BackupGenerator.backup_files",
fg="yellow",
)
return self.backup_files()

View file

@ -1633,7 +1633,7 @@ def get_thumbnail_base64_for_image(src: str) -> dict[str, str] | None:
return
try:
image, unused_filename, extn = get_local_image(src)
image, _unused_filename, extn = get_local_image(src)
except OSError:
return

View file

@ -116,7 +116,7 @@ def get_monthly_goal_graph_data(
{
"title": _("Completed"),
"color": "#28a745",
"value": f"{int(round(flt(current_month_value) / flt(goal) * 100))}%",
"value": f"{round(flt(current_month_value) / flt(goal) * 100)}%",
},
]
y_markers = {"yMarkers": [{"label": _("Goal"), "lineType": "dashed", "value": flt(goal)}]}

View file

@ -100,7 +100,7 @@ class PrintFormatGenerator:
def render_pdf(self):
"""Return a bytes sequence of the rendered PDF."""
HTML, CSS = import_weasyprint()
HTML, _CSS = import_weasyprint()
self._make_header_footer()

View file

@ -229,7 +229,7 @@ def get_rendered_template(
if letter_head.header_script:
letter_head.content += f"""
<script>
{ letter_head.header_script }
{letter_head.header_script}
</script>
"""
@ -238,7 +238,7 @@ def get_rendered_template(
if letter_head.footer_script:
letter_head.footer += f"""
<script>
{ letter_head.footer_script }
{letter_head.footer_script}
</script>
"""