The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
test(android): bridge 校验值投影改走 TaskService
XiaoYouChR22cd869a97f1
diff --git a/tests/test_android_checksum_bridge.py b/tests/test_android_checksum_bridge.pynew file mode 100644index 00000000..1a19f79c--- /dev/null+++ b/tests/test_android_checksum_bridge.py@@ -0,0 +1,99 @@+"""Bridge 的 Checksum 投影:比对、算法分组、进度 tick 启停、notice。++Seam: Bridge 方法与槽(StubTaskService,真实 CoroutineRunner + loop 线程)+"""+from __future__ import annotations++import json+from dataclasses import dataclass, field++from app.checksum import COMMON_ALGORITHMS+from app.models.task import TaskError+from tests.test_android_request import engine # noqa: F401+from tests.test_android_task_push import stubPushes, waitForLoop+++@dataclass+class StubTask:+ taskId: str+ name: str = "ubuntu.iso"+ checksums: dict[str, str] = field(default_factory=dict)+++class StubTaskService:+ def __init__(self, tasks):+ self.tasks = tasks+ self.progress: dict[str, int] = {}++ def taskById(self, taskId):+ return next((t for t in self.tasks if t.taskId == taskId), None)++ def checksumProgress(self, task):+ return self.progress.get(task.taskId)+++def setUp(engine, *tasks):+ stubPushes(engine)+ engine._checksumTickWorkId = None+ engine._taskService = StubTaskService(list(tasks))+ return engine._taskService+++def notices(engine) -> list[dict]:+ return [json.loads(value) for key, value in engine._flows.events if key == "notice"]+++def test_match_accepts_sha256sum_line(engine):+ setUp(engine, StubTask("t1", checksums={"md5": "aa11", "sha256": "bb22"}))++ assert json.loads(engine.request("matchChecksum", "t1", "BB22 ubuntu.iso")) == "sha256"+ assert json.loads(engine.request("matchChecksum", "t1", "cc33")) is None+++def test_algorithms_are_grouped_by_engine(engine):+ groups = json.loads(engine.request("checksumAlgorithms"))++ assert groups["common"] == list(COMMON_ALGORITHMS)+ assert not set(groups["common"]) & set(groups["others"])+++def test_tick_runs_until_the_last_checksum_ends(engine):+ a, b = StubTask("a"), StubTask("b")+ service = setUp(engine, a, b)++ service.progress = {"a": 0, "b": 0}+ engine.request("_onChecksumStarted", a)+ engine.request("_onChecksumStarted", b)+ tickId = engine._checksumTickWorkId++ del service.progress["a"]+ engine.request("_onChecksumCompleted", a, "sha256")+ assert engine._checksumTickWorkId == tickId++ del service.progress["b"]+ engine.request("_onChecksumStopped", b, None)+ assert engine._checksumTickWorkId is None+++def test_completed_checksum_sends_notice_with_algorithm(engine):+ task = StubTask("t1")+ setUp(engine, task)++ engine.request("_onChecksumCompleted", task, "sha256")+ waitForLoop(engine)++ assert notices(engine) == [+ {"kind": "checksumCompleted", "taskId": "t1", "name": "ubuntu.iso", "algorithm": "sha256"}]+++def test_failed_checksum_notice_carries_error_as_fields(engine):+ task = StubTask("t1")+ setUp(engine, task)++ engine.request("_onChecksumStopped", task, TaskError("无法读取文件:{detail}", detail="gone"))+ engine.request("_onChecksumStopped", task, None)+ waitForLoop(engine)++ [notice] = notices(engine)+ assert notice["kind"] == "checksumFailed"+ assert notice["params"] == {"detail": "gone"}diff --git a/tests/test_android_hash_bridge.py b/tests/test_android_hash_bridge.pydeleted file mode 100644index 084473d3..00000000--- a/tests/test_android_hash_bridge.py+++ /dev/null@@ -1,135 +0,0 @@-from __future__ import annotations--import asyncio-import hashlib-import json-import time-from dataclasses import dataclass-from pathlib import Path-from threading import Thread--import pytest--from app.services.coroutine_runner import CoroutineRunner-from tests.helpers import StubFlows---@dataclass-class StubTask:- taskId: str- outputPath: str---class StubTaskService:- def __init__(self, tasks):- self._tasks = {task.taskId: task for task in tasks}-- def taskById(self, taskId):- return self._tasks.get(taskId)---def engine(bridge):- instance = bridge.Bridge.__new__(bridge.Bridge)- instance._loop = asyncio.new_event_loop()- thread = Thread(target=instance._loop.run_forever, daemon=True)- thread.start()-- instance._coroutineRunner = CoroutineRunner(- dispatcher=instance._loop.call_soon_threadsafe, isAlive=None, loop=instance._loop)- instance._flows = StubFlows()- instance._hashState = bridge.HashState()- instance._hashWorkId = None-- yield instance-- instance._loop.call_soon_threadsafe(instance._loop.stop)- thread.join(timeout=2)- instance._loop.close()---def buildTask(path: Path, name: str) -> StubTask:- return StubTask(taskId=f"tsk_{name}", outputPath=str(path))---def test_idle_state_sends_null_error_never_an_empty_string(engine):- engine._emitHashState()-- payload = json.loads(engine._flows.states["hashState"])- assert payload == {"taskId": "", "algorithm": "", "progress": 0, "digest": "", "error": None}- assert payload["error"] is None---def waitFor(predicate, timeout=5.0):- deadline = time.monotonic() + timeout- while time.monotonic() < deadline:- if predicate():- return- time.sleep(0.01)- raise AssertionError("条件没有在超时前成立")---def test_digest_matches_hashlib(engine, tmp_path):- payload = bytes(range(256)) * 400- path = tmp_path / "blob.bin"- path.write_bytes(payload)- task = buildTask(path, "blob.bin")- engine._taskService = StubTaskService([task])-- engine.startFileHash(task.taskId, "sha256")- waitFor(lambda: engine._hashState.digest != "")-- assert engine._hashState.digest == hashlib.sha256(payload).hexdigest()- assert engine._hashState.progress == 100- assert engine._hashState.error is None---def test_missing_file_reports_error_instead_of_crashing(engine, tmp_path):- task = buildTask(tmp_path / "gone.bin", "gone.bin")- engine._taskService = StubTaskService([task])-- engine.startFileHash(task.taskId, "md5")- waitFor(lambda: engine._hashState.error is not None)-- assert engine._hashState.digest == ""- # Kotlin 的 HashState.error 是 TaskError?,字符串会在这里炸成 JsonDecodingException- assert isinstance(engine._hashState.error, dict)- assert set(engine._hashState.error) == {"message", "params"}---def test_starting_a_second_task_never_reports_under_the_first(engine, tmp_path):- first = tmp_path / "first.bin"- second = tmp_path / "second.bin"- first.write_bytes(b"a" * (64 * 1024 * 1024))- second.write_bytes(b"b" * (64 * 1024 * 1024))- taskA = buildTask(first, "first.bin")- taskB = buildTask(second, "second.bin")- engine._taskService = StubTaskService([taskA, taskB])-- digestA = hashlib.sha256(b"a" * (64 * 1024 * 1024)).hexdigest()-- engine.startFileHash(taskA.taskId, "sha256")- waitFor(lambda: 0 < engine._hashState.progress < 100)- engine.startFileHash(taskB.taskId, "sha256")- waitFor(lambda: engine._hashState.digest != "")-- assert engine._hashState.taskId == taskB.taskId- assert engine._hashState.digest != digestA- assert engine._hashState.digest == hashlib.sha256(b"b" * (64 * 1024 * 1024)).hexdigest()---def test_cancel_after_restart_still_stops_the_new_job(engine, tmp_path):- path = tmp_path / "big.bin"- path.write_bytes(b"c" * (64 * 1024 * 1024))- task = buildTask(path, "big.bin")- engine._taskService = StubTaskService([task])-- engine.startFileHash(task.taskId, "md5")- waitFor(lambda: engine._hashState.progress > 0)- engine.startFileHash(task.taskId, "sha512")- waitFor(lambda: engine._hashState.algorithm == "sha512")- engine.cancelFileHash()-- time.sleep(0.5)- assert engine._hashState.taskId == ""- assert engine._hashState.digest == ""