Merge remote-tracking branch 'origin/v3' into codex/manual-source-classification

This commit is contained in:
yanjunpu
2026-09-07 23:27:11 +08:00
55 changed files with 3166 additions and 656 deletions

View File

@@ -590,7 +590,7 @@
},
"app/runtime/state.py:threading.Timer": {
"owners": {
"SystemHelper._schedule_supervisor_restart": 1
"SystemHelper._schedule_supervisor_command": 1
},
"target": "threading.Timer"
},

View File

@@ -1074,8 +1074,8 @@
"runtime_only": true
}
},
"edge_count": 8263,
"edge_sha256": "461585d4f5b0334163e10192294a20261e68f47f39094326f7c4590c4f1451cc",
"edge_count": 8302,
"edge_sha256": "49000047cece20aa2bd7f1d06916072d06b832f0f2d929693f995206f9a29b84",
"edges": [
"app -> app.foundation",
"app -> app.foundation.environment",
@@ -1270,6 +1270,8 @@
"app.adapters.system.update -> app.foundation.singleton",
"app.adapters.system.update -> app.foundation.version",
"app.adapters.system.update -> app.runtime",
"app.adapters.system.update -> app.runtime.dependencies",
"app.adapters.system.update -> app.runtime.dependencies.profile",
"app.adapters.system.update -> app.runtime.log",
"app.adapters.system.update -> app.runtime.settings",
"app.adapters.system.update -> app.runtime.thread",
@@ -5289,10 +5291,15 @@
"app.chain.workflow -> app.schemas",
"app.chain.workflow -> app.schemas.types",
"app.chain.workflow -> app.schemas.workflow",
"app.cli -> app.adapters",
"app.cli -> app.adapters.system",
"app.cli -> app.adapters.system.update",
"app.cli -> app.application",
"app.cli -> app.application.backup",
"app.cli -> app.doctor",
"app.cli -> app.doctor.formatters",
"app.cli -> app.foundation",
"app.cli -> app.foundation.environment",
"app.cli -> app.runtime",
"app.cli -> app.runtime.config",
"app.cli -> app.runtime.settings",
@@ -6891,6 +6898,38 @@
"app.modules.lrclib -> app.runtime.settings",
"app.modules.lrclib -> app.schemas",
"app.modules.lrclib -> app.schemas.types",
"app.modules.mediavault.api -> app.adapters",
"app.modules.mediavault.api -> app.adapters.network",
"app.modules.mediavault.api -> app.adapters.network.http",
"app.modules.mediavault.api -> app.foundation",
"app.modules.mediavault.api -> app.foundation.url",
"app.modules.mediavault.api -> app.runtime",
"app.modules.mediavault.api -> app.runtime.log",
"app.modules.mediavault.api -> app.runtime.settings",
"app.modules.mediavault.mediavault -> app.application",
"app.modules.mediavault.mediavault -> app.application.mediaserver",
"app.modules.mediavault.mediavault -> app.foundation",
"app.modules.mediavault.mediavault -> app.foundation.url",
"app.modules.mediavault.mediavault -> app.modules",
"app.modules.mediavault.mediavault -> app.modules.mediavault",
"app.modules.mediavault.mediavault -> app.modules.mediavault.api",
"app.modules.mediavault.mediavault -> app.runtime",
"app.modules.mediavault.mediavault -> app.runtime.log",
"app.modules.mediavault.mediavault -> app.schemas",
"app.modules.mediavault.mediavault -> app.schemas.dashboard",
"app.modules.mediavault.mediavault -> app.schemas.mediaserver",
"app.modules.mediavault.mediavault -> app.schemas.types",
"app.modules.mediavault.module -> app.modules",
"app.modules.mediavault.module -> app.modules._base",
"app.modules.mediavault.module -> app.modules._base.mediaserver",
"app.modules.mediavault.module -> app.modules.mediavault",
"app.modules.mediavault.module -> app.modules.mediavault.mediavault",
"app.modules.mediavault.module -> app.runtime",
"app.modules.mediavault.module -> app.runtime.log",
"app.modules.mediavault.module -> app.schemas",
"app.modules.mediavault.module -> app.schemas.dashboard",
"app.modules.mediavault.module -> app.schemas.mediaserver",
"app.modules.mediavault.module -> app.schemas.types",
"app.modules.musicbrainz -> app.adapters",
"app.modules.musicbrainz -> app.adapters.network",
"app.modules.musicbrainz -> app.adapters.network.http",
@@ -9341,7 +9380,7 @@
"app.workflow.actions.transfer_file -> app.workflow",
"app.workflow.actions.transfer_file -> app.workflow.actions"
],
"module_count": 976,
"module_count": 980,
"modules": [
"app",
"app.adapters",
@@ -10002,6 +10041,10 @@
"app.modules.jellyfin.jellyfin",
"app.modules.listenbrainz",
"app.modules.lrclib",
"app.modules.mediavault",
"app.modules.mediavault.api",
"app.modules.mediavault.mediavault",
"app.modules.mediavault.module",
"app.modules.musicbrainz",
"app.modules.musicbrainz.cache",
"app.modules.musixmatch",

View File

@@ -1395,39 +1395,34 @@
"empty-body": 4,
"misc": 3,
"no-any-return": 1,
"no-untyped-call": 5,
"no-untyped-call": 4,
"no-untyped-def": 7,
"union-attr": 4
},
"app/modules/_base/downloader.py": {
"assignment": 1,
"attr-defined": 5,
"no-untyped-call": 1
"attr-defined": 5
},
"app/modules/_base/mediaserver.py": {
"arg-type": 2,
"assignment": 3,
"attr-defined": 5,
"no-any-return": 1,
"no-untyped-call": 1,
"no-untyped-def": 2,
"var-annotated": 1
},
"app/modules/_base/notification.py": {
"arg-type": 1,
"assignment": 1,
"no-untyped-call": 1,
"no-untyped-def": 3,
"type-arg": 5
},
"app/modules/acoustid/__init__.py": {
"arg-type": 1,
"list-item": 1,
"no-untyped-call": 1
"list-item": 1
},
"app/modules/anilist/__init__.py": {
"assignment": 4,
"no-untyped-call": 1,
"no-untyped-def": 5,
"return-value": 1,
"type-arg": 12
@@ -1442,7 +1437,6 @@
"app/modules/bangumi/__init__.py": {
"arg-type": 2,
"assignment": 4,
"no-untyped-call": 1,
"no-untyped-def": 5,
"return-value": 1,
"type-arg": 7
@@ -1452,9 +1446,7 @@
},
"app/modules/dingtalk/__init__.py": {
"arg-type": 2,
"no-untyped-call": 1,
"no-untyped-def": 1,
"override": 1
"no-untyped-def": 1
},
"app/modules/dingtalk/dingtalk.py": {
"no-untyped-def": 1
@@ -1466,7 +1458,6 @@
"empty-body": 1,
"misc": 1,
"no-any-return": 1,
"no-untyped-call": 1,
"no-untyped-def": 1,
"truthy-function": 1,
"type-arg": 8
@@ -1487,7 +1478,7 @@
"empty-body": 1,
"misc": 2,
"no-any-return": 1,
"no-untyped-call": 4,
"no-untyped-call": 3,
"no-untyped-def": 7,
"return-value": 2,
"type-arg": 13,
@@ -1512,7 +1503,6 @@
"arg-type": 3,
"assignment": 13,
"empty-body": 1,
"no-untyped-call": 1,
"no-untyped-def": 1,
"type-arg": 1
},
@@ -1530,7 +1520,6 @@
"app/modules/fanart/__init__.py": {
"misc": 2,
"no-any-return": 1,
"no-untyped-call": 1,
"no-untyped-def": 2,
"type-arg": 10,
"var-annotated": 1
@@ -1539,7 +1528,6 @@
"arg-type": 4,
"assignment": 6,
"attr-defined": 1,
"no-untyped-call": 1,
"no-untyped-def": 1,
"return-value": 1,
"type-arg": 5,
@@ -1561,7 +1549,7 @@
"attr-defined": 1,
"empty-body": 1,
"no-any-return": 2,
"no-untyped-call": 3,
"no-untyped-call": 2,
"no-untyped-def": 5,
"type-arg": 3,
"var-annotated": 3
@@ -1668,7 +1656,7 @@
"assignment": 4,
"empty-body": 1,
"index": 1,
"no-untyped-call": 2,
"no-untyped-call": 1,
"no-untyped-def": 3,
"operator": 2,
"return": 1,
@@ -1678,9 +1666,7 @@
"app/modules/imdb/__init__.py": {
"assignment": 10,
"no-any-return": 1,
"no-untyped-call": 1,
"no-untyped-def": 3,
"override": 1,
"type-arg": 5
},
"app/modules/imdb/api.py": {
@@ -1694,7 +1680,7 @@
"attr-defined": 1,
"empty-body": 1,
"no-any-return": 2,
"no-untyped-call": 4,
"no-untyped-call": 3,
"no-untyped-def": 1,
"return-value": 5,
"type-arg": 19,
@@ -1913,7 +1899,6 @@
"arg-type": 3,
"assignment": 13,
"empty-body": 1,
"no-untyped-call": 1,
"no-untyped-def": 1,
"type-arg": 1
},
@@ -1932,22 +1917,17 @@
},
"app/modules/listenbrainz/__init__.py": {
"misc": 2,
"no-any-return": 2,
"no-untyped-call": 1,
"override": 1
"no-any-return": 2
},
"app/modules/lrclib/__init__.py": {
"misc": 1,
"no-untyped-call": 1,
"override": 1
"misc": 1
},
"app/modules/musicbrainz/__init__.py": {
"arg-type": 1,
"assignment": 5,
"misc": 4,
"no-untyped-call": 4,
"no-untyped-call": 3,
"no-untyped-def": 2,
"override": 1,
"type-arg": 2
},
"app/modules/musicbrainz/cache.py": {
@@ -1958,13 +1938,10 @@
"union-attr": 1
},
"app/modules/musixmatch/__init__.py": {
"no-any-return": 1,
"no-untyped-call": 1
"no-any-return": 1
},
"app/modules/navidrome/__init__.py": {
"arg-type": 9,
"no-untyped-call": 1,
"override": 1,
"type-arg": 1,
"union-attr": 1
},
@@ -1976,7 +1953,7 @@
"arg-type": 7,
"assignment": 16,
"empty-body": 1,
"no-untyped-call": 2,
"no-untyped-call": 1,
"no-untyped-def": 5,
"type-arg": 1
},
@@ -1994,7 +1971,6 @@
},
"app/modules/postgresql/__init__.py": {
"empty-body": 1,
"no-untyped-call": 1,
"no-untyped-def": 1
},
"app/modules/qbittorrent/__init__.py": {
@@ -2002,7 +1978,6 @@
"assignment": 16,
"empty-body": 1,
"no-redef": 2,
"no-untyped-call": 1,
"operator": 1,
"str-bytes-safe": 2,
"type-arg": 8,
@@ -2029,7 +2004,6 @@
"attr-defined": 1,
"empty-body": 1,
"no-any-return": 1,
"no-untyped-call": 1,
"no-untyped-def": 1,
"type-arg": 4,
"var-annotated": 1
@@ -2042,7 +2016,7 @@
},
"app/modules/redis/__init__.py": {
"empty-body": 1,
"no-untyped-call": 2,
"no-untyped-call": 1,
"no-untyped-def": 1
},
"app/modules/rtorrent/__init__.py": {
@@ -2050,7 +2024,6 @@
"assignment": 16,
"empty-body": 1,
"no-redef": 1,
"no-untyped-call": 1,
"no-untyped-def": 1,
"operator": 1,
"str-bytes-safe": 2,
@@ -2072,7 +2045,6 @@
"attr-defined": 1,
"empty-body": 1,
"index": 1,
"no-untyped-call": 1,
"no-untyped-def": 1,
"type-arg": 7
},
@@ -2089,7 +2061,6 @@
"app/modules/subtitle/__init__.py": {
"arg-type": 1,
"empty-body": 1,
"no-untyped-call": 1,
"no-untyped-def": 2,
"var-annotated": 1
},
@@ -2099,7 +2070,6 @@
"attr-defined": 1,
"empty-body": 1,
"no-any-return": 1,
"no-untyped-call": 1,
"no-untyped-def": 2,
"type-arg": 4,
"var-annotated": 1
@@ -2115,7 +2085,6 @@
"assignment": 9,
"attr-defined": 1,
"empty-body": 1,
"no-untyped-call": 1,
"no-untyped-def": 1,
"type-arg": 11,
"union-attr": 1
@@ -2135,9 +2104,7 @@
"app/modules/theaudiodb/__init__.py": {
"assignment": 4,
"misc": 2,
"no-untyped-call": 1,
"no-untyped-def": 2,
"override": 1
"no-untyped-def": 2
},
"app/modules/themoviedb/__init__.py": {
"arg-type": 5,
@@ -2145,7 +2112,7 @@
"empty-body": 1,
"index": 2,
"no-any-return": 4,
"no-untyped-call": 6,
"no-untyped-call": 5,
"no-untyped-def": 3,
"return-value": 2,
"type-arg": 19,
@@ -2291,7 +2258,7 @@
"app/modules/thetvdb/__init__.py": {
"empty-body": 1,
"no-any-return": 2,
"no-untyped-call": 2,
"no-untyped-call": 1,
"no-untyped-def": 4,
"type-arg": 2
},
@@ -2311,7 +2278,7 @@
"empty-body": 1,
"no-any-return": 1,
"no-redef": 2,
"no-untyped-call": 10,
"no-untyped-call": 9,
"no-untyped-def": 7,
"str-bytes-safe": 1,
"type-arg": 6
@@ -2333,7 +2300,7 @@
"assignment": 1,
"empty-body": 1,
"no-any-return": 3,
"no-untyped-call": 2,
"no-untyped-call": 1,
"no-untyped-def": 7,
"return": 1,
"type-arg": 2
@@ -2363,7 +2330,6 @@
"assignment": 1,
"empty-body": 1,
"no-any-return": 3,
"no-untyped-call": 1,
"no-untyped-def": 7,
"type-arg": 2
},
@@ -2383,7 +2349,6 @@
"assignment": 6,
"attr-defined": 1,
"empty-body": 1,
"no-untyped-call": 1,
"no-untyped-def": 3,
"type-arg": 4,
"union-attr": 1
@@ -2398,7 +2363,6 @@
"arg-type": 1,
"assignment": 1,
"empty-body": 1,
"no-untyped-call": 1,
"no-untyped-def": 2,
"type-arg": 1,
"union-attr": 1
@@ -2409,7 +2373,7 @@
"attr-defined": 1,
"empty-body": 1,
"no-any-return": 2,
"no-untyped-call": 3,
"no-untyped-call": 2,
"no-untyped-def": 5,
"type-arg": 4,
"union-attr": 4
@@ -2435,7 +2399,6 @@
"assignment": 3,
"empty-body": 1,
"no-any-return": 1,
"no-untyped-call": 1,
"no-untyped-def": 4,
"type-arg": 2,
"union-attr": 1
@@ -2453,7 +2416,6 @@
"arg-type": 3,
"assignment": 12,
"empty-body": 1,
"no-untyped-call": 1,
"no-untyped-def": 2,
"type-arg": 1
},
@@ -2653,7 +2615,7 @@
"app/runtime/reload.py": {
"misc": 1,
"no-untyped-call": 5,
"no-untyped-def": 6
"no-untyped-def": 5
},
"app/runtime/scheduling.py": {
"import-untyped": 1,
@@ -2668,7 +2630,6 @@
"app/runtime/state.py": {
"attr-defined": 2,
"no-any-return": 2,
"no-untyped-call": 1,
"no-untyped-def": 3,
"type-arg": 1
},

View File

@@ -504,9 +504,6 @@
"app/runtime/reload.py": {
"I001": 1
},
"app/runtime/state.py": {
"I001": 1
},
"app/schemas/common.py": {
"I001": 1
},
@@ -672,9 +669,6 @@
"tests/test_db_session_lifecycle.py": {
"I001": 1
},
"tests/test_docker_entrypoint_permissions.py": {
"I001": 1
},
"tests/test_docker_payload_contract.py": {
"I001": 1
},
@@ -928,9 +922,6 @@
"E402": 5,
"I001": 2
},
"tests/test_system_utils.py": {
"I001": 1
},
"tests/test_systemconfig_oper.py": {
"I001": 1
},

View File

@@ -10,6 +10,8 @@ from pathlib import Path
from types import ModuleType, SimpleNamespace
from unittest.mock import patch
import pytest
MODULE_PATH = Path(__file__).resolve().parents[1] / "app" / "cli.py"
@@ -20,6 +22,7 @@ class _DummySystemHelper:
def load_cli_module():
"""隔离加载 CLI,使用真实布尔配置形状验证启动更新决策。"""
with tempfile.TemporaryDirectory() as temp_dir:
root = Path(temp_dir)
settings = SimpleNamespace(
@@ -35,7 +38,8 @@ def load_cli_module():
PROXY_HOST="",
PIP_PROXY="",
GITHUB_TOKEN="",
MOVIEPILOT_AUTO_UPDATE="false",
MOVIEPILOT_AUTO_UPDATE=False,
MOVIEPILOT_UPDATE_DEV=False,
PROXY={},
REPO_GITHUB_HEADERS=lambda _repo: {},
)
@@ -95,8 +99,9 @@ def test_resolve_auto_update_targets_keeps_dev_branch_tracking():
def test_one_shot_dev_update_overrides_disabled_default():
"""一次性手动更新不受两个自动开关关闭的影响。"""
module = load_cli_module()
module.settings.MOVIEPILOT_AUTO_UPDATE = "false"
module.settings.MOVIEPILOT_AUTO_UPDATE = False
with patch.object(
module.SystemHelper, "consume_one_shot_dev_update", return_value=True
@@ -104,6 +109,16 @@ def test_one_shot_dev_update_overrides_disabled_default():
assert module._auto_update_mode() == "dev"
@pytest.mark.parametrize("auto_update", [True, False])
@pytest.mark.parametrize("update_dev", [True, False])
def test_dev_tracking_is_independent_of_automatic_checks(auto_update, update_dev):
"""检查开关不触发启动更新,Dev 开关单独选择开发分支。"""
module = load_cli_module()
module.settings.MOVIEPILOT_AUTO_UPDATE = auto_update
module.settings.MOVIEPILOT_UPDATE_DEV = update_dev
assert module._auto_update_mode() == ("dev" if update_dev else "false")
def test_release_mode_does_not_update_during_start():
module = load_cli_module()
with patch.object(module, "_auto_update_mode", return_value="release"), patch.object(

View File

@@ -1,6 +1,6 @@
from typing import Any
from app.runtime.config import settings
from app.runtime.config import Settings, settings
def test_update_float_setting_accepts_json_integer(monkeypatch) -> None:
@@ -38,3 +38,34 @@ def test_update_float_setting_accepts_json_integer(monkeypatch) -> None:
"original_value": 1,
"converted_value": 1.0,
}
def test_short_api_token_update_does_not_log_token(monkeypatch) -> None:
"""短 API_TOKEN 自动替换时日志不得包含令牌原文。"""
config = Settings(API_TOKEN="0123456789abcdef")
messages: list[str] = []
monkeypatch.setattr(Settings, "update_env_config", lambda *_args: (True, ""))
monkeypatch.setattr(
"app.runtime.config.logger.warning",
messages.append,
)
success, message = config.update_setting("API_TOKEN", "short-token")
assert success is True
assert message == ""
assert config.API_TOKEN != "short-token"
assert messages
assert "short-token" not in messages[0]
def test_rust_accel_update_uses_field_policy(monkeypatch) -> None:
"""free-threaded 运行时的 Rust 加速约束由字段策略执行。"""
config = Settings(RUST_ACCEL=True)
monkeypatch.setattr("app.runtime.config.is_free_threaded_runtime", lambda: True)
success, message = config.update_setting("RUST_ACCEL", False)
assert success is False
assert message == "free-threaded 运行时必须启用 Rust 加速"
assert config.RUST_ACCEL is True

View File

@@ -6,6 +6,8 @@ from dataclasses import replace
from pathlib import Path
from unittest.mock import Mock
import pytest
from app.application.configuration import SchedulerRuntimeConfig
from app.scheduler import catalog as scheduler_catalog
from app.scheduler import maintenance as scheduler_maintenance
@@ -58,6 +60,7 @@ def _config(**changes) -> SchedulerRuntimeConfig:
usage_statistic_share=False,
site_link=None,
auto_update=False,
auto_update_resource=False,
)
return replace(config, **changes)
@@ -74,8 +77,9 @@ def test_database_backup_schedule_only_watches_job_shape() -> None:
def test_auto_update_setting_is_hot_reloadable() -> None:
"""自动更新开关变更时应触发 Scheduler 重建。"""
"""主程序或资源开关变更时均应触发 Scheduler 重建。"""
assert "MOVIEPILOT_AUTO_UPDATE" in Scheduler.CONFIG_WATCH
assert "AUTO_UPDATE_RESOURCE" in Scheduler.CONFIG_WATCH
def test_disabled_database_backup_does_not_register_job() -> None:
@@ -108,8 +112,12 @@ def test_enabled_database_backup_registers_single_replaceable_job(monkeypatch) -
assert scheduler._scheduler.jobs["database_backup"]["replace_existing"] is True
def test_auto_update_check_is_registered_only_when_enabled(monkeypatch) -> None:
"""只有显式开启自动更新时才注册 Release 检查任务。"""
@pytest.mark.parametrize("auto_update", [False, True])
@pytest.mark.parametrize("auto_update_resource", [False, True])
def test_auto_update_check_is_registered_only_when_enabled(
monkeypatch, auto_update, auto_update_resource
) -> None:
"""任一开关开启即注册检查任务,均关闭则不注册。"""
scheduler = _scheduler()
scheduler._services = Mock()
background_scheduler = Mock()
@@ -120,20 +128,14 @@ def test_auto_update_check_is_registered_only_when_enabled(monkeypatch) -> None:
monkeypatch.setattr(scheduler, "init_agent_task_jobs", lambda: None)
monkeypatch.setattr(scheduler, "init_plugin_jobs", lambda: None)
scheduler_catalog.SchedulerCatalogOwner._initialize_catalog(scheduler, _config(auto_update=False))
assert not any(
call.kwargs.get("id") == "system_update_check"
for call in background_scheduler.add_job.call_args_list
scheduler_catalog.SchedulerCatalogOwner._initialize_catalog(
scheduler, _config(auto_update=auto_update, auto_update_resource=auto_update_resource)
)
assert "system_update_check" not in scheduler._jobs
background_scheduler.add_job.reset_mock()
scheduler_catalog.SchedulerCatalogOwner._initialize_catalog(scheduler, _config(auto_update=True))
assert any(
call.kwargs.get("id") == "system_update_check"
for call in background_scheduler.add_job.call_args_list
)
assert "system_update_check" in scheduler._jobs
) is (auto_update or auto_update_resource)
assert ("system_update_check" in scheduler._jobs) is (auto_update or auto_update_resource)
def test_scheduled_backup_uses_registered_database_governance(monkeypatch) -> None:

View File

@@ -1,5 +1,3 @@
import hashlib
import json
import os
import shlex
import subprocess
@@ -796,17 +794,27 @@ def test_updater_package_proxy_stays_command_scoped(tmp_path: Path) -> None:
@pytest.mark.parametrize(
("mode", "install_result", "expected"),
(("false", "unused", "noop"), ("dev", "success", "updated"), ("dev", "failure", "failed")),
("mode", "dev_update", "install_result", "expected"),
(
("false", "false", "unused", "noop"),
("true", "false", "unused", "noop"),
("false", "true", "success", "updated"),
("true", "True", "failure", "failed"),
("dev", "", "success", "updated"),
("dev", "false", "unused", "noop"),
("release", "", "unused", "noop"),
),
)
def test_updater_exposes_explicit_result(
tmp_path: Path, mode: str, install_result: str, expected: str
tmp_path: Path, mode: str, dev_update: str, install_result: str, expected: str
) -> None:
"""Docker 由独立 Dev 开关决定启动更新,并兼容首次迁移的旧模式。"""
script = textwrap.dedent(
f"""\
CONFIG_DIR="$1"
MOVIEPILOT_AUTO_UPDATE="$2"
INSTALL_RESULT="$3"
MOVIEPILOT_UPDATE_DEV="$4"
PIP_PROXY= PROXY_HOST= GITHUB_PROXY= GITHUB_TOKEN=
source {UPDATER!s}
INFO() {{ :; }}
@@ -827,7 +835,7 @@ def test_updater_exposes_explicit_result(
)
result = subprocess.run(
["bash", "-c", script, "updater-test", str(tmp_path / "config"), mode, install_result],
["bash", "-c", script, "updater-test", str(tmp_path / "config"), mode, install_result, dev_update],
text=True,
capture_output=True,
check=True,
@@ -836,130 +844,14 @@ def test_updater_exposes_explicit_result(
assert result.stdout == f"{expected}\n"
def test_prepared_release_is_verified_and_installed_without_release_lookup(tmp_path: Path) -> None:
config_dir = tmp_path / "config"
update_root = config_dir / "temp" / "moviepilot-update"
update_root.mkdir(parents=True)
backend = update_root / "backend.zip"
frontend = update_root / "frontend.zip"
backend.write_bytes(b"backend-package")
frontend.write_bytes(b"frontend-package")
backend_sha256 = hashlib.sha256(backend.read_bytes()).hexdigest()
frontend_sha256 = hashlib.sha256(frontend.read_bytes()).hexdigest()
(update_root / "install.json").write_text(
json.dumps(
{
"version": "v3.1.0",
"frontend_version": "v3.1.0",
"backend_archive": str(backend),
"frontend_archive": str(frontend),
"backend_sha256": backend_sha256,
"frontend_sha256": frontend_sha256,
}
),
encoding="utf-8",
)
release_probe = tmp_path / "release-probe"
script = textwrap.dedent(
f"""\
CONFIG_DIR="$1"
MOVIEPILOT_AUTO_UPDATE=release
PIP_PROXY= PROXY_HOST= GITHUB_PROXY= GITHUB_TOKEN=
RELEASE_PROBE="$2"
source {UPDATER!s}
INFO() {{ :; }}
WARN() {{ :; }}
ERROR() {{ :; }}
test_connectivity_github() {{ touch "${{RELEASE_PROBE}}"; return 1; }}
install_backend_and_download_resources() {{
test "${{MOVIEPILOT_PREPARED_UPDATE}}" = true
test "$1" = tags/v3.1.0.zip
MOVIEPILOT_UPDATE_RESULT=updated
}}
run_moviepilot_update
printf '%s\n' "${{MOVIEPILOT_UPDATE_RESULT}}"
"""
)
result = subprocess.run(
["bash", "-c", script, "prepared-update-test", str(config_dir), str(release_probe)],
text=True,
capture_output=True,
check=True,
)
assert result.stdout == "updated\n"
assert not release_probe.exists()
assert not (update_root / "install.json").exists()
def test_prepared_resource_update_is_applied_without_backend_or_release_lookup(tmp_path: Path) -> None:
config_dir = tmp_path / "config"
update_root = config_dir / "temp" / "moviepilot-update"
resource_dir = update_root / "resources"
resource_dir.mkdir(parents=True)
resource_files = []
for name, content in (("user.sites.v3.bin", b"index"), ("sites.cpython-test.so", b"auth")):
path = resource_dir / name
path.write_bytes(content)
resource_files.append(
{
"name": name,
"path": str(path),
"sha256": hashlib.sha256(content).hexdigest(),
}
)
(update_root / "install.json").write_text(
json.dumps({"targets": ["resources"], "resource_files": resource_files}),
encoding="utf-8",
)
release_probe = tmp_path / "release-probe"
backend_probe = tmp_path / "backend-probe"
script = textwrap.dedent(
f"""\
CONFIG_DIR="$1"
MOVIEPILOT_AUTO_UPDATE=release
PIP_PROXY= PROXY_HOST= GITHUB_PROXY= GITHUB_TOKEN=
RELEASE_PROBE="$2"
BACKEND_PROBE="$3"
source {UPDATER!s}
INFO() {{ :; }}
WARN() {{ :; }}
ERROR() {{ :; }}
test_connectivity_github() {{ touch "${{RELEASE_PROBE}}"; return 1; }}
install_backend_and_download_resources() {{ touch "${{BACKEND_PROBE}}"; return 1; }}
apply_prepared_resources() {{ test "${{MOVIEPILOT_PREPARED_UPDATE}}" = true; return 0; }}
run_moviepilot_update
printf '%s\\n' "${{MOVIEPILOT_UPDATE_RESULT}}"
"""
)
result = subprocess.run(
[
"bash",
"-c",
script,
"prepared-resource-update-test",
str(config_dir),
str(release_probe),
str(backend_probe),
],
text=True,
capture_output=True,
check=True,
)
assert result.stdout == "noop\n"
assert not release_probe.exists()
assert not backend_probe.exists()
assert not (update_root / "install.json").exists()
def test_release_mode_no_longer_checks_or_installs_during_restart(
tmp_path: Path,
) -> None:
"""Release 模式只能消费准备清单,不得保留启动时查版本的旧实现。"""
"""非 Dev 模式不再由 update.sh 查版本或替换已下载程序。"""
updater = UPDATER.read_text(encoding="utf-8")
assert "install.json" not in updater
assert "MOVIEPILOT_PREPARED_UPDATE" not in updater
assert "apply_prepared" not in updater
for retired_function in (
"fetch_latest_v3_release",
"compare_versions",
@@ -1027,13 +919,29 @@ def test_entrypoint_delegates_restart_to_external_supervisor() -> None:
assert "docker_http_proxy" not in entrypoint
assert "/var/run/docker.sock" not in entrypoint
assert "docker_http_proxy" not in dockerfile
assert "exec /usr/bin/supervisord -n" in entrypoint
assert "/usr/bin/supervisord -n -c /etc/supervisor/supervisord.conf" in entrypoint
assert "run_pending_dev_update_after_supervisor_shutdown" in entrypoint
assert "apply_pending_release_update_at_startup" in entrypoint
assert "-m app.cli apply-prepared-update" in entrypoint
assert "supervisor_exit_code=$?" in entrypoint
assert "supervisor" in dockerfile
assert "[program:moviepilot-nginx]" in supervisor
assert "[program:moviepilot-backend]" in supervisor
assert "[program:moviepilot-update-worker]" in supervisor
assert "user=root" in supervisor
assert "-name '*.sh' ! -name 'launcher.sh'" in dockerfile
assert supervisor.count("autorestart=true") == 2
def test_release_update_worker_applies_before_supervisor_shutdown() -> None:
"""Release worker 必须先调用后端安装器,再关闭 supervisor 触发入口重载。"""
worker = (ROOT / "docker" / "update-worker.sh").read_text(encoding="utf-8")
assert "-m app.cli apply-prepared-update" in worker
assert "supervisorctl -c \"${SUPERVISOR_CONFIG}\" shutdown" in worker
assert worker.index("apply-prepared-update") < worker.index("shutdown")
@pytest.mark.parametrize(
("pyproject_changed", "lock_changed", "expected_route_calls", "expected_sync_calls"),
(

View File

@@ -3,7 +3,6 @@ import subprocess
import textwrap
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
@@ -588,7 +587,13 @@ def test_supervisor_manages_backend_and_nginx() -> None:
assert "supervisord -n" in entrypoint
assert "[program:moviepilot-nginx]" in supervisor
assert "[program:moviepilot-backend]" in supervisor
assert "[program:moviepilot-update-worker]" in supervisor
assert "command=/bin/bash /usr/local/lib/moviepilot/control/update-worker.sh" in supervisor
assert "user=root" in supervisor
assert "file=/run/moviepilot/supervisor.sock" in supervisor
assert "chmod=0770" in supervisor
assert "chown=root:moviepilot" in supervisor
assert "username=moviepilot" in supervisor
assert supervisor.count("password=%(ENV_MOVIEPILOT_SUPERVISOR_PASSWORD)s") == 2
assert "openssl rand -hex 32" in entrypoint
assert supervisor.count("autorestart=true") == 2

View File

@@ -1,5 +1,7 @@
from types import SimpleNamespace
import pytest
from app.api.endpoints.transfer import (
manual_transfer as manual_transfer_endpoint,
)
@@ -210,6 +212,86 @@ def test_history_endpoint_reorganize_uses_chain_cleanup(monkeypatch):
assert captured["cleanup_dest_fileitem"] is None
@pytest.mark.parametrize("accepted", [True, False])
@pytest.mark.parametrize("background", [True, False])
def test_failed_history_manual_auto_uses_durable_retry(monkeypatch, accepted, background):
"""历史入口选择自动识别时仍须检查失败任务,不能绕过调度器重新准入。"""
chain = make_transfer_chain()
fileitem = make_fileitem("/downloads/Test.Show.S01E01.mkv")
history = SimpleNamespace(
id=14,
transfer_task_id="transfer-task-14",
status=False,
mode="copy",
src_fileitem=fileitem.model_dump(),
dest_fileitem=None,
download_hash=None,
downloader=None,
)
planned, deleted, retries = [], [], []
_patch_transfer_planning(monkeypatch, chain, fileitem, history, planned, deleted)
monkeypatch.setattr("app.api.endpoints.transfer.TransferChain", lambda: chain)
def request_retry(record, *, requested_by):
"""记录旧任务重试,模拟调度器接受或拒绝请求。"""
retries.append((record.transfer_task_id, requested_by))
return accepted, "已提交重试" if accepted else "任务需要人工处理"
def reject_new_admission(task):
"""模拟旧任务仍占用源路径时,新规划输入必然冲突。"""
raise AssertionError(f"旧任务重试不应重新准入:{task.fileitem.path}")
monkeypatch.setattr(chain, "_request_durable_transfer_retry", request_retry)
monkeypatch.setattr(chain, "put_to_queue", reject_new_admission)
response = manual_transfer_endpoint(
transer_item=ManualTransferItem(logid=history.id, from_history=False),
background=background,
history_query=SimpleNamespace(get=lambda _history_id: history),
_="token",
)
assert response.success is accepted
assert retries == [(history.transfer_task_id, "manual_reorganize")]
assert planned == []
assert deleted == []
if not accepted:
assert "任务需要人工处理" in response.message
@pytest.mark.parametrize("status", [True, False])
def test_manual_history_auto_preserves_legacy_retry_and_success_force(monkeypatch, status):
"""旧版失败历史仍清理后重试,成功历史保留原有强制整理行为。"""
chain = make_transfer_chain()
fileitem = make_fileitem("/downloads/Test.Show.S01E01.mkv")
history = SimpleNamespace(
id=15,
status=status,
mode="copy",
src=fileitem.path,
src_storage=fileitem.storage,
src_fileitem=fileitem.model_dump(),
dest_fileitem=None,
download_hash=None,
downloader=None,
)
planned, deleted = [], []
_patch_transfer_planning(monkeypatch, chain, fileitem, history, planned, deleted)
monkeypatch.setattr("app.api.endpoints.transfer.TransferChain", lambda: chain)
chain.transfer_execution_repository = None
response = manual_transfer_endpoint(
transer_item=ManualTransferItem(logid=history.id, from_history=False),
background=False,
history_query=SimpleNamespace(get=lambda _history_id: history),
_="token",
)
assert response.success is True
assert planned == [fileitem.path]
assert deleted == ([] if status else [("history", history.id)])
def test_success_history_directory_query_excludes_failed_and_siblings():
"""目录历史查询应限定路径边界,并且只返回成功记录。"""
transfer_history_oper = _history_repository()

View File

@@ -0,0 +1,443 @@
"""MediaVault 自建媒体库客户端的行为契约,全部走假 API 不发真实请求。"""
from pathlib import Path
from typing import Optional
import pytest
from app.modules.mediavault.api import Result
from app.modules.mediavault.mediavault import MediaVault
from app.schemas.mediaserver import RefreshMediaItem
from app.schemas.types import MediaSource, MediaType
class _FakeApi:
"""按路径返回预置数据,并记录调用参数。"""
def __init__(self, routes: dict, host: str = "http://mv.local"):
self.routes = routes
self.calls = []
self.closed = False
self._host = host
@property
def configured(self) -> bool:
return True
def close(self) -> None:
self.closed = True
def image_url(self, item_id: str, image_type: str, host: Optional[str] = None) -> str:
return f"{host or self._host}/api/v1/media-library/items/{item_id}/image/{image_type}?api_key=k"
def request(self, api, method=None, params=None, data=None, base_path=None, suppress_log=False):
self.calls.append({"api": api, "method": method, "params": params or {}, "data": data,
"base_path": base_path})
handler = self.routes.get(api)
if handler is None:
return Result(False, None, "not found", 404)
return handler(params or {}, data) if callable(handler) else handler
def _client(routes: dict, **kwargs) -> MediaVault:
"""构造一个绕过网络探测的客户端。"""
client = MediaVault.__new__(MediaVault)
client._host = "http://mv.local"
client._playhost = kwargs.get("play_host")
client._apikey = "k"
client._sync_libraries = kwargs.get("sync_libraries") or []
client._api = _FakeApi(routes)
client._active = True
return client
def _item_row(index: int, kind: str = "Movie", **extra) -> dict:
row = {"id": f"id-{index}", "library_id": "lib-1", "parent_id": "", "kind": kind,
"title": f"影片{index}", "year": 2020, "tmdb_id": 1000 + index, "overview": "",
"genres": [], "has_poster": True, "has_backdrop": False, "season": 0, "episode": 0,
"duration_ticks": 0, "is_missing": False, "metadata_info": {}, "user_data": {}}
row.update(extra)
return row
def _paged_items(total_rows: list):
"""按 page/page_size 切分预置条目,模拟 MediaVault 的分页语义。"""
def handler(params, _data):
page = int(params.get("page", 1))
size = int(params.get("page_size", 40))
start = (page - 1) * size
return Result(True, {"items": total_rows[start:start + size], "total": len(total_rows)})
return handler
# ── 分页 ────────────────────────────────────────────────────────────
@pytest.mark.parametrize("limit", [1, 30, 100, 130, 250, 356, 400])
def test_get_items_limit_matches_full_scan_prefix(limit):
"""限量遍历的结果必须是全量遍历的前缀,不重复也不跳条。"""
rows = [_item_row(i) for i in range(356)]
client = _client({"/items": _paged_items(rows)})
full = [item.item_id for item in client.get_items("lib-1")]
assert len(full) == len(set(full)) == 356
client = _client({"/items": _paged_items(rows)})
got = [item.item_id for item in client.get_items("lib-1", limit=limit)]
assert got == full[:limit]
@pytest.mark.parametrize("start_index", [0, 30, 100, 130, 250])
def test_get_items_start_index_matches_full_scan_slice(start_index):
"""起始偏移不是页大小整数倍时,也必须精确对齐到全量切片。"""
rows = [_item_row(i) for i in range(356)]
full = [item.item_id for item in _client({"/items": _paged_items(rows)}).get_items("lib-1")]
client = _client({"/items": _paged_items(rows)})
got = [item.item_id for item in client.get_items("lib-1", start_index=start_index, limit=20)]
assert got == full[start_index:start_index + 20]
def test_get_items_always_requests_full_pages():
"""页大小恒为上限,页码才能稳定换算成偏移量。"""
rows = [_item_row(i) for i in range(250)]
client = _client({"/items": _paged_items(rows)})
list(client.get_items("lib-1", limit=130))
sizes = {call["params"]["page_size"] for call in client._api.calls}
pages = [call["params"]["page"] for call in client._api.calls]
assert sizes == {MediaVault.PAGE_LIMIT}
assert pages == [1, 2]
def test_get_items_stops_when_request_fails():
"""中途请求失败时停止产出,不把失败当成遍历结束的空库。"""
rows = [_item_row(i) for i in range(150)]
calls = {"n": 0}
def flaky(params, _data):
calls["n"] += 1
if calls["n"] > 1:
return None
return _paged_items(rows)(params, None)
client = _client({"/items": flaky})
assert len([*client.get_items("lib-1")]) == 100
# ── 媒体库与统计 ────────────────────────────────────────────────────
def test_get_librarys_maps_type_and_builds_image_url():
"""媒体库类型按 MediaVault 的 library_type 映射,封面走带鉴权的图片直链。"""
routes = {
"/libraries": Result(True, {"items": [
{"id": "lib-1", "name": "电影库", "library_type": "movies", "root_paths": ["/mnt/movies"]},
{"id": "lib-2", "name": "剧集库", "library_type": "tvshows", "root_path": "/mnt/tv"},
{"id": "lib-3", "name": "未知库", "library_type": "other", "root_paths": []},
]}),
"/items": _paged_items([_item_row(0)]),
}
libraries = _client(routes).get_librarys()
assert [lib.type for lib in libraries] == [
MediaType.MOVIE.value, MediaType.TV.value, MediaType.UNKNOWN.value
]
assert libraries[0].path == ["/mnt/movies"]
assert libraries[1].path == "/mnt/tv"
assert libraries[0].image.endswith("/items/lib-1/image/primary?api_key=k")
assert libraries[0].server_type == "mediavault"
def test_get_librarys_hidden_respects_sync_selection():
"""开启过滤时只保留已勾选同步的媒体库。"""
routes = {
"/libraries": Result(True, {"items": [
{"id": "lib-1", "name": "A", "library_type": "movies"},
{"id": "lib-2", "name": "B", "library_type": "movies"},
]}),
"/items": _paged_items([]),
}
client = _client(routes, sync_libraries=["lib-2"])
assert [lib.id for lib in client.get_librarys(hidden=True)] == ["lib-2"]
assert [lib.id for lib in client.get_librarys(hidden=False)] == ["lib-1", "lib-2"]
def test_get_librarys_returns_none_when_unreachable():
"""连接失败返回 None,与"媒体库为空"区分开。"""
assert _client({"/libraries": None}).get_librarys() is None
def test_get_medias_count_maps_statistics_fields():
"""统计接口字段映射到 MoviePilot 的统计模型。"""
routes = {"/statistics": Result(True, {"movie_count": 3030, "series_count": 1501,
"episode_count": 69597, "item_count": 74128})}
statistic = _client(routes).get_medias_count()
assert (statistic.movie_count, statistic.tv_count, statistic.episode_count) == (3030, 1501, 69597)
def test_get_items_count_reads_total_not_page_length():
"""条目总数取分页返回的 total,不受页大小影响。"""
rows = [_item_row(i) for i in range(356)]
client = _client({"/items": _paged_items(rows)})
assert client.get_items_count("lib-1") == 356
# ── 存在性判断 ──────────────────────────────────────────────────────
def test_get_movies_filters_by_title_year_and_identity():
"""电影匹配要求标题全等、年份一致且媒体身份不冲突。"""
rows = [
_item_row(1, title="沙丘", year=2021, tmdb_id=438631),
_item_row(2, title="沙丘", year=2024, tmdb_id=693134),
_item_row(3, title="沙丘前传", year=2021, tmdb_id=111),
]
client = _client({"/items": _paged_items(rows)})
assert [m.item_id for m in client.get_movies(title="沙丘")] == ["id-1", "id-2"]
client = _client({"/items": _paged_items(rows)})
assert [m.item_id for m in client.get_movies(title="沙丘", year="2021")] == ["id-1"]
client = _client({"/items": _paged_items(rows)})
matched = client.get_movies(title="沙丘", media_source=MediaSource.TMDB, media_id="693134")
assert [m.item_id for m in matched] == ["id-2"]
def test_get_movies_requests_movie_kind_only():
"""存在性查询按类型收窄,避免剧集与分集混进电影结果。"""
client = _client({"/items": _paged_items([])})
client.get_movies(title="沙丘")
assert client._api.calls[0]["params"]["kinds"] == "Movie"
assert client._api.calls[0]["params"]["keyword"] == "沙丘"
def test_get_tv_episodes_by_item_id_returns_season_map():
"""按条目 ID 查询直接返回季集映射。"""
routes = {
"/items/series-1": Result(True, _item_row(1, kind="Series", title="剧A", tmdb_id=99)),
"/items/series-1/episodes": Result(True, {"seasons": {"1": [1, 2, 3], "2": [1]}}),
}
item_id, seasons = _client(routes).get_tv_episodes(item_id="series-1")
assert item_id == "series-1"
assert seasons == {1: [1, 2, 3], 2: [1]}
def test_get_tv_episodes_filters_requested_season():
"""指定季号时只返回该季。"""
routes = {
"/items/series-1": Result(True, _item_row(1, kind="Series")),
"/items/series-1/episodes": Result(True, {"seasons": {"1": [1, 2], "2": [1]}}),
}
_, seasons = _client(routes).get_tv_episodes(item_id="series-1", season=2)
assert seasons == {2: [1]}
def test_get_tv_episodes_falls_back_to_title_when_cached_id_is_stale():
"""缓存的条目 ID 失效时退回按标题重新定位,不误判整部剧缺失。"""
routes = {
"/items/stale-id": Result(False, None, "not found", 404),
"/items": _paged_items([_item_row(7, kind="Series", title="剧A", year=2020)]),
"/items/id-7/episodes": Result(True, {"seasons": {"1": [1, 2]}}),
}
item_id, seasons = _client(routes).get_tv_episodes(item_id="stale-id", title="剧A", year="2020")
assert item_id == "id-7"
assert seasons == {1: [1, 2]}
def test_get_tv_episodes_returns_empty_when_series_absent():
"""剧集不在库中返回空季集:与 Emby 一致用 (None, {}) 表示"查得到但没有"。"""
routes = {"/items": _paged_items([])}
assert _client(routes).get_tv_episodes(title="不存在的剧") == (None, {})
def test_get_tv_episodes_returns_none_when_unreachable():
"""服务不可达时返回 None,避免被当成"这部剧一集都没有"。"""
routes = {"/items": lambda params, data: None}
assert _client(routes).get_tv_episodes(title="剧A") == (None, None)
def test_get_season_episode_ids_maps_episode_number_to_item_id():
"""季集条目 ID 映射先定位季,再遍历该季的分集。"""
def items(params, _data):
if params.get("kinds") == "Season":
return Result(True, {"items": [_item_row(1, kind="Season", season=1),
_item_row(2, kind="Season", season=2)], "total": 2})
if params.get("parent_id") == "id-2":
return Result(True, {"items": [_item_row(10, kind="Episode", season=2, episode=1),
_item_row(11, kind="Episode", season=2, episode=2)],
"total": 2})
return Result(True, {"items": [], "total": 0})
assert _client({"/items": items}).get_season_episode_ids("series-1", 2) == {
1: "id-10", 2: "id-11",
}
def test_get_season_episode_ids_returns_empty_for_missing_season():
"""季不存在时返回空映射。"""
client = _client({"/items": _paged_items([_item_row(1, kind="Season", season=1)])})
assert client.get_season_episode_ids("series-1", 9) == {}
# ── 条目转换 ────────────────────────────────────────────────────────
def test_iteminfo_extracts_identity_and_path_from_sources():
"""条目详情带媒体源时取文件路径,身份按 ProviderIds 优先级解析。"""
row = _item_row(1, tmdb_id=0, metadata_info={"original_title": "Dune",
"external_ids": {"imdb_id": "tt1160419"}},
sources=[{"id": "s1", "path": "/mnt/movies/Dune/Dune.mkv"}])
client = _client({"/items/id-1": Result(True, row)})
item = client.get_iteminfo("id-1")
assert item.media_source == MediaSource.IMDb
assert item.media_id == "tt1160419"
assert item.original_title == "Dune"
assert item.path == "/mnt/movies/Dune/Dune.mkv"
def test_iteminfo_prefers_tmdb_over_other_providers():
"""同时有 TMDB 与 IMDb 时按统一优先级取 TMDB。"""
row = _item_row(1, tmdb_id=438631, metadata_info={"external_ids": {"imdb_id": "tt1160419"}})
item = _client({"/items/id-1": Result(True, row)}).get_iteminfo("id-1")
assert (item.media_source, item.media_id) == (MediaSource.TMDB, "438631")
def test_iteminfo_returns_none_for_missing_item():
"""条目不存在返回 None。"""
assert _client({}).get_iteminfo("nope") is None
# ── 展示与图片 ──────────────────────────────────────────────────────
def test_get_resume_builds_episode_subtitle_and_percent():
"""继续观看的分集用剧名做标题,进度按播放位置换算。"""
row = _item_row(1, kind="Episode", season=2, episode=5, title="第五集",
series_id="series-1", series_name="剧A",
duration_ticks=1000, user_data={"position_ticks": 250})
client = _client({"/items": _paged_items([row])})
played = client.get_resume(num=5)[0]
assert played.title == "剧A"
assert played.subtitle == "S2:5 - 第五集"
assert played.type == MediaType.TV.value
assert played.percent == 25.0
# 分集海报取所属剧集,避免每集一张缩略图
assert "/items/series-1/image/primary" in played.image
def test_get_latest_backdrops_fills_up_to_requested_count():
"""没有背景图的条目不占名额,取满请求数量为止。"""
rows = [_item_row(i, has_backdrop=(i % 3 == 0)) for i in range(60)]
client = _client({"/items": _paged_items(rows)})
assert len(client.get_latest_backdrops(num=10)) == 10
def test_get_latest_backdrops_uses_play_host_when_remote():
"""外网场景改用播放地址拼图片链接。"""
rows = [_item_row(0, has_backdrop=True)]
client = _client({"/items": _paged_items(rows)}, play_host="https://mv.example.com")
assert client.get_latest_backdrops(num=1, remote=True)[0].startswith("https://mv.example.com")
assert client.get_latest_backdrops(num=1, remote=False)[0].startswith("http://mv.local")
# ── 入库刷新 ────────────────────────────────────────────────────────
def test_refresh_library_by_items_scans_only_matched_libraries():
"""入库路径命中哪个媒体库就只扫哪个,同一媒体库不重复排队。"""
routes = {
"/libraries": Result(True, {"items": [
{"id": "lib-1", "name": "电影", "root_paths": ["/mnt/movies"]},
{"id": "lib-2", "name": "剧集", "root_paths": ["/mnt/tv"]},
]}),
"/libraries/lib-1/scan-task": Result(True, {}),
"/libraries/lib-2/scan-task": Result(True, {}),
}
client = _client(routes)
assert client.refresh_library_by_items([
RefreshMediaItem(title="A", target_path=Path("/mnt/movies/A (2020)")),
RefreshMediaItem(title="B", target_path=Path("/mnt/movies/B (2021)")),
]) is True
scanned = [call["api"] for call in client._api.calls if call["api"].endswith("scan-task")]
assert scanned == ["/libraries/lib-1/scan-task"]
def test_refresh_library_by_items_falls_back_to_full_scan_when_unmatched():
"""路径落在所有媒体库之外时退回全库扫描,避免新片一直不入库。"""
routes = {
"/libraries": Result(True, {"items": [{"id": "lib-1", "root_paths": ["/mnt/movies"]}]}),
"/libraries/lib-1/scan-task": Result(True, {}),
}
client = _client(routes)
assert client.refresh_library_by_items([
RefreshMediaItem(title="C", target_path=Path("/data/other/C")),
]) is True
assert [call["api"] for call in client._api.calls if "scan-task" in call["api"]] == [
"/libraries/lib-1/scan-task"
]
def test_refresh_library_by_items_returns_none_when_unreachable():
"""媒体库列表拿不到时返回 None,交由上层判定为服务不可用。"""
client = _client({"/libraries": None})
assert client.refresh_library_by_items([RefreshMediaItem(title="A", target_path=Path("/x"))]) is None
def test_refresh_root_library_queues_every_library():
"""全库刷新对每个媒体库各排一次后台扫描。"""
routes = {
"/libraries": Result(True, {"items": [{"id": "lib-1"}, {"id": "lib-2"}]}),
"/libraries/lib-1/scan-task": Result(True, {}),
"/libraries/lib-2/scan-task": Result(True, {}),
}
client = _client(routes)
assert client.refresh_root_library() is True
assert [call["api"] for call in client._api.calls if "scan-task" in call["api"]] == [
"/libraries/lib-1/scan-task", "/libraries/lib-2/scan-task",
]
assert all(call["method"] == "post" for call in client._api.calls if "scan-task" in call["api"])
# ── 连接与认证 ──────────────────────────────────────────────────────
def test_reconnect_marks_inactive_when_credentials_rejected():
"""凭据被拒时标记为失活,交给定时重连重试。"""
client = _client({"/libraries": Result(False, None, "unauthorized", 401)})
assert client.reconnect() is False
assert client.is_inactive() is True
assert client.is_authenticated() is False
def test_unconfigured_client_never_reports_inactive():
"""配置不完整的实例不参与重连,避免定时任务空转。"""
client = _client({})
client._apikey = None
assert client.is_configured() is False
assert client.is_inactive() is False
assert client.reconnect() is False
def test_authenticate_posts_to_user_auth_and_returns_token():
"""用户认证走 MediaVault 账号体系,返回访问令牌。"""
routes = {"/login": Result(True, {"access_token": "jwt-token", "token": "legacy"})}
client = _client(routes)
assert client.authenticate("someone", "secret") == "jwt-token"
call = client._api.calls[0]
assert (call["base_path"], call["method"]) == ("/api/v1/user-auth", "post")
assert call["data"] == {"username": "someone", "password": "secret"}
def test_authenticate_returns_none_on_rejection():
"""认证失败返回 None,不把错误响应当成令牌。"""
assert _client({"/login": Result(False, None, "bad credentials", 401)}).authenticate("a", "b") is None
assert _client({}).authenticate("", "") is None
def test_disconnect_closes_session():
"""断开时释放底层会话。"""
client = _client({})
client.disconnect()
assert client._api.closed is True
assert client.is_authenticated() is False

View File

@@ -583,7 +583,7 @@ from app.runtime.extensions.module.adapter import (
registry = build_host_module_registry()
specs = registry.list_specs()
assert len(specs) == 40
assert len(specs) == 41
adapter = HostModuleAdapter()
lifecycle_events = []
@@ -630,7 +630,7 @@ from app.schemas.types import EventType
registry = build_host_module_registry()
specs = registry.list_specs()
assert len(specs) == 40
assert len(specs) == 41
spec_by_id = {spec.id: spec for spec in specs}
events = {spec.id: [] for spec in specs}
@@ -797,7 +797,7 @@ from app.runtime.extensions.module.adapter import (
registry = build_host_module_registry()
specs = registry.list_specs()
assert len(specs) == 40
assert len(specs) == 41
configured_specs = tuple(
spec for spec in specs
if spec.activation is ActivationPolicy.WHEN_CONFIGURED
@@ -893,12 +893,12 @@ from app.application.module import configure_module_runtime
configure_module_runtime(lambda: ModuleManager())
manager = ModuleManager()
assert len(manager.list_specs()) == 40
assert len(manager.list_specs()) == 41
assert manager.get_specs() == manager.list_specs()
from app.api.endpoints.system import modulelist
response = modulelist(None)
assert len(response.data["modules"]) == 40
assert len(response.data["modules"]) == 41
heavy_prefixes = (
"lark_oapi",
@@ -1007,7 +1007,7 @@ from app.runtime.extensions.module.manager import ModuleManager
manager = ModuleManager()
modules = manager.get_modules()
assert len(modules) == len(manager.list_specs()) == 40
assert len(modules) == len(manager.list_specs()) == 41
for spec in manager.list_specs():
implementation = modules[spec.id]
assert implementation.get_name() == spec.metadata["name"]

View File

@@ -103,17 +103,17 @@ def test_music_rename_context_contains_audio_fields():
assert context["fileExt"] == ".flac"
def test_music_rename_prefers_track_meta_over_album_media():
"""专辑整理时应使用每个文件的曲名和曲序,不能把专辑名写成所有目标文件名。"""
def test_music_rename_uses_album_identity_and_track_meta():
"""专辑整理应采用所选专辑身份,同时保留每个文件的曲名和曲序。"""
meta = MetaMusic(
org_string="10. 明天晴天.m4a",
title="明天晴天",
artists=["孙燕姿"],
album="完美的一天",
album_artist="孙燕姿",
year=2005,
album="错误专辑·全精选集",
album_artist="错误艺术家(资源发布者)",
year=1999,
track_number=10,
total_tracks=11,
total_tracks=99,
)
album = MusicInfo(
media_source="musicbrainz",
@@ -137,6 +137,9 @@ def test_music_rename_prefers_track_meta_over_album_media():
assert context["title"] == "明天晴天"
assert context["track"] == "10"
assert context["album"] == "完美的一天"
assert context["album_artist"] == "孙燕姿"
assert context["year"] == 2005
assert rendered == "孙燕姿/完美的一天 (2005)/10 - 明天晴天.m4a"

View File

@@ -24,10 +24,82 @@ def _manager(monkeypatch, tmp_path: Path):
return manager
def _docker_manager(monkeypatch, tmp_path: Path):
"""创建指向隔离 Docker 目录的更新管理器。"""
runtime_settings = {
"TEMP_PATH": tmp_path / "config" / "temp",
"ROOT_PATH": tmp_path / "app",
"FRONTEND_PATH": tmp_path / "public",
"VENV_PATH": tmp_path / "venv",
"UV_BIN": tmp_path / "uv",
"MOVIEPILOT_AUTO_UPDATE": False,
"AUTO_UPDATE_RESOURCE": True,
"PIP_PROXY": "",
"PROXY_HOST": "",
}
monkeypatch.setattr(
update_module,
"get_runtime_setting",
lambda key: runtime_settings[key],
)
monkeypatch.setattr(update_module, "is_docker", lambda: True)
manager = object.__new__(update_module.SystemUpdateManager)
manager._lock = threading.RLock()
manager._download_active = False
manager._active_target = None
return manager
def _response(payload, status_code=200):
return SimpleNamespace(status_code=status_code, json=lambda: payload)
def test_status_reads_live_auto_update_setting_without_discarding_cached_update(monkeypatch, tmp_path):
"""切换提醒设置立即反映到状态,缓存版本仍供手动升级使用。"""
manager = _manager(monkeypatch, tmp_path)
manager._write_state(state="available", version="v3.1.0", can_update=True)
for enabled in (True, False, True):
monkeypatch.setattr(
update_module, "get_runtime_setting",
lambda key: tmp_path if key == "TEMP_PATH" else enabled,
)
status = manager.get_status()
assert status.auto_update is enabled
assert status.state == "available"
assert status.version == "v3.1.0"
assert status.can_update is True
@pytest.mark.parametrize("auto_update", [False, True])
@pytest.mark.parametrize("auto_update_resource", [False, True])
def test_scheduled_check_respects_independent_switches(
monkeypatch, tmp_path, auto_update, auto_update_resource
):
"""自动检查只访问已开启的目标;手动检查仍可访问两类更新。"""
manager = _manager(monkeypatch, tmp_path)
values = {
"TEMP_PATH": tmp_path,
"MOVIEPILOT_AUTO_UPDATE": auto_update,
"AUTO_UPDATE_RESOURCE": auto_update_resource,
}
monkeypatch.setattr(update_module, "get_runtime_setting", values.get)
checked = []
monkeypatch.setattr(manager, "_check_application", lambda: checked.append("application"))
monkeypatch.setattr(manager, "_check_resources", lambda: checked.append("resources"))
status = manager.check_scheduled()
assert checked == [
target for target, enabled in (("application", auto_update), ("resources", auto_update_resource))
if enabled
]
assert status.auto_update is auto_update
assert status.auto_update_resource is auto_update_resource
checked.clear()
manager.check()
assert checked == ["application", "resources"]
def test_check_exposes_new_stable_release(monkeypatch, tmp_path):
manager = _manager(monkeypatch, tmp_path)
logs = []
@@ -342,3 +414,125 @@ def test_cancel_install_returns_prepared_update_to_ready(monkeypatch, tmp_path):
assert status.can_install is True
assert status.error == "restart failed"
assert not manager._install_file.exists()
def test_apply_prepared_application_replaces_docker_payload_and_preserves_plugins(
monkeypatch, tmp_path
):
"""Docker root worker 应替换前后端目录,同时保留运行时插件和站点资源。"""
manager = _docker_manager(monkeypatch, tmp_path)
app_dir = manager._docker_app_dir
public_dir = manager._docker_public_dir
plugin_dir = app_dir / "app" / "plugins"
resource_dir = app_dir / "app" / "application" / "site"
plugin_dir.mkdir(parents=True)
resource_dir.mkdir(parents=True)
public_dir.mkdir()
(plugin_dir / "__init__.py").write_text("# compatibility\n", encoding="utf-8")
(plugin_dir / "local_plugin.py").write_text("local\n", encoding="utf-8")
(resource_dir / "user.sites.v3.bin").write_text("old-resource\n", encoding="utf-8")
(app_dir / "old.py").write_text("old\n", encoding="utf-8")
(app_dir / "pyproject.toml").write_text("old-project\n", encoding="utf-8")
(app_dir / "uv.lock").write_text("old-lock\n", encoding="utf-8")
(public_dir / "index.html").write_text("old-front\n", encoding="utf-8")
manager._root.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(manager._backend_archive, "w") as archive:
archive.writestr(
"MoviePilot-v3.1.0/version.py",
"APP_VERSION = 'v3.1.0'\nFRONTEND_VERSION = 'v3.1.0'\n",
)
archive.writestr("MoviePilot-v3.1.0/pyproject.toml", "[project]\n")
archive.writestr("MoviePilot-v3.1.0/uv.lock", "version = 1\n")
archive.writestr("MoviePilot-v3.1.0/new.py", "new\n")
with zipfile.ZipFile(manager._frontend_archive, "w") as archive:
archive.writestr("dist/index.html", "new-front\n")
archive.writestr("dist/version.txt", "v3.1.0\n")
prepared = {
"targets": ["application"],
"version": "v3.1.0",
"frontend_version": "v3.1.0",
"backend_archive": str(manager._backend_archive),
"frontend_archive": str(manager._frontend_archive),
"backend_sha256": manager._sha256(manager._backend_archive),
"frontend_sha256": manager._sha256(manager._frontend_archive),
}
(manager._root / "prepared.json").write_text(
json.dumps(prepared), encoding="utf-8"
)
manager._install_file.write_text(json.dumps(prepared), encoding="utf-8")
sync_calls = []
monkeypatch.setattr(
manager,
"_sync_docker_dependencies",
lambda project_dir, **kwargs: sync_calls.append((project_dir, kwargs)),
)
success, message = manager.apply_prepared_update()
assert success is True
assert message == "已下载的更新已替换到 Docker 程序目录"
assert len(sync_calls) == 1
assert sync_calls[0][0].name == "App"
assert sync_calls[0][1] == {}
assert (app_dir / "new.py").read_text(encoding="utf-8") == "new\n"
assert not (app_dir / "old.py").exists()
assert (app_dir / "app" / "plugins" / "local_plugin.py").exists()
assert (resource_dir / "user.sites.v3.bin").read_text(encoding="utf-8") == "old-resource\n"
assert (public_dir / "index.html").read_text(encoding="utf-8") == "new-front\n"
assert not manager._install_file.exists()
assert not (manager._root / "prepared.json").exists()
assert not manager._docker_pending_file.exists()
assert not manager._docker_previous_app_dir.exists()
assert not manager._docker_previous_public_dir.exists()
def test_apply_prepared_resources_replaces_complete_docker_resource_package(
monkeypatch, tmp_path
):
"""Docker root worker 应原子替换完整站点资源包而不触碰主程序目录。"""
manager = _docker_manager(monkeypatch, tmp_path)
monkeypatch.setattr(
update_module.ResourceHelper,
"_get_needed_files",
classmethod(lambda cls: ["user.sites.v3.bin", "sites.cpython-test.so"]),
)
monkeypatch.setattr(update_module, "get_resource_versions", lambda: ("1", "1"))
resource_dir = manager._docker_app_dir / "app" / "application" / "site"
resource_dir.mkdir(parents=True)
(manager._docker_app_dir / "keep.py").parent.mkdir(parents=True, exist_ok=True)
(manager._docker_app_dir / "keep.py").write_text("keep\n", encoding="utf-8")
(resource_dir / "user.sites.v3.bin").write_bytes(b"old-index")
(resource_dir / "sites.cpython-old.so").write_bytes(b"old-native")
prepared_files = []
for name, content in (
("user.sites.v3.bin", b"new-index"),
("sites.cpython-test.so", b"new-native"),
):
path = manager._resource_dir / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(content)
prepared_files.append(
{"name": name, "path": str(path), "sha256": manager._sha256(path)}
)
prepared = {
"targets": ["resources"],
"resource_package_version": "10",
"resource_files": prepared_files,
}
manager._root.mkdir(parents=True, exist_ok=True)
(manager._root / "prepared.json").write_text(
json.dumps(prepared), encoding="utf-8"
)
manager._install_file.write_text(json.dumps(prepared), encoding="utf-8")
success, _message = manager.apply_prepared_update()
assert success is True
assert (manager._docker_app_dir / "keep.py").read_text(encoding="utf-8") == "keep\n"
assert (resource_dir / "user.sites.v3.bin").read_bytes() == b"new-index"
assert (resource_dir / "sites.cpython-test.so").read_bytes() == b"new-native"
assert not (resource_dir / "sites.cpython-old.so").exists()
assert not manager._install_file.exists()
assert not (manager._root / "prepared.json").exists()

View File

@@ -13,9 +13,9 @@ from unittest.mock import MagicMock, call, patch
import psutil
import pytest
from app.runtime.state import SystemHelper
from app.runtime.config import ConfigModel, Settings
from app.adapters.system.host import SystemUtils
from app.runtime.config import ConfigModel, Settings
from app.runtime.state import SystemHelper
def test_get_config_path_uses_repository_config_for_source_runtime():
@@ -91,19 +91,50 @@ def test_docker_restart_delegates_to_supervisor():
patch.object(SystemHelper, "_SystemHelper__supervisor_config") as supervisor_config, \
patch.object(SystemHelper, "_SystemHelper__supervisorctl") as supervisorctl, \
patch.object(SystemHelper, "_SystemHelper__supervisor_socket") as supervisor_socket, \
patch.object(SystemHelper, "_SystemHelper__prepared_update_manifest") as prepared_manifest, \
patch.object(SystemHelper, "_SystemHelper__one_shot_dev_update_flag_file") as dev_update_flag, \
patch.object(SystemHelper, "_schedule_supervisor_restart") as restart_mock, \
patch.object(SystemHelper, "_schedule_supervisor_shutdown") as shutdown_mock, \
patch("app.runtime.state.os.kill") as kill_mock:
supervisor_config.exists.return_value = True
supervisorctl.exists.return_value = True
supervisor_socket.exists.return_value = True
prepared_manifest.is_file.return_value = False
dev_update_flag.is_file.return_value = False
ret, msg = SystemHelper.restart()
assert ret
assert msg == ""
restart_mock.assert_called_once_with()
shutdown_mock.assert_not_called()
kill_mock.assert_not_called()
def test_docker_update_restart_reenters_entrypoint_for_pending_install():
"""待安装更新先启动 root worker 替换 Docker 程序目录。"""
with patch("app.runtime.state.is_docker", return_value=True), \
patch.object(SystemHelper, "_SystemHelper__supervisor_config") as supervisor_config, \
patch.object(SystemHelper, "_SystemHelper__supervisorctl") as supervisorctl, \
patch.object(SystemHelper, "_SystemHelper__supervisor_socket") as supervisor_socket, \
patch.object(SystemHelper, "_SystemHelper__prepared_update_manifest") as prepared_manifest, \
patch.object(SystemHelper, "_SystemHelper__one_shot_dev_update_flag_file") as dev_update_flag, \
patch.object(SystemHelper, "_schedule_supervisor_restart") as restart_mock, \
patch.object(SystemHelper, "_schedule_supervisor_shutdown") as shutdown_mock, \
patch.object(SystemHelper, "_schedule_supervisor_command") as command_mock:
supervisor_config.exists.return_value = True
supervisorctl.exists.return_value = True
supervisor_socket.exists.return_value = True
prepared_manifest.is_file.return_value = True
dev_update_flag.is_file.return_value = False
ret, msg = SystemHelper.restart()
assert ret
assert msg == ""
command_mock.assert_called_once_with("start", "moviepilot-update-worker")
restart_mock.assert_not_called()
shutdown_mock.assert_not_called()
def test_supervisor_restart_command_restarts_frontend_and_backend(monkeypatch):
"""延迟任务必须通过本地 supervisor 同时重启前后端进程。"""
callback = None
@@ -126,6 +157,40 @@ def test_supervisor_restart_command_restarts_frontend_and_backend(monkeypatch):
assert popen_mock.call_args.args[0][-2:] == ["restart", "all"]
def test_supervisor_shutdown_command(monkeypatch):
"""一次性 Dev 更新使用 supervisor shutdown,交回 root 入口执行更新流程。"""
callback = None
class ImmediateTimer:
def __init__(self, _delay, timer_callback):
nonlocal callback
callback = timer_callback
self.daemon = False
def start(self):
callback()
popen_mock = MagicMock()
monkeypatch.setattr("app.runtime.state.threading.Timer", ImmediateTimer)
monkeypatch.setattr("app.runtime.state.subprocess.Popen", popen_mock)
SystemHelper._schedule_supervisor_shutdown()
assert popen_mock.call_args.args[0][-1:] == ["shutdown"]
def test_upgrade_dev_always_marks_bootstrap_update():
"""Dev 更新即使已配置 dev 模式也要留下入口消费标记。"""
with patch.object(SystemHelper, "queue_one_shot_dev_update", return_value=(True, "")) as queue_mock, \
patch.object(SystemHelper, "restart", return_value=(True, "")) as restart_mock:
ret, msg = SystemHelper.upgrade_dev()
assert ret
assert msg == "已安排 Dev 更新并重启"
queue_mock.assert_called_once_with()
restart_mock.assert_called_once_with()
def test_execute_with_subprocess_passes_env_to_subprocess():
with patch("app.adapters.system.host.subprocess.run") as run_mock:
run_mock.return_value.stdout = "ok"
@@ -473,8 +538,9 @@ def test_btrfs_fsid_dedup_setting_is_opt_in():
assert ConfigModel(BTRFS_FSID_DEDUP="true").BTRFS_FSID_DEDUP is True
def test_auto_update_mode_is_normalized(monkeypatch):
"""自动更新仅保留 true、dev 和 false 三种运行模式。"""
@pytest.mark.parametrize("mode", ["release", "dev", " DEV ", "RELEASE"])
def test_auto_update_mode_is_normalized(monkeypatch, mode):
"""旧模式规范化为布尔 true,已有的新 Dev 偏好不被覆盖。"""
updates = []
monkeypatch.setattr(
Settings,
@@ -484,14 +550,51 @@ def test_auto_update_mode_is_normalized(monkeypatch):
),
)
assert Settings(MOVIEPILOT_AUTO_UPDATE="release").MOVIEPILOT_AUTO_UPDATE == "false"
assert Settings(MOVIEPILOT_AUTO_UPDATE="true").MOVIEPILOT_AUTO_UPDATE == "true"
assert Settings(MOVIEPILOT_AUTO_UPDATE="dev").MOVIEPILOT_AUTO_UPDATE == "dev"
config = Settings(MOVIEPILOT_AUTO_UPDATE=mode, MOVIEPILOT_UPDATE_DEV=False)
assert config.MOVIEPILOT_AUTO_UPDATE is True
assert config.MOVIEPILOT_UPDATE_DEV is False
assert updates == [
("MOVIEPILOT_AUTO_UPDATE", "release", "false"),
("MOVIEPILOT_AUTO_UPDATE", mode, True),
]
def test_legacy_dev_tracking_is_migrated_once(monkeypatch, tmp_path):
"""首次拆分配置时持久化两个开关,重读后继续保留 Dev 跟踪。"""
env_file = tmp_path / "app.env"
env_file.write_text("MOVIEPILOT_AUTO_UPDATE='dev'\n", encoding="utf-8")
monkeypatch.setattr("app.runtime.config.get_env_path", lambda: env_file)
config = Settings(_env_file=env_file)
assert config.MOVIEPILOT_AUTO_UPDATE is True
assert config.MOVIEPILOT_UPDATE_DEV is True
assert "MOVIEPILOT_AUTO_UPDATE='true'" in env_file.read_text(encoding="utf-8")
assert "MOVIEPILOT_UPDATE_DEV='true'" in env_file.read_text(encoding="utf-8")
reloaded = Settings(_env_file=env_file)
assert reloaded.MOVIEPILOT_AUTO_UPDATE is True
assert reloaded.MOVIEPILOT_UPDATE_DEV is True
@pytest.mark.parametrize("enabled", [True, False, "true", "false"])
def test_update_switches_remain_independent_booleans(enabled):
"""部署设置与调度快照仅暴露布尔值,Dev 跟踪不影响自动检查。"""
from app.startup.composition.configuration import build_scheduler_runtime_config
expected = str(enabled).lower() == "true"
config = Settings(MOVIEPILOT_AUTO_UPDATE=enabled, MOVIEPILOT_UPDATE_DEV=not expected)
assert config.MOVIEPILOT_AUTO_UPDATE is expected
assert config.MOVIEPILOT_UPDATE_DEV is not expected
assert build_scheduler_runtime_config(config).auto_update is expected
@pytest.mark.parametrize("value", ["dev", "release", True, False])
def test_update_setting_normalizes_auto_update_on_save(monkeypatch, value):
"""设置写入入口与启动读取入口使用同一套布尔转换规则。"""
config = Settings(MOVIEPILOT_AUTO_UPDATE=False, MOVIEPILOT_UPDATE_DEV=False)
monkeypatch.setattr(Settings, "update_env_config", lambda *_args: (True, ""))
config.update_setting("MOVIEPILOT_AUTO_UPDATE", value)
assert config.MOVIEPILOT_AUTO_UPDATE is (value is not False)
assert config.MOVIEPILOT_UPDATE_DEV is False
def test_space_usage_default_path_does_not_read_fsid():
with tempfile.TemporaryDirectory() as tmp1, tempfile.TemporaryDirectory() as tmp2:
paths = [Path(tmp1), Path(tmp2)]

View File

@@ -1,5 +1,6 @@
"""验证 TransferChain 步骤 runner 与文件执行器的崩溃恢复边界。"""
from dataclasses import replace
from datetime import datetime, timezone
from pathlib import Path
from unittest.mock import Mock
@@ -30,7 +31,10 @@ from app.db.base import Base
from app.db.models.transferexecutionstep import TransferExecutionStep
from app.db.models.transferhistory import TransferHistory
from app.db.models.transferpending import TransferPending
from app.domain.context import MediaInfo
from app.domain.meta.metabase import MetaBase
from app.modules.filemanager.transhandler import TransHandler
from app.schemas.types import MediaType
from app.schemas.workflow import FileItem
@@ -384,7 +388,7 @@ def test_cross_storage_move_materializes_before_independent_source_delete(tmp_pa
result, error = TransHandler._TransHandler__execute_transfer_with_steps(
step_runner=runner,
fileitem=source_item,
source_fileitem=source_item.model_dump(mode="json"),
target_storage="remote",
source_oper=source_oper,
target_oper=target_oper,
@@ -444,3 +448,79 @@ def test_remote_to_local_transfer_creates_target_directory_before_download(tmp_p
path=target_file.parent,
)
source_oper.delete.assert_called_once_with(source_item)
@pytest.mark.parametrize("sparse", [False, True])
@pytest.mark.parametrize("directory", [False, True])
def test_frozen_disc_plan_executes_and_replays_with_real_step_ledger(
execution_repository, monkeypatch, sparse, directory,
):
"""原盘及旧快照必须通过真实意图校验,重启后不再复制或重复删除源。"""
source = FileItem(
storage="local", path="/disc" if directory else "/disc.iso",
name="disc" if directory else "disc.iso", type="dir" if directory else "file",
size=100,
).model_dump(mode="json", exclude_unset=sparse)
leaf = (
FileItem(storage="local", path="/disc/BDMV/STREAM/00001.m2ts",
name="00001.m2ts", type="file", size=200).model_dump(
mode="json", exclude_unset=sparse,
)
if directory else dict(source)
)
target = "/library/disc" if directory else "/library/disc.iso"
planning_input = TransferPlanningInput(source_fileitem=source)
checkpoint = replace(
_runner_plan_checkpoint(), planning_input=planning_input,
target_storage="remote", final_target_path=target,
resolved_transfer_type="move",
items=(TransferPlanItem(
sequence=0, source_fileitem=leaf, target_storage="remote",
target_path=f"{target}/BDMV/STREAM/00001.m2ts" if directory else target,
),),
)
with execution_repository._session_factory() as session:
pending = session.query(TransferPending).one()
pending.planning_input = planning_input.to_payload()
pending.input_fingerprint = planning_input.fingerprint
pending.checkpoint_payload = checkpoint.to_payload()
session.commit()
def intercept(**kwargs):
"""模拟插件修正运行期大小,冻结计划和步骤身份不应随之变化。"""
kwargs["fileitem"].size = 999
return True, ""
def materialize(**kwargs):
"""模拟存储适配器更新临时链接,源删除步骤仍须沿用冻结输入。"""
assert kwargs["fileitem"].size == leaf["size"]
kwargs["fileitem"].url = "https://temporary.invalid/refreshed"
return FileItem(storage="remote", path=kwargs["target_file"].as_posix()), ""
handler = TransHandler()
monkeypatch.setattr(handler, "_TransHandler__intercept_transfer", intercept)
transfer = Mock(side_effect=materialize)
monkeypatch.setattr(TransHandler, "_TransHandler__transfer_command", transfer)
source_oper = Mock()
target_oper = Mock()
target_oper.get_item_strict.return_value = None
target_oper.get_folder.return_value = FileItem(storage="remote", path="/library", type="dir")
for _ in range(2):
runner = transfer_chain_module._DurableTransferStepRunner(
task_id="task-runner", lease_token="lease",
checkpoint_fingerprint=checkpoint.fingerprint,
repository=execution_repository,
)
result = handler.execute_transfer_plan(
checkpoint, meta=MetaBase("disc.iso"),
mediainfo=MediaInfo(type=MediaType.MOVIE, title="Disc"),
source_oper=source_oper, target_oper=target_oper, step_runner=runner,
)
assert result.success
assert runner.checkpoint(result).payload["outcome"] == "succeeded"
transfer.assert_called_once()
source_oper.delete.assert_called_once()
assert source_oper.delete.call_args.args[0].url is None
assert checkpoint.planning_input.source_fileitem == source
assert checkpoint.items[0].source_fileitem == leaf