The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
test(Task): 测试目录入库,覆盖文件选择与动态改选全部分支
XiaoYouChRf353d2ea1102
diff --git a/.gitignore b/.gitignoreindex 17ac0b8e..b5021f50 100644--- a/.gitignore+++ b/.gitignore@@ -37,6 +37,4 @@ browser_extension/firefox/.playwright-mcp*.jks*.keystore-/config/--tests/\ No newline at end of file+/config/\ No newline at end of filediff --git a/tests/test_file_drag.py b/tests/test_file_drag.pynew file mode 100644index 00000000..1f6b5dbe--- /dev/null+++ b/tests/test_file_drag.py@@ -0,0 +1,64 @@+"""startFileDrag 平台分派与回退的逐分支测试。++覆盖:+ - Windows 原生路径成功时不触发 Qt 回退+ - Windows 准备阶段失败时回退 Qt(原参数透传)+ - 非 Windows 平台直通 Qt 路径+"""+from __future__ import annotations++import sys+from pathlib import Path+from unittest.mock import MagicMock++import pytest++from app.platform import desktop+++def drag(monkeypatch):+ win32 = MagicMock()+ qt = MagicMock()+ monkeypatch.setattr(desktop, "_startFileDragWin32", win32)+ monkeypatch.setattr(desktop, "_startFileDragQt", qt)+ source = MagicMock()+ source.window.return_value.winId.return_value = 42+ return win32, qt, source+++class TestStartFileDrag:++ def test_win32_success_skips_qt(self, drag, monkeypatch):+ win32, qt, source = drag+ monkeypatch.setattr(sys, "platform", "win32")+ paths = [Path("C:/dl/a.txt"), Path("C:/dl/b.txt")]++ desktop.startFileDrag(paths, source)++ win32.assert_called_once_with([str(p) for p in paths], 42)+ qt.assert_not_called()++ def test_win32_failure_falls_back_to_qt(self, drag, monkeypatch):+ win32, qt, source = drag+ monkeypatch.setattr(sys, "platform", "win32")+ win32.side_effect = OSError("SHParseDisplayName failed")+ paths = [Path("C:/dl/a.txt")]++ desktop.startFileDrag(paths, source)++ qt.assert_called_once_with(paths, source)++ def test_non_windows_goes_straight_to_qt(self, drag, monkeypatch):+ win32, qt, source = drag+ monkeypatch.setattr(sys, "platform", "linux")+ paths = [Path("/home/dl/a.txt")]++ desktop.startFileDrag(paths, source)++ win32.assert_not_called()+ qt.assert_called_once_with(paths, source)+++if __name__ == "__main__":+ pytest.main([__file__, "-v", "--tb=short"])diff --git a/tests/test_file_selection.py b/tests/test_file_selection.pynew file mode 100644index 00000000..2699a609--- /dev/null+++ b/tests/test_file_selection.py@@ -0,0 +1,578 @@+"""文件选择标志过滤语义与动态编排的分支测试。++背景:多文件任务的选择语义从"增删 Step"统一为"标志过滤"(ADR 0008),+并支持任意状态下修改选择(taskService.applySelection)。++覆盖:+ - 基类:_isStepSelected 全分支、setSelection 纯标志翻转、+ updateStatus/setStatus/pendingSteps/currentSnapshot 的选择过滤、+ _updateFilesFromSteps 多步聚合+ - M3U8:直播任务加载校正(假暂停定案)全状态分支+ - HF/FTP:旧存档缺失 Step 补建、解析路径不重复建+ - YouTube:setVideos 步骤组、选择感知的大小/快照/待执行步骤、+ extract 兄弟步骤按 fileIndex 更新+ - Bili:三种模式重建、P 后缀与选择解耦、字幕步按稳定身份查页+ - BT:完成后补选打回 WAITING 的判定分支+ - applySelection:暂停重启/复活/直通三条路径及其边界+"""+from __future__ import annotations++import asyncio+import json+import sys+from dataclasses import dataclass, field+from pathlib import Path++import pytest+from PySide6.QtWidgets import QApplication++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "features"))++app = QApplication.instance() or QApplication(sys.argv)++from app.models.task import SpecialFileSize, Task, TaskFile, TaskStatus, TaskStep+from app.services.task_service import TaskQueue, taskService++from bili_pack.task import BiliPage, BilibiliSubtitleStep, BilibiliTask, DownloadMode+from bittorrent_pack.task import BTFile, BTTask, BTTaskStep+from ftp_pack.task import FtpConnectionInfo, FtpTask+from huggingface_pack.task import HuggingFaceFile, HuggingFaceStep, HuggingFaceTask+from m3u8_pack.task import M3U8Task, M3U8TaskStep+from yt_dlp_pack.task import (+ STEPS_PER_VIDEO, YouTubeExtractStep, YouTubeFile,+ YouTubeMergeStep, YouTubeResourceStep, YouTubeTask,+)+++@dataclass(kw_only=True)+class IndexedStep(TaskStep):+ fileIndex: int = -1++ async def run(self):+ self.setStatus(TaskStatus.COMPLETED)+++@dataclass(kw_only=True)+class PlainStep(TaskStep):+ async def run(self):+ self.setStatus(TaskStatus.COMPLETED)+++def buildTask(fileStates, stepStates=None, **kwargs):+ """fileStates: [(selected, completed)],默认每文件一个同状态 Step。"""+ files = [+ TaskFile(index=i, relativePath=f"f{i}.bin", size=10, selected=sel, completed=comp)+ for i, (sel, comp) in enumerate(fileStates)+ ]+ stepStates = stepStates or [+ TaskStatus.COMPLETED if comp else TaskStatus.WAITING for _, comp in fileStates+ ]+ steps = [+ IndexedStep(stepIndex=i + 1, fileIndex=i, status=s)+ for i, s in enumerate(stepStates)+ ]+ return Task(name="t", url="https://example.com", packId="test",+ files=files, steps=steps, **kwargs)+++# ─── 基类:_isStepSelected ─────────────────────────────────+++def test_step_selected_when_no_files():+ task = Task(name="t", url="u", packId="p", steps=[IndexedStep(stepIndex=1, fileIndex=0)])+ assert task._isStepSelected(task.steps[0])+++def test_step_without_file_index_always_selected():+ task = buildTask([(False, False)])+ step = PlainStep(stepIndex=99)+ step._bindTask(task)+ assert task._isStepSelected(step)+++def test_step_selected_follows_file_flag():+ task = buildTask([(True, False), (False, False)])+ assert task._isStepSelected(task.steps[0])+ assert not task._isStepSelected(task.steps[1])+++def test_step_with_unknown_file_index_not_selected():+ task = buildTask([(True, False)])+ orphan = IndexedStep(stepIndex=9, fileIndex=42)+ orphan._bindTask(task)+ assert not task._isStepSelected(orphan)+++# ─── 基类:setSelection 纯标志翻转 ─────────────────────────+++def test_set_selection_flips_flags_without_step_churn():+ task = buildTask([(True, False), (True, False), (True, False)])+ stepIds = [id(s) for s in task.steps]+ task.steps[0].receivedBytes = 55+ task.setSelection({1, 2})+ assert [id(s) for s in task.steps] == stepIds+ assert [f.selected for f in task.files] == [False, True, True]+ assert task.fileSize == 20+ task.setSelection({0, 1, 2})+ assert task.steps[0].receivedBytes == 55 # 断点进度保留+++def test_set_selection_noop_without_files():+ task = Task(name="t", url="u", packId="p", fileSize=77)+ task.setSelection({0})+ assert task.fileSize == 77+++# ─── 基类:状态聚合过滤 ────────────────────────────────────+++def test_update_status_ignores_unselected_failed_step():+ task = buildTask([(True, True), (False, False)],+ stepStates=[TaskStatus.COMPLETED, TaskStatus.FAILED])+ assert task.updateStatus() == TaskStatus.COMPLETED+++def test_update_status_completes_when_selected_done():+ task = buildTask([(True, True), (False, False)])+ assert task.updateStatus() == TaskStatus.COMPLETED+ assert task.completedAt > 0+++def test_update_status_keeps_status_when_nothing_selected():+ task = buildTask([(False, False)], status=TaskStatus.PAUSED)+ assert task.updateStatus() == TaskStatus.PAUSED+++def test_set_status_skips_unselected_and_completed():+ task = buildTask([(True, True), (True, False), (False, False)],+ stepStates=[TaskStatus.COMPLETED, TaskStatus.FAILED, TaskStatus.WAITING])+ task.setStatus(TaskStatus.RUNNING)+ assert task.steps[0].status == TaskStatus.COMPLETED # 已完成不动+ assert task.steps[1].status == TaskStatus.RUNNING # FAILED 被 reset 后置 RUNNING+ assert task.steps[2].status == TaskStatus.WAITING # 未选中不动+++def test_pending_steps_filters_and_sorts():+ task = buildTask([(True, True), (False, False), (True, False)])+ task.steps.reverse()+ task.status = TaskStatus.RUNNING+ pending = [s.fileIndex for s in task.pendingSteps()]+ assert pending == [2] # 跳过已完成 f0、未选中 f1,且按 stepIndex 排序+++def test_pending_steps_stops_when_not_running():+ task = buildTask([(True, False)])+ assert list(task.pendingSteps()) == []+++def test_current_snapshot_counts_only_selected():+ task = buildTask([(True, False), (False, False)])+ task.steps[0].progress, task.steps[0].receivedBytes = 50.0, 500+ task.steps[1].progress, task.steps[1].receivedBytes = 100.0, 999+ progress, _speed, received = task.currentSnapshot()+ assert progress == 50.0+ assert received == 500+++def test_files_mirror_multi_step_group_progress():+ steps = [+ IndexedStep(stepIndex=1, fileIndex=0, status=TaskStatus.COMPLETED),+ IndexedStep(stepIndex=2, fileIndex=0, status=TaskStatus.WAITING),+ ]+ steps[0].receivedBytes, steps[1].receivedBytes = 30, 12+ task = Task(name="t", url="u", packId="p", steps=steps,+ files=[TaskFile(index=0, relativePath="a", size=42)])+ task.updateStatus()+ assert task.files[0].downloadedBytes == 42+ assert not task.files[0].completed # 组内还有未完成步骤+++# ─── M3U8:直播加载校正 ────────────────────────────────────+++def buildLiveTask(status, isLive=True, tmp=None):+ return M3U8Task(+ name="live.ts", url="https://example.com/live.m3u8", isLive=isLive,+ status=status, outputFolder=tmp,+ steps=[M3U8TaskStep(stepIndex=1, status=status)],+ )++[email protected]("status", [TaskStatus.PAUSED, TaskStatus.RUNNING])+def test_live_task_finalized_on_load(tmp_path, status):+ task = buildLiveTask(status, tmp=tmp_path)+ assert task.status == TaskStatus.COMPLETED+ assert task.steps[0].status == TaskStatus.COMPLETED+ assert task.completedAt > 0++[email protected]("status", [TaskStatus.WAITING, TaskStatus.FAILED, TaskStatus.COMPLETED])+def test_live_task_other_statuses_untouched(tmp_path, status):+ task = buildLiveTask(status, tmp=tmp_path)+ assert task.status == status+++def test_vod_task_pause_untouched(tmp_path):+ task = buildLiveTask(TaskStatus.PAUSED, isLive=False, tmp=tmp_path)+ assert task.status == TaskStatus.PAUSED+++# ─── HF/FTP:旧存档补建与解析不重复 ────────────────────────+++def hfRecord(fileStates, stepIndexes):+ return {+ "type": "HuggingFaceTask", "name": "repo", "url": "https://huggingface.co/a/b",+ "packId": "huggingface", "status": "PAUSED", "repoId": "a/b",+ "files": [+ {"index": i, "relativePath": f"f{i}.bin", "size": 10,+ "selected": sel, "downloadUrl": f"u{i}"}+ for i, sel in enumerate(fileStates)+ ],+ "steps": [+ {"type": "HuggingFaceStep", "stepIndex": i + 1, "fileIndex": i,+ "url": f"u{i}", "fileSize": 10, "status": "PAUSED"}+ for i in stepIndexes+ ],+ }+++def test_hf_rebuilds_missing_steps_from_archive():+ task = Task.fromDict(json.dumps(hfRecord([True, False, False], [0])))+ assert len(task.steps) == 3+ rebuilt = next(s for s in task.steps if s.fileIndex == 2)+ assert rebuilt.url == "u2"+++def test_hf_full_archive_no_duplicates():+ task = Task.fromDict(json.dumps(hfRecord([True, True], [0, 1])))+ assert len(task.steps) == 2+++def test_hf_parse_style_construction_no_duplicates():+ """回归:files+steps 一起构造时 __post_init__ 不得再补一份。"""+ files = [HuggingFaceFile(index=i, relativePath=f"f{i}", size=1, downloadUrl=f"u{i}")+ for i in range(3)]+ steps = [HuggingFaceStep(stepIndex=i + 1, url=f"u{i}", fileIndex=i) for i in range(3)]+ task = HuggingFaceTask(name="r", url="u", files=files, steps=steps)+ assert len(task.steps) == 3+++def test_hf_no_files_no_reconciliation():+ task = HuggingFaceTask(name="r", url="u")+ assert task.steps == []+++def test_ftp_rebuilds_missing_steps_from_archive():+ from ftp_pack.task import FtpFile+ task = FtpTask(+ name="dir", url="ftp://h/dir", sourceType="dir",+ connectionInfo=FtpConnectionInfo(+ scheme="ftp", host="h", port=21, username="", password="", sourcePath="/dir"),+ files=[+ FtpFile(index=0, relativePath="a", size=1, remotePath="/dir/a"),+ FtpFile(index=1, relativePath="b", size=2, remotePath="/dir/b", selected=False),+ ],+ )+ assert len(task.steps) == 2+ assert {s.fileIndex for s in task.steps} == {0, 1}+++# ─── YouTube ───────────────────────────────────────────────+++def buildYtTask(videoCount=3):+ task = YouTubeTask(name="list.mp4", url="https://youtube.com/watch?v=x&list=L",+ isPlaylist=True, fileSize=int(SpecialFileSize.UNKNOWN))+ task.setVideos([+ {"id": f"v{i}", "title": f"Video {i}", "duration": 60 + i}+ for i in range(videoCount)+ ])+ return task+++def test_yt_set_videos_builds_indexed_groups():+ task = buildYtTask(3)+ assert len(task.files) == 3 and len(task.steps) == 3 * STEPS_PER_VIDEO+ group1 = [s for s in task.steps if s.fileIndex == 1]+ assert [s.stepIndex for s in group1] == [5, 6, 7, 8]+ assert task.files[1].videoId == "v1"+ extract = next(s for s in group1 if isinstance(s, YouTubeExtractStep))+ assert extract.videoUrl == "https://www.youtube.com/watch?v=v1"+++def test_yt_empty_videos_keeps_placeholder_group():+ task = YouTubeTask(name="v.mp4", url="https://youtube.com/watch?v=x")+ task.setVideos([])+ assert task.files == [] and len(task.steps) == STEPS_PER_VIDEO+++def test_yt_selection_size_unknown_before_extract():+ task = buildYtTask(2)+ task.setSelection({0})+ assert task.fileSize == int(SpecialFileSize.UNKNOWN)+++def test_yt_selection_size_sums_selected_resources():+ task = buildYtTask(2)+ for s in task.steps:+ if isinstance(s, YouTubeResourceStep):+ s.fileSize = 100+ task.setSelection({1})+ assert task.fileSize == 200 # 仅组1的 video+audio+++def test_yt_pending_steps_always_yields_selected_extract():+ task = buildYtTask(2)+ for s in task.steps:+ s.status = TaskStatus.COMPLETED+ task.status = TaskStatus.RUNNING+ pending = list(task.pendingSteps())+ assert all(isinstance(s, YouTubeExtractStep) for s in pending)+ assert {s.fileIndex for s in pending} == {0, 1}+++def test_yt_pending_steps_skips_unselected_group():+ task = buildYtTask(2)+ task.setSelection({1})+ task.status = TaskStatus.RUNNING+ assert {s.fileIndex for s in task.pendingSteps()} == {1}+++def test_yt_snapshot_excludes_extract_and_unselected():+ task = buildYtTask(2)+ task.setSelection({0})+ for s in task.steps:+ s.receivedBytes = 10+ _p, _s, received = task.currentSnapshot()+ assert received == 30 # 组0的 video+audio+merge,不含 extract 与组1+++def test_yt_extract_updates_only_own_group():+ task = buildYtTask(2)+ extract = next(s for s in task.steps+ if isinstance(s, YouTubeExtractStep) and s.fileIndex == 0)+ videoFmt = {"url": "https://cdn/video", "filesize": 500, "ext": "mp4"}+ audioFmt = {"url": "https://cdn/audio", "filesize": 100, "ext": "m4a"}+ extract._updateSiblingSteps(videoFmt, audioFmt, {"title": "T"})+ group0 = [s for s in task.steps if isinstance(s, YouTubeResourceStep) and s.fileIndex == 0]+ group1 = [s for s in task.steps if isinstance(s, YouTubeResourceStep) and s.fileIndex == 1]+ assert all(s.url for s in group0)+ assert all(not s.url for s in group1)+ assert task.fileSize == 600+++def test_yt_serialization_roundtrip():+ task = buildYtTask(2)+ task.setSelection({1})+ restored = Task.fromDict(json.dumps(task.toDict()))+ assert type(restored.files[0]) is YouTubeFile+ assert [f.selected for f in restored.files] == [False, True]+ assert len(restored.steps) == 2 * STEPS_PER_VIDEO+++# ─── Bilibili ──────────────────────────────────────────────+++def buildBiliTask(pageCount=3, subsOnPage=(0,), **kwargs):+ pages = [+ BiliPage(index=i, relativePath=f"P{i + 1}", pagePart=f"第{i + 1}集",+ videoUrl=f"v{i}", audioUrl=f"a{i}", videoSize=100, audioSize=10,+ subtitles=[{"lan": "zh", "subtitle_url": "u"}] if i in subsOnPage else [])+ for i in range(pageCount)+ ]+ task = BilibiliTask(name="合集.mp4", url="https://bilibili.com/video/BVx",+ files=pages, _baseName="合集", **kwargs)+ task._rebuildSteps()+ return task+++def test_bili_video_mode_step_layout():+ task = buildBiliTask(2, subsOnPage=(0,), subtitleLanguages=["zh"])+ assert len(task.steps) == 3 + 1 + 3 # P1 三步+字幕,P2 三步+ group0 = sorted(s.stepIndex for s in task.steps if s.fileIndex == 0)+ assert group0 == [1, 2, 3, 4]+ group1 = sorted(s.stepIndex for s in task.steps if s.fileIndex == 1)+ assert group1 == [5, 6, 7]+++def test_bili_no_subtitle_language_no_subtitle_steps():+ task = buildBiliTask(2, subsOnPage=(0, 1))+ assert not any(isinstance(s, BilibiliSubtitleStep) for s in task.steps)+++def test_bili_audio_mode():+ task = buildBiliTask(2)+ task.setMode(DownloadMode.AUDIO)+ assert task.name == "合集.m4a"+ assert len(task.steps) == 2+ assert task.fileSize == 20+ assert all(f.size == f.audioSize for f in task.files)+++def test_bili_cover_mode():+ task = buildBiliTask(2, coverUrl="https://c/pic.jpg", coverSize=5)+ task.setMode(DownloadMode.COVER)+ assert task.name == "合集.jpg"+ assert len(task.steps) == 1 and task.fileSize == 5+++def test_bili_suffix_follows_total_not_selection():+ task = buildBiliTask(3)+ task.setSelection({1})+ assert len(task.steps) == 9 # 改选不重建+ suffix = next(s.pageSuffix for s in task.steps if s.fileIndex == 1)+ assert suffix == " - P2 第2集"+ assert task.fileSize == 110+++def test_bili_single_page_no_suffix():+ task = buildBiliTask(1)+ assert all(s.pageSuffix == "" for s in task.steps)+++def test_bili_suffix_omits_part_equal_to_base_name():+ page = BiliPage(index=1, relativePath="P2", pagePart="合集",+ videoUrl="v", audioUrl="a")+ task = buildBiliTask(3)+ assert task._pageSuffix(page) == " - P2"+++def test_bili_subtitle_step_finds_page_by_stable_index():+ task = buildBiliTask(3, subsOnPage=(2,), subtitleLanguages=["en"])+ sub = next(s for s in task.steps if isinstance(s, BilibiliSubtitleStep))+ assert sub.fileIndex == 2+ asyncio.run(sub.run()) # 页面存在但语言不匹配 -> 直接完成,不发网络请求+ assert sub.status == TaskStatus.COMPLETED+++def test_bili_subtitle_step_missing_page_completes():+ task = buildBiliTask(1)+ sub = BilibiliSubtitleStep(stepIndex=99, fileIndex=42)+ sub._bindTask(task)+ asyncio.run(sub.run())+ assert sub.status == TaskStatus.COMPLETED+++# ─── BT:完成后补选 ────────────────────────────────────────+++def buildBTTask(fileStates):+ return BTTask(+ name="t", url="magnet:?xt=urn:btih:x",+ files=[+ BTFile(index=i, relativePath=f"t/f{i}", size=10, selected=sel, completed=comp)+ for i, (sel, comp) in enumerate(fileStates)+ ],+ steps=[BTTaskStep(stepIndex=0, status=TaskStatus.COMPLETED)],+ status=TaskStatus.COMPLETED,+ )+++def test_bt_reselect_uncompleted_revives_step():+ task = buildBTTask([(True, True), (False, False)])+ task.setSelection({0, 1})+ assert task.step.status == TaskStatus.WAITING+ assert task.status == TaskStatus.WAITING+++def test_bt_deselect_completed_stays_completed():+ task = buildBTTask([(True, True), (True, True)])+ task.setSelection({0})+ assert task.step.status == TaskStatus.COMPLETED+++def test_bt_unchanged_selection_early_return():+ task = buildBTTask([(True, True), (False, False)])+ task.files[1].priority = 0 # 与未选中状态一致,构成真正的"无变化"+ version = task._fileSelectionVersion+ task.setSelection({0})+ assert task._fileSelectionVersion == version+++def test_bt_empty_selection_rejected():+ task = buildBTTask([(True, True)])+ with pytest.raises(ValueError):+ task.setSelection(set())+++# ─── taskService.applySelection ────────────────────────────+++def serviceProbe(monkeypatch):+ calls = []+ monkeypatch.setattr(taskService, "_queue", TaskQueue())+ monkeypatch.setattr(taskService, "_pump", lambda: calls.append("pump"))+ monkeypatch.setattr(taskService, "_schedule",+ lambda t: calls.append("schedule"))+ monkeypatch.setattr(taskService, "_unwatchFile",+ lambda t: calls.append("unwatch"))+ monkeypatch.setattr(+ taskService, "_cancelRun",+ lambda t, finished=None: (calls.append("cancel"), finished and finished()))+ return calls+++def test_apply_selection_waiting_passthrough(serviceProbe):+ task = buildTask([(True, False), (True, False)])+ taskService.applySelection(task, {0})+ assert serviceProbe == []+ assert not task.files[1].selected+++def test_apply_selection_revives_completed(serviceProbe):+ task = buildTask([(True, True), (False, False)], completedAt=123)+ task.status = TaskStatus.COMPLETED+ taskService.applySelection(task, {0, 1})+ assert serviceProbe == ["unwatch", "schedule"]+ assert task.completedAt == 0+ assert task.status == TaskStatus.WAITING+++def test_apply_selection_completed_no_new_work_no_revive(serviceProbe):+ task = buildTask([(True, True), (True, True)], completedAt=123)+ task.status = TaskStatus.COMPLETED+ taskService.applySelection(task, {0})+ assert serviceProbe == []+ assert task.completedAt == 123+ assert task.status == TaskStatus.COMPLETED+++def test_apply_selection_restarts_when_running_step_deselected(serviceProbe):+ task = buildTask([(True, False), (True, False)],+ stepStates=[TaskStatus.RUNNING, TaskStatus.WAITING])+ task.status = TaskStatus.RUNNING+ taskService._queue.run(task.taskId, "w")+ taskService.applySelection(task, {1})+ assert serviceProbe == ["cancel", "schedule"]+ assert not task.files[0].selected+++def test_apply_selection_keeps_running_when_other_deselected(serviceProbe):+ task = buildTask([(True, False), (True, False)],+ stepStates=[TaskStatus.RUNNING, TaskStatus.WAITING])+ task.status = TaskStatus.RUNNING+ taskService._queue.run(task.taskId, "w")+ taskService.applySelection(task, {0})+ assert serviceProbe == []+ assert not task.files[1].selected+++def test_apply_selection_running_step_without_file_index_not_interrupted(serviceProbe):+ step = PlainStep(stepIndex=1, status=TaskStatus.RUNNING)+ task = Task(name="t", url="u", packId="p", steps=[step],+ files=[TaskFile(index=0, relativePath="a", size=1)])+ task.status = TaskStatus.RUNNING+ taskService._queue.run(task.taskId, "w")+ taskService.applySelection(task, set())+ assert serviceProbe == []+++def test_apply_selection_files_none_safe(serviceProbe):+ task = Task(name="t", url="u", packId="p")+ taskService.applySelection(task, {0})+ assert serviceProbe == []diff --git a/tests/test_oobe_runtime_page.py b/tests/test_oobe_runtime_page.pynew file mode 100644index 00000000..a98cd60a--- /dev/null+++ b/tests/test_oobe_runtime_page.py@@ -0,0 +1,157 @@+"""RuntimeInstallPage(OOBE 推荐组件页)的逐分支测试。++覆盖:+ - mount 过滤:canInstall=False / title 未声明的 runtime 不出现+ - mount 排序:推荐组件在前,组内保持 pack 加载序(稳定排序)+ - 已安装 runtime:展示但不可勾选+ - 未安装 runtime:勾选默认值 = isRecommended+ - mount 幂等+ - selectedRuntimes 只返回勾选项+ - 四个真实 pack 的自描述声明齐全+"""+from __future__ import annotations++import sys+from unittest.mock import MagicMock++import pytest+from PySide6.QtWidgets import QApplication+from qfluentwidgets import FluentIcon++app = QApplication.instance() or QApplication(sys.argv)++from app.models.pack import BinaryRuntime+++class FakeRuntime(BinaryRuntime):++ def __init__(self, title="组件", name="bin", canInstall=True,+ isRecommended=False, installedPath=""):+ self.title = title+ self.description = f"{title} 的说明"+ self.icon = FluentIcon.VIDEO+ self.name = name+ self.canInstall = canInstall+ self.isRecommended = isRecommended+ self._installedPath = installedPath++ def path(self) -> str:+ return self._installedPath+++def page():+ from app.view.windows.oobe_window import RuntimeInstallPage+ p = RuntimeInstallPage()+ p._card.addGroup = MagicMock()+ return p+++def _mount(page, monkeypatch, runtimes):+ monkeypatch.setattr(+ "app.services.feature_service.featureService",+ MagicMock(runtimes=MagicMock(return_value=runtimes)),+ )+ page.mount()+++def _shownTitles(page) -> list[str]:+ return [call.args[1] for call in page._card.addGroup.call_args_list]+++class TestMountFiltering:++ def test_excludes_not_installable(self, page, monkeypatch):+ _mount(page, monkeypatch, [+ FakeRuntime(title="可装"),+ FakeRuntime(title="不可装", canInstall=False),+ ])+ assert _shownTitles(page) == ["可装"]++ def test_excludes_without_title(self, page, monkeypatch):+ _mount(page, monkeypatch, [+ FakeRuntime(title="有自描述"),+ FakeRuntime(title=""),+ ])+ assert _shownTitles(page) == ["有自描述"]+++class TestMountOrdering:++ def test_recommended_first_stable(self, page, monkeypatch):+ _mount(page, monkeypatch, [+ FakeRuntime(title="普通"),+ FakeRuntime(title="推荐甲", isRecommended=True),+ FakeRuntime(title="推荐乙", isRecommended=True),+ ])+ assert _shownTitles(page) == ["推荐甲", "推荐乙", "普通"]+++class TestMountInstalledState:++ def test_installed_runtime_has_no_checkbox(self, page, monkeypatch):+ _mount(page, monkeypatch, [+ FakeRuntime(title="已装", installedPath="C:/bin/x.exe"),+ FakeRuntime(title="未装"),+ ])+ assert len(_shownTitles(page)) == 2+ assert [rt.title for _, rt in page._checkBoxes] == ["未装"]++ def test_checkbox_follows_recommendation(self, page, monkeypatch):+ _mount(page, monkeypatch, [+ FakeRuntime(title="推荐", isRecommended=True),+ FakeRuntime(title="普通", isRecommended=False),+ ])+ checkedByTitle = {rt.title: cb.isChecked() for cb, rt in page._checkBoxes}+ assert checkedByTitle == {"推荐": True, "普通": False}+++class TestMountIdempotent:++ def test_mount_twice_adds_once(self, page, monkeypatch):+ runtimes = [FakeRuntime(title="唯一")]+ _mount(page, monkeypatch, runtimes)+ _mount(page, monkeypatch, runtimes)+ assert page._card.addGroup.call_count == 1+ assert len(page._checkBoxes) == 1+++class TestSelectedRuntimes:++ def test_returns_only_checked(self, page, monkeypatch):+ _mount(page, monkeypatch, [+ FakeRuntime(title="推荐", isRecommended=True),+ FakeRuntime(title="普通", isRecommended=False),+ ])+ assert [rt.title for rt in page.selectedRuntimes()] == ["推荐"]++ for checkBox, _ in page._checkBoxes:+ checkBox.setChecked(not checkBox.isChecked())+ assert [rt.title for rt in page.selectedRuntimes()] == ["普通"]+++class TestPackDeclarations:+ """四个真实 pack 的 runtime 自描述齐全,策展值固化。"""++ def test_all_runtimes_self_described(self):+ sys.path.insert(0, "features")+ from ffmpeg_pack.config import FFmpegRuntime+ from m3u8_pack.config import M3U8Runtime+ from yt_dlp_pack.config import YouTubeRuntime+ from ed2k_pack.config import ED2kRuntime++ expected = {+ FFmpegRuntime: True,+ M3U8Runtime: True,+ YouTubeRuntime: True,+ ED2kRuntime: False,+ }+ for cls, isRecommended in expected.items():+ assert cls.title, cls.__name__+ assert cls.description, cls.__name__+ assert cls.icon is not None, cls.__name__+ assert cls.isRecommended is isRecommended, cls.__name__+++if __name__ == "__main__":+ pytest.main([__file__, "-v", "--tb=short"])diff --git a/tests/test_task_card_progress.py b/tests/test_task_card_progress.pynew file mode 100644index 00000000..ce4cc21d--- /dev/null+++ b/tests/test_task_card_progress.py@@ -0,0 +1,358 @@+"""任务卡进度条协议的回归测试。++背景:UniversalTaskCard.refresh() 曾假设进度条实现 stop()/error() 等+qfluentwidgets 专有方法,SegmentedProgressBar / ProgressBar 缺少 stop()+导致 COMPLETED 且 fileSize<=0 时 AttributeError 崩溃。++覆盖:+ - 7 种 FeaturePack 卡片 × 全部状态分支 × fileSize {0, >0},refresh 不抛异常+ - COMPLETED 隐藏进度条,回到 RUNNING 重新显示(redownload 回归)+ - 基类 refresh 只使用收窄后的进度条协议动词+ - SegmentedProgressBar 仅在大小已知且多线程时被选择+ - FAILED 时 SegmentedProgressBar 进入错误配色+ - pack 特有分支:BT 做种、YtDlp 播放列表、M3U8 未知大小百分比、+ M3U8 直播录制、FTP/HuggingFace 多文件计数+"""+from __future__ import annotations++import sys+from pathlib import Path+from unittest.mock import MagicMock++import pytest+from PySide6.QtCore import QObject, Signal+from PySide6.QtWidgets import QApplication++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "features"))++app = QApplication.instance() or QApplication(sys.argv)++from app.models.task import Task, TaskStatus+from app.view.cards.task_cards import UniversalTaskCard++from bittorrent_pack.cards import BTTaskCard+from bittorrent_pack.task import BTFile, BTTask, BTTaskStep+from ftp_pack.cards import FtpTaskCard+from ftp_pack.task import FtpConnectionInfo, FtpFile, FtpTask+from http_pack.cards import HttpTaskCard, SegmentedProgressBar+from http_pack.task import HttpTask, HttpTaskStep+from huggingface_pack.cards import HuggingFaceTaskCard+from huggingface_pack.task import HuggingFaceFile, HuggingFaceTask+from m3u8_pack.cards import M3U8LiveTaskCard, M3U8TaskCard+from m3u8_pack.task import M3U8Task, M3U8TaskStep+from yt_dlp_pack.cards import YtDlpTaskCard+from yt_dlp_pack.task import YouTubeExtractStep, YouTubeTask++ALL_STATUSES = [+ TaskStatus.WAITING,+ TaskStatus.RUNNING,+ TaskStatus.PAUSED,+ TaskStatus.FAILED,+ TaskStatus.COMPLETED,+]++ALLOWED_PROGRESS_VERBS = {"setValue", "setError", "pause", "show", "hide", "setGeometry"}+++class StubCategoryService(QObject):+ categoriesChanged = Signal()++ def categories(self):+ return []++ def categoryById(self, cid):+ return None++[email protected](autouse=True)+def categoryStub(monkeypatch):+ monkeypatch.setattr(+ "app.services.category_service.categoryService", StubCategoryService()+ )+++def makeCard():+ cards = []++ def make(cardFactory):+ card = cardFactory()+ cards.append(card)+ card.show()+ return card++ yield make+ for card in cards:+ card.close()+ card.deleteLater()+ app.processEvents()+++# ─── 各 pack 的任务/卡片构造 ─────────────────────────────────+++def buildHttpTask(fileSize=100, canUseRangeRequests=True, subworkerCount=8):+ url = "https://example.com/file.bin"+ step = HttpTaskStep(+ stepIndex=0,+ url=url,+ fileSize=fileSize,+ canUseRangeRequests=canUseRangeRequests,+ subworkerCount=subworkerCount,+ )+ return HttpTask(name="file.bin", url=url, fileSize=fileSize, steps=[step])+++def buildHttpCard(fileSize):+ return HttpTaskCard(buildHttpTask(fileSize=fileSize))+++def buildYtDlpCard(fileSize):+ task = YouTubeTask(+ name="video", url="https://youtube.com/watch?v=x", fileSize=fileSize+ )+ return YtDlpTaskCard(task)+++def buildBtCard(fileSize):+ files = [BTFile(index=0, relativePath="file.bin", size=fileSize)] if fileSize else []+ task = BTTask(+ name="file.bin",+ url="magnet:?xt=urn:btih:0",+ files=files,+ steps=[BTTaskStep(stepIndex=0)],+ )+ return BTTaskCard(task)+++def buildM3U8Card(fileSize):+ task = M3U8Task(+ name="video",+ url="https://example.com/index.m3u8",+ fileSize=fileSize,+ steps=[M3U8TaskStep(stepIndex=0)],+ )+ return M3U8TaskCard(task)+++def buildM3U8LiveCard(fileSize):+ task = M3U8Task(+ name="live",+ url="https://example.com/live.m3u8",+ fileSize=fileSize,+ isLive=True,+ steps=[M3U8TaskStep(stepIndex=0)],+ )+ return M3U8LiveTaskCard(task)+++def buildFtpCard(fileSize):+ task = FtpTask(+ name="file.bin",+ url="ftp://127.0.0.1/file.bin",+ connectionInfo=FtpConnectionInfo(+ scheme="ftp",+ host="127.0.0.1",+ port=21,+ username="",+ password="",+ sourcePath="/file.bin",+ ),+ fileSize=fileSize,+ )+ return FtpTaskCard(task)+++def buildHuggingFaceCard(fileSize):+ task = HuggingFaceTask(+ name="model", url="https://huggingface.co/org/model", fileSize=fileSize+ )+ return HuggingFaceTaskCard(task)+++CARD_BUILDERS = {+ "http": buildHttpCard,+ "ytdlp": buildYtDlpCard,+ "bt": buildBtCard,+ "m3u8": buildM3U8Card,+ "m3u8live": buildM3U8LiveCard,+ "ftp": buildFtpCard,+ "huggingface": buildHuggingFaceCard,+}+++# ─── 全 pack × 全状态矩阵 ────────────────────────────────────++[email protected]("fileSize", [0, 100], ids=["unknownSize", "knownSize"])[email protected]("buildCard", CARD_BUILDERS.values(), ids=CARD_BUILDERS.keys())+class TestRefreshMatrix:++ def test_refresh_covers_every_status(self, makeCard, buildCard, fileSize):+ card = makeCard(lambda: buildCard(fileSize))+ for status in ALL_STATUSES:+ card._task.status = status+ card.refresh(force=True)++ def test_completed_hides_bar_and_running_shows_again(self, makeCard, buildCard, fileSize):+ card = makeCard(lambda: buildCard(fileSize))+ card._task.status = TaskStatus.COMPLETED+ card.refresh(force=True)+ assert card.progressBar.isHidden()++ card._task.status = TaskStatus.RUNNING+ card.refresh(force=True)+ assert not card.progressBar.isHidden()+++# ─── 协议钉死:基类只用收窄后的动词 ──────────────────────────+++def test_refresh_only_uses_shared_progress_verbs(makeCard):+ task = Task(name="file.bin", url="https://example.com/file.bin", packId="test")+ card = makeCard(lambda: UniversalTaskCard(task))+ bar = MagicMock()+ card.progressBar = bar+ app.processEvents()+ bar.reset_mock()++ for status in ALL_STATUSES:+ task.status = status+ card.refresh(force=True)++ calledVerbs = {name.split(".")[0] for name, _, _ in bar.method_calls}+ assert calledVerbs <= ALLOWED_PROGRESS_VERBS+++# ─── SegmentedProgressBar 选择守卫 ───────────────────────────+++ "fileSize,canUseRangeRequests,subworkerCount,expectSegmented",+ [+ (100, True, 8, True),+ (0, True, 8, False),+ (100, False, 8, False),+ (100, True, 1, False),+ ],+ ids=["knownSizeMultiWorker", "unknownSize", "noRangeRequests", "singleWorker"],+)+def test_segmented_bar_requires_known_size(+ makeCard, fileSize, canUseRangeRequests, subworkerCount, expectSegmented+):+ task = buildHttpTask(+ fileSize=fileSize,+ canUseRangeRequests=canUseRangeRequests,+ subworkerCount=subworkerCount,+ )+ card = makeCard(lambda: HttpTaskCard(task))+ assert isinstance(card.progressBar, SegmentedProgressBar) is expectSegmented+++def test_failed_segmented_bar_enters_error_state(makeCard):+ card = makeCard(lambda: buildHttpCard(100))+ assert isinstance(card.progressBar, SegmentedProgressBar)+ card._task.status = TaskStatus.FAILED+ card.refresh(force=True)+ assert card.progressBar._isError+++# ─── pack 特有分支 ───────────────────────────────────────────+++def test_bt_seeding_hides_bar_and_shows_status(makeCard):+ card = makeCard(lambda: buildBtCard(100))+ card._task.isSeeding = True+ card._task.status = TaskStatus.RUNNING+ card.refresh(force=True)+ assert card.progressBar.isHidden()+ assert "做种中" in card.statusLabel.text()++ card._task.isSeeding = False+ card.refresh(force=True)+ assert not card.progressBar.isHidden()+++def test_ytdlp_playlist_completed_shows_video_count(makeCard):+ task = YouTubeTask(+ name="playlist",+ url="https://youtube.com/playlist?list=x",+ isPlaylist=True,+ steps=[+ YouTubeExtractStep(stepIndex=i, receivedBytes=25) for i in range(4)+ ],+ )+ card = makeCard(lambda: YtDlpTaskCard(task))+ task.status = TaskStatus.COMPLETED+ card.refresh(force=True)+ assert "个视频" in card.sizeLabel.text()+ assert not card.sizeLabel.isHidden()+++def test_m3u8_running_unknown_size_shows_percent(makeCard):+ card = makeCard(lambda: buildM3U8Card(0))+ step = card._task.steps[0]+ step.progress = 42.0+ step.receivedBytes = 1000+ card._task.status = TaskStatus.RUNNING+ card.refresh(force=True)+ assert "%" in card.sizeLabel.text()+++def test_m3u8_live_running_shows_recording(makeCard):+ card = makeCard(lambda: buildM3U8LiveCard(0))+ card._task.status = TaskStatus.RUNNING+ card.refresh(force=True)+ assert card.sizeLabel.text() == "录制中"++ card._task.steps[0].liveStatus = "Waiting"+ card.refresh(force=True)+ assert card.sizeLabel.text() == "等待中"+++def test_ftp_multifile_shows_selection_count(makeCard):+ task = FtpTask(+ name="folder",+ url="ftp://127.0.0.1/dir",+ sourceType="dir",+ connectionInfo=FtpConnectionInfo(+ scheme="ftp",+ host="127.0.0.1",+ port=21,+ username="",+ password="",+ sourcePath="/dir",+ ),+ fileSize=100,+ files=[+ FtpFile(index=0, relativePath="a.bin", size=50, remotePath="/a.bin"),+ FtpFile(index=1, relativePath="b.bin", size=50, remotePath="/b.bin"),+ ],+ )+ card = makeCard(lambda: FtpTaskCard(task))+ card._task.status = TaskStatus.WAITING+ card.refresh(force=True)+ assert "2/2" in card.statusLabel.text()+ assert card.selectFilesButton is not None+++def test_huggingface_multifile_shows_selection_count(makeCard):+ task = HuggingFaceTask(+ name="model",+ url="https://huggingface.co/org/model",+ files=[+ HuggingFaceFile(index=0, relativePath="a.safetensors", size=50),+ HuggingFaceFile(index=1, relativePath="b.safetensors", size=50),+ ],+ )+ card = makeCard(lambda: HuggingFaceTaskCard(task))+ card._task.status = TaskStatus.WAITING+ card.refresh(force=True)+ assert card.selectFilesButton is not None+ assert "2/2" in card.statusLabel.text()+++if __name__ == "__main__":+ pytest.main([__file__, "-v", "--tb=short"])diff --git a/tests/test_task_page_lazy.py b/tests/test_task_page_lazy.pynew file mode 100644index 00000000..76f8377d--- /dev/null+++ b/tests/test_task_page_lazy.py@@ -0,0 +1,711 @@+"""TaskPage 懒加载重构的逐分支测试。++覆盖:+ - 视口卡片生命周期(创建/销毁)+ - 选择状态提升(_selectedIds)+ - selectAll / invertSelection / selectMissing+ - Shift+Click 范围选择+ - CommandView 批量操作(重下载/删除/移动分类)+ - 筛选切换后选择态保留与恢复+ - 空状态判断+ - _onTaskAdded / _onTaskRemoved+ - _onFileDisappeared+"""+from __future__ import annotations++import sys+from dataclasses import dataclass, field+from pathlib import Path+from time import time+from typing import ClassVar, Type+from unittest.mock import MagicMock, patch++import pytest+from PySide6.QtCore import Signal, QObject+from PySide6.QtWidgets import QApplication++app = QApplication.instance() or QApplication(sys.argv)+++# ─── 轻量 stub ───────────────────────────────────────────────+++class StubTaskStore:+ def __init__(self):+ self._tasks: dict[str, StubTask] = {}++ def tasks(self):+ return dict(self._tasks)++ def taskById(self, taskId):+ return self._tasks.get(taskId)++ def flush(self):+ pass+++class StubTaskService(QObject):+ taskAdded = Signal(object)+ taskRemoved = Signal(str)+ taskStarted = Signal(object)+ taskPaused = Signal(object)+ taskCompleted = Signal(object)+ taskFailed = Signal(object)+ fileDisappeared = Signal(object)++ def __init__(self):+ super().__init__()+ self._store = StubTaskStore()+ self._redownloaded: list[str] = []+ self._deleted: list[tuple[str, bool]] = []+ self._categories: dict[str, str] = {}++ @property+ def tasks(self) -> list[StubTask]:+ return list(self._store._tasks.values())++ def taskById(self, taskId: str):+ return self._store.taskById(taskId)++ def addTask(self, task: StubTask):+ self._store._tasks[task.taskId] = task+ self.taskAdded.emit(task)++ def removeTask(self, taskId: str):+ self._store._tasks.pop(taskId, None)+ self.taskRemoved.emit(taskId)++ def redownload(self, task):+ self._redownloaded.append(task.taskId)++ def delete(self, task, shouldDeleteFiles: bool):+ self._deleted.append((task.taskId, shouldDeleteFiles))+ self.removeTask(task.taskId)++ def setCategory(self, task, categoryId: str):+ task.category = categoryId+ self._categories[task.taskId] = categoryId++ def startAll(self):+ pass++ def pauseAll(self):+ pass+++class StubTask:+ hasOutputFile: ClassVar[bool] = True++ def __init__(self, taskId: str, name: str = "", status=None, fileSize: int = 100,+ createdAt: int = 0, completedAt: int = 0, category: str = ""):+ from app.models.task import TaskStatus+ self.taskId = taskId+ self.name = name or taskId+ self.url = f"https://example.com/{taskId}"+ self.packId = "stub"+ self.status = status or TaskStatus.WAITING+ self.fileSize = fileSize+ self.createdAt = createdAt or int(time())+ self.completedAt = completedAt+ self.outputFolder = Path("C:/tmp/downloads")+ self.category = category+ self.steps = []++ @property+ def outputPath(self) -> str:+ return str(self.outputFolder / self.name)++ @property+ def canPause(self) -> bool:+ return True++ @property+ def lastError(self):+ return None++ def currentSnapshot(self):+ return 50.0, 1024, self.fileSize // 2+++class StubSpeedMeter(QObject):+ speedChanged = Signal(int)+++class StubCategoryService(QObject):+ categoriesChanged = Signal()++ def categories(self):+ return []++ def categoryById(self, cid):+ return None+++# ─── fixtures ────────────────────────────────────────────────++def env(monkeypatch):+ """搭建完整的 stub 环境,返回 (taskPage, stubTaskService)。"""+ stubService = StubTaskService()+ stubSpeed = StubSpeedMeter()+ stubCategory = StubCategoryService()++ monkeypatch.setattr("app.services.task_service.taskService", stubService)+ monkeypatch.setattr("app.view.pages.task_page.taskService", stubService)+ monkeypatch.setattr("app.view.pages.task_page.speedMeter", stubSpeed)+ monkeypatch.setattr("app.services.category_service.categoryService", stubCategory)++ from app.view.cards.task_cards import UniversalTaskCard++ def fakeTaskCard(task, parent=None):+ return UniversalTaskCard(task, parent)++ monkeypatch.setattr("app.view.pages.task_page.featureService",+ MagicMock(taskCard=MagicMock(side_effect=fakeTaskCard)))++ # cfg stubs+ monkeypatch.setattr("app.view.pages.task_page.cfg.isCategoryEnabled",+ MagicMock(value=False, valueChanged=MagicMock(connect=MagicMock())))+ monkeypatch.setattr("app.view.pages.task_page.cfg.isSpeedLimitEnabled",+ MagicMock(value=False))++ from app.view.pages.task_page import TaskPage+ page = TaskPage()+ page.resize(400, 800)+ page.show()++ app.processEvents()++ return page, stubService+++def _addTasks(svc: StubTaskService, count: int, **kwargs) -> list[StubTask]:+ tasks = []+ for i in range(count):+ t = StubTask(taskId=f"t{i}", name=f"file_{i}.zip", createdAt=1000 + i, **kwargs)+ tasks.append(t)+ for t in tasks:+ svc.addTask(t)+ app.processEvents()+ return tasks+++def _visibleIds(page) -> set[str]:+ return set(page._liveCards.keys())+++# ─── 视口生命周期 ─────────────────────────────────────────────++class TestViewportLifecycle:++ def test_only_viewport_cards_created(self, env):+ page, svc = env+ tasks = _addTasks(svc, 50)+ assert len(page._liveCards) < 50+ assert len(page._liveCards) > 0++ def test_scroll_creates_and_destroys(self, env):+ page, svc = env+ _addTasks(svc, 50)+ initialIds = set(page._liveCards.keys())++ page.scrollArea.verticalScrollBar().setValue(+ page.scrollArea.verticalScrollBar().maximum()+ )+ app.processEvents()+ page._refreshViewport()++ afterScrollIds = set(page._liveCards.keys())+ assert afterScrollIds != initialIds++ def test_empty_state_no_tasks(self, env):+ page, svc = env+ app.processEvents()+ assert page.emptyStatusWidget.isVisible()++ def test_empty_state_with_filter(self, env):+ from app.models.task import TaskStatus+ page, svc = env+ _addTasks(svc, 3, status=TaskStatus.COMPLETED)+ from app.view.pages.task_page import FilterMode+ page.setFilterMode(FilterMode.ACTIVE)+ assert page.emptyStatusWidget.isVisible()++ def test_task_added_creates_card_in_viewport(self, env):+ page, svc = env+ t = StubTask(taskId="new1", createdAt=9999)+ svc.addTask(t)+ app.processEvents()+ assert "new1" in page._displayOrder++ def test_task_removed_destroys_card(self, env):+ page, svc = env+ _addTasks(svc, 5)+ assert "t0" in page._liveCards+ svc.removeTask("t0")+ app.processEvents()+ assert "t0" not in page._liveCards++ def test_create_card_returns_none(self, env):+ """pack 不可用时 featureService.taskCard 返回 None,不崩溃。"""+ page, svc = env+ from app.view.pages.task_page import featureService+ featureService.taskCard.side_effect = lambda task, parent=None: None+ t = StubTask(taskId="orphan", createdAt=9999)+ svc.addTask(t)+ app.processEvents()+ assert "orphan" not in page._liveCards+++# ─── 选择状态提升 ─────────────────────────────────────────────++class TestSelectionState:++ def test_select_all_includes_offscreen(self, env):+ page, svc = env+ _addTasks(svc, 50)+ page.setSelectionMode(True)+ page.selectAll()+ assert page._selectedIds == set(page._displayOrder)+ assert len(page._selectedIds) == 50++ def test_invert_selection(self, env):+ page, svc = env+ _addTasks(svc, 50)+ page.setSelectionMode(True)+ page._selectedIds.add("t0")+ page._selectedIds.add("t1")+ page.invertSelection()+ assert "t0" not in page._selectedIds+ assert "t1" not in page._selectedIds+ assert "t2" in page._selectedIds++ def test_select_missing_checks_filesystem(self, env, tmp_path):+ page, svc = env+ tasks = _addTasks(svc, 5)+ for t in tasks:+ t.outputFolder = tmp_path+ existing = tmp_path / "file_0.zip"+ existing.write_bytes(b"data")++ page.setSelectionMode(True)+ page.selectMissing()++ assert "t0" not in page._selectedIds+ assert "t1" in page._selectedIds+ assert "t2" in page._selectedIds++ def test_exit_selection_clears_selectedIds(self, env):+ page, svc = env+ _addTasks(svc, 5)+ page.setSelectionMode(True)+ page.selectAll()+ assert len(page._selectedIds) > 0+ page.setSelectionMode(False)+ assert len(page._selectedIds) == 0++ def test_selection_restored_on_scroll(self, env):+ page, svc = env+ _addTasks(svc, 50)+ page.setSelectionMode(True)+ page.selectAll()++ page.scrollArea.verticalScrollBar().setValue(+ page.scrollArea.verticalScrollBar().maximum()+ )+ app.processEvents()+ page._refreshViewport()++ for taskId, card in page._liveCards.items():+ assert card.isChecked(), f"Card {taskId} should be checked after scroll"++ def test_shift_click_range(self, env):+ page, svc = env+ _addTasks(svc, 10)+ page.setSelectionMode(True)++ page._onCardSelectionChanged("t2", True, False)+ assert page._selectionAnchor == "t2"++ page._onCardSelectionChanged("t5", True, True)+ assert page._selectedIds == {"t2", "t3", "t4", "t5"}++ def test_uncheck_last_exits_selection_mode(self, env):+ page, svc = env+ _addTasks(svc, 3)+ page._onCardSelectionChanged("t0", True, False)+ assert page._isSelectionMode is True+ page._onCardSelectionChanged("t0", False, False)+ assert page._isSelectionMode is False++ def test_selection_survives_filter_change(self, env):+ from app.models.task import TaskStatus+ from app.view.pages.task_page import FilterMode+ page, svc = env+ tasks = _addTasks(svc, 10)+ tasks[0].status = TaskStatus.COMPLETED+ tasks[1].status = TaskStatus.COMPLETED+ for t in tasks[2:]:+ t.status = TaskStatus.WAITING++ page.setSelectionMode(True)+ page.selectAll()+ allSelected = set(page._selectedIds)++ page.setFilterMode(FilterMode.ACTIVE)+ assert page._selectedIds == allSelected++ page.setFilterMode(FilterMode.ALL)+ for taskId in page._liveCards:+ card = page._liveCards[taskId]+ if taskId in allSelected:+ assert card.isChecked()+++# ─── CommandView 批量操作 ────────────────────────────────────++class TestCommandViewActions:++ def test_redownload_selected(self, env):+ page, svc = env+ _addTasks(svc, 5)+ page.setSelectionMode(True)+ page._selectedIds.update(["t1", "t3"])+ for tid, card in page._liveCards.items():+ card.setChecked(tid in page._selectedIds)++ page._onRedownloadSelected()+ assert set(svc._redownloaded) == {"t1", "t3"}+ assert page._isSelectionMode is False++ def test_delete_selected(self, env):+ page, svc = env+ _addTasks(svc, 5)+ page.setSelectionMode(True)+ page._selectedIds.update(["t0", "t2", "t4"])+ for tid, card in page._liveCards.items():+ card.setChecked(tid in page._selectedIds)++ page._onDeleteConfirmed(shouldDeleteFiles=True)+ deletedIds = {tid for tid, _ in svc._deleted}+ assert deletedIds == {"t0", "t2", "t4"}+ assert page._isSelectionMode is False++ def test_delete_scoped_to_display_order(self, env):+ """只删除 _displayOrder 中的选中任务,不删除被筛选掉的。"""+ from app.models.task import TaskStatus+ from app.view.pages.task_page import FilterMode+ page, svc = env+ tasks = _addTasks(svc, 5)+ tasks[0].status = TaskStatus.COMPLETED+ for t in tasks[1:]:+ t.status = TaskStatus.WAITING++ page.setSelectionMode(True)+ page.selectAll()+ page.setFilterMode(FilterMode.ACTIVE)++ page._onDeleteConfirmed(shouldDeleteFiles=False)+ deletedIds = {tid for tid, _ in svc._deleted}+ assert "t0" not in deletedIds++ def test_move_category_selected(self, env):+ page, svc = env+ _addTasks(svc, 3)+ page.setSelectionMode(True)+ page._selectedIds.update(["t0", "t2"])++ targets = [+ task for taskId in page._displayOrder+ if taskId in page._selectedIds and (task := svc.taskById(taskId))+ ]+ assert len(targets) == 2+ for task in targets:+ svc.setCategory(task, "cat1")+ assert svc._categories["t0"] == "cat1"+ assert svc._categories["t2"] == "cat1"++ def test_redownload_only_displayed(self, env):+ """重下载只操作当前 displayOrder 中的选中任务。"""+ from app.models.task import TaskStatus+ from app.view.pages.task_page import FilterMode+ page, svc = env+ tasks = _addTasks(svc, 5)+ tasks[0].status = TaskStatus.COMPLETED+ for t in tasks[1:]:+ t.status = TaskStatus.WAITING++ page.setSelectionMode(True)+ page.selectAll()+ page.setFilterMode(FilterMode.ACTIVE)++ page._onRedownloadSelected()+ assert "t0" not in svc._redownloaded+++# ─── _onFileDisappeared ──────────────────────────────────────++class TestFileDisappeared:++ def test_refresh_visible_card(self, env):+ page, svc = env+ tasks = _addTasks(svc, 3)+ card = page._liveCards.get("t0")+ assert card is not None+ card.refresh = MagicMock()+ svc.fileDisappeared.emit(tasks[0])+ assert card.refresh.called+ assert card.refresh.call_args == ((True,),) or \+ card.refresh.call_args.kwargs.get("force") is True++ def test_ignore_offscreen_card(self, env):+ page, svc = env+ tasks = _addTasks(svc, 50)+ # 默认 createdAt 降序,最早创建的 t0 排在最底部(index 49),应在视口外+ offscreen = tasks[0]+ assert offscreen.taskId not in page._liveCards+ svc.fileDisappeared.emit(offscreen)+++# ─── _refreshVisibleCards ────────────────────────────────────++class TestRefreshVisibleCards:++ def test_refreshes_all_live_cards(self, env):+ page, svc = env+ _addTasks(svc, 5)+ mocks = {}+ for tid, card in page._liveCards.items():+ m = MagicMock()+ card.refresh = m+ mocks[tid] = m++ page._refreshVisibleCards()+ for tid, m in mocks.items():+ assert m.called, f"Card {tid} should have been refreshed"+++# ─── Delete 快捷键 ───────────────────────────────────────────++class TestDeleteShortcut:++ def test_delete_key_triggers_delete_dialog(self, env):+ from unittest.mock import patch as _patch+ from PySide6.QtCore import Qt+ from PySide6.QtGui import QKeyEvent+ page, svc = env+ _addTasks(svc, 3)+ page.setSelectionMode(True)+ page._selectedIds.update(["t0", "t1"])++ with _patch.object(page, "_onDeleteSelected") as mock:+ event = QKeyEvent(QKeyEvent.Type.KeyPress, Qt.Key.Key_Delete, Qt.KeyboardModifier.NoModifier)+ page.keyPressEvent(event)+ assert mock.called++ def test_delete_key_ignored_outside_selection_mode(self, env):+ from unittest.mock import patch as _patch+ from PySide6.QtCore import Qt+ from PySide6.QtGui import QKeyEvent+ page, svc = env+ _addTasks(svc, 3)++ with _patch.object(page, "_onDeleteSelected") as mock:+ event = QKeyEvent(QKeyEvent.Type.KeyPress, Qt.Key.Key_Delete, Qt.KeyboardModifier.NoModifier)+ page.keyPressEvent(event)+ assert not mock.called+++# ─── BandSelector ────────────────────────────────────────────++class TestBandSelector:++ def test_band_selector_exists(self, env):+ page, svc = env+ assert hasattr(page, "_bandSelector")+ from app.view.components.band_selector import BandSelector+ assert isinstance(page._bandSelector, BandSelector)++ def test_band_drag_started_enters_selection_mode(self, env):+ page, svc = env+ _addTasks(svc, 10)+ assert page._isSelectionMode is False+ page._onBandDragStarted(False)+ assert page._isSelectionMode is True++ def test_band_drag_started_with_shift_saves_snapshot(self, env):+ page, svc = env+ _addTasks(svc, 10)+ page.setSelectionMode(True)+ page._selectedIds.update(["t8", "t9"])+ page._onBandDragStarted(True)+ assert page._bandSnapshot == {"t8", "t9"}++ def test_band_drag_started_without_shift_clears_snapshot(self, env):+ page, svc = env+ _addTasks(svc, 10)+ page.setSelectionMode(True)+ page._selectedIds.update(["t8", "t9"])+ page._onBandDragStarted(False)+ assert page._bandSnapshot == set()++ def test_band_changed_selects_range(self, env):+ page, svc = env+ _addTasks(svc, 10)+ page._onBandDragStarted(False)+ # 选中 displayOrder 中 index 0..2(降序排列: t9, t8, t7)+ page._onBandChanged(0, 2)+ assert len(page._selectedIds) == 3+ assert page._displayOrder[0] in page._selectedIds+ assert page._displayOrder[1] in page._selectedIds+ assert page._displayOrder[2] in page._selectedIds++ def test_band_changed_replaces_previous(self, env):+ page, svc = env+ _addTasks(svc, 10)+ page._onBandDragStarted(False)+ page._onBandChanged(0, 4)+ assert len(page._selectedIds) == 5+ page._onBandChanged(2, 3)+ assert len(page._selectedIds) == 2++ def test_band_changed_with_shift_appends(self, env):+ page, svc = env+ _addTasks(svc, 10)+ page.setSelectionMode(True)+ page._selectedIds.update(["t0", "t1"])+ page._onBandDragStarted(True)+ page._onBandChanged(0, 2)+ # 原来的 t0, t1 + band 选中的 3 个+ assert "t0" in page._selectedIds+ assert "t1" in page._selectedIds+ assert len(page._selectedIds) >= 3++ def test_band_changed_negative_clears(self, env):+ page, svc = env+ _addTasks(svc, 10)+ page._onBandDragStarted(False)+ page._onBandChanged(0, 2)+ assert len(page._selectedIds) == 3+ page._onBandChanged(-1, -1)+ assert len(page._selectedIds) == 0++ def test_band_finished_exits_if_empty(self, env):+ page, svc = env+ _addTasks(svc, 10)+ page._onBandDragStarted(False)+ page._onBandChanged(-1, -1)+ page._onBandDragFinished()+ assert page._isSelectionMode is False++ def test_band_finished_stays_if_selected(self, env):+ page, svc = env+ _addTasks(svc, 10)+ page._onBandDragStarted(False)+ page._onBandChanged(0, 2)+ page._onBandDragFinished()+ assert page._isSelectionMode is True+ assert len(page._selectedIds) == 3++ def test_band_syncs_live_card_checkboxes(self, env):+ page, svc = env+ _addTasks(svc, 5)+ page._onBandDragStarted(False)+ page._onBandChanged(0, len(page._displayOrder) - 1)+ for card in page._liveCards.values():+ assert card.isChecked()++ def test_band_selector_disabled_on_item_count_change(self, env):+ page, svc = env+ _addTasks(svc, 10)+ page._bandSelector._isDragging = True+ page._bandSelector.setItemCount(5)+ assert page._bandSelector._isDragging is False++ def test_set_enabled_false_clears_drag(self, env):+ page, svc = env+ _addTasks(svc, 10)+ page._bandSelector._isDragging = True+ page._bandSelector.setEnabled(False)+ assert page._bandSelector._isDragging is False+++# ─── 卸载推迟(嵌套事件循环安全) ─────────────────────────────++class TestUnmountDeferral:++ def test_unmount_deferred_inside_nested_loop(self, env):+ """嵌套循环(对话框 exec)中卸载的卡片推迟真删,回主循环后回收。"""+ import shiboken6+ from PySide6.QtCore import QEventLoop, QTimer++ page, svc = env+ tasks = _addTasks(svc, 5)+ cardId = tasks[0].taskId+ card = page._liveCards[cardId]++ results = {}+ outer, inner = QEventLoop(), QEventLoop()++ def innerBody(): # loopLevel == 2,模拟对话框 exec 期间+ svc.removeTask(cardId)+ app.processEvents()+ results["alive"] = shiboken6.isValid(card)+ results["hidden"] = not card.isVisible()+ results["pending"] = card in page._pendingUnmounts+ inner.quit()++ def outerBody(): # loopLevel == 1,模拟主循环+ QTimer.singleShot(0, innerBody)+ inner.exec()+ outer.quit()++ QTimer.singleShot(0, outerBody)+ outer.exec()++ assert results == {"alive": True, "hidden": True, "pending": True}++ def reap(): # loopLevel == 1:刷新触发回收+ page._refreshViewport()+ outer.quit()++ QTimer.singleShot(0, reap)+ outer.exec()+ app.processEvents() # DeferredDelete 需回到更浅层级才执行++ assert not page._pendingUnmounts+ assert not shiboken6.isValid(card)++ def test_unmount_immediate_at_main_loop(self, env):+ """无嵌套循环时卸载走 deleteLater,不积压。"""+ page, svc = env+ tasks = _addTasks(svc, 5)+ svc.removeTask(tasks[0].taskId)+ assert not page._pendingUnmounts+++# ─── 拖拽队列投递 ─────────────────────────────────────────────++class TestDragRequestedQueued:++ def test_drag_starts_from_page_frame(self, env, monkeypatch):+ """dragRequested 队列投递:emit 同步阶段不启动拖拽,事件循环后启动。"""+ from app.models.task import TaskStatus++ page, svc = env+ tasks = _addTasks(svc, 3, status=TaskStatus.COMPLETED)+ card = page._liveCards[tasks[0].taskId]++ calls = []+ monkeypatch.setattr("app.platform.desktop.startFileDrag",+ lambda paths, source: calls.append(paths))++ card.dragRequested.emit(tasks[0].taskId)+ assert not calls # 直连会立刻执行;队列投递此刻必须为空++ app.processEvents()+ assert calls == [[Path(tasks[0].outputPath)]]+++if __name__ == "__main__":+ pytest.main([__file__, "-v", "--tb=short"])