Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

refactor(platform): SMB 挂载与桌面定位各自出走

longmeidao4279877b57eb
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 0c5256104..afbe33cdf 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -20,10 +20,12 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_taste_history.py", "test_web_ui.py", "test_web_resource_sync.py",
"test_web_review.py"),
"media": ("test_endcard.py", "test_fastapi_api.py", "test_jobs.py",
- "test_media.py", "test_providers.py", "test_segments.py",
+ "test_interaction.py", "test_media.py", "test_providers.py",
+ "test_segments.py",
"test_streaming.py", "test_transcodes.py"),
- "sync": ("test_sync*.py", "test_platform.py", "test_tray.py", "test_mdns.py",
- "test_netwatch.py", "test_certs.py", "test_review_mirror.py"),
+ "sync": ("test_sync*.py", "test_platform.py", "test_mount.py", "test_tray.py",
+ "test_mdns.py", "test_netwatch.py", "test_certs.py",
+ "test_review_mirror.py"),
"metadata": ("test_metadata*.py", "test_fc2*.py", "test_babepedia_match.py",
"test_jav*.py", "test_code_creators.py", "test_logo_provider.py",
"test_avatar_provider.py", "test_performer*.py",
diff --git a/src/peach/api.py b/src/peach/api.py
index 0d2d5f5f6..8c58b3040 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -41,9 +41,9 @@ from .media import (
StashAdapter,
)
from .mdns import create_mdns_publisher
+from .interaction import reveal_path
from .platform import (
is_unmapped,
- reveal_path,
root_online,
translate_ledger_path,
)
diff --git a/src/peach/interaction.py b/src/peach/interaction.py
new file mode 100644
index 000000000..555f1c4b6
--- /dev/null
+++ b/src/peach/interaction.py
@@ -0,0 +1,68 @@
+"""在桌面文件管理器里定位一个文件。
+
+从 `platform` 拆出:路径翻译是纯计算,这里却要调 Shell COM、起子进程,
+是唯一会把窗口弹到用户面前的模块。混在一起会让「翻译层」看起来带副作用。
+"""
+from __future__ import annotations
+
+import ctypes
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+
+def _windows_reveal(path: Path) -> None:
+ """用 Shell 原生接口打开父目录并选中文件。
+
+ `explorer /select` 只负责发起导航;现代 Explorer 已有多个窗口/标签时,新打开的
+ 正确目录可能留在旧「文档」窗口后面。`SHOpenFolderAndSelectItems` 是 Windows 为
+ 「在资源管理器中显示」提供的原生接口,直接接收完整 PIDL,不再依赖命令行解析。
+ """
+ from ctypes import wintypes
+
+ ole32 = ctypes.WinDLL("ole32")
+ shell32 = ctypes.WinDLL("shell32")
+ ole32.CoInitializeEx.argtypes = [ctypes.c_void_p, wintypes.DWORD]
+ ole32.CoInitializeEx.restype = ctypes.c_long
+ ole32.CoUninitialize.argtypes = []
+ ole32.CoTaskMemFree.argtypes = [ctypes.c_void_p]
+ shell32.SHParseDisplayName.argtypes = [
+ wintypes.LPCWSTR, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p),
+ wintypes.DWORD, ctypes.c_void_p,
+ ]
+ shell32.SHParseDisplayName.restype = ctypes.c_long
+ shell32.SHOpenFolderAndSelectItems.argtypes = [
+ ctypes.c_void_p, wintypes.UINT, ctypes.c_void_p, wintypes.DWORD,
+ ]
+ shell32.SHOpenFolderAndSelectItems.restype = ctypes.c_long
+
+ initialized = ole32.CoInitializeEx(None, 0x2) in (0, 1)
+ pidl = ctypes.c_void_p()
+ try:
+ parsed = shell32.SHParseDisplayName(
+ os.fspath(path), None, ctypes.byref(pidl), 0, None,
+ )
+ if parsed < 0 or not pidl.value:
+ raise OSError(f"SHParseDisplayName failed: 0x{parsed & 0xffffffff:08x}")
+ opened = shell32.SHOpenFolderAndSelectItems(pidl, 0, None, 0)
+ if opened < 0:
+ raise OSError(
+ f"SHOpenFolderAndSelectItems failed: 0x{opened & 0xffffffff:08x}"
+ )
+ finally:
+ if pidl.value:
+ ole32.CoTaskMemFree(pidl)
+ if initialized:
+ ole32.CoUninitialize()
+
+
+def reveal_path(path: Path) -> bool:
+ """在本机文件管理器中定位文件;不支持的平台返回 False。"""
+ if os.name == "nt":
+ _windows_reveal(path)
+ return True
+ if sys.platform == "darwin":
+ subprocess.Popen(["open", "-R", os.fspath(path)], close_fds=True)
+ return True
+ return False
diff --git a/src/peach/mount.py b/src/peach/mount.py
new file mode 100644
index 000000000..2221b4d5c
--- /dev/null
+++ b/src/peach/mount.py
@@ -0,0 +1,108 @@
+"""挂载共享盘。
+
+从 `platform` 拆出:那个模块的职责是盘符↔挂载点的路径翻译(ARCHITECTURE 里说的
+「唯一翻译层」),而这里做的是 NetFS 调用和钥匙串查询,两件事只是都碰 macOS。
+
+钥匙串检查在挂载之前先做:没有记录时直接快速失败,不要让 NetFS 弹出阻塞式认证框——
+服务是 launchd 起的,那个框没人能点。
+"""
+from __future__ import annotations
+
+import logging
+import subprocess
+import sys
+from typing import Callable
+from urllib.parse import quote
+
+LOGGER = logging.getLogger(__name__)
+
+
+#: 挂载超时。这是兜底,不是常规耗时——本机实测一次成功挂载 0.6 秒。
+MOUNT_TIMEOUT_SECONDS = 15.0
+
+#: 钥匙串里 SMB 记录的协议标识。四字符定长,末尾那个空格是格式的一部分。
+_SMB_PROTOCOL = "smb "
+
+
+def share_url(host: str, share: str, user: str = "") -> str:
+ """SMB URL。每一段都做百分号编码,引号和反斜杠因此不可能落进 AppleScript 字面量。"""
+ credentials = f"{quote(user, safe='')}@" if user else ""
+ return f"smb://{credentials}{quote(host, safe='')}/{quote(share, safe='')}"
+
+
+def mount_share_command(url: str) -> list[str] | None:
+ """挂上一个 SMB 共享的 argv;本平台没有这条路径时返回 None。
+
+ 走 `osascript` 的 `mount volume` 而不是 `open smb://`:两者都经 NetFS,会自己在
+ `/Volumes` 下建挂载点并取钥匙串里的凭据(`/Volumes` 归 root,脚本 mkdir 不了,
+ 而 `mount_smbfs` 又要求挂载点已经存在),区别是 `open` 会顺带弹一个 Finder 窗口。
+ 2026-08-27 本机实测:卸载后跑这条命令 0.6 秒挂回来,无窗口,返回 0。
+ """
+ if sys.platform != "darwin":
+ return None
+ return ["osascript", "-e", f'mount volume "{url}"']
+
+
+def share_credentials_command(host: str, user: str) -> list[str]:
+ """查钥匙串里有没有这台主机的 SMB 记录的 argv。
+
+ 刻意不带 `-w`:只判断记录在不在,密码不会被读出来,也就不会经过本进程。
+ """
+ return [
+ "security", "find-internet-password",
+ "-s", host, "-a", user, "-r", _SMB_PROTOCOL,
+ ]
+
+
+def share_credentials_present(
+ host: str,
+ user: str,
+ *,
+ run: Callable[..., subprocess.CompletedProcess] = subprocess.run,
+) -> bool:
+ """钥匙串里有没有这台主机、这个账号的 SMB 记录。
+
+ 2026-08-27 实测:没有记录时 NetFS 不会失败,而是拉起 NetAuthAgent 弹一个认证框
+ 然后一直等——托盘那次点击既卡到超时,又在用户没要求的时候把密码框推到屏幕上。
+ 先查一次就把这条路径变成一次快速失败。记录按**主机名**存:同一台机器的 IP 和
+ mDNS 名是两条不同的记录,换一个主机名就要重新记一次密码。
+ """
+ try:
+ result = run(share_credentials_command(host, user),
+ capture_output=True, text=True, timeout=10, check=False)
+ except (OSError, subprocess.SubprocessError) as exc:
+ LOGGER.warning("查钥匙串失败:%s", exc)
+ return False
+ return result.returncode == 0
+
+
+def mount_share(
+ host: str,
+ share: str,
+ user: str = "",
+ *,
+ timeout: float = MOUNT_TIMEOUT_SECONDS,
+ run: Callable[..., subprocess.CompletedProcess] = subprocess.run,
+) -> bool:
+ """挂一次共享,成败只用返回值表示。
+
+ 任何失败都不抛:调用方是「挂不上就照旧降级」的那条路径,异常在那里只会把一条
+ 清楚的消息换成一次崩溃。失败原因写日志,否则事后完全无从查起。
+ """
+ command = mount_share_command(share_url(host, share, user))
+ if command is None:
+ return False
+ if user and not share_credentials_present(host, user, run=run):
+ LOGGER.warning("钥匙串里没有 %s@%s 的 SMB 记录,不去弹认证框", user, host)
+ return False
+ try:
+ result = run(command, capture_output=True, text=True,
+ timeout=timeout, check=False)
+ except (OSError, subprocess.SubprocessError) as exc:
+ LOGGER.warning("挂载 //%s/%s 失败:%s", host, share, exc)
+ return False
+ if result.returncode:
+ LOGGER.warning("挂载 //%s/%s 失败:%s", host, share,
+ (result.stderr or result.stdout or "").strip())
+ return False
+ return True
diff --git a/src/peach/platform.py b/src/peach/platform.py
index b95c83b1d..122595d0b 100644
--- a/src/peach/platform.py
+++ b/src/peach/platform.py
@@ -12,15 +12,10 @@ Windows 上运行,账本因此保持单一路径口径。
"""
from __future__ import annotations
-import ctypes
import logging
import os
-import subprocess
-import sys
from functools import lru_cache
from pathlib import Path, PureWindowsPath
-from typing import Callable
-from urllib.parse import quote
LOGGER = logging.getLogger(__name__)
@@ -73,95 +68,6 @@ def root_online(root: Path) -> bool:
return True
-#: 挂载超时。这是兜底,不是常规耗时——本机实测一次成功挂载 0.6 秒。
-MOUNT_TIMEOUT_SECONDS = 15.0
-
-#: 钥匙串里 SMB 记录的协议标识。四字符定长,末尾那个空格是格式的一部分。
-_SMB_PROTOCOL = "smb "
-
-
-def share_url(host: str, share: str, user: str = "") -> str:
- """SMB URL。每一段都做百分号编码,引号和反斜杠因此不可能落进 AppleScript 字面量。"""
- credentials = f"{quote(user, safe='')}@" if user else ""
- return f"smb://{credentials}{quote(host, safe='')}/{quote(share, safe='')}"
-
-
-def mount_share_command(url: str) -> list[str] | None:
- """挂上一个 SMB 共享的 argv;本平台没有这条路径时返回 None。
-
- 走 `osascript` 的 `mount volume` 而不是 `open smb://`:两者都经 NetFS,会自己在
- `/Volumes` 下建挂载点并取钥匙串里的凭据(`/Volumes` 归 root,脚本 mkdir 不了,
- 而 `mount_smbfs` 又要求挂载点已经存在),区别是 `open` 会顺带弹一个 Finder 窗口。
- 2026-08-27 本机实测:卸载后跑这条命令 0.6 秒挂回来,无窗口,返回 0。
- """
- if sys.platform != "darwin":
- return None
- return ["osascript", "-e", f'mount volume "{url}"']
-
-
-def share_credentials_command(host: str, user: str) -> list[str]:
- """查钥匙串里有没有这台主机的 SMB 记录的 argv。
-
- 刻意不带 `-w`:只判断记录在不在,密码不会被读出来,也就不会经过本进程。
- """
- return [
- "security", "find-internet-password",
- "-s", host, "-a", user, "-r", _SMB_PROTOCOL,
- ]
-
-
-def share_credentials_present(
- host: str,
- user: str,
- *,
- run: Callable[..., subprocess.CompletedProcess] = subprocess.run,
-) -> bool:
- """钥匙串里有没有这台主机、这个账号的 SMB 记录。
-
- 2026-08-27 实测:没有记录时 NetFS 不会失败,而是拉起 NetAuthAgent 弹一个认证框
- 然后一直等——托盘那次点击既卡到超时,又在用户没要求的时候把密码框推到屏幕上。
- 先查一次就把这条路径变成一次快速失败。记录按**主机名**存:同一台机器的 IP 和
- mDNS 名是两条不同的记录,换一个主机名就要重新记一次密码。
- """
- try:
- result = run(share_credentials_command(host, user),
- capture_output=True, text=True, timeout=10, check=False)
- except (OSError, subprocess.SubprocessError) as exc:
- LOGGER.warning("查钥匙串失败:%s", exc)
- return False
- return result.returncode == 0
-
-
-def mount_share(
- host: str,
- share: str,
- user: str = "",
- *,
- timeout: float = MOUNT_TIMEOUT_SECONDS,
- run: Callable[..., subprocess.CompletedProcess] = subprocess.run,
-) -> bool:
- """挂一次共享,成败只用返回值表示。
-
- 任何失败都不抛:调用方是「挂不上就照旧降级」的那条路径,异常在那里只会把一条
- 清楚的消息换成一次崩溃。失败原因写日志,否则事后完全无从查起。
- """
- command = mount_share_command(share_url(host, share, user))
- if command is None:
- return False
- if user and not share_credentials_present(host, user, run=run):
- LOGGER.warning("钥匙串里没有 %s@%s 的 SMB 记录,不去弹认证框", user, host)
- return False
- try:
- result = run(command, capture_output=True, text=True,
- timeout=timeout, check=False)
- except (OSError, subprocess.SubprocessError) as exc:
- LOGGER.warning("挂载 //%s/%s 失败:%s", host, share, exc)
- return False
- if result.returncode:
- LOGGER.warning("挂载 //%s/%s 失败:%s", host, share,
- (result.stderr or result.stdout or "").strip())
- return False
- return True
def within_root(path: Path, root: Path) -> bool:
@@ -236,57 +142,3 @@ def media_root_status(roots) -> tuple[dict[str, object], ...]:
return tuple(status)
-def _windows_reveal(path: Path) -> None:
- """用 Shell 原生接口打开父目录并选中文件。
-
- `explorer /select` 只负责发起导航;现代 Explorer 已有多个窗口/标签时,新打开的
- 正确目录可能留在旧「文档」窗口后面。`SHOpenFolderAndSelectItems` 是 Windows 为
- 「在资源管理器中显示」提供的原生接口,直接接收完整 PIDL,不再依赖命令行解析。
- """
- from ctypes import wintypes
-
- ole32 = ctypes.WinDLL("ole32")
- shell32 = ctypes.WinDLL("shell32")
- ole32.CoInitializeEx.argtypes = [ctypes.c_void_p, wintypes.DWORD]
- ole32.CoInitializeEx.restype = ctypes.c_long
- ole32.CoUninitialize.argtypes = []
- ole32.CoTaskMemFree.argtypes = [ctypes.c_void_p]
- shell32.SHParseDisplayName.argtypes = [
- wintypes.LPCWSTR, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p),
- wintypes.DWORD, ctypes.c_void_p,
- ]
- shell32.SHParseDisplayName.restype = ctypes.c_long
- shell32.SHOpenFolderAndSelectItems.argtypes = [
- ctypes.c_void_p, wintypes.UINT, ctypes.c_void_p, wintypes.DWORD,
- ]
- shell32.SHOpenFolderAndSelectItems.restype = ctypes.c_long
-
- initialized = ole32.CoInitializeEx(None, 0x2) in (0, 1)
- pidl = ctypes.c_void_p()
- try:
- parsed = shell32.SHParseDisplayName(
- os.fspath(path), None, ctypes.byref(pidl), 0, None,
- )
- if parsed < 0 or not pidl.value:
- raise OSError(f"SHParseDisplayName failed: 0x{parsed & 0xffffffff:08x}")
- opened = shell32.SHOpenFolderAndSelectItems(pidl, 0, None, 0)
- if opened < 0:
- raise OSError(
- f"SHOpenFolderAndSelectItems failed: 0x{opened & 0xffffffff:08x}"
- )
- finally:
- if pidl.value:
- ole32.CoTaskMemFree(pidl)
- if initialized:
- ole32.CoUninitialize()
-
-
-def reveal_path(path: Path) -> bool:
- """在本机文件管理器中定位文件;不支持的平台返回 False。"""
- if os.name == "nt":
- _windows_reveal(path)
- return True
- if sys.platform == "darwin":
- subprocess.Popen(["open", "-R", os.fspath(path)], close_fds=True)
- return True
- return False
diff --git a/src/peach/tray.py b/src/peach/tray.py
index 4f474fa02..84e1e9957 100644
--- a/src/peach/tray.py
+++ b/src/peach/tray.py
@@ -25,7 +25,7 @@ from .config import (
)
from .mdns import lan_ipv4
from .netwatch import NetworkChangeWatcher
-from .platform import mount_share as mount_smb_share
+from .mount import mount_share as mount_smb_share
from .sync import COPY_ACTIONS, SyncPlan, device_id, resolve
from .versioning import VersionManager, VersionSnapshot
from .windows_update import WindowsUpdateInstaller
diff --git a/tests/test_interaction.py b/tests/test_interaction.py
new file mode 100644
index 000000000..3cecc9728
--- /dev/null
+++ b/tests/test_interaction.py
@@ -0,0 +1,56 @@
+"""在文件管理器里定位源文件。
+
+随 `interaction` 从 `platform` 一同拆出。patch 目标必须跟着代码走——打在
+`peach.platform` 上不会报错,只是再也 patch 不到真正执行的那份,测试照样「通过」。
+"""
+import os
+import unittest
+from pathlib import Path
+from unittest.mock import Mock, patch
+
+from peach.interaction import _windows_reveal, reveal_path
+
+
+class RevealPathTests(unittest.TestCase):
+ """在文件管理器里定位源文件。"""
+
+ @unittest.skipUnless(os.name == "nt", "Windows Shell API only")
+ def test_windows_uses_the_native_shell_selection_api(self):
+ ole32, shell32 = Mock(), Mock()
+ ole32.CoInitializeEx.return_value = 0
+
+ def parse(_path, _bind, output, _attributes, _read_attributes):
+ output._obj.value = 1234
+ return 0
+
+ shell32.SHParseDisplayName.side_effect = parse
+ shell32.SHOpenFolderAndSelectItems.return_value = 0
+ with patch("peach.interaction.ctypes.WinDLL",
+ side_effect=lambda name: ole32 if name == "ole32" else shell32):
+ _windows_reveal(Path(r"B:\创作者 a\c,d.mp4"))
+ self.assertEqual(shell32.SHParseDisplayName.call_args.args[0],
+ r"B:\创作者 a\c,d.mp4")
+ self.assertEqual(shell32.SHOpenFolderAndSelectItems.call_args.args[1:],
+ (0, None, 0))
+ ole32.CoTaskMemFree.assert_called_once()
+ ole32.CoUninitialize.assert_called_once_with()
+
+ def test_windows_reveal_delegates_to_the_native_shell(self):
+ source = Path(r"B:\创作者 a\c,d.mp4")
+ with (patch("peach.interaction.os.name", "nt"),
+ patch("peach.interaction._windows_reveal") as reveal):
+ self.assertTrue(reveal_path(source))
+ reveal.assert_called_once_with(source)
+
+ def test_macos_reveals_in_finder(self):
+ source = Path("/Volumes/RESOURCES/media/a.mp4")
+ with (patch("peach.interaction.os.name", "posix"),
+ patch("peach.interaction.sys.platform", "darwin"),
+ patch("peach.interaction.subprocess.Popen") as launch):
+ self.assertTrue(reveal_path(source))
+ launch.assert_called_once_with(["open", "-R", str(source)], close_fds=True)
+
+ def test_unsupported_platform_returns_false_instead_of_guessing(self):
+ with (patch("peach.interaction.os.name", "posix"),
+ patch("peach.interaction.sys.platform", "linux")):
+ self.assertFalse(reveal_path(Path("/srv/a.mp4")))
diff --git a/tests/test_mount.py b/tests/test_mount.py
new file mode 100644
index 000000000..3d8982264
--- /dev/null
+++ b/tests/test_mount.py
@@ -0,0 +1,117 @@
+"""把掉了的 SMB 共享挂回来。
+
+随 `mount` 从 `platform` 一同拆出;patch 目标同样跟着代码走。
+"""
+import subprocess
+import unittest
+from unittest.mock import Mock, patch
+
+from peach.mount import (
+ mount_share,
+ mount_share_command,
+ share_credentials_command,
+ share_credentials_present,
+ share_url,
+)
+
+
+def _found(*_args, **_kwargs):
+ """`security find-internet-password` 找到了记录。"""
+ return Mock(returncode=0, stdout="", stderr="")
+
+
+class ShareMountTests(unittest.TestCase):
+ """把掉了的 SMB 共享挂回来。这条路径失败必须降级,不能抛、不能卡、不能弹框。"""
+
+ def test_url_keeps_the_ordinary_case_readable(self):
+ self.assertEqual(
+ share_url("peach-win.local", "peach-sync", "peachsync"),
+ "smb://[email protected]/peach-sync")
+
+ def test_url_without_a_user_has_no_stray_at_sign(self):
+ self.assertEqual(
+ share_url("peach-win.local", "peach-sync"),
+ "smb://peach-win.local/peach-sync")
+
+ def test_url_percent_encodes_every_segment(self):
+ # URL 在 AppleScript 里落在一对双引号中间:账号或主机带引号、反斜杠就能拼出
+ # 第二条语句。编码之后这两个字符不可能出现在字面量里。
+ url = share_url('pe"ach\\win', 'sh"are', 'us"er')
+ self.assertNotIn('"', url)
+ self.assertNotIn("\\", url)
+
+ def test_macos_mounts_through_netfs_without_a_finder_window(self):
+ with patch("peach.mount.sys.platform", "darwin"):
+ command = mount_share_command("smb://[email protected]/peach-sync")
+ # `open smb://` 也走 NetFS、也能挂上,但会顺带弹一个 Finder 窗口;
+ # 菜单栏那条动作不该在用户没看着的时候把窗口翻到前面来。
+ self.assertEqual(command, [
+ "osascript", "-e",
+ 'mount volume "smb://[email protected]/peach-sync"'])
+
+ def test_other_platforms_have_no_mount_path(self):
+ runner = Mock()
+ with patch("peach.mount.sys.platform", "linux"):
+ self.assertIsNone(mount_share_command("smb://host/share"))
+ self.assertFalse(mount_share("host", "share", "user", run=runner))
+ runner.assert_not_called()
+
+ def test_keychain_lookup_never_asks_for_the_password_itself(self):
+ # 带 `-w` 就会把密码打到 stdout,于是密码要经过本进程。只判断记录在不在,
+ # 不需要它,也不该碰它。
+ command = share_credentials_command("peach-win.local", "peachsync")
+ self.assertNotIn("-w", command)
+ self.assertEqual(command[:2], ["security", "find-internet-password"])
+ self.assertIn("peach-win.local", command)
+ self.assertIn("peachsync", command)
+
+ def test_a_missing_keychain_entry_fails_fast_instead_of_prompting(self):
+ # 2026-08-27 实测:钥匙串里没有这台主机的记录时,NetFS 不报错,而是拉起
+ # NetAuthAgent 弹认证框并一直等到超时——用户没点过密码框,却看见一个。
+ runner = Mock(return_value=Mock(returncode=44, stdout="", stderr="not found"))
+ with patch("peach.mount.sys.platform", "darwin"):
+ self.assertFalse(mount_share("peach-win.local", "peach-sync", "peachsync",
+ run=runner))
+ runner.assert_called_once()
+ self.assertEqual(runner.call_args.args[0][:2],
+ ["security", "find-internet-password"])
+
+ def test_a_present_keychain_entry_goes_on_to_mount(self):
+ runner = Mock(side_effect=[_found(), Mock(returncode=0, stdout="", stderr="")])
+ with patch("peach.mount.sys.platform", "darwin"):
+ self.assertTrue(mount_share("peach-win.local", "peach-sync", "peachsync",
+ run=runner))
+ self.assertEqual(runner.call_args.args[0][0], "osascript")
+
+ def test_an_anonymous_mount_skips_the_keychain_check(self):
+ runner = Mock(return_value=Mock(returncode=0, stdout="", stderr=""))
+ with patch("peach.mount.sys.platform", "darwin"):
+ self.assertTrue(mount_share("peach-win.local", "peach-sync", run=runner))
+ runner.assert_called_once()
+ self.assertEqual(runner.call_args.args[0][0], "osascript")
+
+ def test_a_failed_keychain_lookup_is_false_not_an_exception(self):
+ self.assertFalse(share_credentials_present(
+ "peach-win.local", "peachsync", run=Mock(side_effect=OSError("没有 security"))))
+
+ def test_mount_is_bounded_by_a_timeout(self):
+ # 认证框只是最常见的一种等待;网络半通时 SMB 协商同样会挂着。没有超时,
+ # 托盘那个线程就永远停在这里,「同步 Ledger」再也点不动。
+ runner = Mock(side_effect=[_found(), Mock(returncode=0, stdout="", stderr="")])
+ with patch("peach.mount.sys.platform", "darwin"):
+ self.assertTrue(mount_share("peach-win.local", "peach-sync", "peachsync",
+ run=runner))
+ self.assertGreater(runner.call_args.kwargs["timeout"], 0)
+
+ def test_every_mount_failure_is_false_not_an_exception(self):
+ failures = (
+ Mock(returncode=1, stdout="", stderr="No route to host"),
+ subprocess.TimeoutExpired("osascript", 15),
+ OSError("osascript 不存在"),
+ )
+ with patch("peach.mount.sys.platform", "darwin"):
+ for failure in failures:
+ with self.subTest(failure=failure):
+ self.assertFalse(mount_share(
+ "peach-win.local", "peach-sync", "peachsync",
+ run=Mock(side_effect=[_found(), failure])))
diff --git a/tests/test_platform.py b/tests/test_platform.py
index 0efa1a0f1..099371037 100644
--- a/tests/test_platform.py
+++ b/tests/test_platform.py
@@ -10,14 +10,7 @@ from peach.platform import (
UNMAPPED_ROOT,
is_unmapped,
is_windows_path,
- mount_share,
- mount_share_command,
- _windows_reveal,
- reveal_path,
root_online,
- share_credentials_command,
- share_credentials_present,
- share_url,
system_volume,
translate_ledger_path,
translate_roots,
@@ -138,49 +131,6 @@ class OfflineModeTests(unittest.TestCase):
self.assertEqual([row["online"] for row in status], [True, False])
-class RevealPathTests(unittest.TestCase):
- """在文件管理器里定位源文件。"""
-
- @unittest.skipUnless(os.name == "nt", "Windows Shell API only")
- def test_windows_uses_the_native_shell_selection_api(self):
- ole32, shell32 = Mock(), Mock()
- ole32.CoInitializeEx.return_value = 0
-
- def parse(_path, _bind, output, _attributes, _read_attributes):
- output._obj.value = 1234
- return 0
-
- shell32.SHParseDisplayName.side_effect = parse
- shell32.SHOpenFolderAndSelectItems.return_value = 0
- with patch("peach.platform.ctypes.WinDLL",
- side_effect=lambda name: ole32 if name == "ole32" else shell32):
- _windows_reveal(Path(r"B:\创作者 a\c,d.mp4"))
- self.assertEqual(shell32.SHParseDisplayName.call_args.args[0],
- r"B:\创作者 a\c,d.mp4")
- self.assertEqual(shell32.SHOpenFolderAndSelectItems.call_args.args[1:],
- (0, None, 0))
- ole32.CoTaskMemFree.assert_called_once()
- ole32.CoUninitialize.assert_called_once_with()
-
- def test_windows_reveal_delegates_to_the_native_shell(self):
- source = Path(r"B:\创作者 a\c,d.mp4")
- with (patch("peach.platform.os.name", "nt"),
- patch("peach.platform._windows_reveal") as reveal):
- self.assertTrue(reveal_path(source))
- reveal.assert_called_once_with(source)
-
- def test_macos_reveals_in_finder(self):
- source = Path("/Volumes/RESOURCES/media/a.mp4")
- with (patch("peach.platform.os.name", "posix"),
- patch("peach.platform.sys.platform", "darwin"),
- patch("peach.platform.subprocess.Popen") as launch):
- self.assertTrue(reveal_path(source))
- launch.assert_called_once_with(["open", "-R", str(source)], close_fds=True)
-
- def test_unsupported_platform_returns_false_instead_of_guessing(self):
- with (patch("peach.platform.os.name", "posix"),
- patch("peach.platform.sys.platform", "linux")):
- self.assertFalse(reveal_path(Path("/srv/a.mp4")))
@@ -188,103 +138,5 @@ if __name__ == "__main__":
unittest.main()
-def _found(*_args, **_kwargs):
- """`security find-internet-password` 找到了记录。"""
- return Mock(returncode=0, stdout="", stderr="")
-
-
-class ShareMountTests(unittest.TestCase):
- """把掉了的 SMB 共享挂回来。这条路径失败必须降级,不能抛、不能卡、不能弹框。"""
-
- def test_url_keeps_the_ordinary_case_readable(self):
- self.assertEqual(
- share_url("peach-win.local", "peach-sync", "peachsync"),
- "smb://[email protected]/peach-sync")
-
- def test_url_without_a_user_has_no_stray_at_sign(self):
- self.assertEqual(
- share_url("peach-win.local", "peach-sync"),
- "smb://peach-win.local/peach-sync")
-
- def test_url_percent_encodes_every_segment(self):
- # URL 在 AppleScript 里落在一对双引号中间:账号或主机带引号、反斜杠就能拼出
- # 第二条语句。编码之后这两个字符不可能出现在字面量里。
- url = share_url('pe"ach\\win', 'sh"are', 'us"er')
- self.assertNotIn('"', url)
- self.assertNotIn("\\", url)
-
- def test_macos_mounts_through_netfs_without_a_finder_window(self):
- with patch("peach.platform.sys.platform", "darwin"):
- command = mount_share_command("smb://[email protected]/peach-sync")
- # `open smb://` 也走 NetFS、也能挂上,但会顺带弹一个 Finder 窗口;
- # 菜单栏那条动作不该在用户没看着的时候把窗口翻到前面来。
- self.assertEqual(command, [
- "osascript", "-e",
- 'mount volume "smb://[email protected]/peach-sync"'])
-
- def test_other_platforms_have_no_mount_path(self):
- runner = Mock()
- with patch("peach.platform.sys.platform", "linux"):
- self.assertIsNone(mount_share_command("smb://host/share"))
- self.assertFalse(mount_share("host", "share", "user", run=runner))
- runner.assert_not_called()
-
- def test_keychain_lookup_never_asks_for_the_password_itself(self):
- # 带 `-w` 就会把密码打到 stdout,于是密码要经过本进程。只判断记录在不在,
- # 不需要它,也不该碰它。
- command = share_credentials_command("peach-win.local", "peachsync")
- self.assertNotIn("-w", command)
- self.assertEqual(command[:2], ["security", "find-internet-password"])
- self.assertIn("peach-win.local", command)
- self.assertIn("peachsync", command)
-
- def test_a_missing_keychain_entry_fails_fast_instead_of_prompting(self):
- # 2026-08-27 实测:钥匙串里没有这台主机的记录时,NetFS 不报错,而是拉起
- # NetAuthAgent 弹认证框并一直等到超时——用户没点过密码框,却看见一个。
- runner = Mock(return_value=Mock(returncode=44, stdout="", stderr="not found"))
- with patch("peach.platform.sys.platform", "darwin"):
- self.assertFalse(mount_share("peach-win.local", "peach-sync", "peachsync",
- run=runner))
- runner.assert_called_once()
- self.assertEqual(runner.call_args.args[0][:2],
- ["security", "find-internet-password"])
-
- def test_a_present_keychain_entry_goes_on_to_mount(self):
- runner = Mock(side_effect=[_found(), Mock(returncode=0, stdout="", stderr="")])
- with patch("peach.platform.sys.platform", "darwin"):
- self.assertTrue(mount_share("peach-win.local", "peach-sync", "peachsync",
- run=runner))
- self.assertEqual(runner.call_args.args[0][0], "osascript")
-
- def test_an_anonymous_mount_skips_the_keychain_check(self):
- runner = Mock(return_value=Mock(returncode=0, stdout="", stderr=""))
- with patch("peach.platform.sys.platform", "darwin"):
- self.assertTrue(mount_share("peach-win.local", "peach-sync", run=runner))
- runner.assert_called_once()
- self.assertEqual(runner.call_args.args[0][0], "osascript")
-
- def test_a_failed_keychain_lookup_is_false_not_an_exception(self):
- self.assertFalse(share_credentials_present(
- "peach-win.local", "peachsync", run=Mock(side_effect=OSError("没有 security"))))
- def test_mount_is_bounded_by_a_timeout(self):
- # 认证框只是最常见的一种等待;网络半通时 SMB 协商同样会挂着。没有超时,
- # 托盘那个线程就永远停在这里,「同步 Ledger」再也点不动。
- runner = Mock(side_effect=[_found(), Mock(returncode=0, stdout="", stderr="")])
- with patch("peach.platform.sys.platform", "darwin"):
- self.assertTrue(mount_share("peach-win.local", "peach-sync", "peachsync",
- run=runner))
- self.assertGreater(runner.call_args.kwargs["timeout"], 0)
- def test_every_mount_failure_is_false_not_an_exception(self):
- failures = (
- Mock(returncode=1, stdout="", stderr="No route to host"),
- subprocess.TimeoutExpired("osascript", 15),
- OSError("osascript 不存在"),
- )
- with patch("peach.platform.sys.platform", "darwin"):
- for failure in failures:
- with self.subTest(failure=failure):
- self.assertFalse(mount_share(
- "peach-win.local", "peach-sync", "peachsync",
- run=Mock(side_effect=[_found(), failure])))