Skip to content

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

test(android): 校验 Android 配置与 pack 加载

XiaoYouChR4c5463f6df6e
diff --git a/tests/fixtures/import_android_packs.py b/tests/fixtures/import_android_packs.py
new file mode 100644
index 00000000..54892519
--- /dev/null
+++ b/tests/fixtures/import_android_packs.py
@@ -0,0 +1,32 @@
+import importlib
+import json
+import sys
+from pathlib import Path
+from types import ModuleType
+from unittest.mock import MagicMock
+
+BLOCKED = ("PySide6", "qfluentwidgets", "qframelesswindow", "shiboken6")
+
+
+class BlockQt:
+ def find_spec(self, name, path=None, target=None):
+ if name.split(".")[0] in BLOCKED:
+ raise ImportError(f"{name} 不在 Android 运行时里")
+
+
+tree, packs = Path(sys.argv[1]), sys.argv[2:]
+sys.meta_path.insert(0, BlockQt())
+sys.modules["java"] = MagicMock()
+sys.path.insert(0, str(tree))
+sys.path.insert(0, str(tree / "features"))
+
+failures = {}
+for pack in packs:
+ for module in ("pack", "android"):
+ if not (tree / "features" / pack / f"{module}.py").exists():
+ continue
+ try:
+ importlib.import_module(f"{pack}.{module}")
+ except Exception as e:
+ failures[f"{pack}.{module}"] = f"{type(e).__name__}: {e}"
+print(json.dumps(failures))
diff --git a/tests/test_android_config_parity.py b/tests/test_android_config_parity.py
new file mode 100644
index 00000000..41c86f55
--- /dev/null
+++ b/tests/test_android_config_parity.py
@@ -0,0 +1,48 @@
+from __future__ import annotations
+
+import importlib.util
+from pathlib import Path
+
+from app.config.cfg import Config
+
+ANDROID_CFG_PATH = Path(__file__).parents[1] / "android/app/src/main/python/app/config/cfg.py"
+
+# 桌面窗口/Dock/菜单栏/开机自启/URL scheme/剪贴板监听/下载目录历史/设置页折叠状态;
+# 主题与语言在 Android 走 SharedPreferences(见 android/CLAUDE.md「Config 按消费者分路」)
+DESKTOP_ONLY = {
+ ("Browser", "UrlSchemeRegistered"),
+ ("GeneralDownload", "HistoryDownloadFolder"),
+ ("Personalization", "BackgroundEffect"),
+ ("Personalization", "DpiScale"),
+ ("Personalization", "Language"),
+ ("Personalization", "ShowDockIcon"),
+ ("Personalization", "ShowDockSpeed"),
+ ("Personalization", "ShowMenuBarSpeed"),
+ ("Personalization", "ThemeMode"),
+ ("Software", "AutoRun"),
+ ("Software", "ClipboardListener"),
+ ("Software", "CloseMode"),
+ ("Software", "Geometry"),
+ ("UI", "ExpandedSettingGroups"),
+ ("UI", "SettingGroupOrder"),
+}
+
+
+def loadAndroidConfig():
+ spec = importlib.util.spec_from_file_location("android_cfg", ANDROID_CFG_PATH)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module.AndroidConfig
+
+
+def keysOf(configClass) -> set[tuple[str, str]]:
+ return {
+ (item.group, item.name)
+ for item in vars(configClass).values()
+ if hasattr(item, "group") and hasattr(item, "name") and hasattr(item, "validator")
+ }
+
+
+def test_android_config_covers_every_desktop_setting_except_desktop_only():
+ missing = keysOf(Config) - keysOf(loadAndroidConfig()) - DESKTOP_ONLY
+ assert missing == set()
diff --git a/tests/test_android_pack_import.py b/tests/test_android_pack_import.py
new file mode 100644
index 00000000..c40d7cb0
--- /dev/null
+++ b/tests/test_android_pack_import.py
@@ -0,0 +1,63 @@
+from __future__ import annotations
+
+import json
+import re
+import shutil
+import subprocess
+import sys
+from fnmatch import fnmatch
+from pathlib import Path
+
+ROOT = Path(__file__).parents[1]
+GRADLE = (ROOT / "android/app/build.gradle.kts").read_text(encoding="utf-8")
+SCRIPT = ROOT / "tests/fixtures/import_android_packs.py"
+
+
+def gradleBlock(name: str) -> str:
+ start = GRADLE.index(f'register<Sync>("{name}")')
+ return GRADLE[start:GRADLE.index("\n}\n", start)]
+
+
+def excludesOf(block: str) -> list[str]:
+ return re.findall(r'exclude\("([^"]+)"\)', block)
+
+
+def copyPy(source: Path, target: Path, excludes: list[str], includes: tuple[str, ...]) -> None:
+ for path in source.rglob("*"):
+ relative = path.relative_to(source).as_posix()
+ if not path.is_file() or "__pycache__" in path.parts:
+ continue
+ if not any(fnmatch(relative, pattern) for pattern in includes):
+ continue
+ if any(fnmatch(relative, pattern) for pattern in excludes):
+ continue
+ (target / relative).parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy(path, target / relative)
+
+
+def buildAndroidTree(tree: Path) -> list[str]:
+ engine = gradleBlock("syncEngineSource")
+ copyPy(ROOT / "app", tree / "app", excludesOf(engine), ("*.py",))
+ shutil.copytree(ROOT / "android/app/src/main/python/app", tree / "app", dirs_exist_ok=True,
+ ignore=shutil.ignore_patterns("__pycache__"))
+
+ packs = re.search(r"androidPacks = listOf\((.*?)\)", GRADLE, re.S).group(1)
+ packs = re.findall(r'"([^"]+)"', packs)
+ featureExcludes = excludesOf(gradleBlock("syncFeatureSource"))
+ for pack in packs:
+ copyPy(ROOT / "features" / pack, tree / "features" / pack, featureExcludes,
+ ("*.py", "manifest.toml", "lists/*"))
+ (tree / "features/__init__.py").write_text("")
+ return packs
+
+
+def test_every_android_pack_imports_in_the_android_runtime(tmp_path):
+ packs = buildAndroidTree(tmp_path / "tree")
+
+ result = subprocess.run(
+ [sys.executable, "-I", str(SCRIPT), str(tmp_path / "tree"), *packs],
+ capture_output=True, text=True, cwd=tmp_path,
+ )
+
+ assert result.returncode == 0, result.stderr
+ assert json.loads(result.stdout.splitlines()[-1]) == {}