Skip to content

The only downloader you need. 下载器的集大成者。

refactor(tests): 精简测试套件至核心 seam

XiaoYouChR48e697fe34a9
diff --git a/tests/test_aria2_rpc_e2e.py b/tests/test_aria2_rpc_e2e.py
deleted file mode 100644
index 4065a195..00000000
--- a/tests/test_aria2_rpc_e2e.py
+++ /dev/null
@@ -1,140 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-import http.client
-import json
-import time
-
-import pytest
-
-from app.config.cfg import cfg
-from app.services.aria2_rpc import Aria2RpcServer
-from app.services.coroutine_runner import CoroutineRunner
-
-
-def _findFreePort() -> int:
- import socket
- with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
- s.bind(('127.0.0.1', 0))
- return s.getsockname()[1]
-
-
-def _rpcRequest(port: int, method: str, params: list | None = None, rpcId: int = 1) -> dict:
- body = json.dumps({
- "jsonrpc": "2.0",
- "id": rpcId,
- "method": method,
- "params": params or [],
- }).encode("utf-8")
-
- conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
- conn.request("POST", "/jsonrpc", body=body, headers={
- "Content-Type": "application/json",
- "Content-Length": str(len(body)),
- })
- resp = conn.getresponse()
- data = json.loads(resp.read())
- conn.close()
- return data
-
-
-def runner(qapp):
- from PySide6.QtCore import QTimer
- from shiboken6 import isValid
-
- dispatcher = lambda fn: QTimer.singleShot(0, qapp, fn)
- cr = CoroutineRunner(dispatcher, isAlive=isValid, loop=asyncio.new_event_loop())
- cr.start()
- yield cr
- cr.stop()
-
-
-def server(runner):
- port = _findFreePort()
- cfg.set(cfg.aria2RpcPort, port)
- cfg.set(cfg.aria2RpcToken, "")
-
- async def mockParse(options):
- raise RuntimeError("parse not implemented in test")
-
- srv = Aria2RpcServer(runner, parse=mockParse, addTask=lambda t: None)
- yield srv, port
- srv.stop()
-
-
-class TestAria2RpcServer:
-
- def test_start_binds_port(self, server):
- srv, port = server
- srv.start()
- time.sleep(0.2)
- assert srv._serveWorkId is not None
-
- def test_getVersion(self, server):
- srv, port = server
- srv.start()
- time.sleep(0.2)
-
- resp = _rpcRequest(port, "aria2.getVersion")
- assert resp["jsonrpc"] == "2.0"
- assert resp["id"] == 1
- assert "version" in resp["result"]
- assert "enabledFeatures" in resp["result"]
-
- def test_addUri(self, server):
- srv, port = server
- srv.start()
- time.sleep(0.2)
-
- resp = _rpcRequest(port, "aria2.addUri", [["https://example.com/file.zip"]])
- assert resp["jsonrpc"] == "2.0"
- assert resp["id"] == 1
- assert isinstance(resp["result"], str)
- assert len(resp["result"]) == 16
-
- def test_method_not_found(self, server):
- srv, port = server
- srv.start()
- time.sleep(0.2)
-
- resp = _rpcRequest(port, "aria2.unknownMethod")
- assert "error" in resp
- assert resp["error"]["code"] == -32601
-
- def test_stop_and_restart(self, server):
- srv, port = server
- srv.start()
- time.sleep(0.2)
-
- resp = _rpcRequest(port, "aria2.getVersion")
- assert "result" in resp
-
- srv.stop()
- time.sleep(0.3)
- assert srv._serveWorkId is None
-
- cfg.set(cfg.aria2RpcPort, port)
- srv.start()
- time.sleep(0.2)
-
- resp = _rpcRequest(port, "aria2.getVersion")
- assert "result" in resp
-
- def test_token_auth(self, server):
- srv, port = server
- cfg.set(cfg.aria2RpcToken, "mysecret")
- srv.start()
- time.sleep(0.2)
-
- resp = _rpcRequest(port, "aria2.getVersion", ["token:mysecret"])
- assert "result" in resp
-
- resp = _rpcRequest(port, "aria2.getVersion", ["token:wrong"])
- assert "error" in resp
- assert resp["error"]["message"] == "Unauthorized"
-
- resp = _rpcRequest(port, "aria2.getVersion", [])
- assert "error" in resp
- assert resp["error"]["message"] == "Unauthorized"
diff --git a/tests/test_browser_service_e2e.py b/tests/test_browser_service_e2e.py
deleted file mode 100644
index 9f99eabf..00000000
--- a/tests/test_browser_service_e2e.py
+++ /dev/null
@@ -1,226 +0,0 @@
-"""BrowserService E2E: websockets transport + Signal I/O bridge."""
-from __future__ import annotations
-
-import asyncio
-import json
-import time
-
-import pytest
-import websockets
-
-from app.services.browser_service import BrowserService, PROTOCOL_VERSION
-from app.services.coroutine_runner import CoroutineRunner
-
-
-class StubTaskService:
- tasks = []
-
- def add(self, task):
- pass
-
- def pause(self, task):
- pass
-
- def start(self, task):
- pass
-
- def delete(self, task, shouldDeleteFiles=False):
- pass
-
- def redownload(self, task):
- pass
-
- def taskById(self, taskId):
- return None
-
-
-TEST_TOKEN = "test-pair-token-abc"
-
-
-def processEventsUntil(qapp, predicate, timeout=5.0):
- deadline = time.monotonic() + timeout
- while time.monotonic() < deadline:
- qapp.processEvents()
- if predicate():
- return True
- time.sleep(0.02)
- return False
-
-
-def runner(qapp):
- from PySide6.QtCore import QTimer
- from shiboken6 import isValid
-
- dispatcher = lambda fn: QTimer.singleShot(0, qapp, fn)
- cr = CoroutineRunner(dispatcher, isAlive=isValid, loop=asyncio.new_event_loop())
- cr.start()
- yield cr
- cr.stop()
-
-
-def service(qapp, runner, monkeypatch):
- from app.config.cfg import cfg
- monkeypatch.setattr(cfg.browserExtensionPairToken, "value", TEST_TOKEN)
- monkeypatch.setattr(cfg.shouldDraftTakenDownload, "value", False)
-
- svc = BrowserService(runner, StubTaskService(), parse=lambda opts: None, loadCrx=lambda: b"")
- yield svc
- svc.stop()
-
-
-def startOnFreePort(service):
- """Start BrowserService on a random free port, bypassing config validation."""
- import socket as _socket
- if service._serveWorkId is not None:
- return
- sock = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
- sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1)
- sock.bind(('127.0.0.1', 0))
- sock.listen()
- sock.setblocking(False)
- service._boundPort = sock.getsockname()[1]
- service._serveWorkId = service._coroutineRunner.submit(service._run(sock))
- service._snapshotWorkId = service._coroutineRunner.submit(service._broadcastLoop())
-
-
-class TestBrowserServiceE2E:
-
- def test_start_binds_port_immediately(self, service):
- startOnFreePort(service)
- assert service.boundPort > 0
-
- def test_stop_resets_port(self, service):
- startOnFreePort(service)
- assert service.boundPort > 0
- service.stop()
- assert service.boundPort == 0
-
- def test_restart_after_stop(self, service):
- startOnFreePort(service)
- port1 = service.boundPort
- assert port1 > 0
- service.stop()
- assert service.boundPort == 0
- startOnFreePort(service)
- port2 = service.boundPort
- assert port2 > 0
-
- def test_websocket_connect(self, qapp, service):
- startOnFreePort(service)
- port = service.boundPort
-
- connected = [False]
-
- async def tryConnect():
- async with websockets.connect(f"ws://127.0.0.1:{port}"):
- connected[0] = True
-
- service._coroutineRunner.submit(tryConnect())
- assert processEventsUntil(qapp, lambda: connected[0])
-
- def test_hello_handshake(self, qapp, service):
- startOnFreePort(service)
- port = service.boundPort
-
- result = [None]
-
- async def doHandshake():
- async with websockets.connect(f"ws://127.0.0.1:{port}") as ws:
- await ws.send(json.dumps({
- "type": "hello",
- "protocolVersion": PROTOCOL_VERSION,
- "token": TEST_TOKEN,
- "extensionVersion": "1.0.0",
- "installType": "normal",
- }))
- resp = json.loads(await asyncio.wait_for(ws.recv(), timeout=5))
- result[0] = resp
-
- service._coroutineRunner.submit(doHandshake())
- assert processEventsUntil(qapp, lambda: result[0] is not None)
- assert result[0]["type"] == "hello_ack"
- assert result[0]["protocolVersion"] == PROTOCOL_VERSION
-
- def test_hello_wrong_token(self, qapp, service):
- startOnFreePort(service)
- port = service.boundPort
-
- result = [None]
-
- async def doHandshake():
- async with websockets.connect(f"ws://127.0.0.1:{port}") as ws:
- await ws.send(json.dumps({
- "type": "hello",
- "protocolVersion": PROTOCOL_VERSION,
- "token": "wrong-token",
- "extensionVersion": "1.0.0",
- "installType": "normal",
- }))
- resp = json.loads(await asyncio.wait_for(ws.recv(), timeout=5))
- result[0] = resp
-
- service._coroutineRunner.submit(doHandshake())
- assert processEventsUntil(qapp, lambda: result[0] is not None)
- assert result[0]["type"] == "error"
- assert result[0]["code"] == "unauthorized"
-
- def test_pair_request_flow(self, qapp, service):
- startOnFreePort(service)
- port = service.boundPort
-
- pairPayload = [None]
- result = [None]
-
- def onPairRequested(req):
- pairPayload[0] = req
- service.approvePair(req["session"], req["requestId"])
-
- service.pairRequested.connect(onPairRequested)
-
- async def doPair():
- async with websockets.connect(f"ws://127.0.0.1:{port}") as ws:
- await ws.send(json.dumps({
- "type": "pair_request",
- "requestId": "pr-1",
- "protocolVersion": PROTOCOL_VERSION,
- "extensionVersion": "1.0.0",
- "clientKind": "chrome",
- }))
- resp = json.loads(await asyncio.wait_for(ws.recv(), timeout=5))
- result[0] = resp
-
- service._coroutineRunner.submit(doPair())
- assert processEventsUntil(qapp, lambda: result[0] is not None)
- assert pairPayload[0] is not None
- assert pairPayload[0]["requestId"] == "pr-1"
- assert result[0]["type"] == "pair_result"
- assert result[0]["ok"] is True
- assert result[0]["token"] == TEST_TOKEN
-
- def test_connection_changed_signal(self, qapp, service):
- startOnFreePort(service)
- port = service.boundPort
-
- signals = []
- service.connectionChanged.connect(lambda: signals.append("changed"))
-
- handshakeDone = [False]
-
- async def doHello():
- async with websockets.connect(f"ws://127.0.0.1:{port}") as ws:
- await ws.send(json.dumps({
- "type": "hello",
- "protocolVersion": PROTOCOL_VERSION,
- "token": TEST_TOKEN,
- "extensionVersion": "1.0.0",
- "installType": "normal",
- }))
- await asyncio.wait_for(ws.recv(), timeout=5)
- handshakeDone[0] = True
- await asyncio.sleep(0.2)
-
- service._coroutineRunner.submit(doHello())
- assert processEventsUntil(qapp, lambda: handshakeDone[0])
- assert "changed" in signals
diff --git a/tests/test_bt_session.py b/tests/test_bt_session.py
deleted file mode 100644
index 33ceb7f6..00000000
--- a/tests/test_bt_session.py
+++ /dev/null
@@ -1,160 +0,0 @@
-"""BTSession 集成测试。
-
-Seam: BTSession.run / duplicate rejection / updatePriorities / close
-使用合成本地种子,不依赖网络。
-"""
-from __future__ import annotations
-
-import asyncio
-import os
-import tempfile
-
-import libtorrent as lt
-import pytest
-
-from features.bittorrent_pack.session import BTSession, TorrentParams, TorrentProgress
-from features.bittorrent_pack.config import bittorrentConfig
-
-
-def torrent_env():
- """创建一个包含两个小文件的本地种子和对应目录。"""
- with tempfile.TemporaryDirectory() as srcDir:
- root = os.path.join(srcDir, "test_torrent")
- os.makedirs(root)
- for name, size in [("a.txt", 16384), ("b.txt", 8192)]:
- with open(os.path.join(root, name), "wb") as f:
- f.write(os.urandom(size))
-
- ct = lt.create_torrent(lt.list_files(root), piece_size=16384)
- lt.set_piece_hashes(ct, srcDir)
- torrentBytes = lt.bencode(ct.generate())
-
- with tempfile.TemporaryDirectory() as dlDir:
- yield torrentBytes, srcDir, dlDir
-
-
-async def session():
- s = BTSession()
- yield s
- await s.close()
-
-
-def _params(torrentBytes, savePath, priorities=None):
- ti = lt.torrent_info(torrentBytes)
- return TorrentParams(
- torrentData=torrentBytes,
- savePath=savePath,
- filePriorities=priorities or [4] * ti.num_files(),
- )
-
-
-async def test_run_downloads_and_enters_seeding(session, torrent_env):
- torrentBytes, srcDir, _dlDir = torrent_env
- params = _params(torrentBytes, srcDir)
-
- progressEvents: list[TorrentProgress] = []
- task = asyncio.create_task(
- session.run("run-1", params, onProgress=progressEvents.append)
- )
-
- seeding = False
- for _ in range(15):
- await asyncio.sleep(1)
- if any(p.isSeeding for p in progressEvents):
- seeding = True
- break
-
- task.cancel()
- with pytest.raises(asyncio.CancelledError):
- await task
-
- assert seeding, "torrent should enter seeding after verifying local files"
- assert len(progressEvents) > 0
-
-
-async def test_run_completes_when_seed_limit_reached(session, torrent_env):
- torrentBytes, srcDir, _dlDir = torrent_env
- params = _params(torrentBytes, srcDir)
-
- old = bittorrentConfig.seedingTimeLimit.value
- bittorrentConfig.seedingTimeLimit.value = 1
- try:
- resumeData = await asyncio.wait_for(
- session.run("seed-limit-1", params),
- timeout=120,
- )
- finally:
- bittorrentConfig.seedingTimeLimit.value = old
-
- assert isinstance(resumeData, bytes)
- assert len(resumeData) > 0
-
-
-async def test_cancel_cleans_active_entry(session, torrent_env):
- torrentBytes, _srcDir, dlDir = torrent_env
- params = _params(torrentBytes, dlDir)
-
- task = asyncio.create_task(session.run("cancel-1", params))
- await asyncio.sleep(2)
-
- task.cancel()
- with pytest.raises(asyncio.CancelledError):
- await task
-
- assert "cancel-1" not in session._active
-
-
-async def test_duplicate_info_hash_rejected(session, torrent_env):
- torrentBytes, srcDir, _dlDir = torrent_env
- params = _params(torrentBytes, srcDir)
-
- task1 = asyncio.create_task(session.run("dup-1", params))
- await asyncio.sleep(1)
-
- with pytest.raises(Exception, match="已在下载中"):
- await session.run("dup-2", params)
-
- task1.cancel()
- with pytest.raises(asyncio.CancelledError):
- await task1
-
-
-async def test_update_priorities_applied(session, torrent_env):
- torrentBytes, srcDir, _dlDir = torrent_env
- params = _params(torrentBytes, srcDir)
-
- task = asyncio.create_task(session.run("prio-1", params))
- await asyncio.sleep(1)
-
- session.updatePriorities("prio-1", [4, 0])
- await asyncio.sleep(2)
-
- entry = session._active.get("prio-1")
- assert entry is not None
- assert entry.pendingPriorities is None
-
- task.cancel()
- with pytest.raises(asyncio.CancelledError):
- await task
-
-
-async def test_update_priorities_noop_when_not_active(session):
- session.updatePriorities("nonexistent", [4, 0])
-
-
-async def test_close_cleans_everything(session, torrent_env):
- torrentBytes, srcDir, _dlDir = torrent_env
- params = _params(torrentBytes, srcDir)
-
- task = asyncio.create_task(session.run("close-1", params))
- await asyncio.sleep(1)
-
- await session.close()
-
- assert len(session._active) == 0
- assert session._session is None
-
- with pytest.raises(asyncio.CancelledError):
- await task
diff --git a/tests/test_file_drag.py b/tests/test_file_drag.py
deleted file mode 100644
index 1f6b5dbe..00000000
--- a/tests/test_file_drag.py
+++ /dev/null
@@ -1,64 +0,0 @@
-"""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_github_fallback.py b/tests/test_github_fallback.py
deleted file mode 100644
index d7e9200d..00000000
--- a/tests/test_github_fallback.py
+++ /dev/null
@@ -1,259 +0,0 @@
-"""GitHub proxy fallback 端到端测试。
-
-使用本地 aiohttp 服务器模拟代理站宕机 → 自动 fallback 场景。
-
-Seam S-GH1: GitHubHttpTaskStep.run() — download-time fallback
-Seam S-GH2: GitHubParser.parse() — parse-time fallback chain
-"""
-from __future__ import annotations
-
-import socket
-
-import pytest
-from aiohttp import web
-
-from github_pack.pack import GitHubHttpTaskStep, GitHubParser
-from http_pack.task import HttpTask, HttpTaskStep
-from app.models.task import TaskOptions, ResourceTaskOptions, TaskStatus, TaskError
-from tests.helpers import buildFileContent, buildRangeHandler, runStep
-
-
[email protected](autouse=True)
-def noProxy(monkeypatch):
- monkeypatch.setattr("app.client.proxy", lambda: None)
-
-
-def closedPort() -> str:
- s = socket.socket()
- s.bind(("127.0.0.1", 0))
- port = s.getsockname()[1]
- s.close()
- return f"http://127.0.0.1:{port}/file"
-
-
-def deadUrl():
- return closedPort()
-
-
-def makeGitHubStep(url, tmp_path, *, fileSize, fallbackUrls=None,
- subworkerCount=2, canUseRangeRequests=True):
- step = GitHubHttpTaskStep(
- stepIndex=0,
- url=url,
- fileSize=fileSize,
- subworkerCount=subworkerCount,
- canUseRangeRequests=canUseRangeRequests,
- clientProfile="raw",
- fallbackUrls=list(fallbackUrls or []),
- )
- task = HttpTask(
- name="test.bin",
- url="https://github.com/example/repo/releases/download/v1.0/file.zip",
- outputFolder=tmp_path,
- fileSize=fileSize,
- steps=[step],
- )
- step._bindTask(task)
- return task, step
-
-
-# ── S-GH1: Download-time fallback ──
-
-
-class TestDownloadTimeFallback:
-
- async def test_fallback_on_connection_refused(self, server, tmp_path, deadUrl):
- content = buildFileContent(1000)
- okUrl = await server(buildRangeHandler(content))
-
- task, step = makeGitHubStep(
- deadUrl, tmp_path, fileSize=1000, fallbackUrls=[okUrl],
- )
- task.setStatus(TaskStatus.RUNNING)
-
- await runStep(step)
-
- assert (tmp_path / "test.bin").read_bytes() == content
- assert step.url == okUrl
-
- async def test_fallback_on_proxy_http_error(self, server, tmp_path):
- content = buildFileContent(100)
-
- async def forbidden(request):
- return web.Response(status=403, text="Forbidden")
-
- forbiddenUrl = await server(forbidden)
- okUrl = await server(buildRangeHandler(content))
-
- task, step = makeGitHubStep(
- forbiddenUrl, tmp_path, fileSize=100, fallbackUrls=[okUrl],
- )
- task.setStatus(TaskStatus.RUNNING)
-
- await runStep(step)
-
- assert (tmp_path / "test.bin").read_bytes() == content
- assert step.url == okUrl
-
- async def test_permanent_error_without_fallback(self, server, tmp_path):
- async def forbidden(request):
- return web.Response(status=403, text="Forbidden")
-
- forbiddenUrl = await server(forbidden)
-
- task, step = makeGitHubStep(
- forbiddenUrl, tmp_path, fileSize=100,
- )
- task.setStatus(TaskStatus.RUNNING)
-
- with pytest.raises(TaskError, match="403"):
- await runStep(step)
-
- async def test_fallback_chain_tries_each(self, server, tmp_path, deadUrl):
- content = buildFileContent(500)
- okUrl = await server(buildRangeHandler(content))
-
- task, step = makeGitHubStep(
- deadUrl, tmp_path, fileSize=500, fallbackUrls=[closedPort(), okUrl],
- )
- task.setStatus(TaskStatus.RUNNING)
-
- await runStep(step)
-
- assert (tmp_path / "test.bin").read_bytes() == content
- assert step.url == okUrl
-
- async def test_fallback_restores_range_support(self, server, tmp_path):
- content = buildFileContent(200)
-
- async def rangeDegradeThenReject(request):
- if request.headers.get("Range"):
- return web.Response(status=200, body=b"x")
- return web.Response(status=403, text="Forbidden")
-
- firstUrl = await server(rangeDegradeThenReject)
- okUrl = await server(buildRangeHandler(content))
-
- task, step = makeGitHubStep(
- firstUrl, tmp_path, fileSize=200,
- fallbackUrls=[okUrl], canUseRangeRequests=True,
- )
- task.setStatus(TaskStatus.RUNNING)
-
- await runStep(step)
-
- assert (tmp_path / "test.bin").read_bytes() == content
- assert step.url == okUrl
- assert step.canUseRangeRequests is True
-
- async def test_all_fallbacks_exhausted(self, tmp_path, deadUrl):
- task, step = makeGitHubStep(
- deadUrl, tmp_path, fileSize=100,
- fallbackUrls=[closedPort()],
- )
- task.setStatus(TaskStatus.RUNNING)
-
- with pytest.raises(Exception):
- await runStep(step)
-
-
-# ── S-GH2: Parse-time fallback ──
-
-
-async def passThroughDelegate(options):
- step = HttpTaskStep(stepIndex=0, url=options.url, fileSize=100, clientProfile="raw")
- task = HttpTask(name="file.zip", url=options.url, fileSize=100, steps=[step])
- step._bindTask(task)
- return task
-
-
-class TestParseTimeFallback:
-
- async def test_skips_dead_proxy(self, monkeypatch):
- parser = GitHubParser()
-
- callUrls = []
- async def rejectDeadProxy(options):
- callUrls.append(options.url)
- if "dead-proxy.com" in options.url:
- raise ConnectionError("refused")
- return await passThroughDelegate(options)
-
- parser.delegate = rejectDeadProxy
- monkeypatch.setattr("github_pack.pack.selectedProxySite", lambda: "https://dead-proxy.com")
- monkeypatch.setattr("github_pack.pack.GITHUB_PROXY_SITES", ("https://dead-proxy.com", "https://good-proxy.com"))
-
- options = TaskOptions(url="https://github.com/user/repo/releases/download/v1.0/file.zip")
- task = await parser.parse(options)
-
- assert task.packId == "github"
- assert task.url == options.url
- assert "good-proxy.com" in callUrls[-1]
-
- async def test_step_has_remaining_fallback_urls(self, monkeypatch):
- parser = GitHubParser()
- parser.delegate = passThroughDelegate
- monkeypatch.setattr("github_pack.pack.selectedProxySite", lambda: "https://proxy1.com")
- monkeypatch.setattr("github_pack.pack.GITHUB_PROXY_SITES", ("https://proxy1.com", "https://proxy2.com"))
-
- options = TaskOptions(url="https://github.com/user/repo/releases/download/v1.0/file.zip")
- task = await parser.parse(options)
-
- step = task.steps[0]
- assert isinstance(step, GitHubHttpTaskStep)
- assert len(step.fallbackUrls) == 2
- assert "proxy2.com" in step.fallbackUrls[0]
- assert step.fallbackUrls[1] == options.url
-
- async def test_direct_url_bypasses_delegate(self, monkeypatch):
- from http_pack.pack import HttpParser
-
- parser = GitHubParser()
-
- delegateUrls = []
- async def trackingDelegate(options):
- delegateUrls.append(options.url)
- if "dead-proxy.com" in options.url:
- raise ConnectionError("refused")
- return await passThroughDelegate(options)
-
- parser.delegate = trackingDelegate
- monkeypatch.setattr("github_pack.pack.selectedProxySite", lambda: "https://dead-proxy.com")
- monkeypatch.setattr("github_pack.pack.GITHUB_PROXY_SITES", ("https://dead-proxy.com",))
-
- async def fakeHttpParse(self, options):
- return await passThroughDelegate(options)
- monkeypatch.setattr(HttpParser, "parse", fakeHttpParse)
-
- options = TaskOptions(url="https://github.com/user/repo/releases/download/v1.0/file.zip")
- task = await parser.parse(options)
-
- assert task.packId == "github"
- assert task.url == options.url
- assert all("dead-proxy.com" in u for u in delegateUrls), (
- "direct URL should not go through delegate"
- )
-
- async def test_resource_options_probes_proxy(self, monkeypatch):
- parser = GitHubParser()
- probedUrls = []
-
- async def trackingProbe(url, headers):
- probedUrls.append(url)
- raise ConnectionError("simulated")
-
- parser._probeProxy = trackingProbe
- parser.delegate = passThroughDelegate
- monkeypatch.setattr("github_pack.pack.selectedProxySite", lambda: "https://proxy.com")
- monkeypatch.setattr("github_pack.pack.GITHUB_PROXY_SITES", ("https://proxy.com",))
-
- options = ResourceTaskOptions(
- url="https://objects.githubusercontent.com/some/asset",
- name="file.zip", size=100, canUseRangeRequests=True,
- )
- task = await parser.parse(options)
-
- assert len(probedUrls) == 1
- assert "proxy.com" in probedUrls[0]
- assert task.url == options.url
diff --git a/tests/test_identity_preset.py b/tests/test_identity_preset.py
deleted file mode 100644
index 62eb1344..00000000
--- a/tests/test_identity_preset.py
+++ /dev/null
@@ -1,626 +0,0 @@
-"""Tests for the identity preset system.
-
-Covers: matchIdentityPreset, buildClient userAgent param, _effectiveHeaders,
-featureService.parse preset injection, backward compat, toEmulation auto logic.
-"""
-from __future__ import annotations
-
-import sys
-from dataclasses import replace
-from unittest.mock import MagicMock, patch
-
-import pytest
-
-
-# ---------------------------------------------------------------------------
-# Fixtures: mock cfg so tests don't depend on user config
-# ---------------------------------------------------------------------------
-
[email protected](autouse=True)
-def _mock_cfg(monkeypatch):
- """Provide a clean cfg with known defaults for every test."""
- from app.config.cfg import cfg
- monkeypatch.setattr(cfg.identityPresets, "value", [
- {"name": "百度网盘客户端", "clientProfile": "raw", "userAgent": "pan.baidu.com",
- "hosts": ["*.pcs.baidu.com"], "isEnabled": True},
- ])
- monkeypatch.setattr(cfg.clientProfile, "value", "auto")
- monkeypatch.setattr(cfg.headersPresets, "value", [
- {"name": "默认", "headers": {"accept-encoding": "deflate, br, gzip"}},
- ])
- monkeypatch.setattr(cfg.currentHeadersPreset, "value", 0)
-
-
-# ===========================================================================
-# B. matchIdentityPreset — host matching
-# ===========================================================================
-
-class TestMatchIdentityPreset:
-
- def _match(self, host: str) -> dict | None:
- from app.client import matchIdentityPreset
- return matchIdentityPreset(host)
-
- def test_b1_exact_host_match(self, monkeypatch):
- from app.config.cfg import cfg
- monkeypatch.setattr(cfg.identityPresets, "value", [
- {"name": "exact", "clientProfile": "raw", "userAgent": "ua",
- "hosts": ["pan.baidu.com"], "isEnabled": True},
- ])
- assert self._match("pan.baidu.com") is not None
- assert self._match("pan.baidu.com")["name"] == "exact"
-
- def test_b2_wildcard_subdomain_match(self):
- result = self._match("d.pcs.baidu.com")
- assert result is not None
- assert result["name"] == "百度网盘客户端"
-
- def test_b3_wildcard_root_domain_match(self):
- result = self._match("pcs.baidu.com")
- assert result is not None
- assert result["name"] == "百度网盘客户端"
-
- def test_b4_no_match(self):
- assert self._match("google.com") is None
-
- def test_b5_disabled_preset_skipped(self, monkeypatch):
- from app.config.cfg import cfg
- monkeypatch.setattr(cfg.identityPresets, "value", [
- {"name": "disabled", "clientProfile": "raw", "userAgent": "ua",
- "hosts": ["*.example.com"], "isEnabled": False},
- ])
- assert self._match("test.example.com") is None
-
- def test_b6_first_match_wins(self, monkeypatch):
- from app.config.cfg import cfg
- monkeypatch.setattr(cfg.identityPresets, "value", [
- {"name": "first", "clientProfile": "raw", "userAgent": "ua1",
- "hosts": ["*.baidu.com"], "isEnabled": True},
- {"name": "second", "clientProfile": "chrome", "userAgent": "ua2",
- "hosts": ["*.baidu.com"], "isEnabled": True},
- ])
- result = self._match("d.pcs.baidu.com")
- assert result["name"] == "first"
-
- def test_b7_empty_hosts_not_matched(self, monkeypatch):
- from app.config.cfg import cfg
- monkeypatch.setattr(cfg.identityPresets, "value", [
- {"name": "manual-only", "clientProfile": "raw", "userAgent": "ua",
- "hosts": [], "isEnabled": True},
- ])
- assert self._match("anything.com") is None
-
- def test_b8_empty_hostname(self):
- assert self._match("") is None
-
- def test_b9_broad_wildcard(self, monkeypatch):
- from app.config.cfg import cfg
- monkeypatch.setattr(cfg.identityPresets, "value", [
- {"name": "broad", "clientProfile": "raw", "userAgent": "ua",
- "hosts": ["*.com"], "isEnabled": True},
- ])
- assert self._match("google.com") is not None
- assert self._match("baidu.com") is not None
-
- def test_b_missing_isEnabled_defaults_true(self, monkeypatch):
- from app.config.cfg import cfg
- monkeypatch.setattr(cfg.identityPresets, "value", [
- {"name": "old", "clientProfile": "raw", "userAgent": "ua",
- "hosts": ["*.example.com"]},
- ])
- assert self._match("test.example.com") is not None
-
- def test_b_deep_subdomain(self):
- result = self._match("a.b.c.pcs.baidu.com")
- assert result is not None
-
-
-# ===========================================================================
-# C. buildClient userAgent parameter (mock wreq)
-# ===========================================================================
-
-class TestBuildClientUserAgent:
- """Test that buildClient correctly handles the userAgent parameter.
-
- Since wreq is not available in test env, we patch it.
- """
-
- @pytest.fixture(autouse=True)
- def _mock_wreq(self, monkeypatch):
- wreq_mock = MagicMock()
- wreq_mock.Client = MagicMock(return_value=MagicMock())
- wreq_mock.Emulation = MagicMock()
- wreq_mock.Proxy = MagicMock()
-
- profile_mock = MagicMock()
- wreq_mock.emulation.Platform = MagicMock()
- wreq_mock.emulation.Profile = type(profile_mock)
- wreq_mock.redirect.Policy = MagicMock()
- wreq_mock.dns.DnsOptions = MagicMock(return_value=MagicMock())
-
- monkeypatch.setitem(sys.modules, "wreq", wreq_mock)
- monkeypatch.setitem(sys.modules, "wreq.emulation", wreq_mock.emulation)
- monkeypatch.setitem(sys.modules, "wreq.redirect", wreq_mock.redirect)
- monkeypatch.setitem(sys.modules, "wreq.dns", wreq_mock.dns)
-
- if "app.client" in sys.modules:
- del sys.modules["app.client"]
-
- def _build(self, **kwargs):
- from app.client import buildClient
- return buildClient(**kwargs)
-
- def test_c9_no_headers_with_useragent(self):
- from app.client import buildClient
- import wreq
- buildClient(emulation=None, headers=None, userAgent="netdisk")
- call_kwargs = wreq.Client.call_args[1]
- assert call_kwargs.get("headers", {}).get("user-agent") == "netdisk"
-
- def test_c10_no_headers_no_useragent(self):
- from app.client import buildClient
- import wreq
- buildClient(emulation=None, headers=None, userAgent=None)
- call_kwargs = wreq.Client.call_args[1]
- assert "headers" not in call_kwargs or "user-agent" not in call_kwargs.get("headers", {})
-
-
- def test_c11_build_client_uses_system_dns(self):
- from app.client import buildClient
- import wreq
- buildClient(emulation=None, headers=None, userAgent=None)
- wreq.dns.DnsOptions.assert_called_once_with(system_dns=True)
- call_kwargs = wreq.Client.call_args[1]
- assert call_kwargs["dns_options"] is wreq.dns.DnsOptions.return_value
-
- def test_c12_build_client_skips_system_dns_when_disabled(self, monkeypatch):
- from app.client import buildClient
- from app.config.cfg import cfg
- import wreq
- monkeypatch.setattr(cfg.shouldUseSystemDns, "value", False)
- buildClient(emulation=None, headers=None, userAgent=None)
- assert "dns_options" not in wreq.Client.call_args[1]
-
-
-# ===========================================================================
-# D. HttpTaskStep._effectiveHeaders
-# ===========================================================================
-
-class TestEffectiveHeaders:
-
- def test_d1_no_useragent_no_headers_ua(self):
- headers = {"cookie": "x"}
- effective = {**headers}
- user_agent = ""
- if user_agent and not any(k.lower() == "user-agent" for k in headers):
- effective["user-agent"] = user_agent
- assert "user-agent" not in effective
-
- def test_d2_no_useragent_headers_has_ua(self):
- headers = {"cookie": "x", "user-agent": "browser"}
- effective = {**headers}
- user_agent = ""
- if user_agent and not any(k.lower() == "user-agent" for k in headers):
- effective["user-agent"] = user_agent
- assert effective["user-agent"] == "browser"
-
- def test_d3_useragent_no_headers_ua(self):
- headers = {"cookie": "x"}
- effective = {**headers}
- user_agent = "netdisk"
- if user_agent and not any(k.lower() == "user-agent" for k in headers):
- effective["user-agent"] = user_agent
- assert effective["user-agent"] == "netdisk"
-
- def test_d4_useragent_headers_has_ua_manual_wins(self):
- headers = {"cookie": "x", "user-agent": "custom"}
- effective = {**headers}
- user_agent = "netdisk"
- if user_agent and not any(k.lower() == "user-agent" for k in headers):
- effective["user-agent"] = user_agent
- assert effective["user-agent"] == "custom"
-
-
-# ===========================================================================
-# E1. toEmulation — profile selection (real wreq)
-# ===========================================================================
-
-
-class TestToEmulation:
-
- @pytest.fixture(autouse=True)
- def _fresh_client(self):
- if "app.client" in sys.modules:
- del sys.modules["app.client"]
-
- def test_raw_returns_none(self):
- from app.client import toEmulation
- assert toEmulation("raw") is None
-
- def test_auto_empty_ua_returns_emulation(self):
- from app.client import toEmulation
- result = toEmulation("auto", "")
- assert result is not None
-
- def test_auto_with_chrome_ua(self):
- from app.client import toEmulation
- result = toEmulation("auto", "Mozilla/5.0 (Windows NT 10.0) Chrome/120.0.0.0 Safari/537.36")
- assert result is not None
-
- def test_known_family_chrome(self):
- from app.client import toEmulation
- assert toEmulation("chrome") is not None
-
- def test_known_family_firefox(self):
- from app.client import toEmulation
- assert toEmulation("firefox") is not None
-
- def test_unknown_profile_falls_back(self):
- from app.client import toEmulation
- result = toEmulation("nonexistent_browser_xyz")
- assert result is not None
-
- def test_profile_families_includes_mobile(self):
- from app.client import profileFamilies, PROFILES_BY_FAMILY
- families = profileFamilies()
- for mobile in ("firefox-android", "safari-ios", "safari-ipad"):
- if mobile in PROFILES_BY_FAMILY:
- assert mobile in families, f"{mobile} missing from profileFamilies()"
-
-
-# ===========================================================================
-# E2. matchEmulation — UA parsing + version matching (real wreq)
-# ===========================================================================
-
-
-class TestMatchEmulation:
-
- @pytest.fixture(autouse=True)
- def _fresh_client(self):
- if "app.client" in sys.modules:
- del sys.modules["app.client"]
-
- @pytest.fixture(autouse=True)
- def _platform(self):
- from wreq.emulation import Platform
- self.host = Platform.Windows
-
- def test_empty_ua_returns_none(self):
- from app.client import matchEmulation
- assert matchEmulation("", self.host) is None
-
- def test_chrome_ua_matches(self):
- from app.client import matchEmulation
- result = matchEmulation(
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
- self.host,
- )
- assert result is not None
-
- def test_edge_ua_takes_priority_over_chrome(self):
- from app.client import matchEmulation
- ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0"
- result = matchEmulation(ua, self.host)
- assert result is not None
-
- def test_safari_iphone_matches(self):
- from app.client import matchEmulation
- from wreq.emulation import Platform
- ua = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 Version/17.0 Mobile/15E148 Safari/604.1"
- result = matchEmulation(ua, Platform.MacOS)
- assert result is not None
-
- def test_firefox_android_matches(self):
- from app.client import matchEmulation
- from wreq.emulation import Platform
- ua = "Mozilla/5.0 (Android 13; Mobile; rv:119.0) Gecko/119.0 Firefox/119.0"
- result = matchEmulation(ua, Platform.Linux)
- assert result is not None
-
- def test_safari_ipad_uses_ipad_family(self):
- from app.client import matchEmulation, PROFILES_BY_FAMILY
- from wreq.emulation import Platform
- ua = "Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X) AppleWebKit/605.1.15 Version/17.0 Mobile/15E148 Safari/604.1"
- result = matchEmulation(ua, Platform.MacOS)
- assert result is not None
- if "safari-ipad" in PROFILES_BY_FAMILY:
- iphone_ua = ua.replace("iPad", "iPhone")
- iphone_result = matchEmulation(iphone_ua, Platform.MacOS)
- assert iphone_result is not None
-
- def test_opera_ua_takes_priority_over_chrome(self):
- from app.client import matchEmulation
- ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36 OPR/120.0.0.0"
- result = matchEmulation(ua, self.host)
- assert result is not None
-
- def test_unknown_ua_returns_none(self):
- from app.client import matchEmulation
- assert matchEmulation("curl/7.88.1", self.host) is None
-
-
-# ===========================================================================
-# E3. buildClient header filtering (real wreq, mock Client constructor)
-# ===========================================================================
-
-
-class TestBuildClientHeaderFiltering:
-
- @pytest.fixture(autouse=True)
- def _mock_client_only(self, monkeypatch):
- if "app.client" in sys.modules:
- del sys.modules["app.client"]
- import app.client
- self._client_cls = MagicMock(return_value=MagicMock())
- monkeypatch.setattr(app.client, "Client", self._client_cls)
-
- def test_emulation_strips_useragent_from_headers(self):
- from app.client import buildClient, toEmulation
- emulation = toEmulation("chrome")
- buildClient(emulation=emulation, headers={"user-agent": "custom", "accept": "text/html"})
- headers = self._client_cls.call_args[1].get("headers", {})
- assert "user-agent" not in headers
- assert headers.get("accept") == "text/html"
-
- def test_emulation_strips_sec_ch_ua_headers(self):
- from app.client import buildClient, toEmulation
- emulation = toEmulation("chrome")
- buildClient(emulation=emulation, headers={
- "sec-ch-ua": '"Chromium";v="120"',
- "sec-ch-ua-platform": '"Windows"',
- "accept": "text/html",
- })
- headers = self._client_cls.call_args[1].get("headers", {})
- assert "sec-ch-ua" not in headers
- assert "sec-ch-ua-platform" not in headers
- assert headers.get("accept") == "text/html"
-
- def test_no_emulation_adds_default_ua_when_missing(self):
- from app.client import buildClient
- buildClient(emulation=None, headers={"accept": "text/html"})
- headers = self._client_cls.call_args[1].get("headers", {})
- assert "user-agent" in headers
- assert "Chrome" in headers["user-agent"]
-
-
-# ===========================================================================
-# F. Preset field interactions in featureService.parse()
-# ===========================================================================
-
-class TestPresetFieldInteraction:
- """Test the inline preset matching logic from featureService.parse().
-
- We replicate the logic here to test without needing async/parser infra.
- """
-
- def _apply_preset(self, url: str, client_profile: str = "", user_agent: str = ""):
- from urllib.parse import urlparse
- from app.client import matchIdentityPreset
- from app.models.task import TaskOptions
-
- options = TaskOptions(url=url, clientProfile=client_profile, userAgent=user_agent)
-
- if not options.clientProfile:
- host = urlparse(options.url).hostname or ""
- preset = matchIdentityPreset(host)
- if preset is not None:
- kwargs = {}
- if preset["clientProfile"]:
- kwargs["clientProfile"] = preset["clientProfile"]
- if preset["userAgent"]:
- kwargs["userAgent"] = preset["userAgent"]
- if kwargs:
- options = replace(options, **kwargs)
-
- return options
-
- def test_f1_preset_sets_both_fields(self):
- options = self._apply_preset("https://d.pcs.baidu.com/file/abc")
- assert options.clientProfile == "raw"
- assert options.userAgent == "pan.baidu.com"
-
- def test_f2_preset_only_useragent(self, monkeypatch):
- from app.config.cfg import cfg
- monkeypatch.setattr(cfg.identityPresets, "value", [
- {"name": "ua-only", "clientProfile": "", "userAgent": "netdisk",
- "hosts": ["*.example.com"], "isEnabled": True},
- ])
- options = self._apply_preset("https://dl.example.com/file")
- assert options.clientProfile == ""
- assert options.userAgent == "netdisk"
-
- def test_f3_preset_only_profile(self, monkeypatch):
- from app.config.cfg import cfg
- monkeypatch.setattr(cfg.identityPresets, "value", [
- {"name": "profile-only", "clientProfile": "chrome", "userAgent": "",
- "hosts": ["*.example.com"], "isEnabled": True},
- ])
- options = self._apply_preset("https://dl.example.com/file")
- assert options.clientProfile == "chrome"
- assert options.userAgent == ""
-
- def test_f4_preset_empty_both_fields(self, monkeypatch):
- from app.config.cfg import cfg
- monkeypatch.setattr(cfg.identityPresets, "value", [
- {"name": "empty", "clientProfile": "", "userAgent": "",
- "hosts": ["*.example.com"], "isEnabled": True},
- ])
- options = self._apply_preset("https://dl.example.com/file")
- assert options.clientProfile == ""
- assert options.userAgent == ""
-
- def test_f5_explicit_clientprofile_skips_preset(self):
- options = self._apply_preset(
- "https://d.pcs.baidu.com/file/abc",
- client_profile="chrome",
- )
- assert options.clientProfile == "chrome"
- assert options.userAgent == ""
-
- def test_f_no_host_match(self):
- options = self._apply_preset("https://google.com/file")
- assert options.clientProfile == ""
- assert options.userAgent == ""
-
- def test_f_file_url_no_crash(self):
- options = self._apply_preset("file:///tmp/test.m3u8")
- assert options.clientProfile == ""
-
-
-# ===========================================================================
-# G. Backward compatibility
-# ===========================================================================
-
-class TestBackwardCompat:
-
- def test_g1_old_step_missing_useragent(self):
- from app.models.serialization import filterFields
- from features.http_pack.task import HttpTaskStep
-
- old_data = {
- "stepIndex": 1,
- "url": "https://example.com/file.zip",
- "fileSize": 1024,
- "headers": {"cookie": "x"},
- "clientProfile": "auto",
- "subworkerCount": 8,
- "canUseRangeRequests": True,
- }
- filtered = filterFields(HttpTaskStep, old_data)
- step = HttpTaskStep(**filtered)
- assert step.userAgent == ""
-
- def test_g2_old_step_unknown_fields_dropped(self):
- from app.models.serialization import filterFields
- from features.http_pack.task import HttpTaskStep
-
- old_data = {
- "stepIndex": 1,
- "url": "https://example.com/file.zip",
- "unknownField": "should be dropped",
- "anotherUnknown": 42,
- }
- filtered = filterFields(HttpTaskStep, old_data)
- assert "unknownField" not in filtered
- assert "anotherUnknown" not in filtered
-
- def test_g_new_step_has_useragent(self):
- from features.http_pack.task import HttpTaskStep
-
- step = HttpTaskStep(stepIndex=1, url="https://example.com", userAgent="test")
- assert step.userAgent == "test"
-
- def test_g_setoptions_useragent(self):
- from features.http_pack.task import HttpTaskStep
-
- step = HttpTaskStep(stepIndex=1, url="https://example.com")
- step.setOptions({"userAgent": "netdisk"})
- assert step.userAgent == "netdisk"
-
- def test_g_setoptions_partial(self):
- from features.http_pack.task import HttpTaskStep
-
- step = HttpTaskStep(
- stepIndex=1, url="https://example.com",
- clientProfile="chrome", userAgent="old",
- )
- step.setOptions({"clientProfile": "raw"})
- assert step.clientProfile == "raw"
- assert step.userAgent == "old"
-
-
-# ===========================================================================
-# Validator
-# ===========================================================================
-
-class TestIdentityPresetListValidator:
-
- def test_valid(self):
- from app.config.cfg import IdentityPresetListValidator
- v = IdentityPresetListValidator()
- data = [{"name": "test", "clientProfile": "raw", "userAgent": "ua",
- "hosts": ["*.example.com"]}]
- assert v.validate(data) is True
-
- def test_valid_with_isEnabled(self):
- from app.config.cfg import IdentityPresetListValidator
- v = IdentityPresetListValidator()
- data = [{"name": "test", "clientProfile": "raw", "userAgent": "ua",
- "hosts": ["*.example.com"], "isEnabled": False}]
- assert v.validate(data) is True
-
- def test_invalid_missing_key(self):
- from app.config.cfg import IdentityPresetListValidator
- v = IdentityPresetListValidator()
- data = [{"name": "test"}]
- assert v.validate(data) is False
-
- def test_invalid_hosts_not_list(self):
- from app.config.cfg import IdentityPresetListValidator
- v = IdentityPresetListValidator()
- data = [{"name": "test", "clientProfile": "raw", "userAgent": "ua",
- "hosts": "*.example.com"}]
- assert v.validate(data) is False
-
- def test_correct_filters_bad_entries(self):
- from app.config.cfg import IdentityPresetListValidator
- v = IdentityPresetListValidator()
- data = [
- {"name": "good", "clientProfile": "raw", "userAgent": "ua", "hosts": []},
- {"name": "bad"},
- {"name": "also-good", "clientProfile": "", "userAgent": "", "hosts": ["*.x.com"]},
- ]
- corrected = v.correct(data)
- assert len(corrected) == 2
- assert corrected[0]["name"] == "good"
- assert corrected[1]["name"] == "also-good"
-
- def test_empty_list_valid(self):
- from app.config.cfg import IdentityPresetListValidator
- v = IdentityPresetListValidator()
- assert v.validate([]) is True
-
- def test_not_list_invalid(self):
- from app.config.cfg import IdentityPresetListValidator
- v = IdentityPresetListValidator()
- assert v.validate("not a list") is False
- assert v.correct("not a list") == []
-
-
-# ===========================================================================
-# TaskOptions.userAgent field
-# ===========================================================================
-
-class TestTaskOptionsUserAgent:
-
- def test_default_empty(self):
- from app.models.task import TaskOptions
- options = TaskOptions(url="https://example.com")
- assert options.userAgent == ""
-
- def test_explicit_value(self):
- from app.models.task import TaskOptions
- options = TaskOptions(url="https://example.com", userAgent="netdisk")
- assert options.userAgent == "netdisk"
-
- def test_from_options(self):
- from app.models.task import TaskOptions
- options = TaskOptions.fromOptions({
- "url": "https://example.com",
- "userAgent": "custom",
- })
- assert options.userAgent == "custom"
-
- def test_from_options_missing_useragent(self):
- from app.models.task import TaskOptions
- options = TaskOptions.fromOptions({
- "url": "https://example.com",
- })
- assert options.userAgent == ""
-
- def test_replace_useragent(self):
- from app.models.task import TaskOptions
- options = TaskOptions(url="https://example.com")
- modified = replace(options, userAgent="netdisk")
- assert modified.userAgent == "netdisk"
- assert options.userAgent == ""
diff --git a/tests/test_peer_fields.py b/tests/test_peer_fields.py
deleted file mode 100644
index 184e2756..00000000
--- a/tests/test_peer_fields.py
+++ /dev/null
@@ -1,27 +0,0 @@
-from types import SimpleNamespace
-
-from app.models.task import TaskStatus
-from features.bittorrent_pack.cards import BT_PEERS_FIELD, BTTaskCard
-from features.ed2k_pack.cards import ED2K_PEERS_FIELD, ED2kTaskCard
-
-
-def test_ed2k_task_card_displays_active_and_total_peers():
- task = SimpleNamespace(activePeerCount=2, totalPeerCount=10)
-
- assert ED2K_PEERS_FIELD in ED2kTaskCard.infoFields
- assert ED2K_PEERS_FIELD.icon.value == "Info"
- assert ED2K_PEERS_FIELD.formats[TaskStatus.RUNNING](task, 0, 0) == "2/10 Peers"
-
-
-def test_ed2k_peer_field_hides_for_an_older_daemon():
- task = SimpleNamespace(activePeerCount=None, totalPeerCount=10)
-
- assert ED2K_PEERS_FIELD.formats[TaskStatus.RUNNING](task, 0, 0) is None
-
-
-def test_bt_task_card_displays_connected_and_known_peers():
- task = SimpleNamespace(peerCount=3, totalPeerCount=17)
-
- assert BT_PEERS_FIELD in BTTaskCard.infoFields
- assert BT_PEERS_FIELD.icon.value == "Info"
- assert BT_PEERS_FIELD.formats[TaskStatus.RUNNING](task, 0, 0) == "3/17 Peers"
diff --git a/tests/test_segment_e2e.py b/tests/test_segment_e2e.py
deleted file mode 100644
index 24278b49..00000000
--- a/tests/test_segment_e2e.py
+++ /dev/null
@@ -1,190 +0,0 @@
-"""端到端测试:YouTube 时间段下载 (1:00-1:05)。
-
-完整管道:yt-dlp extract → sidx parse → partial download → reconstruct → ffmpeg trim。
-使用真实 YouTube URL,只下载 ~130KB 而非整个 6.7MB 文件。
-"""
-from __future__ import annotations
-
-import importlib
-import subprocess
-import sys
-import tempfile
-import urllib.request
-from pathlib import Path
-
-import pytest
-
-from app.container import buildMp4SegmentRange
-
-VIDEO_URL = "https://www.youtube.com/watch?v=uG44DZMMDtw"
-START_TIME = 60
-END_TIME = 65
-
-
-def _loadYtDlp():
- from features.yt_dlp_pack.config import youTubeRuntime
- vendorPath = str(youTubeRuntime.ytDlpFolder())
- if vendorPath and vendorPath not in sys.path:
- sys.path.insert(0, vendorPath)
- return importlib.import_module("yt_dlp")
-
-
-def _extractFormats(yt_dlp):
- from features.yt_dlp_pack.config import youTubeRuntime
- opts = {
- "quiet": True, "no_warnings": True,
- "allowed_extractors": ["youtube.*"],
- "nocheckcertificate": True,
- "noplaylist": True,
- }
- qjsPath = youTubeRuntime.qjsPath()
- if qjsPath:
- opts["js_runtimes"] = {"quickjs": {"path": qjsPath}}
- with yt_dlp.YoutubeDL(opts) as ydl:
- return ydl.extract_info(VIDEO_URL, download=False)
-
-
-def _pickFormat(formats, role):
- if role == "video":
- candidates = [f for f in formats if f.get("vcodec", "none") != "none"
- and f.get("acodec", "none") == "none" and f.get("ext") == "mp4"]
- return sorted(candidates, key=lambda f: f.get("height", 0))[0] if candidates else None
- candidates = [f for f in formats if f.get("acodec", "none") != "none"
- and f.get("vcodec", "none") == "none" and f.get("ext") in ("mp4", "m4a")]
- return sorted(candidates, key=lambda f: f.get("abr", 0))[0] if candidates else None
-
-
-def _fetchBytes(url, headers, start, end):
- req = urllib.request.Request(url, headers={
- **headers,
- "Range": f"bytes={start}-{end - 1}",
- })
- with urllib.request.urlopen(req) as resp:
- return resp.read()
-
-
-def _probeDuration(ffprobe, path):
- result = subprocess.run(
- [ffprobe, "-v", "error", "-show_entries", "format=duration",
- "-of", "default=noprint_wrappers=1:nokey=1", str(path)],
- capture_output=True, text=True,
- )
- return float(result.stdout.strip())
-
-
[email protected](scope="module")
-def yt_info():
- yt_dlp = _loadYtDlp()
- return _extractFormats(yt_dlp)
-
-
[email protected](scope="module")
-def ffmpeg_paths():
- from features.ffmpeg_pack.config import ffmpegRuntime
- ffmpeg = ffmpegRuntime.path()
- ffprobe = ffmpegRuntime.ffprobePath()
- if not ffmpeg or not ffprobe:
- pytest.skip("FFmpeg not installed")
- return ffmpeg, ffprobe
-
-
-class TestSegmentE2E:
-
- def test_video_segment_download_and_trim(self, yt_info, ffmpeg_paths):
- ffmpeg, ffprobe = ffmpeg_paths
- formats = yt_info.get("formats", [])
- fmt = _pickFormat(formats, "video")
- assert fmt, "no video format found"
-
- url = fmt["url"]
- headers = dict(fmt.get("http_headers") or {})
-
- # 1. Fetch header (4KB)
- headerData = _fetchBytes(url, headers, 0, 4096)
- assert len(headerData) >= 2048
-
- # 2. Parse sidx → SegmentRange
- seg = buildMp4SegmentRange(headerData, START_TIME, END_TIME)
- segmentSize = seg.segEnd - seg.segStart
- fullSize = int(fmt.get("filesize") or fmt.get("filesize_approx") or 0)
-
- print(f"\nSegment: {seg.segStart}-{seg.segEnd} ({segmentSize} bytes)")
- print(f"Full file: {fullSize} bytes")
- print(f"Saving: {100 - segmentSize * 100 // fullSize}%")
-
- assert segmentSize < fullSize // 2, "segment should be much smaller than full file"
-
- # 3. Download segment bytes
- segmentData = _fetchBytes(url, headers, seg.segStart, seg.segEnd)
- assert len(segmentData) == segmentSize
-
- # 4. Reconstruct: patchedHeader + segment → valid MP4
- with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmp:
- tmp.write(seg.patchedHeader)
- tmp.write(segmentData)
- reconstructed = Path(tmp.name)
-
- try:
- # 5. ffmpeg trim
- outputPath = reconstructed.with_name("trimmed.mp4")
- result = subprocess.run(
- [ffmpeg, "-y", "-v", "error",
- "-ss", str(START_TIME - seg.segStartTime),
- "-i", str(reconstructed),
- "-t", str(END_TIME - START_TIME),
- "-c", "copy", str(outputPath)],
- capture_output=True, text=True,
- )
- assert result.returncode == 0, f"ffmpeg failed: {result.stderr}"
- assert outputPath.exists()
- assert outputPath.stat().st_size > 0
-
- # 6. Verify duration
- duration = _probeDuration(ffprobe, outputPath)
- print(f"Output duration: {duration:.2f}s (expected ~{END_TIME - START_TIME}s)")
- assert 3.0 <= duration <= 8.0, f"unexpected duration: {duration}"
-
- finally:
- reconstructed.unlink(missing_ok=True)
- outputPath.unlink(missing_ok=True)
-
- def test_audio_segment_download_and_trim(self, yt_info, ffmpeg_paths):
- ffmpeg, ffprobe = ffmpeg_paths
- formats = yt_info.get("formats", [])
- fmt = _pickFormat(formats, "audio")
- assert fmt, "no audio format found"
-
- url = fmt["url"]
- headers = dict(fmt.get("http_headers") or {})
-
- headerData = _fetchBytes(url, headers, 0, 4096)
- seg = buildMp4SegmentRange(headerData, START_TIME, END_TIME)
-
- segmentData = _fetchBytes(url, headers, seg.segStart, seg.segEnd)
-
- with tempfile.NamedTemporaryFile(suffix=".m4a", delete=False) as tmp:
- tmp.write(seg.patchedHeader)
- tmp.write(segmentData)
- reconstructed = Path(tmp.name)
-
- try:
- outputPath = reconstructed.with_name("trimmed.m4a")
- result = subprocess.run(
- [ffmpeg, "-y", "-v", "error",
- "-ss", str(START_TIME - seg.segStartTime),
- "-i", str(reconstructed),
- "-t", str(END_TIME - START_TIME),
- "-c", "copy", str(outputPath)],
- capture_output=True, text=True,
- )
- assert result.returncode == 0, f"ffmpeg failed: {result.stderr}"
- assert outputPath.exists()
-
- duration = _probeDuration(ffprobe, outputPath)
- print(f"\nAudio output duration: {duration:.2f}s")
- assert 3.0 <= duration <= 8.0
-
- finally:
- reconstructed.unlink(missing_ok=True)
- outputPath.unlink(missing_ok=True)
diff --git a/tests/test_task_card.py b/tests/test_task_card.py
deleted file mode 100644
index 5e5821a5..00000000
--- a/tests/test_task_card.py
+++ /dev/null
@@ -1,131 +0,0 @@
-"""TaskCard.refresh() 回归测试 — 历史上断过 2 次。
-
-Seam S10: refresh() 在所有状态 × fileSize 组合下不抛异常。
-"""
-from __future__ import annotations
-
-from dataclasses import dataclass
-
-import pytest
-
-from app.models.task import Task, TaskStep, TaskStatus, TaskError
-
-
-@dataclass(kw_only=True)
-class StubStep(TaskStep):
- stepIndex: int = 0
-
- async def run(self, reportSpeed, waitForSpeedLimit):
- pass
-
-
-class StubTaskService:
- def pause(self, task): pass
- def start(self, task): pass
- def delete(self, task, **kw): pass
- def redownload(self, task): pass
- def setCategory(self, task, cat): pass
-
-
-class StubFeatureService:
- def editCards(self, task, parent=None):
- return []
-
-
-class StubCategoryService:
- def __init__(self):
- from PySide6.QtCore import Signal, QObject
- class _Obj(QObject):
- categoriesChanged = Signal()
- self._obj = _Obj()
-
- @property
- def categoriesChanged(self):
- return self._obj.categoriesChanged
-
- def categoryById(self, cid):
- return None
-
- def categories(self):
- return []
-
-
-_stubCategoryService = None
-
-def makeCard(qapp, status, fileSize=1000, withError=False):
- from app.view.cards.task_cards import TaskCard
- global _stubCategoryService
- if _stubCategoryService is None:
- _stubCategoryService = StubCategoryService()
-
- step = StubStep(stepIndex=0, status=status)
- if status == TaskStatus.COMPLETED:
- step.progress = 100
- step.receivedBytes = fileSize
- if withError:
- step.error = TaskError("测试错误")
-
- task = Task(name="test.txt", url="http://test", packId="test",
- steps=[step], fileSize=fileSize)
- step._bindTask(task)
- task.updateStatus()
-
- card = TaskCard(task, StubTaskService(), StubFeatureService(), _stubCategoryService)
- return card
-
-
-ALL_STATUSES = [
- TaskStatus.WAITING,
- TaskStatus.RUNNING,
- TaskStatus.PAUSED,
- TaskStatus.COMPLETED,
- TaskStatus.FAILED,
-]
-
-
-class TestRefreshNoCrash:
-
- @pytest.mark.parametrize("status", ALL_STATUSES, ids=lambda s: s.name)
- def test_refresh_with_filesize(self, qapp, status):
- card = makeCard(qapp, status, fileSize=1024)
- card.refresh()
- card.refresh(force=True)
-
- @pytest.mark.parametrize("status", ALL_STATUSES, ids=lambda s: s.name)
- def test_refresh_zero_filesize(self, qapp, status):
- card = makeCard(qapp, status, fileSize=0)
- card.refresh()
- card.refresh(force=True)
-
- def test_refresh_failed_with_error(self, qapp):
- card = makeCard(qapp, TaskStatus.FAILED, withError=True)
- card.refresh()
-
- def test_refresh_failed_without_error(self, qapp):
- card = makeCard(qapp, TaskStatus.FAILED, withError=False)
- card.refresh()
-
- def test_refresh_skips_unchanged_non_running(self, qapp):
- card = makeCard(qapp, TaskStatus.PAUSED)
- card.refresh()
- card.refresh()
-
- def test_refresh_always_runs_for_running(self, qapp):
- card = makeCard(qapp, TaskStatus.RUNNING)
- card.refresh()
- card.refresh()
-
- def test_progress_bar_visible_when_created_during_running(self, qapp):
- card = makeCard(qapp, TaskStatus.RUNNING)
- card.refresh()
- assert not card.progressBar.isHidden()
- assert card.statusLabel.isHidden()
-
- def test_progress_bar_hidden_when_completed(self, qapp):
- card = makeCard(qapp, TaskStatus.COMPLETED)
- card.refresh()
- assert card.progressBar.isHidden()
-
-
-if __name__ == "__main__":
- pytest.main([__file__, "-v", "--tb=short"])
diff --git a/tests/test_task_edit.py b/tests/test_task_edit.py
deleted file mode 100644
index 6b271812..00000000
--- a/tests/test_task_edit.py
+++ /dev/null
@@ -1,250 +0,0 @@
-"""LiveEditDialog 的 6 分支决策逻辑测试。
-
-Seam S8: LiveEditDialog.accept() 的分支覆盖
- 1. URL 不变 → taskService.edit(task, options) 直接调用
- 2. URL 变 + parse 成功 + canReuseProgress → edit 不丢数据
- 3. URL 变 + parse 成功 + 不可复用 + 无已下载数据 → 直接 edit
- 4. URL 变 + parse 成功 + 不可复用 + 有已下载数据 → 弹确认框
- 5. URL 变 + parse 失败 → 显示错误,task 不变
- 6. reject 时取消进行中的 parse
-"""
-from __future__ import annotations
-
-from dataclasses import dataclass, field
-from unittest.mock import MagicMock, patch
-
-import pytest
-from PySide6.QtWidgets import QWidget
-
-from app.models.task import Task, TaskStep, TaskStatus
-
-
-@dataclass(kw_only=True)
-class StubStep(TaskStep):
- stepIndex: int = 0
-
- async def run(self, reportSpeed, waitForSpeedLimit):
- pass
-
-
-def makeTask(url="http://example.com/file.zip", receivedBytes=0) -> Task:
- step = StubStep(stepIndex=0, receivedBytes=receivedBytes)
- task = Task(name="file.zip", url=url, packId="http", steps=[step])
- step._bindTask(task)
- return task
-
-
-class RecordingTaskService:
- def __init__(self):
- self.editCalls: list[tuple] = []
-
- def edit(self, task, options, newTask=None):
- self.editCalls.append((task, options, newTask))
-
-
-class RecordingCoroutineRunner:
- def __init__(self):
- self._counter = 0
- self._pending: dict[str, tuple] = {}
-
- def submit(self, work, done=None, failed=None, **kwargs) -> str:
- self._counter += 1
- workId = f"wrk_{self._counter}"
- self._pending[workId] = (work, done, failed, kwargs)
- return workId
-
- def cancel(self, workId, finished=None):
- self._pending.pop(workId, None)
-
- def resolveLast(self, result):
- workId = f"wrk_{self._counter}"
- _, done, _, kwargs = self._pending.pop(workId)
- if done:
- done(result, **{k: v for k, v in kwargs.items() if k not in ("owner",)})
-
- def failLast(self, error: str):
- workId = f"wrk_{self._counter}"
- _, _, failed, kwargs = self._pending.pop(workId)
- if failed:
- failed(error, **{k: v for k, v in kwargs.items() if k not in ("owner",)})
-
-
-class StubFeatureService:
- async def parse(self, options):
- return makeTask(url=options.url)
-
- def editCards(self, task, parent=None):
- return []
-
-
-class StubOptionCard(QWidget):
- def __init__(self, opts: dict, parent=None):
- super().__init__(parent)
- self._opts = opts
-
- def options(self):
- return dict(self._opts)
-
-
-def parentWindow(qapp):
- from PySide6.QtWidgets import QWidget
- w = QWidget()
- w.resize(800, 600)
- yield w
- w.deleteLater()
-
-
-def env(parentWindow):
- ts = RecordingTaskService()
- cr = RecordingCoroutineRunner()
- fs = StubFeatureService()
- return ts, cr, fs, parentWindow
-
-
-def makeDialog(task, cards, ts, cr, fs, parent):
- from app.view.dialogs.edit_task import LiveEditDialog
- return LiveEditDialog(task, cards, cr, fs, ts, parent)
-
-
-class TestEditNoUrlChange:
-
- def test_direct_edit(self, env):
- ts, cr, fs, parent = env
- task = makeTask()
- card = StubOptionCard({"subworkerCount": 8})
- dialog = makeDialog(task, [card], ts, cr, fs, parent)
-
- dialog.accept()
-
- assert len(ts.editCalls) == 1
- called_task, called_opts, called_new = ts.editCalls[0]
- assert called_task is task
- assert called_opts == {"subworkerCount": 8}
- assert called_new is None
-
- def test_empty_url_treated_as_no_change(self, env):
- ts, cr, fs, parent = env
- task = makeTask()
- card = StubOptionCard({"url": "", "subworkerCount": 4})
- dialog = makeDialog(task, [card], ts, cr, fs, parent)
-
- dialog.accept()
-
- assert len(ts.editCalls) == 1
- _, opts, newTask = ts.editCalls[0]
- assert newTask is None
-
- def test_same_url_treated_as_no_change(self, env):
- ts, cr, fs, parent = env
- task = makeTask(url="http://example.com/file.zip")
- card = StubOptionCard({"url": "http://example.com/file.zip"})
- dialog = makeDialog(task, [card], ts, cr, fs, parent)
-
- dialog.accept()
-
- assert len(ts.editCalls) == 1
- _, _, newTask = ts.editCalls[0]
- assert newTask is None
-
-
-class TestEditWithUrlChange:
-
- def test_reusable_progress(self, env):
- ts, cr, fs, parent = env
- task = makeTask()
- task.canReuseProgress = lambda newTask: True
- card = StubOptionCard({"url": "http://example.com/new.zip"})
- dialog = makeDialog(task, [card], ts, cr, fs, parent)
-
- dialog.accept()
- newTask = makeTask(url="http://example.com/new.zip")
- cr.resolveLast(newTask)
-
- assert len(ts.editCalls) == 1
- _, _, editNewTask = ts.editCalls[0]
- assert editNewTask is newTask
-
- def test_not_reusable_no_data(self, env):
- ts, cr, fs, parent = env
- task = makeTask(receivedBytes=0)
- card = StubOptionCard({"url": "http://example.com/new.zip"})
- dialog = makeDialog(task, [card], ts, cr, fs, parent)
-
- dialog.accept()
- newTask = makeTask(url="http://example.com/new.zip")
- cr.resolveLast(newTask)
-
- assert len(ts.editCalls) == 1
- _, _, editNewTask = ts.editCalls[0]
- assert editNewTask is newTask
-
- def test_not_reusable_with_data_confirm(self, env):
- ts, cr, fs, parent = env
- task = makeTask(receivedBytes=1024)
- card = StubOptionCard({"url": "http://example.com/new.zip"})
- dialog = makeDialog(task, [card], ts, cr, fs, parent)
-
- dialog.accept()
- newTask = makeTask(url="http://example.com/new.zip")
-
- with patch("app.view.dialogs.edit_task.MessageBox") as MockBox:
- MockBox.return_value.exec.return_value = True
- cr.resolveLast(newTask)
-
- assert len(ts.editCalls) == 1
- _, _, editNewTask = ts.editCalls[0]
- assert editNewTask is newTask
-
- def test_not_reusable_with_data_cancel(self, env):
- ts, cr, fs, parent = env
- task = makeTask(receivedBytes=1024)
- card = StubOptionCard({"url": "http://example.com/new.zip"})
- dialog = makeDialog(task, [card], ts, cr, fs, parent)
-
- dialog.accept()
- newTask = makeTask(url="http://example.com/new.zip")
-
- with patch("app.view.dialogs.edit_task.MessageBox") as MockBox:
- MockBox.return_value.exec.return_value = False
- cr.resolveLast(newTask)
-
- assert len(ts.editCalls) == 0
-
-
-class TestEditParseFail:
-
- def test_parse_failure_shows_error(self, env):
- ts, cr, fs, parent = env
- task = makeTask()
- card = StubOptionCard({"url": "http://example.com/new.zip"})
- dialog = makeDialog(task, [card], ts, cr, fs, parent)
-
- dialog.accept()
-
- with patch("app.view.dialogs.edit_task.InfoBar") as MockInfoBar:
- cr.failLast("解析失败")
-
- assert len(ts.editCalls) == 0
- assert dialog.yesButton.isEnabled()
-
-
-class TestEditReject:
-
- def test_reject_cancels_pending_parse(self, env):
- ts, cr, fs, parent = env
- task = makeTask()
- card = StubOptionCard({"url": "http://example.com/new.zip"})
- dialog = makeDialog(task, [card], ts, cr, fs, parent)
-
- dialog.accept()
- assert len(cr._pending) == 1
-
- dialog.reject()
- assert len(cr._pending) == 0
- assert len(ts.editCalls) == 0
-
-
-if __name__ == "__main__":
- pytest.main([__file__, "-v", "--tb=short"])
diff --git a/tests/test_task_error_translation.py b/tests/test_task_error_translation.py
deleted file mode 100644
index 787057e7..00000000
--- a/tests/test_task_error_translation.py
+++ /dev/null
@@ -1,84 +0,0 @@
-from PySide6.QtCore import QTranslator
-
-from app.i18n import toLocalizedError
-from app.models.task import TaskError
-
-
-class TaskErrorTranslator(QTranslator):
- translations = {
- "该种子已在下载中": "This torrent is already being downloaded",
- "该 eD2k 链接已在下载中": "This eD2k link is already being downloaded",
- }
-
- def translate(self, context, sourceText, disambiguation=None, n=-1):
- if context == "TaskErrors":
- return self.translations.get(sourceText, "")
- return ""
-
-
-def test_task_error_translation_uses_shared_catalog(qapp):
- translator = TaskErrorTranslator()
- qapp.installTranslator(translator)
- try:
- assert toLocalizedError(TaskError("该种子已在下载中")) == (
- "This torrent is already being downloaded"
- )
- assert toLocalizedError(TaskError("该 eD2k 链接已在下载中")) == (
- "This eD2k link is already being downloaded"
- )
- assert toLocalizedError(TaskError("uncatalogued external error")) == (
- "uncatalogued external error"
- )
- finally:
- qapp.removeTranslator(translator)
-
-
-def test_add_task_popup_translates_parse_error(monkeypatch):
- from app.view.dialogs import task_draft as draft_module
-
- captured = {}
-
- class Dialog:
- def _refreshStats(self):
- pass
-
- def tr(self, text):
- return text
-
- def capture(*args, **kwargs):
- captured["content"] = args[1]
-
- monkeypatch.setattr(draft_module, "toLocalizedError", lambda _: "translated error")
- monkeypatch.setattr(draft_module.InfoBar, "error", capture)
-
- draft_module.TaskDraftDialog._onParseFailed(Dialog(), "ed2k://example", "source error")
-
- assert captured["content"] == "ed2k://example\ntranslated error"
-
-
-def test_edit_task_popup_translates_parse_error(monkeypatch):
- from app.view.dialogs import edit_task as edit_module
-
- captured = {}
-
- class Dialog:
- _pendingParseId = "pending"
-
- def _setInteractive(self, enabled):
- self.enabled = enabled
-
- def tr(self, text):
- return text
-
- def capture(*args, **kwargs):
- captured["content"] = kwargs["content"]
-
- dialog = Dialog()
- monkeypatch.setattr(edit_module, "toLocalizedError", lambda _: "translated error")
- monkeypatch.setattr(edit_module.InfoBar, "error", capture)
-
- edit_module.LiveEditDialog._onReparseFailed(dialog, "source error")
-
- assert captured["content"] == "translated error"
- assert dialog._pendingParseId == ""
- assert dialog.enabled is True
diff --git a/tests/test_task_page.py b/tests/test_task_page.py
deleted file mode 100644
index dfe5ece4..00000000
--- a/tests/test_task_page.py
+++ /dev/null
@@ -1,165 +0,0 @@
-"""TaskPage _runningIds 刷新机制测试。
-
-Seam S11: taskStarted/Stopped → 精确刷新 running cards。
-"""
-from __future__ import annotations
-
-from dataclasses import dataclass, field
-import pytest
-
-from app.models.task import Task, TaskStep, TaskStatus
-from app.signal import Signal
-
-
-@dataclass(kw_only=True)
-class StubStep(TaskStep):
- stepIndex: int = 0
-
- async def run(self, reportSpeed, waitForSpeedLimit):
- pass
-
-
-def makeTask(taskId="tsk_1", status=TaskStatus.WAITING):
- step = StubStep(stepIndex=0, status=status)
- task = Task(name="test", url="http://test", packId="test",
- taskId=taskId, steps=[step])
- step._bindTask(task)
- task.updateStatus()
- return task
-
-
-class StubTaskService:
- taskAdded = Signal(object)
- taskRemoved = Signal(str)
- taskStarted = Signal(object)
- taskPaused = Signal(object)
- taskCompleted = Signal(object)
- taskFailed = Signal(object)
- tasksAllCompleted = Signal()
- queueChanged = Signal()
- fileDisappeared = Signal(object)
- fileDeleteDenied = Signal()
- diskSpaceInsufficient = Signal(int, int)
-
- def __init__(self):
- self.tasks = []
-
- def runningCount(self):
- return sum(1 for t in self.tasks if t.status == TaskStatus.RUNNING)
-
- def runningProgress(self):
- return -1.0
-
-
-class StubFeatureService:
- def taskCard(self, task, parent=None):
- return None
-
- def pages(self):
- return []
-
- def settingGroups(self, parent):
- return []
-
- def runtimes(self):
- return []
-
-
-class StubCategoryService:
- categoriesChanged = Signal()
-
- def categories(self):
- return []
-
- def categoryById(self, cid):
- return None
-
-
-class StubSpeedMeter:
- def __init__(self):
- from app.signal import BoundSignal
- self.speedChanged = BoundSignal()
-
-
-class TestRunningIds:
-
- @pytest.fixture
- def page(self, qapp):
- from app.view.pages.task_page import TaskPage
- ts = StubTaskService()
- page = TaskPage(
- taskService=ts,
- featureService=StubFeatureService(),
- categoryService=StubCategoryService(),
- speedMeter=StubSpeedMeter(),
- )
- return page, ts
-
- def test_initial_running_ids_empty(self, page):
- p, ts = page
- assert p._runningIds == set()
-
- def test_task_started_adds_to_running(self, page):
- p, ts = page
- task = makeTask("tsk_a", TaskStatus.RUNNING)
- ts.taskStarted.emit(task)
- assert "tsk_a" in p._runningIds
-
- def test_task_completed_removes_from_running(self, page):
- p, ts = page
- task = makeTask("tsk_a", TaskStatus.RUNNING)
- ts.taskStarted.emit(task)
- assert "tsk_a" in p._runningIds
- task.setStatus(TaskStatus.COMPLETED)
- ts.taskCompleted.emit(task)
- assert "tsk_a" not in p._runningIds
-
- def test_task_failed_removes_from_running(self, page):
- p, ts = page
- task = makeTask("tsk_b", TaskStatus.RUNNING)
- ts.taskStarted.emit(task)
- task.setStatus(TaskStatus.FAILED)
- ts.taskFailed.emit(task)
- assert "tsk_b" not in p._runningIds
-
- def test_task_paused_removes_from_running(self, page):
- p, ts = page
- task = makeTask("tsk_c", TaskStatus.RUNNING)
- ts.taskStarted.emit(task)
- task.setStatus(TaskStatus.PAUSED)
- ts.taskPaused.emit(task)
- assert "tsk_c" not in p._runningIds
-
- def test_all_completed_clears_running(self, page):
- p, ts = page
- for i in range(3):
- ts.taskStarted.emit(makeTask(f"tsk_{i}", TaskStatus.RUNNING))
- assert len(p._runningIds) == 3
- ts.tasksAllCompleted.emit()
- assert p._runningIds == set()
-
- def test_timer_started_on_task_start(self, page):
- p, ts = page
- assert not p._cardRefreshTimer.isActive()
- ts.taskStarted.emit(makeTask("tsk_x", TaskStatus.RUNNING))
- assert p._cardRefreshTimer.isActive()
-
- def test_timer_stopped_when_last_task_stops(self, page):
- p, ts = page
- task = makeTask("tsk_y", TaskStatus.RUNNING)
- ts.taskStarted.emit(task)
- assert p._cardRefreshTimer.isActive()
- task.setStatus(TaskStatus.COMPLETED)
- ts.taskCompleted.emit(task)
- assert not p._cardRefreshTimer.isActive()
-
- def test_timer_stopped_on_all_completed(self, page):
- p, ts = page
- ts.taskStarted.emit(makeTask("tsk_z", TaskStatus.RUNNING))
- assert p._cardRefreshTimer.isActive()
- ts.tasksAllCompleted.emit()
- assert not p._cardRefreshTimer.isActive()
-
-
-if __name__ == "__main__":
- pytest.main([__file__, "-v", "--tb=short"])