refactor(sync): drop favorite-folder tracking and deal
This commit is contained in:
1 parent
62abbd7ea1
commit
6c4287b43a
21 files changed
+1390
-2766
No files matched your search
+352
-352
@@ -1,352 +1,352 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""CLI 入口测试(离线): uv run python tests/test_cli.py"""
|
||||
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
|
||||
from reaction_board.bilibili.models import LoginState # noqa: E402
|
||||
from reaction_board.cli import main # noqa: E402
|
||||
from reaction_board.database import Database # noqa: E402
|
||||
from reaction_board.repository import Repository # noqa: E402
|
||||
import reaction_board.cli as cli # noqa: E402
|
||||
|
||||
|
||||
def write_config(tmp, *, cookie="SESSDATA=x; buvid3=y", csrf="csrf"):
|
||||
path = Path(tmp) / "config.json"
|
||||
path.write_text(json.dumps({
|
||||
"bilibili": {
|
||||
"read": {"mid": 1, "csrf": csrf, "cookie": cookie},
|
||||
"write": {"mid": 2, "csrf": "write-csrf", "cookie": "write-cookie"},
|
||||
},
|
||||
"storage": {
|
||||
"database_path": str(Path(tmp) / "app.db"),
|
||||
"backup_dir": str(Path(tmp) / "backup"),
|
||||
},
|
||||
"folders": [
|
||||
{"year": 2025, "media_id": 11, "title": "2025"},
|
||||
{"year": 2026, "media_id": 22, "title": "2026"},
|
||||
],
|
||||
"up_blacklist_seed": [101, 202],
|
||||
}, ensure_ascii=False), encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def run_cli(argv):
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out):
|
||||
code = main(argv)
|
||||
return code, out.getvalue()
|
||||
|
||||
|
||||
def test_init_and_status():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp)
|
||||
code, output = run_cli(["init", "--config", str(path)])
|
||||
assert code == 0
|
||||
assert '"schema_version": 4' in output
|
||||
|
||||
db = Database(Path(tmp) / "app.db")
|
||||
db.initialize()
|
||||
try:
|
||||
repo = Repository(db)
|
||||
assert len(repo.list_folders()) == 2
|
||||
assert [r["mid"] for r in repo.blacklist()] == [101, 202]
|
||||
assert repo.counts()["video_total"] == 0
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
code, output = run_cli(["status", "--config", str(path)])
|
||||
assert code == 0
|
||||
assert '"configured_folders"' in output
|
||||
assert '"media_count": null' in output
|
||||
assert '"video_total": 0' in output
|
||||
|
||||
|
||||
def test_missing_config():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
code, output = run_cli(["init", "--config", str(Path(tmp) / "nope.json")])
|
||||
assert code == 2
|
||||
payload = json.loads(output.strip().splitlines()[-1])
|
||||
assert payload["level"] == "error"
|
||||
assert "缺少配置文件" in payload["error"]
|
||||
|
||||
|
||||
def test_sync_requires_auth_without_network():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp, cookie="", csrf="")
|
||||
code, output = run_cli(["sync", "--config", str(path)])
|
||||
assert code == 2
|
||||
payload = json.loads(output.strip().splitlines()[-1])
|
||||
assert "cookie" in payload["error"]
|
||||
assert not (Path(tmp) / "app.db").exists()
|
||||
|
||||
|
||||
def test_snapshot_offline_empty_db():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp, cookie="", csrf="")
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
data["folders"] = []
|
||||
data["track_fans"] = []
|
||||
path.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
||||
code, output = run_cli(["snapshot", "--config", str(path)])
|
||||
assert code == 0
|
||||
assert '"completed": true' in output
|
||||
assert '"total": 0' in output
|
||||
assert len(list((Path(tmp) / "backup").glob("app-*.db"))) == 1
|
||||
|
||||
|
||||
def test_auth_check_without_cookie():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp, cookie="", csrf="")
|
||||
code, output = run_cli(["auth-check", "--config", str(path)])
|
||||
assert code == 1
|
||||
payload = json.loads(output)
|
||||
assert payload["is_login"] is False
|
||||
assert "未配置 cookie" in payload["message"]
|
||||
|
||||
|
||||
def test_auth_check_all_and_auth_dispatch():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp, cookie="", csrf="")
|
||||
code, output = run_cli(["auth-check", "--account", "all", "--config", str(path)])
|
||||
assert code == 1
|
||||
payload = json.loads(output)
|
||||
assert payload["ok"] is False
|
||||
assert [item["account"] for item in payload["accounts"]] == ["read", "write"]
|
||||
|
||||
original = cli.AuthService
|
||||
calls = []
|
||||
|
||||
class FakeAuthService:
|
||||
def __init__(self, path, *, account, logger):
|
||||
calls.append((str(path), account))
|
||||
|
||||
def run(self, *, timeout, no_browser):
|
||||
assert timeout == 9 and no_browser is True
|
||||
return 7
|
||||
|
||||
cli.AuthService = FakeAuthService
|
||||
try:
|
||||
code, _ = run_cli([
|
||||
"auth", "--account", "write", "--timeout", "9", "--no-browser", "--config", str(path),
|
||||
])
|
||||
finally:
|
||||
cli.AuthService = original
|
||||
assert code == 7
|
||||
assert calls == [(str(path), "write")]
|
||||
|
||||
|
||||
def test_run_once_offline():
|
||||
class FakeClient:
|
||||
def check_login(self):
|
||||
return LoginState(True, 1, "tester", 0, "OK")
|
||||
|
||||
class FakeDiscovery:
|
||||
def __init__(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def run(self):
|
||||
from reaction_board.services.discovery import DiscoverySummary
|
||||
return DiscoverySummary(started_at=1, finished_at=1)
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp)
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
data["folders"] = []
|
||||
data["track_fans"] = []
|
||||
path.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
original = cli._client
|
||||
original_discovery = cli.DiscoveryService
|
||||
selected = []
|
||||
|
||||
def fake_client(credentials, *args, **kwargs):
|
||||
selected.append(credentials)
|
||||
return FakeClient()
|
||||
|
||||
cli._client = fake_client
|
||||
cli.DiscoveryService = FakeDiscovery
|
||||
try:
|
||||
code, output = run_cli(["run", "--once", "--config", str(path)])
|
||||
finally:
|
||||
cli._client = original
|
||||
cli.DiscoveryService = original_discovery
|
||||
assert code == 0
|
||||
assert '"name": "folder_sync"' in output
|
||||
assert '"name": "snapshot"' in output
|
||||
assert selected and all(credentials.mid == 1 for credentials in selected)
|
||||
|
||||
db = Database(Path(tmp) / "app.db")
|
||||
db.initialize()
|
||||
try:
|
||||
repo = Repository(db)
|
||||
for name in ("folder_sync", "snapshot", "discovery", "candidate_cleanup"):
|
||||
assert repo.kv_get(f"task:last:{name}"), name
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_serve_preview_guard():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp)
|
||||
assert run_cli(["init", "--config", str(path)])[0] == 0
|
||||
db_path = Path(tmp) / "app.db"
|
||||
try:
|
||||
cli._assert_preview_database(db_path)
|
||||
except cli.ConfigError as exc:
|
||||
assert "preview:seeded" in str(exc)
|
||||
else:
|
||||
raise AssertionError("普通数据库不应通过 --preview 校验")
|
||||
|
||||
db = Database(db_path)
|
||||
db.initialize()
|
||||
try:
|
||||
Repository(db).kv_set("preview:seeded", "1")
|
||||
finally:
|
||||
db.close()
|
||||
cli._assert_preview_database(db_path)
|
||||
|
||||
try:
|
||||
cli._assert_preview_database(Path(tmp) / "missing.db")
|
||||
except cli.ConfigError as exc:
|
||||
assert "不存在" in str(exc)
|
||||
else:
|
||||
raise AssertionError("缺失数据库应报错")
|
||||
|
||||
|
||||
def test_default_command_starts_web_and_scheduler():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp)
|
||||
calls = []
|
||||
original = cli.cmd_run
|
||||
|
||||
def fake_run(args, logger, *, serve_web=False):
|
||||
calls.append((args.command, serve_web, args.once, args.allow_empty_folder))
|
||||
return 0
|
||||
|
||||
cli.cmd_run = fake_run
|
||||
try:
|
||||
code = main(["--config", str(path)])
|
||||
finally:
|
||||
cli.cmd_run = original
|
||||
assert code == 0
|
||||
assert calls == [("run", True, False, False)]
|
||||
|
||||
|
||||
def test_snapshot_backup_failure_returns_error_and_retries():
|
||||
import reaction_board.services.snapshot as snapshot_module
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp, cookie="", csrf="")
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
data["folders"] = []
|
||||
data["track_fans"] = []
|
||||
path.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
original = snapshot_module.backup_daily
|
||||
|
||||
def fail_backup(*args, **kwargs):
|
||||
raise OSError("disk full")
|
||||
|
||||
snapshot_module.backup_daily = fail_backup
|
||||
try:
|
||||
code, output = run_cli(["snapshot", "--config", str(path)])
|
||||
finally:
|
||||
snapshot_module.backup_daily = original
|
||||
assert code == 1
|
||||
marker = output.find("{\n")
|
||||
assert marker >= 0, output
|
||||
payload = json.loads(output[marker:])
|
||||
assert payload["completed"] is True
|
||||
assert "disk full" in payload["backup_error"]
|
||||
|
||||
code, output = run_cli(["snapshot", "--config", str(path)])
|
||||
assert code == 0
|
||||
marker = output.find("{\n")
|
||||
payload = json.loads(output[marker:])
|
||||
assert payload["backup_error"] is None
|
||||
assert Path(payload["backup_path"]).exists()
|
||||
|
||||
|
||||
def test_candidates_and_discover_commands():
|
||||
from reaction_board.services.discovery import DiscoverySummary
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp)
|
||||
assert run_cli(["init", "--config", str(path)])[0] == 0
|
||||
db = Database(Path(tmp) / "app.db")
|
||||
db.initialize()
|
||||
try:
|
||||
repo = Repository(db)
|
||||
repo.upsert_candidate(
|
||||
aid=123, bvid="BV123", title="咻咻满 reaction",
|
||||
up_mid=100, up_name="UP", pubdate=1,
|
||||
cover=None, score=3, channel="search:test#p1",
|
||||
)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
code, output = run_cli(["candidates", "--config", str(path)])
|
||||
assert code == 0
|
||||
assert '"count": 1' in output
|
||||
assert '"aid": 123' in output
|
||||
|
||||
class FakeDiscovery:
|
||||
def __init__(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def run(self):
|
||||
return DiscoverySummary(
|
||||
started_at=1, finished_at=2, candidates=3, notified=1
|
||||
)
|
||||
|
||||
original = cli.DiscoveryService
|
||||
cli.DiscoveryService = FakeDiscovery
|
||||
try:
|
||||
code, output = run_cli(["discover", "--config", str(path)])
|
||||
finally:
|
||||
cli.DiscoveryService = original
|
||||
assert code == 0
|
||||
assert '"candidates": 3' in output
|
||||
assert '"notified": 1' in output
|
||||
|
||||
|
||||
def test_backfill_followers_dry_run():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp, cookie="", csrf="")
|
||||
code, output = run_cli([
|
||||
"backfill-followers", "--dry-run", "--config", str(path),
|
||||
])
|
||||
assert code == 0
|
||||
assert '"requested": 0' in output
|
||||
assert '"failed": 0' in output
|
||||
assert '"dry_run": true' in output
|
||||
assert '"total": 0' in output
|
||||
|
||||
|
||||
def main_test():
|
||||
test_init_and_status()
|
||||
test_missing_config()
|
||||
test_sync_requires_auth_without_network()
|
||||
test_snapshot_offline_empty_db()
|
||||
test_auth_check_without_cookie()
|
||||
test_auth_check_all_and_auth_dispatch()
|
||||
test_run_once_offline()
|
||||
test_serve_preview_guard()
|
||||
test_default_command_starts_web_and_scheduler()
|
||||
test_snapshot_backup_failure_returns_error_and_retries()
|
||||
test_candidates_and_discover_commands()
|
||||
test_backfill_followers_dry_run()
|
||||
print("OK: CLI init/sync/snapshot/auth-check/run/status/backfill/错误路径测试全部通过")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main_test()
|
||||
# -*- coding: utf-8 -*-
|
||||
"""CLI 入口测试(离线): uv run python tests/test_cli.py"""
|
||||
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
|
||||
from reaction_board.bilibili.models import LoginState # noqa: E402
|
||||
from reaction_board.cli import main # noqa: E402
|
||||
from reaction_board.database import Database # noqa: E402
|
||||
from reaction_board.repository import Repository # noqa: E402
|
||||
import reaction_board.cli as cli # noqa: E402
|
||||
|
||||
|
||||
def write_config(tmp, *, cookie="SESSDATA=x; buvid3=y", csrf="csrf"):
|
||||
path = Path(tmp) / "config.json"
|
||||
path.write_text(json.dumps({
|
||||
"bilibili": {
|
||||
"read": {"mid": 1, "csrf": csrf, "cookie": cookie},
|
||||
"write": {"mid": 2, "csrf": "write-csrf", "cookie": "write-cookie"},
|
||||
},
|
||||
"storage": {
|
||||
"database_path": str(Path(tmp) / "app.db"),
|
||||
"backup_dir": str(Path(tmp) / "backup"),
|
||||
},
|
||||
"folders": [
|
||||
{"year": 2025, "media_id": 11, "title": "2025"},
|
||||
{"year": 2026, "media_id": 22, "title": "2026"},
|
||||
],
|
||||
"up_blacklist_seed": [101, 202],
|
||||
}, ensure_ascii=False), encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def run_cli(argv):
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out):
|
||||
code = main(argv)
|
||||
return code, out.getvalue()
|
||||
|
||||
|
||||
def test_init_and_status():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp)
|
||||
code, output = run_cli(["init", "--config", str(path)])
|
||||
assert code == 0
|
||||
assert '"schema_version": 5' in output
|
||||
|
||||
db = Database(Path(tmp) / "app.db")
|
||||
db.initialize()
|
||||
try:
|
||||
repo = Repository(db)
|
||||
assert len(repo.list_folders()) == 2
|
||||
assert [r["mid"] for r in repo.blacklist()] == [101, 202]
|
||||
assert repo.counts()["video_total"] == 0
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
code, output = run_cli(["status", "--config", str(path)])
|
||||
assert code == 0
|
||||
assert '"configured_folders"' in output
|
||||
assert '"media_count": null' in output
|
||||
assert '"video_total": 0' in output
|
||||
|
||||
|
||||
def test_missing_config():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
code, output = run_cli(["init", "--config", str(Path(tmp) / "nope.json")])
|
||||
assert code == 2
|
||||
payload = json.loads(output.strip().splitlines()[-1])
|
||||
assert payload["level"] == "error"
|
||||
assert "缺少配置文件" in payload["error"]
|
||||
|
||||
|
||||
def test_ingest_without_refs_is_offline():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp, cookie="", csrf="")
|
||||
code, output = run_cli(["ingest", "--config", str(path), "没有视频"])
|
||||
assert code == 1
|
||||
data = json.loads(output[output.rindex("{\n"):])
|
||||
assert data["refs"] == 0
|
||||
assert data["results"] == []
|
||||
|
||||
|
||||
def test_snapshot_offline_empty_db():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp, cookie="", csrf="")
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
data["folders"] = []
|
||||
data["track_fans"] = []
|
||||
path.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
||||
code, output = run_cli(["snapshot", "--config", str(path)])
|
||||
assert code == 0
|
||||
assert '"completed": true' in output
|
||||
assert '"total": 0' in output
|
||||
assert len(list((Path(tmp) / "backup").glob("app-*.db"))) == 1
|
||||
|
||||
|
||||
def test_auth_check_without_cookie():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp, cookie="", csrf="")
|
||||
code, output = run_cli(["auth-check", "--config", str(path)])
|
||||
assert code == 1
|
||||
payload = json.loads(output)
|
||||
assert payload["is_login"] is False
|
||||
assert "未配置 cookie" in payload["message"]
|
||||
|
||||
|
||||
def test_auth_check_all_and_auth_dispatch():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp, cookie="", csrf="")
|
||||
code, output = run_cli(["auth-check", "--account", "all", "--config", str(path)])
|
||||
assert code == 1
|
||||
payload = json.loads(output)
|
||||
assert payload["ok"] is False
|
||||
assert [item["account"] for item in payload["accounts"]] == ["read", "write"]
|
||||
|
||||
original = cli.AuthService
|
||||
calls = []
|
||||
|
||||
class FakeAuthService:
|
||||
def __init__(self, path, *, account, logger):
|
||||
calls.append((str(path), account))
|
||||
|
||||
def run(self, *, timeout, no_browser):
|
||||
assert timeout == 9 and no_browser is True
|
||||
return 7
|
||||
|
||||
cli.AuthService = FakeAuthService
|
||||
try:
|
||||
code, _ = run_cli([
|
||||
"auth", "--account", "write", "--timeout", "9", "--no-browser", "--config", str(path),
|
||||
])
|
||||
finally:
|
||||
cli.AuthService = original
|
||||
assert code == 7
|
||||
assert calls == [(str(path), "write")]
|
||||
|
||||
|
||||
def test_run_once_offline():
|
||||
class FakeClient:
|
||||
def check_login(self):
|
||||
return LoginState(True, 1, "tester", 0, "OK")
|
||||
|
||||
class FakeDiscovery:
|
||||
def __init__(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def run(self):
|
||||
from reaction_board.services.discovery import DiscoverySummary
|
||||
return DiscoverySummary(started_at=1, finished_at=1)
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp)
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
data["folders"] = []
|
||||
data["track_fans"] = []
|
||||
path.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
original = cli._client
|
||||
original_discovery = cli.DiscoveryService
|
||||
selected = []
|
||||
|
||||
def fake_client(credentials, *args, **kwargs):
|
||||
selected.append(credentials)
|
||||
return FakeClient()
|
||||
|
||||
cli._client = fake_client
|
||||
cli.DiscoveryService = FakeDiscovery
|
||||
try:
|
||||
code, output = run_cli(["run", "--once", "--config", str(path)])
|
||||
finally:
|
||||
cli._client = original
|
||||
cli.DiscoveryService = original_discovery
|
||||
assert code == 0
|
||||
assert '"name": "snapshot"' in output
|
||||
assert '"name": "folder_sync"' not in output
|
||||
assert selected and all(credentials.mid == 1 for credentials in selected)
|
||||
|
||||
db = Database(Path(tmp) / "app.db")
|
||||
db.initialize()
|
||||
try:
|
||||
repo = Repository(db)
|
||||
for name in ("snapshot", "discovery", "candidate_cleanup"):
|
||||
assert repo.kv_get(f"task:last:{name}"), name
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_serve_preview_guard():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp)
|
||||
assert run_cli(["init", "--config", str(path)])[0] == 0
|
||||
db_path = Path(tmp) / "app.db"
|
||||
try:
|
||||
cli._assert_preview_database(db_path)
|
||||
except cli.ConfigError as exc:
|
||||
assert "preview:seeded" in str(exc)
|
||||
else:
|
||||
raise AssertionError("普通数据库不应通过 --preview 校验")
|
||||
|
||||
db = Database(db_path)
|
||||
db.initialize()
|
||||
try:
|
||||
Repository(db).kv_set("preview:seeded", "1")
|
||||
finally:
|
||||
db.close()
|
||||
cli._assert_preview_database(db_path)
|
||||
|
||||
try:
|
||||
cli._assert_preview_database(Path(tmp) / "missing.db")
|
||||
except cli.ConfigError as exc:
|
||||
assert "不存在" in str(exc)
|
||||
else:
|
||||
raise AssertionError("缺失数据库应报错")
|
||||
|
||||
|
||||
def test_default_command_starts_web_and_scheduler():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp)
|
||||
calls = []
|
||||
original = cli.cmd_run
|
||||
|
||||
def fake_run(args, logger, *, serve_web=False):
|
||||
calls.append((args.command, serve_web, args.once))
|
||||
return 0
|
||||
|
||||
cli.cmd_run = fake_run
|
||||
try:
|
||||
code = main(["--config", str(path)])
|
||||
finally:
|
||||
cli.cmd_run = original
|
||||
assert code == 0
|
||||
assert calls == [("run", True, False)]
|
||||
|
||||
|
||||
def test_snapshot_backup_failure_returns_error_and_retries():
|
||||
import reaction_board.services.snapshot as snapshot_module
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp, cookie="", csrf="")
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
data["folders"] = []
|
||||
data["track_fans"] = []
|
||||
path.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
original = snapshot_module.backup_daily
|
||||
|
||||
def fail_backup(*args, **kwargs):
|
||||
raise OSError("disk full")
|
||||
|
||||
snapshot_module.backup_daily = fail_backup
|
||||
try:
|
||||
code, output = run_cli(["snapshot", "--config", str(path)])
|
||||
finally:
|
||||
snapshot_module.backup_daily = original
|
||||
assert code == 1
|
||||
marker = output.find("{\n")
|
||||
assert marker >= 0, output
|
||||
payload = json.loads(output[marker:])
|
||||
assert payload["completed"] is True
|
||||
assert "disk full" in payload["backup_error"]
|
||||
|
||||
code, output = run_cli(["snapshot", "--config", str(path)])
|
||||
assert code == 0
|
||||
marker = output.find("{\n")
|
||||
payload = json.loads(output[marker:])
|
||||
assert payload["backup_error"] is None
|
||||
assert Path(payload["backup_path"]).exists()
|
||||
|
||||
|
||||
def test_candidates_and_discover_commands():
|
||||
from reaction_board.services.discovery import DiscoverySummary
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp)
|
||||
assert run_cli(["init", "--config", str(path)])[0] == 0
|
||||
db = Database(Path(tmp) / "app.db")
|
||||
db.initialize()
|
||||
try:
|
||||
repo = Repository(db)
|
||||
repo.upsert_candidate(
|
||||
aid=123, bvid="BV123", title="咻咻满 reaction",
|
||||
up_mid=100, up_name="UP", pubdate=1,
|
||||
cover=None, score=3, channel="search:test#p1",
|
||||
)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
code, output = run_cli(["candidates", "--config", str(path)])
|
||||
assert code == 0
|
||||
assert '"count": 1' in output
|
||||
assert '"aid": 123' in output
|
||||
|
||||
class FakeDiscovery:
|
||||
def __init__(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def run(self):
|
||||
return DiscoverySummary(
|
||||
started_at=1, finished_at=2, candidates=3, notified=1
|
||||
)
|
||||
|
||||
original = cli.DiscoveryService
|
||||
cli.DiscoveryService = FakeDiscovery
|
||||
try:
|
||||
code, output = run_cli(["discover", "--config", str(path)])
|
||||
finally:
|
||||
cli.DiscoveryService = original
|
||||
assert code == 0
|
||||
assert '"candidates": 3' in output
|
||||
assert '"notified": 1' in output
|
||||
|
||||
|
||||
def test_backfill_followers_dry_run():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = write_config(tmp, cookie="", csrf="")
|
||||
code, output = run_cli([
|
||||
"backfill-followers", "--dry-run", "--config", str(path),
|
||||
])
|
||||
assert code == 0
|
||||
assert '"requested": 0' in output
|
||||
assert '"failed": 0' in output
|
||||
assert '"dry_run": true' in output
|
||||
assert '"total": 0' in output
|
||||
|
||||
|
||||
def main_test():
|
||||
test_init_and_status()
|
||||
test_missing_config()
|
||||
test_ingest_without_refs_is_offline()
|
||||
test_snapshot_offline_empty_db()
|
||||
test_auth_check_without_cookie()
|
||||
test_auth_check_all_and_auth_dispatch()
|
||||
test_run_once_offline()
|
||||
test_serve_preview_guard()
|
||||
test_default_command_starts_web_and_scheduler()
|
||||
test_snapshot_backup_failure_returns_error_and_retries()
|
||||
test_candidates_and_discover_commands()
|
||||
test_backfill_followers_dry_run()
|
||||
print("OK: CLI init/sync/snapshot/auth-check/run/status/backfill/错误路径测试全部通过")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main_test()
|
||||
+142
-142
@@ -1,142 +1,142 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""数据库单写队列测试(不联网): uv run python tests/test_database.py"""
|
||||
|
||||
import os
|
||||
import sqlite3
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
|
||||
from reaction_board.database import Database, DatabaseClosed # noqa: E402
|
||||
|
||||
|
||||
def make_db(tmp):
|
||||
db = Database(Path(tmp) / "app.db", backup_dir=Path(tmp) / "backup")
|
||||
db.initialize()
|
||||
return db
|
||||
|
||||
|
||||
def test_write_read_transaction():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db = make_db(tmp)
|
||||
try:
|
||||
assert db.schema_version == 4
|
||||
db.write(lambda c: c.execute("INSERT INTO kv(k, v) VALUES ('a', '1')"))
|
||||
assert db.read(lambda c: c.execute("SELECT v FROM kv WHERE k='a'").fetchone()[0]) == "1"
|
||||
|
||||
def boom(conn):
|
||||
conn.execute("UPDATE kv SET v='2' WHERE k='a'")
|
||||
raise RuntimeError("boom")
|
||||
try:
|
||||
db.transaction(boom)
|
||||
except RuntimeError as exc:
|
||||
assert str(exc) == "boom"
|
||||
else:
|
||||
raise AssertionError("事务应抛错")
|
||||
assert db.read(lambda c: c.execute("SELECT v FROM kv WHERE k='a'").fetchone()[0]) == "1"
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_concurrent_writes_are_serialized():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db = make_db(tmp)
|
||||
try:
|
||||
db.write(lambda c: c.execute(
|
||||
"CREATE TABLE counter (id INTEGER PRIMARY KEY, n INTEGER NOT NULL)"
|
||||
))
|
||||
db.write(lambda c: c.execute("INSERT INTO counter(id, n) VALUES (1, 0)"))
|
||||
errors = []
|
||||
|
||||
def worker():
|
||||
try:
|
||||
for _ in range(10):
|
||||
db.transaction(
|
||||
lambda conn: conn.execute(
|
||||
"UPDATE counter SET n = n + 1 WHERE id = 1"
|
||||
)
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors.append(exc)
|
||||
|
||||
threads = [threading.Thread(target=worker) for _ in range(8)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
assert not errors, errors
|
||||
assert db.read(lambda c: c.execute("SELECT n FROM counter").fetchone()[0]) == 80
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_close_and_reinitialize():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db = make_db(tmp)
|
||||
db.close()
|
||||
db.close() # 幂等
|
||||
try:
|
||||
db.write(lambda c: None)
|
||||
except DatabaseClosed:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("关闭后写入应失败")
|
||||
try:
|
||||
db.read(lambda c: None)
|
||||
except DatabaseClosed:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("关闭后读取应失败")
|
||||
|
||||
db2 = make_db(tmp)
|
||||
try:
|
||||
assert db2.schema_version == 4
|
||||
assert db2.read(lambda c: c.execute("SELECT MAX(version) FROM schema_version").fetchone()[0]) == 4
|
||||
finally:
|
||||
db2.close()
|
||||
|
||||
|
||||
def test_wal_enabled():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db = make_db(tmp)
|
||||
try:
|
||||
mode = db.read(lambda c: c.execute("PRAGMA journal_mode").fetchone()[0])
|
||||
assert str(mode).lower() == "wal"
|
||||
assert db.read(lambda c: c.execute("PRAGMA foreign_keys").fetchone()[0]) == 1
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_migration_backup_on_existing_db():
|
||||
"""已有数据升级时由 Database 自动备份。"""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / "app.db"
|
||||
# 先建一个旧库(只有 schema_version v0),Database.initialize 会升级并备份
|
||||
conn = sqlite3.connect(path)
|
||||
conn.execute("CREATE TABLE legacy (x INTEGER)")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
db = Database(path, backup_dir=Path(tmp) / "backup")
|
||||
try:
|
||||
applied = db.initialize()
|
||||
assert applied == [1, 2, 3, 4]
|
||||
assert len(list((Path(tmp) / "backup").glob("app-pre-v0-*.db"))) == 1
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def main():
|
||||
test_write_read_transaction()
|
||||
test_concurrent_writes_are_serialized()
|
||||
test_close_and_reinitialize()
|
||||
test_wal_enabled()
|
||||
test_migration_backup_on_existing_db()
|
||||
print("OK: 数据库单写队列与迁移入口测试全部通过")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
# -*- coding: utf-8 -*-
|
||||
"""数据库单写队列测试(不联网): uv run python tests/test_database.py"""
|
||||
|
||||
import os
|
||||
import sqlite3
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
|
||||
from reaction_board.database import Database, DatabaseClosed # noqa: E402
|
||||
|
||||
|
||||
def make_db(tmp):
|
||||
db = Database(Path(tmp) / "app.db", backup_dir=Path(tmp) / "backup")
|
||||
db.initialize()
|
||||
return db
|
||||
|
||||
|
||||
def test_write_read_transaction():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db = make_db(tmp)
|
||||
try:
|
||||
assert db.schema_version == 5
|
||||
db.write(lambda c: c.execute("INSERT INTO kv(k, v) VALUES ('a', '1')"))
|
||||
assert db.read(lambda c: c.execute("SELECT v FROM kv WHERE k='a'").fetchone()[0]) == "1"
|
||||
|
||||
def boom(conn):
|
||||
conn.execute("UPDATE kv SET v='2' WHERE k='a'")
|
||||
raise RuntimeError("boom")
|
||||
try:
|
||||
db.transaction(boom)
|
||||
except RuntimeError as exc:
|
||||
assert str(exc) == "boom"
|
||||
else:
|
||||
raise AssertionError("事务应抛错")
|
||||
assert db.read(lambda c: c.execute("SELECT v FROM kv WHERE k='a'").fetchone()[0]) == "1"
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_concurrent_writes_are_serialized():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db = make_db(tmp)
|
||||
try:
|
||||
db.write(lambda c: c.execute(
|
||||
"CREATE TABLE counter (id INTEGER PRIMARY KEY, n INTEGER NOT NULL)"
|
||||
))
|
||||
db.write(lambda c: c.execute("INSERT INTO counter(id, n) VALUES (1, 0)"))
|
||||
errors = []
|
||||
|
||||
def worker():
|
||||
try:
|
||||
for _ in range(10):
|
||||
db.transaction(
|
||||
lambda conn: conn.execute(
|
||||
"UPDATE counter SET n = n + 1 WHERE id = 1"
|
||||
)
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors.append(exc)
|
||||
|
||||
threads = [threading.Thread(target=worker) for _ in range(8)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
assert not errors, errors
|
||||
assert db.read(lambda c: c.execute("SELECT n FROM counter").fetchone()[0]) == 80
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_close_and_reinitialize():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db = make_db(tmp)
|
||||
db.close()
|
||||
db.close() # 幂等
|
||||
try:
|
||||
db.write(lambda c: None)
|
||||
except DatabaseClosed:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("关闭后写入应失败")
|
||||
try:
|
||||
db.read(lambda c: None)
|
||||
except DatabaseClosed:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("关闭后读取应失败")
|
||||
|
||||
db2 = make_db(tmp)
|
||||
try:
|
||||
assert db2.schema_version == 5
|
||||
assert db2.read(lambda c: c.execute("SELECT MAX(version) FROM schema_version").fetchone()[0]) == 5
|
||||
finally:
|
||||
db2.close()
|
||||
|
||||
|
||||
def test_wal_enabled():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db = make_db(tmp)
|
||||
try:
|
||||
mode = db.read(lambda c: c.execute("PRAGMA journal_mode").fetchone()[0])
|
||||
assert str(mode).lower() == "wal"
|
||||
assert db.read(lambda c: c.execute("PRAGMA foreign_keys").fetchone()[0]) == 1
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_migration_backup_on_existing_db():
|
||||
"""已有数据升级时由 Database 自动备份。"""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / "app.db"
|
||||
# 先建一个旧库(只有 schema_version v0),Database.initialize 会升级并备份
|
||||
conn = sqlite3.connect(path)
|
||||
conn.execute("CREATE TABLE legacy (x INTEGER)")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
db = Database(path, backup_dir=Path(tmp) / "backup")
|
||||
try:
|
||||
applied = db.initialize()
|
||||
assert applied == [1, 2, 3, 4, 5]
|
||||
assert len(list((Path(tmp) / "backup").glob("app-pre-v0-*.db"))) == 1
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def main():
|
||||
test_write_read_transaction()
|
||||
test_concurrent_writes_are_serialized()
|
||||
test_close_and_reinitialize()
|
||||
test_wal_enabled()
|
||||
test_migration_backup_on_existing_db()
|
||||
print("OK: 数据库单写队列与迁移入口测试全部通过")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,80 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""新视频插入位置纯函数测试: uv run python tests/test_fav_position.py"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
|
||||
from reaction_board.fav_position import VideoMeta, plan_insertion # noqa: E402
|
||||
|
||||
|
||||
def meta(up_mid, pubdate):
|
||||
return VideoMeta(up_mid=up_mid, pubdate=pubdate)
|
||||
|
||||
|
||||
def test_empty_and_single():
|
||||
assert plan_insertion([], 9, {}, meta(100, 200)).moves == ()
|
||||
assert plan_insertion([], 9, {}, meta(100, 200)).target_position == 1
|
||||
plan = plan_insertion([1], 9, {1: meta(200, 50)}, meta(100, 200))
|
||||
assert plan.target_position == 1
|
||||
assert plan.moves == ((1, 9), (9, 1))
|
||||
|
||||
|
||||
def test_same_up_group():
|
||||
current = [1, 2, 3, 4]
|
||||
metadata = {
|
||||
1: meta(100, 100),
|
||||
2: meta(100, 90),
|
||||
3: meta(200, 80),
|
||||
4: meta(200, 70),
|
||||
}
|
||||
# 同 UP 组在中间:插到组头
|
||||
plan = plan_insertion(current, 9, metadata, meta(200, 95))
|
||||
assert plan.target_position == 3
|
||||
assert plan.moves == ((2, 9),)
|
||||
|
||||
# 同 UP 组在首位:两次移动
|
||||
plan = plan_insertion(current, 9, metadata, meta(100, 200))
|
||||
assert plan.target_position == 1
|
||||
assert plan.moves == ((1, 9), (9, 1))
|
||||
|
||||
|
||||
def test_new_group_by_earliest_pubdate():
|
||||
current = [1, 2, 3, 4]
|
||||
metadata = {
|
||||
1: meta(100, 100),
|
||||
2: meta(100, 90),
|
||||
3: meta(200, 80),
|
||||
4: meta(200, 70),
|
||||
}
|
||||
# 新 UP 的组键 85,应插到组键 70 的组之前
|
||||
plan = plan_insertion(current, 9, metadata, meta(300, 85))
|
||||
assert plan.target_position == 3
|
||||
assert plan.moves == ((2, 9),)
|
||||
|
||||
# 比所有组都旧:追加到末尾
|
||||
plan = plan_insertion(current, 9, metadata, meta(300, 60))
|
||||
assert plan.target_position == 5
|
||||
assert plan.moves == ((4, 9),)
|
||||
|
||||
|
||||
def test_excludes_new_aid_if_present():
|
||||
current = [1, 9, 2]
|
||||
metadata = {1: meta(100, 100), 2: meta(100, 90)}
|
||||
plan = plan_insertion(current, 9, metadata, meta(100, 95))
|
||||
assert plan.target_position == 1
|
||||
assert plan.moves == ((1, 9), (9, 1))
|
||||
|
||||
|
||||
def main():
|
||||
test_empty_and_single()
|
||||
test_same_up_group()
|
||||
test_new_group_by_earliest_pubdate()
|
||||
test_excludes_new_aid_if_present()
|
||||
print("OK: 新视频插入位置计算测试全部通过")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,211 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""收藏/忽略/拉黑动作测试(假写客户端,不联网): uv run python tests/test_favorites.py"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
|
||||
from reaction_board.bilibili.client import BilibiliAPIError # noqa: E402
|
||||
from reaction_board.bilibili.models import FavResource # noqa: E402
|
||||
from reaction_board.config import ConfigStore # noqa: E402
|
||||
from reaction_board.database import Database # noqa: E402
|
||||
from reaction_board.repository import Repository # noqa: E402
|
||||
from reaction_board.services.favorites import FavoriteActionService # noqa: E402
|
||||
|
||||
NOW = 1_793_444_393
|
||||
FOLDER_ID = 3700023351
|
||||
|
||||
|
||||
@dataclass
|
||||
class FakeFavId:
|
||||
aid: int
|
||||
type: int = 2
|
||||
|
||||
|
||||
class FakeWriteClient:
|
||||
def __init__(self, order, *, fail_deal=False):
|
||||
self.order = list(order)
|
||||
self.fail_deal = fail_deal
|
||||
self.dealt = []
|
||||
self.sorts = []
|
||||
|
||||
def fav_ids(self, media_id):
|
||||
return [FakeFavId(aid) for aid in self.order]
|
||||
|
||||
def deal(self, aid, folder_id):
|
||||
if self.fail_deal:
|
||||
raise BilibiliAPIError(-1, "收藏夹已满")
|
||||
self.dealt.append((aid, folder_id))
|
||||
self.order.append(aid)
|
||||
|
||||
def sort(self, media_id, spec):
|
||||
predecessor, _, moved, _ = (int(part) for part in spec.split(":"))
|
||||
self.sorts.append(spec)
|
||||
self.order.remove(moved)
|
||||
index = self.order.index(predecessor)
|
||||
self.order.insert(index + 1, moved)
|
||||
|
||||
|
||||
class FakeProvider:
|
||||
def __init__(self, client):
|
||||
self.client = client
|
||||
|
||||
def get(self):
|
||||
return self.client
|
||||
|
||||
|
||||
def write_config(tmp):
|
||||
data = {
|
||||
"bilibili": {
|
||||
"read": {"mid": 1, "csrf": "r", "cookie": "read-cookie"},
|
||||
"write": {"mid": 2, "csrf": "w", "cookie": "write-cookie"},
|
||||
},
|
||||
"storage": {
|
||||
"database_path": str(Path(tmp) / "app.db"),
|
||||
"backup_dir": str(Path(tmp) / "backup"),
|
||||
},
|
||||
"folders": [{"year": 2026, "media_id": FOLDER_ID, "title": "2026"}],
|
||||
"discover": {"keywords": ["x"], "pages": 1, "window_days": 14},
|
||||
}
|
||||
path = Path(tmp) / "config.json"
|
||||
path.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def add_video(repo, aid, up_mid, pubdate):
|
||||
repo.upsert_from_fav(
|
||||
FavResource(
|
||||
aid=aid, bvid=f"BV{aid}", title=f"视频{aid}", up_mid=up_mid,
|
||||
up_name=f"UP{up_mid}", pubdate=pubdate, duration=600,
|
||||
cover=None, attr=0, fav_time=None,
|
||||
),
|
||||
FOLDER_ID,
|
||||
was_added=True,
|
||||
)
|
||||
|
||||
|
||||
def add_candidate(repo, aid, up_mid=100, pubdate=NOW - 3600):
|
||||
return repo.upsert_candidate(
|
||||
aid=aid,
|
||||
bvid=f"BV{aid}",
|
||||
title=f"咻咻满 reaction {aid}",
|
||||
up_mid=up_mid,
|
||||
up_name=f"UP{up_mid}",
|
||||
pubdate=pubdate,
|
||||
cover="https://example/cover.jpg",
|
||||
score=3,
|
||||
channel="search:test#p1",
|
||||
now=NOW,
|
||||
)
|
||||
|
||||
|
||||
def setup(tmp, order, *, fail_deal=False):
|
||||
path = write_config(tmp)
|
||||
store = ConfigStore(path, env={})
|
||||
db = Database(Path(tmp) / "app.db", backup_dir=Path(tmp) / "backup")
|
||||
db.initialize()
|
||||
repo = Repository(db, clock=lambda: NOW)
|
||||
add_video(repo, 1, 100, 1_792_000_000)
|
||||
add_video(repo, 2, 200, 1_791_000_000)
|
||||
add_candidate(repo, 9, up_mid=100, pubdate=1_793_000_000)
|
||||
client = FakeWriteClient(order, fail_deal=fail_deal)
|
||||
service = FavoriteActionService(
|
||||
store, repo, FakeProvider(client), clock=lambda: NOW
|
||||
)
|
||||
return db, repo, client, service
|
||||
|
||||
|
||||
def test_favorite_inserts_and_positions():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, repo, client, service = setup(tmp, [1, 2])
|
||||
try:
|
||||
result = service.favorite(9)
|
||||
assert result.ok is True
|
||||
assert result.position == 1
|
||||
assert result.already_in_folder is False
|
||||
assert client.dealt == [(9, FOLDER_ID)]
|
||||
assert client.sorts == ["1:2:9:2", "9:2:1:2"]
|
||||
assert client.order == [9, 1, 2]
|
||||
assert repo.get_candidate(9) is None
|
||||
video = repo.get_video(9)
|
||||
assert video["status"] == "active"
|
||||
assert video["folder_id"] == FOLDER_ID
|
||||
action = repo.get_fav_action("fav:9")
|
||||
assert action["state"] == "done"
|
||||
assert action["position"] == 1
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_favorite_already_in_folder_skips_writes():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, repo, client, service = setup(tmp, [1, 9, 2])
|
||||
try:
|
||||
result = service.favorite(9)
|
||||
assert result.ok is True
|
||||
assert result.already_in_folder is True
|
||||
assert result.position == 2
|
||||
assert client.dealt == []
|
||||
assert client.sorts == []
|
||||
assert repo.get_candidate(9) is None
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_favorite_failure_keeps_candidate_and_allows_retry():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, repo, client, service = setup(tmp, [1, 2], fail_deal=True)
|
||||
try:
|
||||
result = service.favorite(9)
|
||||
assert result.ok is False
|
||||
assert "收藏夹已满" in result.message
|
||||
assert repo.get_candidate(9) is not None
|
||||
action = repo.get_fav_action("fav:9")
|
||||
assert action["state"] == "failed"
|
||||
assert "收藏夹已满" in action["err"]
|
||||
|
||||
client.fail_deal = False
|
||||
retry = service.favorite(9)
|
||||
assert retry.ok is True
|
||||
assert retry.position == 1
|
||||
assert repo.get_candidate(9) is None
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_ignore_and_blacklist():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, repo, client, service = setup(tmp, [1, 2])
|
||||
try:
|
||||
add_candidate(repo, 11, up_mid=300)
|
||||
add_candidate(repo, 12, up_mid=300)
|
||||
ignored = service.ignore(11)
|
||||
assert ignored.ok is True
|
||||
assert repo.get_candidate(11)["decision"] == "rejected"
|
||||
|
||||
result = service.blacklist(12)
|
||||
assert result.ok is True
|
||||
assert repo.is_blacklisted(300)
|
||||
assert repo.get_candidate(12)["decision"] == "rejected"
|
||||
# 已有视频不受拉黑影响
|
||||
assert repo.get_video(1)["status"] == "active"
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def main():
|
||||
test_favorite_inserts_and_positions()
|
||||
test_favorite_already_in_folder_skips_writes()
|
||||
test_favorite_failure_keeps_candidate_and_allows_retry()
|
||||
test_ignore_and_blacklist()
|
||||
print("OK: 收藏、忽略、拉黑与失败重试测试全部通过")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,373 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""收藏夹同步集成测试(用真实接口形状的 transport Mock,不联网):
|
||||
uv run python tests/test_folder_sync.py
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.parse
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from fixtures import info_for # noqa: E402
|
||||
from reaction_board.bilibili.client import ( # noqa: E402
|
||||
BilibiliClient,
|
||||
HTTPResponse,
|
||||
Pacer,
|
||||
TransportError,
|
||||
)
|
||||
from reaction_board.config import ConfigStore # noqa: E402
|
||||
from reaction_board.database import Database # noqa: E402
|
||||
from reaction_board.repository import Repository # noqa: E402
|
||||
from reaction_board.services.folder_sync import FolderSyncService # noqa: E402
|
||||
|
||||
F1 = 4451053851
|
||||
F2 = 3700023351
|
||||
|
||||
|
||||
def http_json(payload):
|
||||
return HTTPResponse(
|
||||
200, {"content-type": "application/json"},
|
||||
json.dumps(payload, ensure_ascii=False).encode("utf-8"),
|
||||
)
|
||||
|
||||
|
||||
class FakeFavTransport:
|
||||
def __init__(self, folders, infos, *, fail_media=None, omit_ids_data=None):
|
||||
self.folders = {k: list(v) for k, v in folders.items()}
|
||||
self.infos = dict(infos)
|
||||
self.fail_media = fail_media
|
||||
self.omit_ids_data = omit_ids_data
|
||||
self.ids_calls = []
|
||||
self.info_calls = []
|
||||
self.relation_calls = []
|
||||
|
||||
def request(self, method, url, headers, data=None, timeout=30):
|
||||
query = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)
|
||||
if "/x/relation/stat" in url:
|
||||
mid = int(query["vmid"][0])
|
||||
self.relation_calls.append(mid)
|
||||
return http_json({
|
||||
"code": 0, "message": "0", "ttl": 1,
|
||||
"data": {"mid": mid, "following": 5, "follower": 1000 + mid},
|
||||
})
|
||||
if "/x/v3/fav/resource/ids" in url:
|
||||
media_id = int(query["media_id"][0])
|
||||
self.ids_calls.append(media_id)
|
||||
if self.fail_media == media_id:
|
||||
raise TransportError("ids 网络错误")
|
||||
if self.omit_ids_data == media_id:
|
||||
return http_json({"code": 0, "message": "OK", "ttl": 1})
|
||||
data_rows = [
|
||||
{"id": aid, "type": 2, "bv_id": f"BV{aid}", "bvid": f"BV{aid}"}
|
||||
for aid in self.folders.get(media_id, [])
|
||||
]
|
||||
return http_json({"code": 0, "message": "0", "ttl": 1, "data": data_rows})
|
||||
if "/x/v3/fav/resource/infos" in url:
|
||||
media_id = int(query["folder_id"][0])
|
||||
resources = query["resources"][0]
|
||||
aids = [int(part.split(":")[0]) for part in resources.split(",")]
|
||||
self.info_calls.append((media_id, aids))
|
||||
rows = [self.infos[aid] for aid in aids if aid in self.infos]
|
||||
return http_json({"code": 0, "message": "0", "ttl": 1, "data": rows})
|
||||
if "/x/v3/fav/folder/created/list-all" in url:
|
||||
return http_json({
|
||||
"code": 0, "message": "0", "ttl": 1,
|
||||
"data": {"count": 0, "list": []},
|
||||
})
|
||||
raise AssertionError(f"未预期的 URL: {url}")
|
||||
|
||||
|
||||
def write_config(tmp, folders):
|
||||
data = {
|
||||
"bilibili": {
|
||||
"read": {"mid": 28802351, "csrf": "csrf-secret", "cookie": "SESSDATA=secret; bili_jct=csrf-secret; buvid3=device"},
|
||||
"write": {"mid": 2, "csrf": "write-csrf", "cookie": "write-cookie"},
|
||||
},
|
||||
"storage": {
|
||||
"database_path": str(Path(tmp) / "app.db"),
|
||||
"backup_dir": str(Path(tmp) / "backup"),
|
||||
},
|
||||
"folders": folders,
|
||||
"up_blacklist_seed": [999],
|
||||
"schedule": {
|
||||
"discover_minutes": 60,
|
||||
"folder_sync_minutes": 60,
|
||||
"full_folder_refresh_hours": 6,
|
||||
"snapshot_at": "00:01",
|
||||
"candidate_ttl_days": 7,
|
||||
},
|
||||
}
|
||||
path = Path(tmp) / "config.json"
|
||||
path.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def make_service(tmp, transport, clock, *, capacity_warn=950):
|
||||
folders = [
|
||||
{"year": 2025, "media_id": F1, "title": "2025"},
|
||||
{"year": 2026, "media_id": F2, "title": "2026"},
|
||||
]
|
||||
path = write_config(tmp, folders)
|
||||
store = ConfigStore(path, env={}, require_auth=True)
|
||||
db = Database(Path(tmp) / "app.db", backup_dir=Path(tmp) / "backup")
|
||||
db.initialize()
|
||||
repo = Repository(db, clock=lambda: clock[0])
|
||||
client = BilibiliClient(
|
||||
cookie="SESSDATA=secret; bvid3=device",
|
||||
csrf="csrf",
|
||||
mid=28802351,
|
||||
transport=transport,
|
||||
pacer=Pacer(0, 0),
|
||||
retries=1,
|
||||
)
|
||||
service = FolderSyncService(
|
||||
store, repo, client, clock=lambda: clock[0], capacity_warn=capacity_warn
|
||||
)
|
||||
return db, repo, service
|
||||
|
||||
|
||||
def valid(aid, *, up_mid=100, title=None):
|
||||
return info_for(aid, title=title or f"视频{aid}", up_mid=up_mid, up_name="UP")
|
||||
|
||||
|
||||
def test_initial_import_and_incremental_skip():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
transport = FakeFavTransport(
|
||||
{F1: [1101, 1102, 1103, 1104], F2: []},
|
||||
{
|
||||
1101: valid(1101),
|
||||
1102: valid(1102, up_mid=999), # 黑名单 UP 也必须正常入库
|
||||
1103: valid(1103, title="已失效", up_mid=100),
|
||||
},
|
||||
)
|
||||
# 1103 标记为 attr=9;1104 静默缺失
|
||||
transport.infos[1103]["attr"] = 9
|
||||
clock = [1_800_000_000]
|
||||
db, repo, service = make_service(tmp, transport, clock)
|
||||
try:
|
||||
repo.upsert_candidate(
|
||||
aid=1101, bvid="BV1101", title="咻咻满 reaction",
|
||||
up_mid=100, up_name="UP", pubdate=1_799_000_000,
|
||||
cover=None, score=3, channel="search:test#p1",
|
||||
now=1_799_999_000,
|
||||
)
|
||||
summary = service.run()
|
||||
assert summary.ok
|
||||
assert summary.added == 4
|
||||
assert summary.missing == 1
|
||||
assert summary.refreshed == 3
|
||||
# 人工加入收藏夹后,同 aid 候选自动移除
|
||||
assert repo.get_candidate(1101) is None
|
||||
assert repo.seed_blacklist([999], now=0) == 0 # 已由 service 写入
|
||||
|
||||
assert repo.get_video(1101)["status"] == "active"
|
||||
assert repo.get_video(1102)["status"] == "active" # 黑名单不影响收藏夹导入
|
||||
assert repo.get_video(1103)["status"] == "removed"
|
||||
assert repo.get_video(1104)["status"] == "removed"
|
||||
assert repo.get_video(1104)["bvid"] == "BV1104"
|
||||
assert repo.folder_active_aids(F1) == {1101, 1102, 1103, 1104}
|
||||
assert repo.is_blacklisted(999)
|
||||
# 新入库视频记录入库时粉丝数;失效视频不再采集
|
||||
assert summary.followers_updated == 2
|
||||
assert summary.followers_failed == 0
|
||||
assert repo.get_video(1101)["up_follower"] == 1100
|
||||
assert repo.get_video(1101)["up_follower_backfilled"] == 0
|
||||
assert repo.get_video(1102)["up_follower"] == 1999
|
||||
assert sorted(transport.relation_calls) == [100, 999]
|
||||
|
||||
folder = repo.get_folder(F1)
|
||||
assert folder.media_count == 4
|
||||
assert folder.last_full_at == 1_800_000_000
|
||||
|
||||
# 6 小时内再次运行:没有新增,不请求 infos
|
||||
clock[0] += 60
|
||||
info_before = len(transport.info_calls)
|
||||
relation_before = len(transport.relation_calls)
|
||||
summary2 = service.run()
|
||||
assert summary2.added == 0
|
||||
assert summary2.refreshed == 0
|
||||
assert len(transport.info_calls) == info_before
|
||||
assert len(transport.relation_calls) == relation_before
|
||||
assert summary2.folders[0].full_refresh is False
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_diff_add_and_remove():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
transport = FakeFavTransport(
|
||||
{F1: [1101, 1102], F2: []},
|
||||
{1101: valid(1101), 1102: valid(1102)},
|
||||
)
|
||||
clock = [1_800_000_000]
|
||||
db, repo, service = make_service(tmp, transport, clock)
|
||||
try:
|
||||
service.run()
|
||||
assert repo.get_video(1101)["status"] == "active"
|
||||
assert repo.get_video(1102)["status"] == "active"
|
||||
|
||||
transport.folders[F1] = [1102, 1103]
|
||||
transport.infos[1103] = valid(1103)
|
||||
clock[0] += 3600
|
||||
summary = service.run()
|
||||
assert summary.added == 1
|
||||
assert summary.removed == 1
|
||||
assert summary.refreshed == 1
|
||||
assert repo.get_video(1101)["status"] == "unfaved"
|
||||
assert repo.get_video(1102)["status"] == "active"
|
||||
assert repo.get_video(1103)["status"] == "active"
|
||||
assert repo.folder_active_aids(F1) == {1102, 1103}
|
||||
assert repo.get_folder(F1).media_count == 2
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_full_refresh_marks_invalid_and_missing():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
transport = FakeFavTransport(
|
||||
{F1: [1101, 1102], F2: []},
|
||||
{1101: valid(1101), 1102: valid(1102)},
|
||||
)
|
||||
clock = [1_800_000_000]
|
||||
db, repo, service = make_service(tmp, transport, clock)
|
||||
try:
|
||||
service.run()
|
||||
assert repo.get_video(1101)["status"] == "active"
|
||||
assert repo.get_video(1102)["status"] == "active"
|
||||
|
||||
# 6 小时后:1101 失效,1102 静默缺失
|
||||
clock[0] += 6 * 3600 + 1
|
||||
transport.infos[1101]["attr"] = 9
|
||||
del transport.infos[1102]
|
||||
summary = service.run()
|
||||
assert summary.folders[0].full_refresh is True
|
||||
assert summary.missing == 1
|
||||
assert repo.get_video(1101)["status"] == "removed"
|
||||
assert repo.get_video(1102)["status"] == "removed"
|
||||
assert repo.get_folder(F1).last_full_at == clock[0]
|
||||
# 全量刷新请求了夹内全部 aid
|
||||
assert set(transport.info_calls[-1][1]) == {1101, 1102}
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_capacity_warning_does_not_move_folder():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
transport = FakeFavTransport(
|
||||
{F1: [1, 2, 3], F2: []},
|
||||
{i: valid(i) for i in (1, 2, 3)},
|
||||
)
|
||||
clock = [1_800_000_000]
|
||||
db, repo, service = make_service(tmp, transport, clock, capacity_warn=3)
|
||||
try:
|
||||
summary = service.run()
|
||||
assert summary.folders[0].warning
|
||||
assert "预警线 3" in summary.folders[0].warning
|
||||
assert "不会自动换夹" in summary.folders[0].warning
|
||||
# 视频仍在原夹,不被移动
|
||||
assert all(repo.get_video(i)["folder_id"] == F1 for i in (1, 2, 3))
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_folder_error_does_not_block_other_folders():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
transport = FakeFavTransport(
|
||||
{F1: [1101], F2: [2201]},
|
||||
{1101: valid(1101), 2201: valid(2201)},
|
||||
fail_media=F1,
|
||||
)
|
||||
clock = [1_800_000_000]
|
||||
db, repo, service = make_service(tmp, transport, clock)
|
||||
try:
|
||||
summary = service.run()
|
||||
assert summary.ok is False
|
||||
assert len(summary.errors) == 1 and str(F1) in summary.errors[0]
|
||||
assert summary.folders[0].error
|
||||
assert summary.folders[1].error is None
|
||||
assert repo.get_video(2201)["status"] == "active"
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_blacklist_seed_only_once():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
transport = FakeFavTransport({F1: [1101], F2: []}, {1101: valid(1101)})
|
||||
clock = [1_800_000_000]
|
||||
db, repo, service = make_service(tmp, transport, clock)
|
||||
try:
|
||||
first = service.run()
|
||||
assert first.blacklist_seeded == 1
|
||||
clock[0] += 60
|
||||
second = service.run()
|
||||
assert second.blacklist_seeded == 0
|
||||
assert len(repo.blacklist()) == 1
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_empty_remote_requires_explicit_opt_in():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
transport = FakeFavTransport(
|
||||
{F1: [1101, 1102], F2: []},
|
||||
{1101: valid(1101), 1102: valid(1102)},
|
||||
)
|
||||
clock = [1_800_000_000]
|
||||
db, repo, service = make_service(tmp, transport, clock)
|
||||
try:
|
||||
service.run()
|
||||
transport.folders[F1] = []
|
||||
clock[0] += 3600
|
||||
summary = service.run()
|
||||
assert summary.ok is False
|
||||
assert "疑似接口异常" in summary.folders[0].error
|
||||
assert repo.get_video(1101)["status"] == "active"
|
||||
assert repo.folder_active_aids(F1) == {1101, 1102}
|
||||
|
||||
service.allow_empty_folders = True
|
||||
summary = service.run()
|
||||
assert summary.ok is True
|
||||
assert repo.get_video(1101)["status"] == "unfaved"
|
||||
assert repo.folder_active_aids(F1) == set()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_missing_ids_data_aborts_folder():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
transport = FakeFavTransport(
|
||||
{F1: [1101], F2: []},
|
||||
{1101: valid(1101)},
|
||||
omit_ids_data=F1,
|
||||
)
|
||||
clock = [1_800_000_000]
|
||||
db, repo, service = make_service(tmp, transport, clock)
|
||||
try:
|
||||
summary = service.run()
|
||||
assert summary.ok is False
|
||||
assert "data" in summary.folders[0].error
|
||||
assert repo.get_video(1101) is None
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def main():
|
||||
test_initial_import_and_incremental_skip()
|
||||
test_diff_add_and_remove()
|
||||
test_full_refresh_marks_invalid_and_missing()
|
||||
test_capacity_warning_does_not_move_folder()
|
||||
test_folder_error_does_not_block_other_folders()
|
||||
test_blacklist_seed_only_once()
|
||||
test_empty_remote_requires_explicit_opt_in()
|
||||
test_missing_ids_data_aborts_folder()
|
||||
print("OK: 收藏夹初始导入、差集同步、失效识别与容量预警测试全部通过")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -37,8 +37,8 @@ def test_fresh_and_idempotent():
|
||||
conn = sqlite3.connect(Path(tmp) / "app.db")
|
||||
try:
|
||||
applied = run_migrations(conn)
|
||||
assert applied == [1, 2, 3, 4]
|
||||
assert current_version(conn) == 4
|
||||
assert applied == [1, 2, 3, 4, 5]
|
||||
assert current_version(conn) == 5
|
||||
assert EXPECTED_TABLES <= table_names(conn)
|
||||
assert "schema_version" in table_names(conn)
|
||||
columns = {
|
||||
@@ -66,7 +66,7 @@ def test_fresh_and_idempotent():
|
||||
# 再跑一次不应重复应用
|
||||
assert run_migrations(conn) == []
|
||||
row = conn.execute("SELECT COUNT(*) FROM schema_version").fetchone()
|
||||
assert row[0] == 4
|
||||
assert row[0] == 5
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
@@ -81,15 +81,15 @@ def test_backup_before_upgrade():
|
||||
conn.execute("INSERT INTO kv(k, v) VALUES ('hello', 'world')")
|
||||
conn.commit()
|
||||
|
||||
v5 = Migration(5, "add probe", ("CREATE TABLE probe (id INTEGER PRIMARY KEY)",))
|
||||
v6 = Migration(6, "add probe", ("CREATE TABLE probe (id INTEGER PRIMARY KEY)",))
|
||||
applied = run_migrations(
|
||||
conn,
|
||||
backup_dir=backup_dir,
|
||||
now=1_800_000_000,
|
||||
migrations=MIGRATIONS + (v5,),
|
||||
migrations=MIGRATIONS + (v6,),
|
||||
)
|
||||
assert applied == [5]
|
||||
backups = list(backup_dir.glob("app-pre-v4-*.db"))
|
||||
assert applied == [6]
|
||||
backups = list(backup_dir.glob("app-pre-v5-*.db"))
|
||||
assert len(backups) == 1
|
||||
check = sqlite3.connect(backups[0])
|
||||
try:
|
||||
@@ -159,12 +159,35 @@ def test_validate_migration_order():
|
||||
conn.close()
|
||||
|
||||
|
||||
def test_v5_normalizes_unfaved():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
conn = sqlite3.connect(Path(tmp) / "app.db")
|
||||
try:
|
||||
run_migrations(conn, migrations=MIGRATIONS[:4])
|
||||
conn.execute(
|
||||
"INSERT INTO video(aid, title, pubdate, status, first_seen) "
|
||||
"VALUES (1, 't', 1, 'unfaved', 1)"
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO video(aid, title, pubdate, status, first_seen) "
|
||||
"VALUES (2, 't', 1, 'dropped', 1)"
|
||||
)
|
||||
conn.commit()
|
||||
applied = run_migrations(conn)
|
||||
assert applied == [5]
|
||||
rows = dict(conn.execute("SELECT aid, status FROM video").fetchall())
|
||||
assert rows == {1: "active", 2: "dropped"}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def main():
|
||||
test_fresh_and_idempotent()
|
||||
test_backup_before_upgrade()
|
||||
test_failed_migration_rolls_back()
|
||||
test_prune_backups()
|
||||
test_validate_migration_order()
|
||||
test_v5_normalizes_unfaved()
|
||||
print("OK: SQLite 迁移、备份与回滚测试全部通过")
|
||||
|
||||
|
||||
|
||||
+491
-492
@@ -1,492 +1,491 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""只读查询层测试(离线): uv run python tests/test_web_queries.py"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
|
||||
from reaction_board.config import ConfigStore # noqa: E402
|
||||
from reaction_board.database import Database # noqa: E402
|
||||
from reaction_board.repository import Repository # noqa: E402
|
||||
from reaction_board.timeutil import day_bounds # noqa: E402
|
||||
from reaction_board.web.cache import DASHBOARD_CACHE # noqa: E402
|
||||
from reaction_board.web.queries import DashboardQueries # noqa: E402
|
||||
from tests.web_fixtures import DATES, build_db, write_config # noqa: E402
|
||||
|
||||
FIXED_NOW = 1_793_459_000 # 2026-10-31 前后
|
||||
|
||||
|
||||
def setup(tmp: str):
|
||||
build_db(tmp)
|
||||
config = write_config(tmp)
|
||||
db = Database(Path(tmp) / "app.db")
|
||||
db.initialize()
|
||||
store = ConfigStore(config)
|
||||
queries = DashboardQueries(db, store, clock=lambda: FIXED_NOW)
|
||||
return db, queries
|
||||
|
||||
|
||||
def test_overview():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
overview = q.overview()
|
||||
assert overview["data_date"] == DATES[-1]
|
||||
assert overview["snapshot_days"] == 3
|
||||
assert overview["is_first_day"] is False
|
||||
assert overview["initial_import_count"] == 2
|
||||
assert overview["counts"]["active"] == 2
|
||||
assert overview["counts"]["unfaved"] == 1
|
||||
assert overview["counts"]["removed"] == 1
|
||||
assert overview["counts"]["active_ups"] == 2
|
||||
assert overview["counts"]["candidates_pending"] == 1
|
||||
assert overview["totals"]["view"] == 1200 + 5200 + 120
|
||||
assert overview["interactions"] > 0
|
||||
assert overview["view_delta"] == (100 + 100 + 0) # 101/102 的日增量
|
||||
assert overview["snapshot_health"]["total"] == 3
|
||||
assert overview["folders"][0]["media_count"] == 3
|
||||
assert overview["folders"][0]["ratio"] < 1
|
||||
assert overview["fans"]["follower"] == 1020
|
||||
assert overview["fans"]["delta_1d"] == 10
|
||||
assert overview["preview"] is False
|
||||
assert overview["years"] == [2026]
|
||||
assert "snapshot" in overview["tasks"]
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_video_listing_filters_and_sorting():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
heat = q.list_videos(sort="heat")
|
||||
aids = [item["aid"] for item in heat["items"]]
|
||||
assert 104 not in aids, "removed 视频不应进入榜单"
|
||||
# 综合热度榜应用最小播放门槛 2000:101(1200)与 103(120)被排除
|
||||
assert aids == [102], aids
|
||||
assert heat["items"][0]["heat_percentile"] == 100.0
|
||||
|
||||
views = q.list_videos(sort="view")
|
||||
assert [item["aid"] for item in views["items"]] == [102, 101, 103]
|
||||
|
||||
interactions = q.list_videos(sort="interaction")
|
||||
assert interactions["items"][0]["aid"] == 101
|
||||
|
||||
added = q.list_videos(sort="added", within_days=1)
|
||||
assert [item["aid"] for item in added["items"]] == [103]
|
||||
|
||||
published = q.list_videos(sort="published", within_days=2)
|
||||
assert {item["aid"] for item in published["items"]} == {101, 103}
|
||||
|
||||
searched = q.list_videos(sort="view", q="UP B")
|
||||
assert [item["aid"] for item in searched["items"]] == [103]
|
||||
searched = q.list_videos(sort="view", q="视频 102")
|
||||
assert [item["aid"] for item in searched["items"]] == [102]
|
||||
|
||||
folder = q.list_videos(sort="view", folder_id=3700023351)
|
||||
assert folder["total"] == 3
|
||||
folder = q.list_videos(sort="view", folder_id=999)
|
||||
assert folder["total"] == 0
|
||||
|
||||
page = q.list_videos(sort="view", page=2, page_size=1)
|
||||
assert page["total"] == 3
|
||||
assert page["pages"] == 3
|
||||
assert [item["aid"] for item in page["items"]] == [101]
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_growth_and_cold_start():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
growth = q.list_videos(sort="growth", growth_days=2)
|
||||
assert growth["available"] is True
|
||||
assert {item["aid"] for item in growth["items"]} == {101, 102}
|
||||
first = next(item for item in growth["items"] if item["aid"] == 101)
|
||||
assert first["growth"]["available"] is True
|
||||
assert first["growth"]["delta"] == 200
|
||||
assert first["growth"]["gap_days"] == 2
|
||||
|
||||
rate = q.list_videos(sort="growth_rate", growth_days=2)
|
||||
assert {item["aid"] for item in rate["items"]} == {101, 102}
|
||||
|
||||
# 只有一个快照日时增长不可用,不能返回假 0
|
||||
for day in DATES[:-1]:
|
||||
db.write(lambda conn, day=day: conn.execute(
|
||||
"DELETE FROM snapshot WHERE stat_date = ?", (day,)
|
||||
))
|
||||
DASHBOARD_CACHE.clear()
|
||||
cold = q.list_videos(sort="growth", growth_days=2)
|
||||
assert cold["available"] is False
|
||||
assert cold["items"] == []
|
||||
assert "两天" in cold["reason"]
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_video_detail_and_trend():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
detail = q.video_detail(101)
|
||||
assert detail["aid"] == 101
|
||||
assert detail["metrics"]["view"] == 1200
|
||||
assert detail["growth"]["delta"] == 100
|
||||
assert detail["snapshot_count"] == 3
|
||||
assert detail["folder_title"] == "2026"
|
||||
assert detail["url"].endswith("BV101")
|
||||
assert q.video_detail(999999) is None
|
||||
|
||||
trend = q.video_trend(101, days=3)
|
||||
assert trend["dates"] == list(DATES)
|
||||
assert trend["series"]["view"] == [1000, 1100, 1200]
|
||||
assert trend["available"] is True
|
||||
assert len(trend["points"]) == 3
|
||||
|
||||
# 请求区间早于首次快照时,从首次快照开始,不制造空白历史
|
||||
wide = q.video_trend(101, days=30)
|
||||
assert wide["dates"] == list(DATES)
|
||||
|
||||
# 删除中间一天,折线在缺失日期应为 None,而不是插值
|
||||
db.write(lambda conn: conn.execute(
|
||||
"DELETE FROM snapshot WHERE aid=101 AND stat_date=?",
|
||||
("2026-10-30",),
|
||||
))
|
||||
trend = q.video_trend(101, days=3)
|
||||
assert trend["series"]["view"] == [1000, None, 1200]
|
||||
|
||||
# 失败快照也视为缺失
|
||||
db.write(lambda conn: conn.execute(
|
||||
"UPDATE snapshot SET ok=0, view=NULL WHERE aid=101 AND stat_date=?",
|
||||
(DATES[-1],),
|
||||
))
|
||||
trend = q.video_trend(101, days=3)
|
||||
assert trend["series"]["view"][-1] is None
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_up_queries():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
ups = q.list_ups()
|
||||
assert ups["sort"] == "avg_views"
|
||||
assert ups["total"] == 2
|
||||
assert ups["items"][0]["up_mid"] == 1
|
||||
assert ups["items"][0]["video_count"] == 2
|
||||
assert ups["items"][0]["total_views"] == 6400
|
||||
assert ups["items"][0]["avg_views"] == 3200.0
|
||||
|
||||
one = q.list_ups(min_videos=2)
|
||||
assert one["total"] == 1
|
||||
|
||||
detail = q.up_detail(1)
|
||||
assert detail["video_count"] == 2
|
||||
assert detail["total_views"] == 6400
|
||||
assert detail["blacklisted"] is False
|
||||
assert detail["series"]["dates"] == list(DATES)
|
||||
assert detail["series"]["views"] == [6000, 6200, 6400]
|
||||
assert detail["space_url"].endswith("/1")
|
||||
|
||||
blacklisted = q.up_detail(2)
|
||||
assert blacklisted["blacklisted"] is True
|
||||
assert blacklisted["video_count"] == 1
|
||||
assert q.up_detail(999999) is None
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_query_cache_invalidation():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
DASHBOARD_CACHE.clear()
|
||||
first = q.overview()
|
||||
db.write(lambda conn: conn.execute(
|
||||
"UPDATE snapshot SET \"view\" = 999999 WHERE aid=101 AND stat_date=?",
|
||||
(DATES[-1],),
|
||||
))
|
||||
cached = q.overview()
|
||||
assert cached["totals"]["view"] == first["totals"]["view"]
|
||||
|
||||
repo = Repository(db)
|
||||
repo.bump_cache_version("videos")
|
||||
refreshed = q.overview()
|
||||
assert refreshed["totals"]["view"] > first["totals"]["view"]
|
||||
|
||||
fans_first = q.fans(days=3)
|
||||
db.write(lambda conn: conn.execute(
|
||||
"UPDATE up_stat SET follower=999999 WHERE mid=37754047 AND stat_date=?",
|
||||
(DATES[-1],),
|
||||
))
|
||||
fans_cached = q.fans(days=3)
|
||||
assert fans_cached["follower"] == fans_first["follower"]
|
||||
|
||||
repo.bump_cache_version("fans")
|
||||
fans_refreshed = q.fans(days=3)
|
||||
assert fans_refreshed["follower"] == 999999
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_fans_custom_range_modes():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
daily = q.fans(start="2026-10-29", end="2026-10-31")
|
||||
assert daily["mode"] == "daily"
|
||||
assert daily["range_start"] == "2026-10-29"
|
||||
assert daily["range_end"] == "2026-10-31"
|
||||
assert daily["dates"] == list(DATES)
|
||||
assert daily["series"] == [1000, 1010, 1020]
|
||||
|
||||
# 超过一年触发按月峰值模式
|
||||
db.write(lambda conn: conn.execute(
|
||||
"INSERT OR REPLACE INTO up_stat"
|
||||
"(stat_date, mid, follower, following, captured_at, ok) "
|
||||
"VALUES ('2025-01-01', 37754047, 500, NULL, 1, 1)"
|
||||
))
|
||||
DASHBOARD_CACHE.clear()
|
||||
monthly = q.fans(start="2025-01-01", end="2026-10-31")
|
||||
assert monthly["mode"] == "monthly"
|
||||
assert monthly["span_days"] == 669
|
||||
assert monthly["dates"][0] == "2025-01-01"
|
||||
assert monthly["series"][0] == 500
|
||||
assert monthly["dates"][-1] == "2026-10-31"
|
||||
assert monthly["series"][-1] == 1020
|
||||
|
||||
# 同月多条时取峰值日期,并优先较晚日期
|
||||
db.write(lambda conn: conn.execute(
|
||||
"INSERT OR REPLACE INTO up_stat"
|
||||
"(stat_date, mid, follower, following, captured_at, ok) "
|
||||
"VALUES ('2026-10-15', 37754047, 5000, NULL, 1, 1), "
|
||||
"('2026-10-16', 37754047, 5000, NULL, 1, 1)"
|
||||
))
|
||||
DASHBOARD_CACHE.clear()
|
||||
monthly = q.fans(start="2025-01-01", end="2026-10-31")
|
||||
assert monthly["dates"][-1] == "2026-10-16"
|
||||
assert monthly["series"][-1] == 5000
|
||||
|
||||
try:
|
||||
q.fans(start="2026-11-01", end="2026-10-01")
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("start 晚于 end 应报错")
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_fans_candidates_system_and_export():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
fans = q.fans(days=3)
|
||||
assert fans["mid"] == 37754047
|
||||
assert fans["name"] == "咻咻满"
|
||||
assert fans["dates"] == list(DATES)
|
||||
assert fans["series"] == [1000, 1010, 1020]
|
||||
assert fans["delta_1d"] == 10
|
||||
assert fans["delta_7d"] is None
|
||||
assert fans["delta_cum"] == 20
|
||||
assert fans["options"][0]["mid"] == 37754047
|
||||
wide = q.fans(days=30)
|
||||
assert wide["dates"] == list(DATES)
|
||||
|
||||
# “最近记录”只返回最近 14 天,早于窗口的记录不进入表格
|
||||
db.write(lambda conn: conn.execute(
|
||||
"INSERT OR REPLACE INTO up_stat"
|
||||
"(stat_date, mid, follower, following, captured_at, ok) "
|
||||
"VALUES (?, ?, ?, NULL, 1, 1)",
|
||||
("2026-10-01", 37754047, 900),
|
||||
))
|
||||
DASHBOARD_CACHE.clear()
|
||||
recent = q.fans(days=90)
|
||||
assert recent["recent_days"] == 14
|
||||
assert [point["stat_date"] for point in recent["recent_points"]] == list(DATES)
|
||||
deltas = {point["stat_date"]: point["delta"] for point in recent["recent_points"]}
|
||||
assert deltas["2026-10-29"] == 100 # 对比 2026-10-01 的 900
|
||||
assert deltas["2026-10-30"] == 10
|
||||
assert deltas["2026-10-31"] == 10
|
||||
one_day = q.fans(days=90, recent_days=1)
|
||||
assert [point["stat_date"] for point in one_day["recent_points"]] == [DATES[-1]]
|
||||
|
||||
# 缺失前一天时不能把跨多天的变化标成“日增”
|
||||
db.write(lambda conn: conn.execute(
|
||||
"DELETE FROM up_stat WHERE mid=37754047 AND stat_date=?",
|
||||
("2026-10-30",),
|
||||
))
|
||||
DASHBOARD_CACHE.clear()
|
||||
gapped = q.fans(days=3)
|
||||
assert gapped["delta_1d"] is None
|
||||
assert gapped["delta_7d"] is None
|
||||
|
||||
candidates = q.candidates()
|
||||
assert candidates["total"] == 2
|
||||
assert candidates["pending"] == 1
|
||||
assert candidates["items"][0]["aid"] == 201
|
||||
assert 1 <= candidates["items"][0]["days_left"] <= 7
|
||||
assert candidates["items"][1]["decision"] == "rejected"
|
||||
|
||||
system = q.system()
|
||||
assert system["data_date"] == DATES[-1]
|
||||
assert system["snapshot_days"] == 3
|
||||
assert system["blacklist"][0]["video_count"] == 1
|
||||
assert system["tasks"]["snapshot"]["ok"] is True
|
||||
assert system["errors"] == []
|
||||
assert system["preview"] is False
|
||||
assert system["next_runs"]["snapshot"] > 0
|
||||
assert system["next_runs"]["folder_sync"] > FIXED_NOW
|
||||
assert system["next_runs"]["discover"] > FIXED_NOW
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_duration_efficiency_queries():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
db.write(lambda conn: conn.executemany(
|
||||
"UPDATE video SET duration = ?, pubdate = ? WHERE aid = ?",
|
||||
[
|
||||
(9000, 1_756_684_800, 101), # 2025-09-01 前后,2.5 小时
|
||||
(7200, 1_756_771_200, 102), # 2 小时
|
||||
(300, 1_756_857_600, 103), # 5 分钟,应被排除
|
||||
],
|
||||
))
|
||||
DASHBOARD_CACHE.clear()
|
||||
|
||||
efficiency = q.list_videos(sort="efficiency")
|
||||
assert [item["aid"] for item in efficiency["items"]] == [102]
|
||||
first = efficiency["items"][0]
|
||||
assert first["duration"] == 7200
|
||||
assert first["content_hours"] == 2.0
|
||||
assert first["efficiency"] == 2600.0 # 原始播放/小时,详情页口径
|
||||
assert abs(first["efficiency_score"] - 2207.5) < 0.1
|
||||
assert efficiency["duration_filter"] == {
|
||||
"min_duration_seconds": 600, "maturity_days": 2,
|
||||
"min_view": 2000, "shrink_minutes": 60,
|
||||
}
|
||||
|
||||
# 播放不足 2000 的视频不进入效率榜(101 只有 1200)
|
||||
assert all(item["aid"] != 101 for item in efficiency["items"])
|
||||
|
||||
interaction = q.list_videos(sort="interaction_efficiency")
|
||||
assert [item["aid"] for item in interaction["items"]] == [102]
|
||||
assert abs(interaction["items"][0]["interaction_efficiency_score"] - 159.36) < 0.1
|
||||
|
||||
# 综合热度榜也应用最小播放门槛
|
||||
heat = q.list_videos(sort="heat")
|
||||
assert [item["aid"] for item in heat["items"]] == [102]
|
||||
|
||||
# 时长缺失不计入时长效率榜
|
||||
ups = q.list_ups(sort="efficiency")
|
||||
assert ups["sort"] == "efficiency"
|
||||
up_a = next(item for item in ups["items"] if item["up_mid"] == 1)
|
||||
assert up_a["total_duration"] == int(9000 + 7200)
|
||||
assert up_a["content_hours"] == 4.5
|
||||
assert up_a["views_per_hour"] == round(6400 / 4.5, 1)
|
||||
assert up_a["efficiency"] is not None
|
||||
assert up_a["interaction_efficiency"] is not None
|
||||
|
||||
by_duration = q.list_ups(sort="duration")
|
||||
assert [item["up_mid"] for item in by_duration["items"]][0] == 1
|
||||
|
||||
db.write(lambda conn: conn.execute(
|
||||
"UPDATE video SET duration = NULL WHERE aid = 101"
|
||||
))
|
||||
DASHBOARD_CACHE.clear()
|
||||
missing = q.list_videos(sort="efficiency")
|
||||
assert [item["aid"] for item in missing["items"]] == [102]
|
||||
|
||||
# 发布未满 2 天的视频不进入效率榜
|
||||
db.write(lambda conn: conn.execute(
|
||||
"UPDATE video SET duration = 7200, pubdate = ? WHERE aid = 102",
|
||||
(int(day_bounds("2026-10-30")[0]),),
|
||||
))
|
||||
DASHBOARD_CACHE.clear()
|
||||
fresh = q.list_videos(sort="efficiency")
|
||||
assert fresh["items"] == []
|
||||
assert fresh["available"] is False
|
||||
assert "发布满 2 天" in fresh["reason"]
|
||||
assert "播放 ≥ 2000" in fresh["reason"]
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_year_filter_and_published_sort():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
by_year = q.list_videos(sort="view", year=2026)
|
||||
assert [item["aid"] for item in by_year["items"]] == [102, 101, 103]
|
||||
assert by_year["year"] == 2026
|
||||
|
||||
none = q.list_videos(sort="view", year=2025)
|
||||
assert none["items"] == []
|
||||
assert none["total"] == 0
|
||||
|
||||
published = q.list_videos(sort="published")
|
||||
assert [item["aid"] for item in published["items"]] == [103, 101, 102]
|
||||
|
||||
added = q.list_videos(sort="added")
|
||||
assert added["total"] == 3
|
||||
|
||||
ups = q.list_ups(sort="efficiency", year=2026)
|
||||
assert ups["year"] == 2026 and ups["total"] == 2
|
||||
ups_none = q.list_ups(sort="views", year=2025)
|
||||
assert ups_none["total"] == 0
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_about_payload():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
about = q.about()
|
||||
assert about["data_date"] == DATES[-1]
|
||||
assert about["snapshot_days"] == 3
|
||||
assert about["snapshot_first_date"] == DATES[0]
|
||||
assert about["fans_start_date"] == DATES[0]
|
||||
assert about["schema_version"] == 4
|
||||
assert about["analytics"] == {
|
||||
"min_duration_seconds": 600,
|
||||
"maturity_days": 2,
|
||||
"min_view_for_ranking": 2000,
|
||||
"video_shrink_minutes": 60,
|
||||
"shrink_minutes": None,
|
||||
}
|
||||
assert about["heat_weights"]["view"] == 0.30
|
||||
assert about["followers"]["videos_total"] == 3
|
||||
assert about["followers"]["videos_covered"] == 0
|
||||
assert about["followers"]["videos_missing"] == 3
|
||||
assert about["folders"][0]["media_id"] == 3700023351
|
||||
assert about["preview"] is False
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def main_test():
|
||||
test_overview()
|
||||
test_video_listing_filters_and_sorting()
|
||||
test_growth_and_cold_start()
|
||||
test_video_detail_and_trend()
|
||||
test_up_queries()
|
||||
test_query_cache_invalidation()
|
||||
test_duration_efficiency_queries()
|
||||
test_year_filter_and_published_sort()
|
||||
test_about_payload()
|
||||
test_fans_custom_range_modes()
|
||||
test_fans_candidates_system_and_export()
|
||||
print("OK: Web 查询层总览/榜单/详情/UP/时长效率/粉丝/候选/系统测试全部通过")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main_test()
|
||||
# -*- coding: utf-8 -*-
|
||||
"""只读查询层测试(离线): uv run python tests/test_web_queries.py"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
|
||||
from reaction_board.config import ConfigStore # noqa: E402
|
||||
from reaction_board.database import Database # noqa: E402
|
||||
from reaction_board.repository import Repository # noqa: E402
|
||||
from reaction_board.timeutil import day_bounds # noqa: E402
|
||||
from reaction_board.web.cache import DASHBOARD_CACHE # noqa: E402
|
||||
from reaction_board.web.queries import DashboardQueries # noqa: E402
|
||||
from tests.web_fixtures import DATES, build_db, write_config # noqa: E402
|
||||
|
||||
FIXED_NOW = 1_793_459_000 # 2026-10-31 前后
|
||||
|
||||
|
||||
def setup(tmp: str):
|
||||
build_db(tmp)
|
||||
config = write_config(tmp)
|
||||
db = Database(Path(tmp) / "app.db")
|
||||
db.initialize()
|
||||
store = ConfigStore(config)
|
||||
queries = DashboardQueries(db, store, clock=lambda: FIXED_NOW)
|
||||
return db, queries
|
||||
|
||||
|
||||
def test_overview():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
overview = q.overview()
|
||||
assert overview["data_date"] == DATES[-1]
|
||||
assert overview["snapshot_days"] == 3
|
||||
assert overview["is_first_day"] is False
|
||||
assert overview["initial_import_count"] == 2
|
||||
assert overview["counts"]["active"] == 2
|
||||
assert overview["counts"]["unfaved"] == 1
|
||||
assert overview["counts"]["removed"] == 1
|
||||
assert overview["counts"]["active_ups"] == 2
|
||||
assert overview["counts"]["candidates_pending"] == 1
|
||||
assert overview["totals"]["view"] == 1200 + 5200 + 120
|
||||
assert overview["interactions"] > 0
|
||||
assert overview["view_delta"] == (100 + 100 + 0) # 101/102 的日增量
|
||||
assert overview["snapshot_health"]["total"] == 3
|
||||
assert overview["folders"][0]["media_count"] == 3
|
||||
assert overview["folders"][0]["ratio"] < 1
|
||||
assert overview["fans"]["follower"] == 1020
|
||||
assert overview["fans"]["delta_1d"] == 10
|
||||
assert overview["preview"] is False
|
||||
assert overview["years"] == [2026]
|
||||
assert "snapshot" in overview["tasks"]
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_video_listing_filters_and_sorting():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
heat = q.list_videos(sort="heat")
|
||||
aids = [item["aid"] for item in heat["items"]]
|
||||
assert 104 not in aids, "removed 视频不应进入榜单"
|
||||
# 综合热度榜应用最小播放门槛 2000:101(1200)与 103(120)被排除
|
||||
assert aids == [102], aids
|
||||
assert heat["items"][0]["heat_percentile"] == 100.0
|
||||
|
||||
views = q.list_videos(sort="view")
|
||||
assert [item["aid"] for item in views["items"]] == [102, 101, 103]
|
||||
|
||||
interactions = q.list_videos(sort="interaction")
|
||||
assert interactions["items"][0]["aid"] == 101
|
||||
|
||||
added = q.list_videos(sort="added", within_days=1)
|
||||
assert [item["aid"] for item in added["items"]] == [103]
|
||||
|
||||
published = q.list_videos(sort="published", within_days=2)
|
||||
assert {item["aid"] for item in published["items"]} == {101, 103}
|
||||
|
||||
searched = q.list_videos(sort="view", q="UP B")
|
||||
assert [item["aid"] for item in searched["items"]] == [103]
|
||||
searched = q.list_videos(sort="view", q="视频 102")
|
||||
assert [item["aid"] for item in searched["items"]] == [102]
|
||||
|
||||
folder = q.list_videos(sort="view", folder_id=3700023351)
|
||||
assert folder["total"] == 3
|
||||
folder = q.list_videos(sort="view", folder_id=999)
|
||||
assert folder["total"] == 0
|
||||
|
||||
page = q.list_videos(sort="view", page=2, page_size=1)
|
||||
assert page["total"] == 3
|
||||
assert page["pages"] == 3
|
||||
assert [item["aid"] for item in page["items"]] == [101]
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_growth_and_cold_start():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
growth = q.list_videos(sort="growth", growth_days=2)
|
||||
assert growth["available"] is True
|
||||
assert {item["aid"] for item in growth["items"]} == {101, 102}
|
||||
first = next(item for item in growth["items"] if item["aid"] == 101)
|
||||
assert first["growth"]["available"] is True
|
||||
assert first["growth"]["delta"] == 200
|
||||
assert first["growth"]["gap_days"] == 2
|
||||
|
||||
rate = q.list_videos(sort="growth_rate", growth_days=2)
|
||||
assert {item["aid"] for item in rate["items"]} == {101, 102}
|
||||
|
||||
# 只有一个快照日时增长不可用,不能返回假 0
|
||||
for day in DATES[:-1]:
|
||||
db.write(lambda conn, day=day: conn.execute(
|
||||
"DELETE FROM snapshot WHERE stat_date = ?", (day,)
|
||||
))
|
||||
DASHBOARD_CACHE.clear()
|
||||
cold = q.list_videos(sort="growth", growth_days=2)
|
||||
assert cold["available"] is False
|
||||
assert cold["items"] == []
|
||||
assert "两天" in cold["reason"]
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_video_detail_and_trend():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
detail = q.video_detail(101)
|
||||
assert detail["aid"] == 101
|
||||
assert detail["metrics"]["view"] == 1200
|
||||
assert detail["growth"]["delta"] == 100
|
||||
assert detail["snapshot_count"] == 3
|
||||
assert detail["folder_title"] == "2026"
|
||||
assert detail["url"].endswith("BV101")
|
||||
assert q.video_detail(999999) is None
|
||||
|
||||
trend = q.video_trend(101, days=3)
|
||||
assert trend["dates"] == list(DATES)
|
||||
assert trend["series"]["view"] == [1000, 1100, 1200]
|
||||
assert trend["available"] is True
|
||||
assert len(trend["points"]) == 3
|
||||
|
||||
# 请求区间早于首次快照时,从首次快照开始,不制造空白历史
|
||||
wide = q.video_trend(101, days=30)
|
||||
assert wide["dates"] == list(DATES)
|
||||
|
||||
# 删除中间一天,折线在缺失日期应为 None,而不是插值
|
||||
db.write(lambda conn: conn.execute(
|
||||
"DELETE FROM snapshot WHERE aid=101 AND stat_date=?",
|
||||
("2026-10-30",),
|
||||
))
|
||||
trend = q.video_trend(101, days=3)
|
||||
assert trend["series"]["view"] == [1000, None, 1200]
|
||||
|
||||
# 失败快照也视为缺失
|
||||
db.write(lambda conn: conn.execute(
|
||||
"UPDATE snapshot SET ok=0, view=NULL WHERE aid=101 AND stat_date=?",
|
||||
(DATES[-1],),
|
||||
))
|
||||
trend = q.video_trend(101, days=3)
|
||||
assert trend["series"]["view"][-1] is None
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_up_queries():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
ups = q.list_ups()
|
||||
assert ups["sort"] == "avg_views"
|
||||
assert ups["total"] == 2
|
||||
assert ups["items"][0]["up_mid"] == 1
|
||||
assert ups["items"][0]["video_count"] == 2
|
||||
assert ups["items"][0]["total_views"] == 6400
|
||||
assert ups["items"][0]["avg_views"] == 3200.0
|
||||
|
||||
one = q.list_ups(min_videos=2)
|
||||
assert one["total"] == 1
|
||||
|
||||
detail = q.up_detail(1)
|
||||
assert detail["video_count"] == 2
|
||||
assert detail["total_views"] == 6400
|
||||
assert detail["blacklisted"] is False
|
||||
assert detail["series"]["dates"] == list(DATES)
|
||||
assert detail["series"]["views"] == [6000, 6200, 6400]
|
||||
assert detail["space_url"].endswith("/1")
|
||||
|
||||
blacklisted = q.up_detail(2)
|
||||
assert blacklisted["blacklisted"] is True
|
||||
assert blacklisted["video_count"] == 1
|
||||
assert q.up_detail(999999) is None
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_query_cache_invalidation():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
DASHBOARD_CACHE.clear()
|
||||
first = q.overview()
|
||||
db.write(lambda conn: conn.execute(
|
||||
"UPDATE snapshot SET \"view\" = 999999 WHERE aid=101 AND stat_date=?",
|
||||
(DATES[-1],),
|
||||
))
|
||||
cached = q.overview()
|
||||
assert cached["totals"]["view"] == first["totals"]["view"]
|
||||
|
||||
repo = Repository(db)
|
||||
repo.bump_cache_version("videos")
|
||||
refreshed = q.overview()
|
||||
assert refreshed["totals"]["view"] > first["totals"]["view"]
|
||||
|
||||
fans_first = q.fans(days=3)
|
||||
db.write(lambda conn: conn.execute(
|
||||
"UPDATE up_stat SET follower=999999 WHERE mid=37754047 AND stat_date=?",
|
||||
(DATES[-1],),
|
||||
))
|
||||
fans_cached = q.fans(days=3)
|
||||
assert fans_cached["follower"] == fans_first["follower"]
|
||||
|
||||
repo.bump_cache_version("fans")
|
||||
fans_refreshed = q.fans(days=3)
|
||||
assert fans_refreshed["follower"] == 999999
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_fans_custom_range_modes():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
daily = q.fans(start="2026-10-29", end="2026-10-31")
|
||||
assert daily["mode"] == "daily"
|
||||
assert daily["range_start"] == "2026-10-29"
|
||||
assert daily["range_end"] == "2026-10-31"
|
||||
assert daily["dates"] == list(DATES)
|
||||
assert daily["series"] == [1000, 1010, 1020]
|
||||
|
||||
# 超过一年触发按月峰值模式
|
||||
db.write(lambda conn: conn.execute(
|
||||
"INSERT OR REPLACE INTO up_stat"
|
||||
"(stat_date, mid, follower, following, captured_at, ok) "
|
||||
"VALUES ('2025-01-01', 37754047, 500, NULL, 1, 1)"
|
||||
))
|
||||
DASHBOARD_CACHE.clear()
|
||||
monthly = q.fans(start="2025-01-01", end="2026-10-31")
|
||||
assert monthly["mode"] == "monthly"
|
||||
assert monthly["span_days"] == 669
|
||||
assert monthly["dates"][0] == "2025-01-01"
|
||||
assert monthly["series"][0] == 500
|
||||
assert monthly["dates"][-1] == "2026-10-31"
|
||||
assert monthly["series"][-1] == 1020
|
||||
|
||||
# 同月多条时取峰值日期,并优先较晚日期
|
||||
db.write(lambda conn: conn.execute(
|
||||
"INSERT OR REPLACE INTO up_stat"
|
||||
"(stat_date, mid, follower, following, captured_at, ok) "
|
||||
"VALUES ('2026-10-15', 37754047, 5000, NULL, 1, 1), "
|
||||
"('2026-10-16', 37754047, 5000, NULL, 1, 1)"
|
||||
))
|
||||
DASHBOARD_CACHE.clear()
|
||||
monthly = q.fans(start="2025-01-01", end="2026-10-31")
|
||||
assert monthly["dates"][-1] == "2026-10-16"
|
||||
assert monthly["series"][-1] == 5000
|
||||
|
||||
try:
|
||||
q.fans(start="2026-11-01", end="2026-10-01")
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("start 晚于 end 应报错")
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_fans_candidates_system_and_export():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
fans = q.fans(days=3)
|
||||
assert fans["mid"] == 37754047
|
||||
assert fans["name"] == "咻咻满"
|
||||
assert fans["dates"] == list(DATES)
|
||||
assert fans["series"] == [1000, 1010, 1020]
|
||||
assert fans["delta_1d"] == 10
|
||||
assert fans["delta_7d"] is None
|
||||
assert fans["delta_cum"] == 20
|
||||
assert fans["options"][0]["mid"] == 37754047
|
||||
wide = q.fans(days=30)
|
||||
assert wide["dates"] == list(DATES)
|
||||
|
||||
# “最近记录”只返回最近 14 天,早于窗口的记录不进入表格
|
||||
db.write(lambda conn: conn.execute(
|
||||
"INSERT OR REPLACE INTO up_stat"
|
||||
"(stat_date, mid, follower, following, captured_at, ok) "
|
||||
"VALUES (?, ?, ?, NULL, 1, 1)",
|
||||
("2026-10-01", 37754047, 900),
|
||||
))
|
||||
DASHBOARD_CACHE.clear()
|
||||
recent = q.fans(days=90)
|
||||
assert recent["recent_days"] == 14
|
||||
assert [point["stat_date"] for point in recent["recent_points"]] == list(DATES)
|
||||
deltas = {point["stat_date"]: point["delta"] for point in recent["recent_points"]}
|
||||
assert deltas["2026-10-29"] == 100 # 对比 2026-10-01 的 900
|
||||
assert deltas["2026-10-30"] == 10
|
||||
assert deltas["2026-10-31"] == 10
|
||||
one_day = q.fans(days=90, recent_days=1)
|
||||
assert [point["stat_date"] for point in one_day["recent_points"]] == [DATES[-1]]
|
||||
|
||||
# 缺失前一天时不能把跨多天的变化标成“日增”
|
||||
db.write(lambda conn: conn.execute(
|
||||
"DELETE FROM up_stat WHERE mid=37754047 AND stat_date=?",
|
||||
("2026-10-30",),
|
||||
))
|
||||
DASHBOARD_CACHE.clear()
|
||||
gapped = q.fans(days=3)
|
||||
assert gapped["delta_1d"] is None
|
||||
assert gapped["delta_7d"] is None
|
||||
|
||||
candidates = q.candidates()
|
||||
assert candidates["total"] == 2
|
||||
assert candidates["pending"] == 1
|
||||
assert candidates["items"][0]["aid"] == 201
|
||||
assert 1 <= candidates["items"][0]["days_left"] <= 7
|
||||
assert candidates["items"][1]["decision"] == "rejected"
|
||||
|
||||
system = q.system()
|
||||
assert system["data_date"] == DATES[-1]
|
||||
assert system["snapshot_days"] == 3
|
||||
assert system["blacklist"][0]["video_count"] == 1
|
||||
assert system["tasks"]["snapshot"]["ok"] is True
|
||||
assert system["errors"] == []
|
||||
assert system["preview"] is False
|
||||
assert system["next_runs"]["snapshot"] > 0
|
||||
assert system["next_runs"]["discover"] > FIXED_NOW
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_duration_efficiency_queries():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
db.write(lambda conn: conn.executemany(
|
||||
"UPDATE video SET duration = ?, pubdate = ? WHERE aid = ?",
|
||||
[
|
||||
(9000, 1_756_684_800, 101), # 2025-09-01 前后,2.5 小时
|
||||
(7200, 1_756_771_200, 102), # 2 小时
|
||||
(300, 1_756_857_600, 103), # 5 分钟,应被排除
|
||||
],
|
||||
))
|
||||
DASHBOARD_CACHE.clear()
|
||||
|
||||
efficiency = q.list_videos(sort="efficiency")
|
||||
assert [item["aid"] for item in efficiency["items"]] == [102]
|
||||
first = efficiency["items"][0]
|
||||
assert first["duration"] == 7200
|
||||
assert first["content_hours"] == 2.0
|
||||
assert first["efficiency"] == 2600.0 # 原始播放/小时,详情页口径
|
||||
assert abs(first["efficiency_score"] - 2207.5) < 0.1
|
||||
assert efficiency["duration_filter"] == {
|
||||
"min_duration_seconds": 600, "maturity_days": 2,
|
||||
"min_view": 2000, "shrink_minutes": 60,
|
||||
}
|
||||
|
||||
# 播放不足 2000 的视频不进入效率榜(101 只有 1200)
|
||||
assert all(item["aid"] != 101 for item in efficiency["items"])
|
||||
|
||||
interaction = q.list_videos(sort="interaction_efficiency")
|
||||
assert [item["aid"] for item in interaction["items"]] == [102]
|
||||
assert abs(interaction["items"][0]["interaction_efficiency_score"] - 159.36) < 0.1
|
||||
|
||||
# 综合热度榜也应用最小播放门槛
|
||||
heat = q.list_videos(sort="heat")
|
||||
assert [item["aid"] for item in heat["items"]] == [102]
|
||||
|
||||
# 时长缺失不计入时长效率榜
|
||||
ups = q.list_ups(sort="efficiency")
|
||||
assert ups["sort"] == "efficiency"
|
||||
up_a = next(item for item in ups["items"] if item["up_mid"] == 1)
|
||||
assert up_a["total_duration"] == int(9000 + 7200)
|
||||
assert up_a["content_hours"] == 4.5
|
||||
assert up_a["views_per_hour"] == round(6400 / 4.5, 1)
|
||||
assert up_a["efficiency"] is not None
|
||||
assert up_a["interaction_efficiency"] is not None
|
||||
|
||||
by_duration = q.list_ups(sort="duration")
|
||||
assert [item["up_mid"] for item in by_duration["items"]][0] == 1
|
||||
|
||||
db.write(lambda conn: conn.execute(
|
||||
"UPDATE video SET duration = NULL WHERE aid = 101"
|
||||
))
|
||||
DASHBOARD_CACHE.clear()
|
||||
missing = q.list_videos(sort="efficiency")
|
||||
assert [item["aid"] for item in missing["items"]] == [102]
|
||||
|
||||
# 发布未满 2 天的视频不进入效率榜
|
||||
db.write(lambda conn: conn.execute(
|
||||
"UPDATE video SET duration = 7200, pubdate = ? WHERE aid = 102",
|
||||
(int(day_bounds("2026-10-30")[0]),),
|
||||
))
|
||||
DASHBOARD_CACHE.clear()
|
||||
fresh = q.list_videos(sort="efficiency")
|
||||
assert fresh["items"] == []
|
||||
assert fresh["available"] is False
|
||||
assert "发布满 2 天" in fresh["reason"]
|
||||
assert "播放 ≥ 2000" in fresh["reason"]
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_year_filter_and_published_sort():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
by_year = q.list_videos(sort="view", year=2026)
|
||||
assert [item["aid"] for item in by_year["items"]] == [102, 101, 103]
|
||||
assert by_year["year"] == 2026
|
||||
|
||||
none = q.list_videos(sort="view", year=2025)
|
||||
assert none["items"] == []
|
||||
assert none["total"] == 0
|
||||
|
||||
published = q.list_videos(sort="published")
|
||||
assert [item["aid"] for item in published["items"]] == [103, 101, 102]
|
||||
|
||||
added = q.list_videos(sort="added")
|
||||
assert added["total"] == 3
|
||||
|
||||
ups = q.list_ups(sort="efficiency", year=2026)
|
||||
assert ups["year"] == 2026 and ups["total"] == 2
|
||||
ups_none = q.list_ups(sort="views", year=2025)
|
||||
assert ups_none["total"] == 0
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_about_payload():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db, q = setup(tmp)
|
||||
try:
|
||||
about = q.about()
|
||||
assert about["data_date"] == DATES[-1]
|
||||
assert about["snapshot_days"] == 3
|
||||
assert about["snapshot_first_date"] == DATES[0]
|
||||
assert about["fans_start_date"] == DATES[0]
|
||||
assert about["schema_version"] == 5
|
||||
assert about["analytics"] == {
|
||||
"min_duration_seconds": 600,
|
||||
"maturity_days": 2,
|
||||
"min_view_for_ranking": 2000,
|
||||
"video_shrink_minutes": 60,
|
||||
"shrink_minutes": None,
|
||||
}
|
||||
assert about["heat_weights"]["view"] == 0.30
|
||||
assert about["followers"]["videos_total"] == 3
|
||||
assert about["followers"]["videos_covered"] == 0
|
||||
assert about["followers"]["videos_missing"] == 3
|
||||
assert about["folders"][0]["media_id"] == 3700023351
|
||||
assert about["preview"] is False
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def main_test():
|
||||
test_overview()
|
||||
test_video_listing_filters_and_sorting()
|
||||
test_growth_and_cold_start()
|
||||
test_video_detail_and_trend()
|
||||
test_up_queries()
|
||||
test_query_cache_invalidation()
|
||||
test_duration_efficiency_queries()
|
||||
test_year_filter_and_published_sort()
|
||||
test_about_payload()
|
||||
test_fans_custom_range_modes()
|
||||
test_fans_candidates_system_and_export()
|
||||
print("OK: Web 查询层总览/榜单/详情/UP/时长效率/粉丝/候选/系统测试全部通过")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main_test()
|
||||
+308
-308
@@ -1,308 +1,308 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""只读 Web 服务测试(离线): uv run python tests/test_web_server.py"""
|
||||
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import urllib.parse
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
|
||||
from reaction_board.config import ConfigStore # noqa: E402
|
||||
from reaction_board.database import Database # noqa: E402
|
||||
from reaction_board.web.server import create_server # noqa: E402
|
||||
from tests.web_fixtures import build_db, write_config # noqa: E402
|
||||
|
||||
|
||||
class RunningServer:
|
||||
def __init__(self, tmp: str, *, token: str = "", preview: bool = False):
|
||||
self.config = write_config(tmp, token=token)
|
||||
build_db(tmp)
|
||||
self.db = Database(Path(tmp) / "app.db")
|
||||
self.db.initialize()
|
||||
if preview:
|
||||
self.db.write(lambda conn: conn.execute(
|
||||
"INSERT OR REPLACE INTO kv(k, v) VALUES ('preview:seeded', '1')"
|
||||
))
|
||||
self.store = ConfigStore(self.config)
|
||||
self.server = create_server(
|
||||
self.store, self.db, port=0, preview=preview,
|
||||
clock=lambda: 1_793_459_000,
|
||||
)
|
||||
self.port = self.server.server_address[1]
|
||||
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
|
||||
self.thread.start()
|
||||
|
||||
def request(self, path: str, *, method: str = "GET", headers=None, body=None):
|
||||
conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=5)
|
||||
conn.request(method, path, body=body, headers=headers or {})
|
||||
response = conn.getresponse()
|
||||
payload = response.read()
|
||||
result = response.status, dict(response.getheaders()), payload
|
||||
conn.close()
|
||||
return result
|
||||
|
||||
def json(self, path: str, **kwargs):
|
||||
status, headers, payload = self.request(path, **kwargs)
|
||||
return status, headers, json.loads(payload.decode("utf-8"))
|
||||
|
||||
def close(self):
|
||||
self.server.shutdown()
|
||||
self.server.server_close()
|
||||
self.db.close()
|
||||
|
||||
|
||||
def test_readonly_routes_and_static():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
running = RunningServer(tmp)
|
||||
try:
|
||||
status, _, health = running.json("/api/health")
|
||||
assert status == 200 and health["ok"] is True
|
||||
assert health["data"]["preview"] is False
|
||||
|
||||
status, _, payload = running.json("/api/session")
|
||||
assert status == 200
|
||||
assert payload["data"]["auth_enabled"] is False
|
||||
assert payload["data"]["authenticated"] is True
|
||||
status, _, payload = running.json("/api/candidates")
|
||||
assert status == 200 and payload["ok"] is True
|
||||
status, _, payload = running.json("/api/system")
|
||||
assert status == 200 and payload["ok"] is True
|
||||
status, _, payload = running.json("/api/about")
|
||||
assert status == 200
|
||||
assert payload["data"]["schema_version"] == 4
|
||||
assert payload["data"]["analytics"]["min_duration_seconds"] == 600
|
||||
|
||||
status, _, overview = running.json("/api/overview")
|
||||
assert status == 200 and overview["ok"] is True
|
||||
assert overview["data"]["data_date"] == "2026-10-31"
|
||||
|
||||
status, headers, payload = running.request("/")
|
||||
assert status == 200
|
||||
assert "text/html" in headers["Content-Type"]
|
||||
assert b"<html" in payload.lower()
|
||||
|
||||
for asset in ("/static/style.css", "/static/app.js", "/static/vendor/echarts.min.js"):
|
||||
status, asset_headers, asset_payload = running.request(asset)
|
||||
assert status == 200, asset
|
||||
assert asset_payload, asset
|
||||
content_type = asset_headers["Content-Type"]
|
||||
assert "text/css" in content_type or "javascript" in content_type, asset
|
||||
|
||||
status, _, payload = running.request("/static/../config.json")
|
||||
assert status == 404
|
||||
|
||||
# 伪静态前端路由:直接访问 /rank、/video/... 返回 index.html
|
||||
for route_path in ("/rank", "/videos", "/ups", "/about", "/video/114775988111033", "/up/230020975", "/fans"):
|
||||
status, route_headers, route_payload = running.request(route_path)
|
||||
assert status == 200, route_path
|
||||
assert "text/html" in route_headers["Content-Type"], route_path
|
||||
assert b"<html" in route_payload.lower(), route_path
|
||||
status, _, _ = running.request("/nope.js")
|
||||
assert status == 404
|
||||
|
||||
status, _, payload = running.request("/api/videos")
|
||||
assert status == 200
|
||||
items = json.loads(payload)["data"]["items"]
|
||||
assert items and items[0]["aid"] == 102
|
||||
|
||||
status, _, payload = running.json("/api/videos?year=2026")
|
||||
assert status == 200
|
||||
assert payload["data"]["year"] == 2026
|
||||
status, _, payload = running.json("/api/videos?year=1800")
|
||||
assert status == 400
|
||||
status, _, payload = running.json("/api/ups?year=2026")
|
||||
assert status == 200
|
||||
assert payload["data"]["year"] == 2026
|
||||
|
||||
status, _, payload = running.request("/api/ups")
|
||||
assert status == 200
|
||||
assert json.loads(payload)["data"]["sort"] == "efficiency"
|
||||
|
||||
status, _, payload = running.request("/api/fans?days=7&recent_days=14")
|
||||
assert status == 200
|
||||
fans = json.loads(payload)["data"]
|
||||
assert fans["recent_days"] == 14
|
||||
assert all(
|
||||
point["stat_date"] >= "2026-10-18"
|
||||
for point in fans["recent_points"]
|
||||
)
|
||||
assert all("delta" in point for point in fans["recent_points"])
|
||||
|
||||
status, _, payload = running.request(
|
||||
"/api/fans?start=2026-10-29&end=2026-10-31"
|
||||
)
|
||||
assert status == 200
|
||||
data = json.loads(payload)["data"]
|
||||
assert data["mode"] == "daily"
|
||||
assert data["dates"] == ["2026-10-29", "2026-10-30", "2026-10-31"]
|
||||
|
||||
running.db.write(lambda conn: conn.execute(
|
||||
"INSERT OR REPLACE INTO up_stat"
|
||||
"(stat_date, mid, follower, following, captured_at, ok) "
|
||||
"VALUES ('2025-01-01', 37754047, 500, NULL, 1, 1)"
|
||||
))
|
||||
status, _, payload = running.request(
|
||||
"/api/fans?start=2025-01-01&end=2026-10-31"
|
||||
)
|
||||
assert status == 200
|
||||
assert json.loads(payload)["data"]["mode"] == "monthly"
|
||||
|
||||
status, headers, payload = running.request("/api/videos", method="HEAD")
|
||||
assert status == 200 and payload == b""
|
||||
assert "Content-Length" in headers
|
||||
|
||||
# 只读:所有业务写方法都被拒绝,且数据库不变
|
||||
before = running.db.read(lambda conn: conn.execute(
|
||||
"SELECT COUNT(*) FROM candidate"
|
||||
).fetchone()[0])
|
||||
for method in ("POST", "PUT", "PATCH", "DELETE"):
|
||||
status, _, _ = running.request("/api/videos/101", method=method)
|
||||
assert status == 405, method
|
||||
after = running.db.read(lambda conn: conn.execute(
|
||||
"SELECT COUNT(*) FROM candidate"
|
||||
).fetchone()[0])
|
||||
assert after == before
|
||||
|
||||
status, _, error = running.json("/api/videos?sort=bad")
|
||||
assert status == 400 and error["ok"] is False
|
||||
status, _, error = running.json("/api/videos?page=0")
|
||||
assert status == 400
|
||||
status, _, error = running.json("/api/videos/abc")
|
||||
assert status == 400
|
||||
status, _, error = running.json("/api/nope")
|
||||
assert status == 404
|
||||
|
||||
status, _, payload = running.request("/api/export.csv?sort=view")
|
||||
assert status == 404
|
||||
|
||||
status, headers, _ = running.request("/api/overview")
|
||||
assert headers["X-Content-Type-Options"] == "nosniff"
|
||||
assert "default-src 'self'" in headers["Content-Security-Policy"]
|
||||
assert headers["X-Frame-Options"] == "DENY"
|
||||
finally:
|
||||
running.close()
|
||||
|
||||
|
||||
def test_token_auth_and_login():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
running = RunningServer(tmp, token="test-token")
|
||||
try:
|
||||
# 公共页面与公共 API 访客可见
|
||||
status, _, body = running.json("/api/overview")
|
||||
assert status == 200 and body["ok"] is True
|
||||
status, _, body = running.json("/api/videos")
|
||||
assert status == 200 and body["ok"] is True
|
||||
status, _, body = running.json("/api/fans?days=7")
|
||||
assert status == 200 and body["ok"] is True
|
||||
status, _, payload = running.request("/")
|
||||
assert status == 200 and b"<html" in payload.lower()
|
||||
status, _, payload = running.request("/rank")
|
||||
assert status == 200 and b"<html" in payload.lower()
|
||||
|
||||
# 候选与系统需要登录
|
||||
status, _, body = running.json("/api/candidates")
|
||||
assert status == 401 and body["error"]["code"] == "unauthorized"
|
||||
status, _, body = running.json("/api/system")
|
||||
assert status == 401
|
||||
status, headers, _ = running.request("/candidates")
|
||||
assert status == 303 and headers["Location"] == "/login?next=/candidates"
|
||||
status, headers, _ = running.request("/system")
|
||||
assert status == 303 and headers["Location"] == "/login?next=/system"
|
||||
|
||||
status, _, body = running.json("/api/session")
|
||||
assert status == 200
|
||||
assert body["data"]["auth_enabled"] is True
|
||||
assert body["data"]["authenticated"] is False
|
||||
|
||||
status, _, payload = running.request("/login?next=/candidates")
|
||||
assert status == 200 and b"web.auth_token" in payload
|
||||
assert b"action=\"/login?next=/candidates\"" in payload
|
||||
|
||||
status, _, _ = running.request(
|
||||
"/login",
|
||||
method="POST",
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
body="token=wrong",
|
||||
)
|
||||
assert status == 401
|
||||
|
||||
status, headers, _ = running.request(
|
||||
"/login?next=/candidates",
|
||||
method="POST",
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
body="token=test-token",
|
||||
)
|
||||
assert status == 303 and headers["Location"] == "/candidates"
|
||||
cookie = headers["Set-Cookie"].split(";", 1)[0]
|
||||
assert cookie.startswith("rb_session=")
|
||||
|
||||
status, _, body = running.json("/api/candidates", headers={"Cookie": cookie})
|
||||
assert status == 200 and body["ok"] is True
|
||||
status, _, body = running.json("/api/system", headers={"Cookie": cookie})
|
||||
assert status == 200 and body["ok"] is True
|
||||
status, _, body = running.json(
|
||||
"/api/candidates", headers={"Authorization": "Bearer test-token"}
|
||||
)
|
||||
assert status == 200
|
||||
|
||||
tampered = cookie[:-1] + ("0" if cookie[-1] != "0" else "1")
|
||||
status, _, _ = running.json("/api/candidates", headers={"Cookie": tampered})
|
||||
assert status == 401
|
||||
status, _, body = running.json("/api/overview", headers={"Cookie": tampered})
|
||||
assert status == 200
|
||||
|
||||
status, _, _ = running.json("/api/health")
|
||||
assert status == 200
|
||||
finally:
|
||||
running.close()
|
||||
|
||||
|
||||
def test_preview_and_loopback_guards():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
config = write_config(tmp)
|
||||
build_db(tmp)
|
||||
db = Database(Path(tmp) / "app.db")
|
||||
db.initialize()
|
||||
store = ConfigStore(config)
|
||||
try:
|
||||
try:
|
||||
create_server(store, db, host="0.0.0.0", port=0)
|
||||
except ValueError as exc:
|
||||
assert "web.auth_token" in str(exc)
|
||||
else:
|
||||
raise AssertionError("非回环地址且无 token 应拒绝启动")
|
||||
|
||||
try:
|
||||
create_server(store, db, port=0, preview=True)
|
||||
except ValueError as exc:
|
||||
assert "preview:seeded" in str(exc)
|
||||
else:
|
||||
raise AssertionError("非预览库不应允许 --preview")
|
||||
|
||||
db.write(lambda conn: conn.execute(
|
||||
"INSERT OR REPLACE INTO kv(k, v) VALUES ('preview:seeded', '1')"
|
||||
))
|
||||
server = create_server(store, db, port=0, preview=True)
|
||||
try:
|
||||
assert server.context.preview is True
|
||||
finally:
|
||||
server.server_close()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def main_test():
|
||||
test_readonly_routes_and_static()
|
||||
test_token_auth_and_login()
|
||||
test_preview_and_loopback_guards()
|
||||
print("OK: Web 只读路由/鉴权/预览/安全边界测试全部通过")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main_test()
|
||||
# -*- coding: utf-8 -*-
|
||||
"""只读 Web 服务测试(离线): uv run python tests/test_web_server.py"""
|
||||
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import urllib.parse
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
|
||||
from reaction_board.config import ConfigStore # noqa: E402
|
||||
from reaction_board.database import Database # noqa: E402
|
||||
from reaction_board.web.server import create_server # noqa: E402
|
||||
from tests.web_fixtures import build_db, write_config # noqa: E402
|
||||
|
||||
|
||||
class RunningServer:
|
||||
def __init__(self, tmp: str, *, token: str = "", preview: bool = False):
|
||||
self.config = write_config(tmp, token=token)
|
||||
build_db(tmp)
|
||||
self.db = Database(Path(tmp) / "app.db")
|
||||
self.db.initialize()
|
||||
if preview:
|
||||
self.db.write(lambda conn: conn.execute(
|
||||
"INSERT OR REPLACE INTO kv(k, v) VALUES ('preview:seeded', '1')"
|
||||
))
|
||||
self.store = ConfigStore(self.config)
|
||||
self.server = create_server(
|
||||
self.store, self.db, port=0, preview=preview,
|
||||
clock=lambda: 1_793_459_000,
|
||||
)
|
||||
self.port = self.server.server_address[1]
|
||||
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
|
||||
self.thread.start()
|
||||
|
||||
def request(self, path: str, *, method: str = "GET", headers=None, body=None):
|
||||
conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=5)
|
||||
conn.request(method, path, body=body, headers=headers or {})
|
||||
response = conn.getresponse()
|
||||
payload = response.read()
|
||||
result = response.status, dict(response.getheaders()), payload
|
||||
conn.close()
|
||||
return result
|
||||
|
||||
def json(self, path: str, **kwargs):
|
||||
status, headers, payload = self.request(path, **kwargs)
|
||||
return status, headers, json.loads(payload.decode("utf-8"))
|
||||
|
||||
def close(self):
|
||||
self.server.shutdown()
|
||||
self.server.server_close()
|
||||
self.db.close()
|
||||
|
||||
|
||||
def test_readonly_routes_and_static():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
running = RunningServer(tmp)
|
||||
try:
|
||||
status, _, health = running.json("/api/health")
|
||||
assert status == 200 and health["ok"] is True
|
||||
assert health["data"]["preview"] is False
|
||||
|
||||
status, _, payload = running.json("/api/session")
|
||||
assert status == 200
|
||||
assert payload["data"]["auth_enabled"] is False
|
||||
assert payload["data"]["authenticated"] is True
|
||||
status, _, payload = running.json("/api/candidates")
|
||||
assert status == 200 and payload["ok"] is True
|
||||
status, _, payload = running.json("/api/system")
|
||||
assert status == 200 and payload["ok"] is True
|
||||
status, _, payload = running.json("/api/about")
|
||||
assert status == 200
|
||||
assert payload["data"]["schema_version"] == 5
|
||||
assert payload["data"]["analytics"]["min_duration_seconds"] == 600
|
||||
|
||||
status, _, overview = running.json("/api/overview")
|
||||
assert status == 200 and overview["ok"] is True
|
||||
assert overview["data"]["data_date"] == "2026-10-31"
|
||||
|
||||
status, headers, payload = running.request("/")
|
||||
assert status == 200
|
||||
assert "text/html" in headers["Content-Type"]
|
||||
assert b"<html" in payload.lower()
|
||||
|
||||
for asset in ("/static/style.css", "/static/app.js", "/static/vendor/echarts.min.js"):
|
||||
status, asset_headers, asset_payload = running.request(asset)
|
||||
assert status == 200, asset
|
||||
assert asset_payload, asset
|
||||
content_type = asset_headers["Content-Type"]
|
||||
assert "text/css" in content_type or "javascript" in content_type, asset
|
||||
|
||||
status, _, payload = running.request("/static/../config.json")
|
||||
assert status == 404
|
||||
|
||||
# 伪静态前端路由:直接访问 /rank、/video/... 返回 index.html
|
||||
for route_path in ("/rank", "/videos", "/ups", "/about", "/video/114775988111033", "/up/230020975", "/fans"):
|
||||
status, route_headers, route_payload = running.request(route_path)
|
||||
assert status == 200, route_path
|
||||
assert "text/html" in route_headers["Content-Type"], route_path
|
||||
assert b"<html" in route_payload.lower(), route_path
|
||||
status, _, _ = running.request("/nope.js")
|
||||
assert status == 404
|
||||
|
||||
status, _, payload = running.request("/api/videos")
|
||||
assert status == 200
|
||||
items = json.loads(payload)["data"]["items"]
|
||||
assert items and items[0]["aid"] == 102
|
||||
|
||||
status, _, payload = running.json("/api/videos?year=2026")
|
||||
assert status == 200
|
||||
assert payload["data"]["year"] == 2026
|
||||
status, _, payload = running.json("/api/videos?year=1800")
|
||||
assert status == 400
|
||||
status, _, payload = running.json("/api/ups?year=2026")
|
||||
assert status == 200
|
||||
assert payload["data"]["year"] == 2026
|
||||
|
||||
status, _, payload = running.request("/api/ups")
|
||||
assert status == 200
|
||||
assert json.loads(payload)["data"]["sort"] == "efficiency"
|
||||
|
||||
status, _, payload = running.request("/api/fans?days=7&recent_days=14")
|
||||
assert status == 200
|
||||
fans = json.loads(payload)["data"]
|
||||
assert fans["recent_days"] == 14
|
||||
assert all(
|
||||
point["stat_date"] >= "2026-10-18"
|
||||
for point in fans["recent_points"]
|
||||
)
|
||||
assert all("delta" in point for point in fans["recent_points"])
|
||||
|
||||
status, _, payload = running.request(
|
||||
"/api/fans?start=2026-10-29&end=2026-10-31"
|
||||
)
|
||||
assert status == 200
|
||||
data = json.loads(payload)["data"]
|
||||
assert data["mode"] == "daily"
|
||||
assert data["dates"] == ["2026-10-29", "2026-10-30", "2026-10-31"]
|
||||
|
||||
running.db.write(lambda conn: conn.execute(
|
||||
"INSERT OR REPLACE INTO up_stat"
|
||||
"(stat_date, mid, follower, following, captured_at, ok) "
|
||||
"VALUES ('2025-01-01', 37754047, 500, NULL, 1, 1)"
|
||||
))
|
||||
status, _, payload = running.request(
|
||||
"/api/fans?start=2025-01-01&end=2026-10-31"
|
||||
)
|
||||
assert status == 200
|
||||
assert json.loads(payload)["data"]["mode"] == "monthly"
|
||||
|
||||
status, headers, payload = running.request("/api/videos", method="HEAD")
|
||||
assert status == 200 and payload == b""
|
||||
assert "Content-Length" in headers
|
||||
|
||||
# 只读:所有业务写方法都被拒绝,且数据库不变
|
||||
before = running.db.read(lambda conn: conn.execute(
|
||||
"SELECT COUNT(*) FROM candidate"
|
||||
).fetchone()[0])
|
||||
for method in ("POST", "PUT", "PATCH", "DELETE"):
|
||||
status, _, _ = running.request("/api/videos/101", method=method)
|
||||
assert status == 405, method
|
||||
after = running.db.read(lambda conn: conn.execute(
|
||||
"SELECT COUNT(*) FROM candidate"
|
||||
).fetchone()[0])
|
||||
assert after == before
|
||||
|
||||
status, _, error = running.json("/api/videos?sort=bad")
|
||||
assert status == 400 and error["ok"] is False
|
||||
status, _, error = running.json("/api/videos?page=0")
|
||||
assert status == 400
|
||||
status, _, error = running.json("/api/videos/abc")
|
||||
assert status == 400
|
||||
status, _, error = running.json("/api/nope")
|
||||
assert status == 404
|
||||
|
||||
status, _, payload = running.request("/api/export.csv?sort=view")
|
||||
assert status == 404
|
||||
|
||||
status, headers, _ = running.request("/api/overview")
|
||||
assert headers["X-Content-Type-Options"] == "nosniff"
|
||||
assert "default-src 'self'" in headers["Content-Security-Policy"]
|
||||
assert headers["X-Frame-Options"] == "DENY"
|
||||
finally:
|
||||
running.close()
|
||||
|
||||
|
||||
def test_token_auth_and_login():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
running = RunningServer(tmp, token="test-token")
|
||||
try:
|
||||
# 公共页面与公共 API 访客可见
|
||||
status, _, body = running.json("/api/overview")
|
||||
assert status == 200 and body["ok"] is True
|
||||
status, _, body = running.json("/api/videos")
|
||||
assert status == 200 and body["ok"] is True
|
||||
status, _, body = running.json("/api/fans?days=7")
|
||||
assert status == 200 and body["ok"] is True
|
||||
status, _, payload = running.request("/")
|
||||
assert status == 200 and b"<html" in payload.lower()
|
||||
status, _, payload = running.request("/rank")
|
||||
assert status == 200 and b"<html" in payload.lower()
|
||||
|
||||
# 候选与系统需要登录
|
||||
status, _, body = running.json("/api/candidates")
|
||||
assert status == 401 and body["error"]["code"] == "unauthorized"
|
||||
status, _, body = running.json("/api/system")
|
||||
assert status == 401
|
||||
status, headers, _ = running.request("/candidates")
|
||||
assert status == 303 and headers["Location"] == "/login?next=/candidates"
|
||||
status, headers, _ = running.request("/system")
|
||||
assert status == 303 and headers["Location"] == "/login?next=/system"
|
||||
|
||||
status, _, body = running.json("/api/session")
|
||||
assert status == 200
|
||||
assert body["data"]["auth_enabled"] is True
|
||||
assert body["data"]["authenticated"] is False
|
||||
|
||||
status, _, payload = running.request("/login?next=/candidates")
|
||||
assert status == 200 and b"web.auth_token" in payload
|
||||
assert b"action=\"/login?next=/candidates\"" in payload
|
||||
|
||||
status, _, _ = running.request(
|
||||
"/login",
|
||||
method="POST",
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
body="token=wrong",
|
||||
)
|
||||
assert status == 401
|
||||
|
||||
status, headers, _ = running.request(
|
||||
"/login?next=/candidates",
|
||||
method="POST",
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
body="token=test-token",
|
||||
)
|
||||
assert status == 303 and headers["Location"] == "/candidates"
|
||||
cookie = headers["Set-Cookie"].split(";", 1)[0]
|
||||
assert cookie.startswith("rb_session=")
|
||||
|
||||
status, _, body = running.json("/api/candidates", headers={"Cookie": cookie})
|
||||
assert status == 200 and body["ok"] is True
|
||||
status, _, body = running.json("/api/system", headers={"Cookie": cookie})
|
||||
assert status == 200 and body["ok"] is True
|
||||
status, _, body = running.json(
|
||||
"/api/candidates", headers={"Authorization": "Bearer test-token"}
|
||||
)
|
||||
assert status == 200
|
||||
|
||||
tampered = cookie[:-1] + ("0" if cookie[-1] != "0" else "1")
|
||||
status, _, _ = running.json("/api/candidates", headers={"Cookie": tampered})
|
||||
assert status == 401
|
||||
status, _, body = running.json("/api/overview", headers={"Cookie": tampered})
|
||||
assert status == 200
|
||||
|
||||
status, _, _ = running.json("/api/health")
|
||||
assert status == 200
|
||||
finally:
|
||||
running.close()
|
||||
|
||||
|
||||
def test_preview_and_loopback_guards():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
config = write_config(tmp)
|
||||
build_db(tmp)
|
||||
db = Database(Path(tmp) / "app.db")
|
||||
db.initialize()
|
||||
store = ConfigStore(config)
|
||||
try:
|
||||
try:
|
||||
create_server(store, db, host="0.0.0.0", port=0)
|
||||
except ValueError as exc:
|
||||
assert "web.auth_token" in str(exc)
|
||||
else:
|
||||
raise AssertionError("非回环地址且无 token 应拒绝启动")
|
||||
|
||||
try:
|
||||
create_server(store, db, port=0, preview=True)
|
||||
except ValueError as exc:
|
||||
assert "preview:seeded" in str(exc)
|
||||
else:
|
||||
raise AssertionError("非预览库不应允许 --preview")
|
||||
|
||||
db.write(lambda conn: conn.execute(
|
||||
"INSERT OR REPLACE INTO kv(k, v) VALUES ('preview:seeded', '1')"
|
||||
))
|
||||
server = create_server(store, db, port=0, preview=True)
|
||||
try:
|
||||
assert server.context.preview is True
|
||||
finally:
|
||||
server.server_close()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def main_test():
|
||||
test_readonly_routes_and_static()
|
||||
test_token_auth_and_login()
|
||||
test_preview_and_loopback_guards()
|
||||
print("OK: Web 只读路由/鉴权/预览/安全边界测试全部通过")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main_test()
|
||||
@@ -48,8 +48,6 @@ def write_config(
|
||||
"up_blacklist_seed": [],
|
||||
"schedule": {
|
||||
"discover_minutes": 60,
|
||||
"folder_sync_minutes": 60,
|
||||
"full_folder_refresh_hours": 6,
|
||||
"snapshot_at": "00:01",
|
||||
"candidate_ttl_days": 7,
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user