Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

chore(lint): 接入 Python 全仓静态检查并修正诊断

longmeidaoe6cc9efff746
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 5f4f71e2a..518f4dc74 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -313,7 +313,9 @@ JAV 默认封面(官方封面/预览图)与视频默认大小(大图/
Python、npm 与 GitHub Actions 的版本由 `.github/dependabot.yml` 每周检查;固定前端文件由
`package-lock.json` 和 `scripts/vendor_web_dependencies.mjs` 重建并核对来源、许可证与 SHA-256。
-## 前端静态检查
+## 静态检查
+
+Python 复用 MIT 许可的 [Ruff](https://docs.astral.sh/ruff/) 0.16.10,版本由开发依赖和 `uv.lock` 固定。规则配置在 `pyproject.toml`;正式入口通过 `tests/test_python_lint.py` 扫描全仓自有 Python 文件,检查 Pyflakes、Ruff 支持的 Pylint 错误规则与四项常见行为隐患。Ruff 的 Pylint 规则覆盖是部分覆盖;需要跨模块推断的问题仍由对应行为回归验证。
复用现有 Oxlint 1.85.0 的 correctness、`eqeqeq` 与 `oxc/no-accumulating-spread`,不新增依赖。源码和测试共用基础规则;shadcn 设计规则仅作用于自有 React 源码。
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 8e501c3e5..e132aefcd 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -46,6 +46,8 @@ Dependabot 的 PR 一律在本地接管,不在网页上合:
## 验证频率
+Python 静态检查使用开发依赖 Ruff,随每个正式测试域扫描全仓自有 Python 文件,覆盖应用、脚本、测试和打包入口。规则为 Pyflakes(`F`)、Ruff 支持的 Pylint 错误规则(`PLE`),以及可变默认参数、`finally` 跳转、无效表达式和循环闭包规则(`B006`、`B012`、`B018`、`B023`)。生成的 `downloads_clouddrive_pb2.py` 排除;公开导出的导入用显式同名别名声明。命名、行数、空行和复杂度偏好不属于这套 lint 门槛。
+
文档与文案检查包含 seiso 稳定规则和最终状态检查,随正式入口执行。分类、范围、独立检查与预览规则用法见 [文档与界面文案](WRITING.md#检查与复核)。seiso 由开发依赖与锁文件固定,运行 Peach 不需要它。
不是每次都跑全量:本机按改动涉及的域选测,CI 按提交类型决定覆盖多宽。
diff --git a/pyproject.toml b/pyproject.toml
index dce674d03..e5873d3df 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -67,6 +67,7 @@ peach-tray = "peach.tray:main"
dev = [
"filelock==4.0.1",
"psutil==7.2.2",
+ "ruff==0.16.10",
"seiso==0.2.0",
]
build = ["pyinstaller==6.22.3"]
@@ -93,3 +94,10 @@ version = {attr = "peach.__version__"}
[tool.setuptools.packages.find]
where = ["src"]
+
+[tool.ruff]
+target-version = "py312"
+extend-exclude = ["src/peach/downloads_clouddrive_pb2.py"]
+
+[tool.ruff.lint]
+select = ["F", "PLE", "B006", "B012", "B018", "B023"]
diff --git a/scripts/audit_performer_portraits.py b/scripts/audit_performer_portraits.py
index b56ab1ae9..025c50cfb 100644
--- a/scripts/audit_performer_portraits.py
+++ b/scripts/audit_performer_portraits.py
@@ -40,11 +40,10 @@ import re
import sqlite3
import threading
import time
-import urllib.parse
import concurrent.futures as futures
import sys
from collections import Counter
-from datetime import datetime, timezone
+from datetime import datetime
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parent.parent
@@ -72,7 +71,6 @@ from peach.gfriends import (
index_age,
normalized,
parse_filetree as parse_gfriends,
- quality_key,
)
from peach.http import HttpRequest, HttpTransport, HttpxTransport
from peach.review_csv import read_rows, write_rows
diff --git a/scripts/audit_video_endcards.py b/scripts/audit_video_endcards.py
index fdc61b0b2..b761ca17d 100644
--- a/scripts/audit_video_endcards.py
+++ b/scripts/audit_video_endcards.py
@@ -30,7 +30,6 @@ from peach.ffmpeg import FFmpegResolver
from peach.jobs import (
DiskGuard,
JobPolicyError,
- PidFileLock,
SourceAccessPolicy,
require_free_space,
job_main,
diff --git a/scripts/creator_boards.py b/scripts/creator_boards.py
index a0344c57a..fde9662ab 100644
--- a/scripts/creator_boards.py
+++ b/scripts/creator_boards.py
@@ -28,7 +28,6 @@ from peach.jobs import (
DiskGuard,
DiskSpaceDenied,
JobPolicyError,
- PidFileLock,
SourceAccessPolicy,
require_free_space,
job_main,
diff --git a/scripts/fetch_fc2_metadata.py b/scripts/fetch_fc2_metadata.py
index c99c8d863..edd983b12 100644
--- a/scripts/fetch_fc2_metadata.py
+++ b/scripts/fetch_fc2_metadata.py
@@ -55,7 +55,7 @@ from peach.scraping_access import client_for
from peach.genre_decisions import load_genre_decisions
from peach.genre_taxonomy import map_genres
from peach.review_csv import read_rows, write_rows
-from peach.scripting import USER_AGENT, open_readonly
+from peach.scripting import open_readonly
from peach.config import DATABASE_PATH, GENERATED_DIR
from peach.sources.fc2 import canonical_code
from peach.sources.fc2cmadb import (VIDEO_ID, Fc2cmadbSource, collection_parts, inertia_props,
diff --git a/scripts/fetch_studio_avatar_candidates.py b/scripts/fetch_studio_avatar_candidates.py
index f1b90808d..14ae98121 100644
--- a/scripts/fetch_studio_avatar_candidates.py
+++ b/scripts/fetch_studio_avatar_candidates.py
@@ -13,7 +13,6 @@ handle 默认必须由 `--handles` 显式提供。脚本不猜 handle:猜错
from __future__ import annotations
import argparse
-import csv
import json
import re
import sys
@@ -23,7 +22,7 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from peach.http import HttpRequest, HttpxTransport # noqa: E402
-from peach.images import REJECT, bake_square, classify, measure_image_size # noqa: E402
+from peach.images import REJECT, bake_square, classify # noqa: E402
from peach.logo_provider import ( # noqa: E402
POLICY_VERSION,
LogoCandidateCache,
diff --git a/scripts/find_ads.py b/scripts/find_ads.py
index 696db9731..2264e1d28 100644
--- a/scripts/find_ads.py
+++ b/scripts/find_ads.py
@@ -26,7 +26,6 @@ from __future__ import annotations
import collections
import argparse
-import os
import re
import sys
from pathlib import Path, PureWindowsPath
diff --git a/scripts/harvest_agency_rosters.py b/scripts/harvest_agency_rosters.py
index 8c4403690..afe72ede0 100644
--- a/scripts/harvest_agency_rosters.py
+++ b/scripts/harvest_agency_rosters.py
@@ -76,7 +76,7 @@ EXTRA_COUNTS = {
#: 对名字时忽略的东西。站上写 `明日花 キララ`,账本别名写 `明日花キララ`;
#: 中点、连字符和各种空白都只是排版,不是名字的一部分。
_NOISE = str.maketrans({" ": "", " ": "", "・": "", "・": "", "‐": "", "-": "",
- "-": "", " ": ""})
+ "-": ""})
def roster_key(name: str) -> str:
diff --git a/scripts/harvest_directory_links.py b/scripts/harvest_directory_links.py
index ffebb1ce6..d12910ecf 100644
--- a/scripts/harvest_directory_links.py
+++ b/scripts/harvest_directory_links.py
@@ -53,7 +53,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from peach import javdb # noqa: E402
from peach.config import STATE_DIR # noqa: E402
from peach.jobs import job_main # noqa: E402
-from peach.page_cache import HttpStatusError, Site, USER_AGENT # noqa: E402
+from peach.page_cache import HttpStatusError, Site # noqa: E402
from peach.review_csv import write_rows # noqa: E402
from peach.social_links import ( # noqa: E402
canonical_url, classify, handle, load_performers, name_key, platform, under,
diff --git a/scripts/harvest_javdb_cn_names.py b/scripts/harvest_javdb_cn_names.py
index 4b53fde4e..f8914d82f 100644
--- a/scripts/harvest_javdb_cn_names.py
+++ b/scripts/harvest_javdb_cn_names.py
@@ -237,7 +237,7 @@ def adopted_name(current: list[str]) -> str:
def judge(record: dict, html: str, url: str) -> dict:
"""一页资料页对一位账本女优的判定。"""
- current, former = javdb.current_names(html), javdb.former_names(html)
+ current = javdb.current_names(html)
wanted = {key(value) for value in record["chain"]}
row = {"entity_id": record["entity_id"], "current_name": record["name"],
"assets": record["assets"], "actor_id": javdb.actor_id(html), "url": url,
diff --git a/scripts/harvest_performer_links.py b/scripts/harvest_performer_links.py
index bc07e05ae..025cddade 100644
--- a/scripts/harvest_performer_links.py
+++ b/scripts/harvest_performer_links.py
@@ -16,9 +16,7 @@
from __future__ import annotations
import argparse
-import sqlite3
import sys
-import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
diff --git a/scripts/harvest_social_avatars.py b/scripts/harvest_social_avatars.py
index 93b4c0c21..34edb9c56 100644
--- a/scripts/harvest_social_avatars.py
+++ b/scripts/harvest_social_avatars.py
@@ -44,19 +44,17 @@ import argparse
import hashlib
import html as html_mod
import json
-import os
import re
import sqlite3
import sys
import time
import urllib.parse
-import uuid
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from peach.avatar_face import ( # noqa: E402
- FaceProbe, drop_sidecar, face_px_width, read_sidecar, write_sidecar,
+ FaceProbe, face_px_width, read_sidecar,
)
from peach.avatar_provider import ( # noqa: E402
POLICY_VERSION,
@@ -433,7 +431,6 @@ def harvest_entity(record: dict, http: HttpTransport, limiter: HostLimiter,
False 的行只进复核 CSV。candidates:全部有效头像(入内容寻址缓存),
调用方做同图去重、竞选与安装。
"""
- entity_id = record["entity_id"]
names = record["names"]
links: list[dict] = []
candidates: list[dict] = []
diff --git a/scripts/localize_performer_names.py b/scripts/localize_performer_names.py
index 7f0105960..7ab25e70d 100644
--- a/scripts/localize_performer_names.py
+++ b/scripts/localize_performer_names.py
@@ -218,8 +218,6 @@ def collect(
FROM entity e WHERE e.kind='performer' ORDER BY e.id
"""
).fetchall()
- by_id = {int(entity["id"]): entity for entity in entities}
-
rows: list[dict[str, object]] = []
resolved_groups: dict[int, list[dict[str, object]]] = defaultdict(list)
for entity in entities:
diff --git a/scripts/probe.py b/scripts/probe.py
index 86b4cda02..e282c825e 100644
--- a/scripts/probe.py
+++ b/scripts/probe.py
@@ -26,7 +26,6 @@ from peach.jobs import (
DiskGuard,
DiskSpaceDenied,
JobPolicyError,
- PidFileLock,
SourceAccessPolicy,
require_free_space,
job_main,
diff --git a/scripts/sheets.py b/scripts/sheets.py
index a7b99ce59..7b5296cf4 100644
--- a/scripts/sheets.py
+++ b/scripts/sheets.py
@@ -27,7 +27,6 @@ from peach.jobs import (
DiskGuard,
DiskSpaceDenied,
JobPolicyError,
- PidFileLock,
SourceAccessPolicy,
require_free_space,
job_main,
diff --git a/scripts/sync_sha1_115.py b/scripts/sync_sha1_115.py
index 346c5f401..44809cc12 100644
--- a/scripts/sync_sha1_115.py
+++ b/scripts/sync_sha1_115.py
@@ -16,8 +16,7 @@
python scripts/sync_sha1_115.py # 拉取并写入 ledger
python scripts/sync_sha1_115.py --dupes # 写入后直接出 SHA1 重复报告
"""
-import os, sys, json, sqlite3, time
-import sys
+import os, sys, sqlite3, time
from collections import defaultdict
from pathlib import Path
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 5925c7d59..d116287dc 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -28,10 +28,10 @@ if not __package__:
from . import test_evidence
COMMON_PATTERNS = ("test_context_budget.py", "test_test_collection.py", "test_complexity_ratchet.py",
- "test_source_assertion_ratchet.py")
+ "test_source_assertion_ratchet.py", "test_python_lint.py")
SCOPES: dict[str, tuple[str, ...]] = {
"checks": ("test_copy_final_state.py", "test_dependency_policy.py", "test_repo_hygiene.py", "test_test_planning.py",
- "test_complexity_ratchet.py", "test_source_assertion_ratchet.py"),
+ "test_complexity_ratchet.py", "test_source_assertion_ratchet.py", "test_python_lint.py"),
"follow": ("test_follow*.py", "test_http.py", "test_migrations.py", "test_wants_web.py"),
"catalog": ("test_ad_judgement.py", "test_composite_name_split.py", "test_media_libraries.py",
"test_content_region.py",
diff --git a/src/peach/api.py b/src/peach/api.py
index 4d9bd1baa..5d5856426 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -22,7 +22,6 @@ import asyncio
import logging
from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager
-from typing import Any
from urllib.parse import quote
from fastapi import FastAPI, Request
diff --git a/src/peach/entities.py b/src/peach/entities.py
index db887bd14..76500d1c8 100644
--- a/src/peach/entities.py
+++ b/src/peach/entities.py
@@ -187,8 +187,8 @@ def split_composite_person_name(name: str) -> list[str]:
#: 空白,`normalized_name` 也就带着它,于是同一个人在账本里能存成两个实体、按名字搜
#: 一个都搜不到。U+200D(ZWJ)不在名单里——emoji 的家庭、职业序列靠它连字,剥掉会把
#: 创作者名字里的一个 emoji 拆成两三个。
-ZERO_WIDTH = str.maketrans({"​": None, "‌": None,
- "⁠": None, "": None})
+ZERO_WIDTH = str.maketrans({"\u200b": None, "\u200c": None,
+ "\u2060": None, "\ufeff": None})
def strip_zero_width(name: str) -> str:
diff --git a/src/peach/follow_store.py b/src/peach/follow_store.py
index 66896e448..67597e5d0 100644
--- a/src/peach/follow_store.py
+++ b/src/peach/follow_store.py
@@ -21,7 +21,7 @@ from . import follow_providers
from .follow import FollowSourceError, write_immutable
from .follow_image_dims import positive_dims
from .follow_sources import (
- FollowCandidate, Rule34VideoConnector, SourceFetch, canonical_source_ref,
+ Rule34VideoConnector, SourceFetch, canonical_source_ref,
official_profile_handle, origin_group_key, profile_link_identity,
)
from .follow_variants import classify, group_duplicates
diff --git a/src/peach/jav_cover_fetch.py b/src/peach/jav_cover_fetch.py
index d34a3c327..73af45918 100644
--- a/src/peach/jav_cover_fetch.py
+++ b/src/peach/jav_cover_fetch.py
@@ -44,7 +44,6 @@ import json
import re
import time
import urllib.parse
-import sys
from dataclasses import dataclass
from html.parser import HTMLParser
from pathlib import Path
diff --git a/src/peach/metadata.py b/src/peach/metadata.py
index 00b4887cc..20b76d45b 100644
--- a/src/peach/metadata.py
+++ b/src/peach/metadata.py
@@ -1,10 +1,8 @@
"""Read-only external metadata providers and Peach-owned candidate normalization."""
from __future__ import annotations
-import json
import re
from datetime import date
-from pathlib import Path
from urllib.parse import urlsplit
from .catalog_rules import (
diff --git a/src/peach/routes_pages.py b/src/peach/routes_pages.py
index 21de447ed..b05952be9 100644
--- a/src/peach/routes_pages.py
+++ b/src/peach/routes_pages.py
@@ -18,7 +18,6 @@ from __future__ import annotations
import hashlib
import json
import os
-import shutil
import sys
from collections.abc import Mapping, Sequence
import re
@@ -37,7 +36,7 @@ from fastapi.responses import (
Response,
)
-from . import auth, distribution, onboarding, settings_file
+from . import distribution, onboarding, settings_file
from .config import PROJECT_ROOT
from .routes_auth import require_asset_auth, require_page_auth, set_auth_cookie
from .web_entry import check_html, entry_page_style, runtime_fact_entries
@@ -354,8 +353,6 @@ def setup_page(
if question.key == "media_dir":
media_dirs = _media_dir_values(values, question.default)
row_errors = errors.get("media_dir", [])
- note = "" if windows else onboarding.mounts_explanation(
- [path for path in media_dirs if path] or ["上面填写的目录"])
fields.append(_media_dirs_html(media_dirs, list(row_errors), "" if windows else
"本机文件夹是这台电脑读取媒体的位置;Windows 中的对应路径用于匹配馆藏中已有的路径。",
locations=values.get("media_location", ()), roots=values.get("media_root", ()), windows=windows))
diff --git a/src/peach/scripting.py b/src/peach/scripting.py
index 3d759b234..ad3f723f2 100644
--- a/src/peach/scripting.py
+++ b/src/peach/scripting.py
@@ -24,7 +24,7 @@ from pathlib import Path
from .config import DATABASE_PATH
from .migrations import sqlite_backup
-from .user_agent import USER_AGENT
+from .user_agent import USER_AGENT as USER_AGENT
#: `--apply` 缺 `--backup` 时的唯一拒绝话术。
BACKUP_REQUIRED = "--apply 必须同时给 --backup"
diff --git a/src/peach/sources/javdb.py b/src/peach/sources/javdb.py
index 974e3e5a4..0e638eab4 100644
--- a/src/peach/sources/javdb.py
+++ b/src/peach/sources/javdb.py
@@ -170,7 +170,7 @@ def parse_magnets(page: Page) -> list[dict]:
except ValueError:
invalid = True
continue
- def text(selector):
+ def text(selector, row=row):
node = row.select_one(selector)
return node.get_text(" ", strip=True) if node else ""
meta = re.split(r"[,,]", text(".meta"), maxsplit=1)
diff --git a/src/peach/taste_history.py b/src/peach/taste_history.py
index 24cdbf9b9..5764f5233 100644
--- a/src/peach/taste_history.py
+++ b/src/peach/taste_history.py
@@ -265,7 +265,7 @@ def refresh_history(
results: list[dict[str, object]] = []
with _open_history_store(store_path, host) as (store, host, now):
for index, source in enumerate(sources):
- def report(count=0):
+ def report(count=0, index=index):
if progress:
progress(stage="reading", checked=count, total=None,
message=f"读取浏览记录:第 {index + 1} / {len(sources)} 个浏览器资料,已读取 {count:,} 条")
diff --git a/src/peach/web_follow.py b/src/peach/web_follow.py
index 41de523ed..a3104d73c 100644
--- a/src/peach/web_follow.py
+++ b/src/peach/web_follow.py
@@ -2180,7 +2180,7 @@ def _run_follow_check(contract, body, job_id=None) -> dict:
break
current = {"source": row["id"], "label": _author_display_name(row),
"provider": PROVIDER_LABELS.get(row["provider"], row["provider"])}
- def progress(**fields):
+ def progress(*, current=current, **fields):
if job_id:
contract.follow_job.update(job_id, total=len(rows), checked=len(results),
results=results.copy(), current={**current, **fields})
diff --git a/src/peach/web_links.py b/src/peach/web_links.py
index a11303e47..a2ddcb804 100644
--- a/src/peach/web_links.py
+++ b/src/peach/web_links.py
@@ -12,7 +12,6 @@
"""
from __future__ import annotations
-import re
import time
from pathlib import Path
from typing import Protocol
diff --git a/tests/test_ad_judgement.py b/tests/test_ad_judgement.py
index 16abc3a97..66c78d346 100644
--- a/tests/test_ad_judgement.py
+++ b/tests/test_ad_judgement.py
@@ -6,7 +6,6 @@
import sqlite3
import tempfile
import unittest
-from pathlib import Path
from unittest import mock
from peach import web_batch
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 531dd1417..9a6f664bf 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -362,7 +362,7 @@ class InteractiveInitTests(unittest.TestCase):
import httpx
- from peach import routes_api, web_resource_sync
+ from peach import web_resource_sync
from peach.api import create_app
from peach.config import PeachSettings
from peach.platform import translate_roots
diff --git a/tests/test_complexity_ratchet.py b/tests/test_complexity_ratchet.py
index d47434e8e..5a0bb719a 100644
--- a/tests/test_complexity_ratchet.py
+++ b/tests/test_complexity_ratchet.py
@@ -38,7 +38,7 @@ LIMIT = 30
BASELINE: dict[str, int] = {
"src/peach/web_batch.py:_scored_junk": 68,
"scripts/scrape_codes.py:_scrape": 35,
- "scripts/localize_performer_names.py:collect": 64,
+ "scripts/localize_performer_names.py:collect": 63,
"src/peach/web_resource_sync.py:_resource_orphan_plan": 50,
"src/peach/web_review.py:_review_rows": 43,
"src/peach/fanbox.py:normalize_fanbox_post": 59,
diff --git a/tests/test_endcard.py b/tests/test_endcard.py
index 1faf87e4e..dd483d119 100644
--- a/tests/test_endcard.py
+++ b/tests/test_endcard.py
@@ -1,7 +1,6 @@
import csv
import hashlib
import importlib.util
-import json
import shutil
import sqlite3
import tempfile
diff --git a/tests/test_feeds.py b/tests/test_feeds.py
index 53e3f0803..62600dbe8 100644
--- a/tests/test_feeds.py
+++ b/tests/test_feeds.py
@@ -1,7 +1,6 @@
"""番号发现源:解析、两层去重、已读与忽略、空壳与真实资产的边界(ADR-0042)。"""
from __future__ import annotations
-import sqlite3
import sys
import tempfile
import unittest
diff --git a/tests/test_follow_connector_base.py b/tests/test_follow_connector_base.py
index 587424d98..50c180c46 100644
--- a/tests/test_follow_connector_base.py
+++ b/tests/test_follow_connector_base.py
@@ -45,7 +45,7 @@ class SharedRequestSkeletonTests(unittest.TestCase):
def test_retries_exhaust_and_post_is_not_replayed(self):
for method, expected in [('GET', 5), ('POST', 1)]:
calls = []
- def transport(*args):
+ def transport(*args, calls=calls):
calls.append(1)
raise httpx.ReadTimeout('temporary')
connector = _Probe(transport=transport, sleeper=lambda _: None)
diff --git a/tests/test_follow_discovery.py b/tests/test_follow_discovery.py
index 705fcc33a..29777a502 100644
--- a/tests/test_follow_discovery.py
+++ b/tests/test_follow_discovery.py
@@ -14,7 +14,7 @@ from peach.follow_discovery import (
archive_suggestions, discover, discovery_plan, forum_queries, identity_key,
rule34video_slugs, search_variants, spelling_variants, suggest_term, tag_suggestions,
)
-from peach.follow_secrets import Credential, CredentialError
+from peach.follow_secrets import Credential
from peach.http import HttpResponse
from support.backoff import no_real_backoff
diff --git a/tests/test_follow_sources.py b/tests/test_follow_sources.py
index 52b26c26e..c6c0cdb4e 100644
--- a/tests/test_follow_sources.py
+++ b/tests/test_follow_sources.py
@@ -6,7 +6,6 @@ thread 50685),不是凭记忆构造的形状。测试本身不联网:trans
"""
import json
import os
-import stat
import tempfile
import unittest
import urllib.parse
diff --git a/tests/test_follow_stream.py b/tests/test_follow_stream.py
index 89e4a6dee..671756d92 100644
--- a/tests/test_follow_stream.py
+++ b/tests/test_follow_stream.py
@@ -4,7 +4,7 @@ from unittest import mock
import httpx
-from peach import follow_stream, http as peach_http
+from peach import http as peach_http
from peach.follow_stream import (
MAX_PROXY_REDIRECTS, FollowMediaResolver, FollowMediaUnavailable,
FollowProxyError, ResolvedFollowMedia, open_upstream, proxy_request_headers,
diff --git a/tests/test_follow_web.py b/tests/test_follow_web.py
index d6f90f3de..66d33ac52 100644
--- a/tests/test_follow_web.py
+++ b/tests/test_follow_web.py
@@ -7,7 +7,6 @@ import hashlib
import json
import os
import re
-import sqlite3
import stat
import tempfile
import threading
diff --git a/tests/test_followups.py b/tests/test_followups.py
index d41282a7c..a534a1329 100644
--- a/tests/test_followups.py
+++ b/tests/test_followups.py
@@ -14,7 +14,7 @@ from peach import seed_followup, seed_pack
from peach import task_runs as task_runs_module
from peach.avatar_followup import TASK_KEY as AVATAR_TASK_KEY
from peach.avatar_followup import followup_key, parse_key, plan
-from peach.followups import Followup, FollowupRunner, FollowupType, lanes
+from peach.followups import FollowupRunner, FollowupType, lanes
from peach.jav_cover_fetch import NotFound
from peach.jobs import BackgroundJob
from peach.library_processing import process_library
diff --git a/tests/test_media_libraries.py b/tests/test_media_libraries.py
index fd8a6b9fb..25b732cd1 100644
--- a/tests/test_media_libraries.py
+++ b/tests/test_media_libraries.py
@@ -4,7 +4,6 @@ import tomllib
import unittest
from dataclasses import replace
from tempfile import TemporaryDirectory
-from pathlib import Path
from types import SimpleNamespace
from peach import media_libraries, settings_file
diff --git a/tests/test_metadata_kmib.py b/tests/test_metadata_kmib.py
index f865528df..b9f98e414 100644
--- a/tests/test_metadata_kmib.py
+++ b/tests/test_metadata_kmib.py
@@ -1,5 +1,4 @@
"""K-MIB 官网解析与采集脚本的隔离测试。"""
-import csv
import importlib.util
import sqlite3
import tempfile
diff --git a/tests/test_module_layering.py b/tests/test_module_layering.py
index 701bbb13e..7791e72e9 100644
--- a/tests/test_module_layering.py
+++ b/tests/test_module_layering.py
@@ -133,7 +133,7 @@ class SharedRuleTests(unittest.TestCase):
for path in sorted((PROJECT_ROOT / "scripts").glob("*.py")):
text = path.read_text(encoding="utf-8")
for rule in ("is_jav_code", "normalise_code_key", "LENGTH_TAGS"):
- if f"from peach.web_contract import" in text and rule in text.split(
+ if "from peach.web_contract import" in text and rule in text.split(
"from peach.web_contract import", 1)[1].split("\n", 1)[0]:
offenders.append(f"{path.name} → web_contract.{rule}")
self.assertEqual(offenders, [],
diff --git a/tests/test_netwatch.py b/tests/test_netwatch.py
index e96ed6f83..3bc0067d2 100644
--- a/tests/test_netwatch.py
+++ b/tests/test_netwatch.py
@@ -1,6 +1,5 @@
import os
import sys
-import threading
import time
import unittest
from unittest.mock import patch
diff --git a/tests/test_onboarding.py b/tests/test_onboarding.py
index dbccd20af..145902efd 100644
--- a/tests/test_onboarding.py
+++ b/tests/test_onboarding.py
@@ -966,7 +966,6 @@ class StandaloneConfigurationTests(_Case):
def test_cloud_configuration_saves_all_sources_and_requests_configured_scan(self):
from peach.routes_configuration import revision
- from peach import media_configuration
with self.client() as client:
response = client.post('/api/configuration', headers={'X-Token': 'test-token'}, json={
'revision': revision(self.config), 'port': 9123, 'scan_now': True,
diff --git a/tests/test_python_lint.py b/tests/test_python_lint.py
new file mode 100644
index 000000000..7a0ba5a5f
--- /dev/null
+++ b/tests/test_python_lint.py
@@ -0,0 +1,18 @@
+"""自有 Python 代码的全仓静态检查。"""
+
+from pathlib import Path
+import subprocess
+import sys
+import unittest
+
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+class PythonLintTests(unittest.TestCase):
+ def test_owned_python_passes_correctness_lint(self):
+ result = subprocess.run(
+ [sys.executable, "-m", "ruff", "check", ".", "--output-format=concise"],
+ cwd=ROOT, capture_output=True, text=True, encoding="utf-8", timeout=60,
+ )
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
diff --git a/tests/test_restart_windows_tray.py b/tests/test_restart_windows_tray.py
index ee57b7001..209a06b9c 100644
--- a/tests/test_restart_windows_tray.py
+++ b/tests/test_restart_windows_tray.py
@@ -486,7 +486,7 @@ class RestartEntryTests(unittest.TestCase):
with (
mock.patch.object(entry, "restart_tray", return_value=finished) as restart,
mock.patch.object(entry, "find_tray_windows",
- return_value=(windows_restart.TrayWindow(10, 20),)) as search,
+ return_value=(windows_restart.TrayWindow(10, 20),)),
contextlib.redirect_stdout(io.StringIO()) as printed,
):
self.assertEqual(entry.main(["--swap-from", "staged.exe"]), 0)
@@ -497,7 +497,7 @@ class RestartEntryTests(unittest.TestCase):
entry = load_entry()
source = windows_restart.RestartResult(True, "源码托盘已重启")
with (
- mock.patch.object(entry, "find_tray_windows", return_value=()) as search,
+ mock.patch.object(entry, "find_tray_windows", return_value=()),
mock.patch.object(entry, "restart_source_tray", return_value=source) as srcs,
contextlib.redirect_stdout(io.StringIO()) as printed,
):
@@ -509,7 +509,7 @@ class RestartEntryTests(unittest.TestCase):
entry = load_entry()
source = windows_restart.RestartResult(True, "源码托盘已重启")
with (
- mock.patch.object(entry, "find_tray_windows", return_value=()) as search,
+ mock.patch.object(entry, "find_tray_windows", return_value=()),
mock.patch.object(entry, "restart_source_tray", return_value=source),
mock.patch.object(entry, "restart_tray") as ghost,
contextlib.redirect_stdout(io.StringIO()),
diff --git a/tests/test_review_csv.py b/tests/test_review_csv.py
index cc5f0fe17..84c6aa54c 100644
--- a/tests/test_review_csv.py
+++ b/tests/test_review_csv.py
@@ -3,7 +3,6 @@
这里守的是编码契约本身。它此前在 46 个读写点各写一遍,而两条要求都属于「写的时候
一切正常、几天后有人用 Excel 打开才发现坏了」那一类,靠人眼复查是拦不住的。
"""
-import csv
import os
import tempfile
import unittest
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index bce42f013..ab4e19419 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -1,11 +1,8 @@
-import csv
import json
-import os
import pathlib
import sqlite3
import tempfile
import threading
-import time
import unittest
from contextlib import closing, contextmanager
from dataclasses import replace
diff --git a/tests/test_runtime_consistency.py b/tests/test_runtime_consistency.py
index d792c6c5f..702bccf54 100644
--- a/tests/test_runtime_consistency.py
+++ b/tests/test_runtime_consistency.py
@@ -68,7 +68,7 @@ class RuntimeConsistencyTests(unittest.TestCase):
def test_aggregate_cache_is_bounded_and_keeps_recent_hits(self):
contract = WebContract(Path("unused.db"))
for key in range(192):
- contract.cached(str(key), lambda: key)
+ contract.cached(str(key), lambda key=key: key)
contract.cached("0", lambda: -1)
contract.cached("new", lambda: 999)
self.assertEqual(len(contract.cache), 192)
diff --git a/tests/test_scripts.py b/tests/test_scripts.py
index d894bcb80..a501e2ac9 100644
--- a/tests/test_scripts.py
+++ b/tests/test_scripts.py
@@ -1085,7 +1085,7 @@ class OperationalScriptTests(unittest.TestCase):
self.assertEqual(len(evidence), 2)
for response in (HttpResponse(403, {}, inside, "https://brand.test/"),
HttpResponse(200, {}, inside, "https://elsewhere.test/")):
- found, _, note = module.scan(lambda *args: response, "https://brand.test/", 1)
+ found, _, note = module.scan(lambda *args, response=response: response, "https://brand.test/", 1)
self.assertEqual(found, set())
self.assertIn("未取得", note)
@@ -1837,7 +1837,7 @@ class OperationalScriptTests(unittest.TestCase):
shot: list[str] = []
- def fake_sheet(_ffmpeg, path, _duration, destination, _frames):
+ def fake_sheet(_ffmpeg, path, _duration, destination, _frames, shot=shot):
shot.append(Path(path).name)
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_bytes(b"x" * 8192)
@@ -1846,7 +1846,7 @@ class OperationalScriptTests(unittest.TestCase):
choice = type("C", (), {"path": "ffmpeg"})
with mock.patch.object(sheets, "make_sheet", fake_sheet), \
mock.patch.object(sheets.FFmpegResolver, "ffmpeg",
- lambda _self: choice), \
+ lambda _self, choice=choice: choice), \
redirect_stdout(io.StringIO()):
sheets.run(args)
self.assertEqual(shot, expected)
@@ -3142,7 +3142,7 @@ class ReleaseTagTests(unittest.TestCase):
({("git", "branch", "--show-current"): "feature"}, []),
({}, [{"ref": "refs/tags/v0.7.14"}])):
with self.subTest(changes=changes, refs=refs), self._shell(changes), \
- mock.patch.object(self.release, "api", side_effect=lambda repo, path: {"object": {"sha": "abc"}} if path == "git/ref/heads/master" else refs), \
+ mock.patch.object(self.release, "api", side_effect=lambda repo, path, refs=refs: {"object": {"sha": "abc"}} if path == "git/ref/heads/master" else refs), \
mock.patch.object(self.release.version_bump, "read_version", return_value="0.7.14"), \
mock.patch.object(Path, "read_text", return_value="## [0.7.14] - 2026-09-07\n"), \
self.assertRaises(ValueError):
diff --git a/tests/test_seed_followup.py b/tests/test_seed_followup.py
index 7d34ed19d..a18be836f 100644
--- a/tests/test_seed_followup.py
+++ b/tests/test_seed_followup.py
@@ -88,7 +88,8 @@ class RunTests(Case):
def test_run_lands_the_pack_and_writes_the_review_file(self):
her, kmp = self.add("performer", "天川そら"), self.add("studio", "K M Produce")
self.add("agency", "STARTUP")
- label, maker = self.add("studio", "PRESTIGE PREMIUM"), self.add("studio", "Prestige")
+ label = self.add("studio", "PRESTIGE PREMIUM")
+ self.add("studio", "Prestige")
with self.database.write_transaction() as connection:
connection.execute("INSERT INTO label_maker(label_id,maker_id,source,confidence,checked_at)"
" VALUES(?,?,?,1.0,?)", (label, kmp, "review:user", STAMP))
diff --git a/tests/test_web_review.py b/tests/test_web_review.py
index f943141fe..86e685d05 100644
--- a/tests/test_web_review.py
+++ b/tests/test_web_review.py
@@ -14,7 +14,6 @@ import re
import pathlib
import sqlite3
import tempfile
-import time
import unittest
from pathlib import Path
from unittest import mock
@@ -2447,7 +2446,6 @@ class ReviewQueueTests(unittest.TestCase):
candidate = {
"candidate_key": "ABC-001:performers:r18dev:abc", "source": "r18dev",
"source_url": "https://r18.dev/example", "confidence": 0.9,
- "provider_id": "ABC-001",
"provider_id": "ABC-001", "content_id": "abc00001",
"value": [{"name": "木村さん", "external_id": "7", "thumb_url": ""}],
"display_value": "木村さん", "warnings": [], "raw_snapshot": "/evidence.json",
diff --git a/uv.lock b/uv.lock
index 9f3d59d84..d81b4d31a 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1193,6 +1193,7 @@ build = [
dev = [
{ name = "filelock" },
{ name = "psutil" },
+ { name = "ruff" },
{ name = "seiso" },
]
macos = [
@@ -1233,6 +1234,7 @@ requires-dist = [
{ name = "pyobjc-framework-cocoa", marker = "sys_platform == 'darwin' and extra == 'macos'", specifier = "==12.2.2" },
{ name = "pystray", specifier = "==0.19.5" },
{ name = "resvg-py", specifier = "==0.5.0" },
+ { name = "ruff", marker = "extra == 'dev'", specifier = "==0.16.10" },
{ name = "seiso", marker = "extra == 'dev'", specifier = "==0.2.0" },
{ name = "socksio", specifier = "==1.0.0" },
{ name = "starlette", specifier = "==1.6.0" },
@@ -2129,6 +2131,31 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/62/e6/25b6616cebbce1412bb5fe8b037545f382b4da875bc614a97ff1ecd7aa28/resvg_py-0.5.0-cp315-abi3.abi3t-win_arm64.whl", hash = "sha256:66e5a7699f2b00024ed7e95ec53df05bb3da277ee5bc86f867d487e310e4d392", size = 1152399, upload-time = "2026-08-24T19:43:12.618Z" },
]
+[[package]]
+name = "ruff"
+version = "0.16.10"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/c4/49/23802c45f093eb14bde54b141d2b2f058edfa63a06db7beed047308cc08f/ruff-0.16.10.tar.gz", hash = "sha256:eff4728c4eaae93f0955cd264d24b2ab348e74bf59986ccf282ba6dc16b3b017", size = 4958724, upload-time = "2026-10-01T18:03:21.697Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2f/21/ebce22e1d90cdb2cd691026b9c6e9bec6499f0b396089481755b5d49efff/ruff-0.16.10-py3-none-linux_armv6l.whl", hash = "sha256:488b0fe3f3574210e5cf80d9f59b9e3ab17a127a8155de3f307b392589cfb511", size = 10095557, upload-time = "2026-10-01T18:02:36.072Z" },
+ { url = "https://files.pythonhosted.org/packages/cb/98/a54de85876a8b2612bfa0d84c7b9abfb39c6a3354aee7800b09c1649b9e3/ruff-0.16.10-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:e748ff95c934c4e978783b8e687bc174e7bd84e8ad24e3243e1ecfcda5e0282d", size = 10340577, upload-time = "2026-10-01T18:02:39.258Z" },
+ { url = "https://files.pythonhosted.org/packages/9f/16/1a5a4a2657effe4806110f2b907313802f1367fcdbb29e8122766e407fab/ruff-0.16.10-py3-none-macosx_11_0_arm64.whl", hash = "sha256:3031a4a2e8e7b8a46f70be45f198c35a11ece509a94b80334d8d397a33c67550", size = 9774282, upload-time = "2026-10-01T18:02:41.79Z" },
+ { url = "https://files.pythonhosted.org/packages/6e/fb/470085af734da396e68cd80fb0a3e7c109a459716ae59588c0f6fab8a17d/ruff-0.16.10-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:494401c86df4c4c25f69b9419605d944467ee98c42fb6ad405ef4fa40b8fb67d", size = 9920895, upload-time = "2026-10-01T18:02:44.458Z" },
+ { url = "https://files.pythonhosted.org/packages/57/de/f10cffe4f88a37ea6615ec460f01bf76f0bc1477737a35d9ee61a630a78b/ruff-0.16.10-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d203abc0ff2b773ee33d00ab8df0bb67046fbc7c07b119332f08b9b345cf8221", size = 9902707, upload-time = "2026-10-01T18:02:47.041Z" },
+ { url = "https://files.pythonhosted.org/packages/ff/44/3fdcedf83ae60ef837dd239170e480dce606a9142cfa2db911afdf855fd9/ruff-0.16.10-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:bd83d1235a5258d318477bc5b576303974cbdef5df0c01a1bff14efcc23bd12a", size = 10619287, upload-time = "2026-10-01T18:02:49.485Z" },
+ { url = "https://files.pythonhosted.org/packages/c1/62/02e76a5574002153618eafbb70e159468addc72a5d2c488e65cbb4639d2d/ruff-0.16.10-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:bc2610fb269fa56dd8a68669ae470fa6272902668c0fc2ebc3aa112b2633d5b8", size = 11339942, upload-time = "2026-10-01T18:02:52.008Z" },
+ { url = "https://files.pythonhosted.org/packages/6b/c4/cde27d47ad8d4126c587e608c67c46e7feac11763f606d261a1bc8a489e6/ruff-0.16.10-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:3e70175e29cc94c26ea296c80e470180b744b7419026898e58f520c6ab32578e", size = 10934316, upload-time = "2026-10-01T18:02:54.811Z" },
+ { url = "https://files.pythonhosted.org/packages/e4/03/17234145f302a645a123e8c3bb2411ecf4669fbc350de3b0d803230a1729/ruff-0.16.10-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f33f43a864a8483eebd160e713336c8bab02c934feaff0a33cf5ccb41546d09a", size = 10387968, upload-time = "2026-10-01T18:02:57.497Z" },
+ { url = "https://files.pythonhosted.org/packages/71/29/2493af60240ee7644b38a4b821f5f9c3b5a4fa3178770fe1d0c685217395/ruff-0.16.10-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:1dfc6f0088149fb6a362c1c446bcbb3fd2157b3852fe2fa68409276eab9ad9b3", size = 10537906, upload-time = "2026-10-01T18:03:00.006Z" },
+ { url = "https://files.pythonhosted.org/packages/2e/9a/f56b28f3b143bb9e518c34fb89ab191b626bca8b70dbf8af0d2e2d473572/ruff-0.16.10-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:6553498afc35f580f036030795810b9e6bcea31604b0fd9e8d352795473042e3", size = 10012938, upload-time = "2026-10-01T18:03:03.006Z" },
+ { url = "https://files.pythonhosted.org/packages/c2/c4/fca37362848ea4d4d80712df13632e645e7c7cfb1bdedf140699ac7a090b/ruff-0.16.10-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:a3b8471dea115d37f123882be852bed13403746d3a76c11de4a19ec5f9ff5a03", size = 9897945, upload-time = "2026-10-01T18:03:05.818Z" },
+ { url = "https://files.pythonhosted.org/packages/7d/c7/e0bc57664d6e0c61fd22f620af260fe9662d7e1ddb320ea7f160e76ef165/ruff-0.16.10-py3-none-musllinux_1_2_i686.whl", hash = "sha256:92e59a70bcbd9d3a5483656da906ec28edfdacfce00afd99edb8b4e9d15644be", size = 10333134, upload-time = "2026-10-01T18:03:08.25Z" },
+ { url = "https://files.pythonhosted.org/packages/21/aa/5c9f3b68737c0e4a33a1db5dfab44f7b786d96ca91a7233112ddab1e6dc2/ruff-0.16.10-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:7ae7375f803b5520dc9f546bed7e3a0acb70b91812e9bb4b19927de22f25b77d", size = 10741702, upload-time = "2026-10-01T18:03:10.775Z" },
+ { url = "https://files.pythonhosted.org/packages/78/fa/0f9c2020dc316c53d983be011720b8157cc052b97e3f4dfa7db6d0f880a6/ruff-0.16.10-py3-none-win32.whl", hash = "sha256:2a12e01cb9156c10c466f63b46eaae5ecea28dfbd21b5836353ae498e7d1349a", size = 10139176, upload-time = "2026-10-01T18:03:13.267Z" },
+ { url = "https://files.pythonhosted.org/packages/99/29/cfb0df9448d4d4ad48c2de029ada9ebd71baa6da983a6c77ee6c6cd0fe82/ruff-0.16.10-py3-none-win_amd64.whl", hash = "sha256:97f2015c92aa97105b0eab19eb5d224884399281cfc5da86a92db4ab5e7fb2ca", size = 10584734, upload-time = "2026-10-01T18:03:16.006Z" },
+ { url = "https://files.pythonhosted.org/packages/fc/05/c16957eb287c3fc062e032619a25868d93d408a844b725bcf514f7a378ff/ruff-0.16.10-py3-none-win_arm64.whl", hash = "sha256:25a65fe998c4e6861ec079ada5826a2fc605e6cbccbe9dcd7fac1f54e791621b", size = 10366440, upload-time = "2026-10-01T18:03:19.04Z" },
+]
+
[[package]]
name = "seiso"
version = "0.2.0"