Peach: Local-first video metadata scraper and media manager.
fix(desktop): 首次设置保存自选数据目录并切换托盘服务
longmeidao76b189c625c8
diff --git a/README.en.md b/README.en.mdindex d6aa29a0b..a60ba5ec8 100644--- a/README.en.md+++ b/README.en.md@@ -144,6 +144,7 @@ Open System diagnostics under Peach configuration → Application and maintenanc- Existing titles, performers, studios and posters show up right away.- **Which cloud drives are supported?**- 115 and PikPak, mounted as local drives with CloudDrive2.+ - CloudDrive2 can also run on a NAS such as Synology. Map the shared folder to a Windows drive letter, then select that folder in Peach; this setup does not require CloudDrive2 or WinFsp on Windows.- For playback, Peach reads them like ordinary folders and does not store your cloud account.- For cloud download, the CloudDrive2 API token and the PikPak sign-in token are kept in this computer's credential file.- For PikPak, "Sign in with browser" is the recommended way: you sign in inside the window it opens, and Peach never sees your password. Signing in with your account and password also works; the password is saved only if you tick "Save password".diff --git a/README.md b/README.mdindex a61ce8b63..ceea13259 100644--- a/README.md+++ b/README.md@@ -143,6 +143,7 @@ macOS 把后两条换成 `uv sync --locked --python 3.14 --extra macos` 和 `./.- 已有的标题、女优、厂牌和海报会直接显示。- **支持哪些网盘?**- 支持通过 CloudDrive2 挂载的 115 和 PikPak。+ - CloudDrive2 也可运行在群晖等 NAS 上。Windows 先把共享目录映射为盘符,再在 Peach 中选择对应文件夹;这种方式无需在 Windows 安装 CloudDrive2 或 WinFsp。- 看片时 Peach 只把它当普通文件夹读,不保存网盘账号。- 用云下载时,CloudDrive2 的 API 令牌和 PikPak 的登录令牌存在这台电脑的凭据文件里。- PikPak 推荐点「用浏览器登录」,在弹出的窗口里登录,Peach 不经手密码;也可以用账号密码登录,密码只在你勾选「保存密码」时保存。diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex 1ffb9134f..9eb738678 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -2,6 +2,8 @@接手时先读这份:跨任务长期成立的判据与约定。运行态见 `STATUS.md`,部署与设置见 `OPERATIONS.md`。+首次设置服务只负责配置,不启动账本任务恢复、关注和订阅轮询、推送发现、云下载对账或挂载检查。`tray-setup.err.log` 中的 `sqlite3.OperationalError: unable to open database file` 可由尚无账本时启动下载对账触发,不能据此判断媒体目录不可读。设置完成后仍回到首启页时,核对实际数据目录:启动落点通过 `state/data-root.txt` 定位自选目录,托盘切换服务时同时迁移单实例锁,并更新迁移检查与查看日志的路径。CloudDrive2 可部署在 NAS,Windows 通过映射盘符读取共享目录,本机软件安装检测只作提示。+## 界面、媒体与复核的既定判据界面门槛见 `.claude/skills/peach-web-ui/SKILL.md`,这里只留代码外的判据。diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.mdindex 2af8348f6..0d565618e 100644--- a/docs/OPERATIONS.md+++ b/docs/OPERATIONS.md@@ -51,7 +51,7 @@2. 项目目录旁边的 `peach-data/`(最多向上找四层,所以主检出、工作树和打包出的 `dist/Peach` 都能找到同一个)。3. 都没有,就是「未配置」。-Windows 测试包的数据根是 `%LOCALAPPDATA%\Peach\peach-data`。+Windows 测试包默认使用 `%LOCALAPPDATA%\Peach\peach-data`。首次设置选择其他数据目录时,启动落点的 `state/data-root.txt` 会记录所选绝对路径;托盘、子服务和再次启动均沿此记录读取设置。该文件只保存本机路径,账本和媒体留在各自目录。记录不可读、路径无效或循环时会报错。同一个设置项的优先级:环境变量 > 设置文件 > 内置默认值。diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 2e085d62a..41e1e364e 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -259,6 +259,7 @@ JAV 默认封面(官方封面/预览图)与视频默认大小(大图/- GET 重试归现有连接器:[HTTPX 原生重试](https://www.python-httpx.org/advanced/transports/)只覆盖连接失败,统一不了 HTTPX 与 curl_cffi 的读超时、临时 HTTP 状态与页面进度。POST 不重放,403 单次终止。- 标签发布用系统 Git、GitHub CLI(MIT)与 [Actions runs REST API](https://docs.github.com/en/rest/actions/workflow-runs);[release_tag.py](../scripts/release_tag.py) 管版本、主线归属、同提交成功 CI 与不可覆盖策略,工作流用 Release 制品验收。- 独立 Windows 测试包用 PyInstaller(GPL-2.0-or-later,带 bootloader 分发例外)的 [onedir 与自启动子进程](https://pyinstaller.org/en/stable/common-issues-and-pitfalls.html):完整目录共享资源、避免重复解包,onefile 托盘入口只用于源码部署;Peach 保留进程所有权、数据目录、配置和扫描策略。+- 首启数据目录定位复用标准库 `pathlib` 和现有 `fsutil.atomic_write_text`,在启动落点记录本机绝对路径,读取限定跳转次数并检查循环。目录选择、单实例锁交接及服务环境属于 Peach 生命周期策略,无新增依赖。临时目录回归覆盖保存配置、真实子服务启动、正常首页、再次发现所选位置和锁冲突。- Windows 安装包用 Inno Setup 6.7.3(Inno Setup License,允许免费分发)与官方 `Files/Languages/Unofficial/ChineseSimplified.isl` 译文(在 `scripts/installer/`)。目录选择与升级目录记忆复用官方 [`DisableDirPage`](https://jrsoftware.org/ishelp/topic_setup_disabledirpage.htm)、[`UsePreviousAppDir`](https://jrsoftware.org/ishelp/topic_setup_usepreviousappdir.htm);Peach 在目录页和安装前校验独立目录、数据重叠、目录链接、写入权限及已有安装位置,使用现有 Inno Setup,无新增依赖。`test_desktop_installer.py` 编译正式脚本并运行共用判据的隔离 EXE,覆盖中文和空格路径、原位升级及目录保护,不安装到真实位置、不写 ledger。`.iss` 只管文件、开始菜单项和卸载登记;停托盘、补迁移、撤快捷方式经 `desktop_installer` 调已有入口,自更新与应用内卸载是唯一实现。- 运行一致性:用 `LedgerDatabase.write_transaction` 的提交边界与 `OrderedDict`;HTTP 导航用 FastAPI/Starlette,图片复验用 `StaticFiles.is_not_modified` 与 `FileResponse` 的 ETag;列表用 SQLite 的 IN/UNION 保留隐藏标签与多标签组合,不引查询框架。- 馆藏侧栏用 `catalog_filter` 的列表条件,已保存在线卡片用关注来源的标签与封面投影,详情用 `openFollowDetail`、Video.js 与媒体队列;导航范围与标签计数在 `frontend/src/sidebar.ts`。diff --git a/docs/STATUS.md b/docs/STATUS.mdindex 67956e812..4aabfb612 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -21,7 +21,7 @@- 封面2001,v11。- 收藏、续播、播放墙续页;[路由](ROUTES.md)、[JAV](JAV_DISCOVERY.md)。- `/healthz` 报 `configurable=true`;配置、选目录共用连接判据;托盘管理 HTTPS 地址、端口及重载。-- 首启、配置页列缺失依赖(CloudDrive、挂载驱动、FFmpeg/ffprobe、OpenSSL);Windows 识别 CloudDrive、WinFsp。+- 首启目录持久化,配置后启动后台任务;依赖提示见 [运行与配置](OPERATIONS.md)。- 密码未开,局域网匿名可读;首启可跳过密码,配置页可改可关,登录可记住设备。- macOS 是 reader,代码与 `peach-data` 在内置盘;`peach.local` 经 8900/8443 和 pf 提供 80/443,GET 正常、写入回 409。- 两端用本机 CA,私钥、凭据不跨机;代码 Git、账本单写者复制、图片 Syncthing;坐标 `<数据根>/config.toml`。diff --git a/frontend/e2e/setup.test.ts b/frontend/e2e/setup.test.tsindex 38794a529..1e63abaa1 100644--- a/frontend/e2e/setup.test.ts+++ b/frontend/e2e/setup.test.ts@@ -93,6 +93,8 @@ describe('首次运行页', { skip: origin && media && dataRoot ? false : '只// 改对:已有目录、默认端口,不扫描。await folder.fill(media);await port.fill(defaultPort);+ const selectedData = join(dataRoot, 'custom-data');+ await page.locator('#f-data_root').fill(selectedData);const accepted = page.waitForResponse((response) => response.url().endsWith('/api/setup')&& response.request().method() === 'POST');await page.getByRole('button', { name: '完成设置' }).click();@@ -108,6 +110,11 @@ describe('首次运行页', { skip: origin && media && dataRoot ? false : '只await page.getByText('稍后在配置页开始扫描媒体库。').waitFor({ state: 'visible' });assert.equal(await page.title(), 'Peach · 设置完成');assert.deepEqual((await layout(page)).offenders, []);+ await page.getByText('运行信息', { exact: true }).click();+ await page.getByText(selectedData, { exact: true }).waitFor({ state: 'visible' });+ const mobile = VIEWPORTS.find((candidate) => candidate.name === 'mobile')!;+ await page.setViewportSize({ width: mobile.width, height: mobile.height });+ assert.deepEqual((await layout(page)).offenders, []);assert.deepEqual(problems.filter((problem) => !expectedRejection(problem)), []);} finally {diff --git a/src/peach/api.py b/src/peach/api.pyindex 2bf962f5d..2871b65a3 100644--- a/src/peach/api.py+++ b/src/peach/api.py@@ -321,16 +321,16 @@ def create_app(loop = asyncio.get_running_loop()previous_error_handler = loop.get_exception_handler()loop.set_exception_handler(asyncio_handler)- _restore_task_center(contract)# 启动握手要等 cloudflared 连上边缘,可以占到几十秒;和 mDNS 一样交给线程,# 不要在事件循环里卡住整条服务的启动。await asyncio.to_thread(_start_tunnel, settings, tunnel_manager)- follow_scheduler.start()- feed_scheduler.start()- automatic_updates.start()- push_discovery.start()- downloads.start()if settings.configured:+ _restore_task_center(contract)+ follow_scheduler.start()+ feed_scheduler.start()+ automatic_updates.start()+ push_discovery.start()+ downloads.start()mount_reachability.start()warmup = asyncio.create_task(warm_startup_entries())aggregate_warmup = asyncio.create_task(_warm_ledger_aggregates(settings, contract))diff --git a/src/peach/media_configuration.py b/src/peach/media_configuration.pyindex e20f9689f..d802c2d40 100644--- a/src/peach/media_configuration.py+++ b/src/peach/media_configuration.py@@ -85,7 +85,7 @@ def validate(raws: object, *, windows: bool) -> tuple[dict, dict, list[str]]:if any(ord(char) < 32 for char in text + root):raise ValueError("路径不能包含控制字符")if not platform.is_windows_path(root) or ".." in PureWindowsPath(root).parts:- raise ValueError("Windows 中的对应路径必须包含盘符,例如 B:\\")+ raise ValueError("Windows 中的对应路径必须包含盘符,例如 B:\\;网络共享请先映射为 Windows 盘符")path = PureWindowsPath(text) if windows else PurePosixPath(text)if not text or not (platform.is_windows_path(text) if windows else text.startswith("/")):raise ValueError("请填写本机挂载点的绝对路径")diff --git a/src/peach/routes_pages.py b/src/peach/routes_pages.pyindex 17c941999..3cbd96ab4 100644--- a/src/peach/routes_pages.py+++ b/src/peach/routes_pages.py@@ -98,7 +98,7 @@ _POSIX_MEDIA_NOTE = "本机文件夹是这台电脑读取媒体的位置;Windo#: 有一行媒体来源选了云盘时,媒体库底下出现的那句提示和它的帮助链接。-_CLOUD_HELP = "先在 CloudDrive 登录网盘并完成挂载。"+_CLOUD_HELP = "CloudDrive 可运行在本机或 NAS。请先挂载网盘;Windows 读取 NAS 共享时,请先映射为盘符,再选择对应文件夹。本机安装提示仅适用于在本机运行 CloudDrive。"_CLOUD_HELP_URL = "https://www.clouddrive2.com/help.html"_CLOUD_HELP_LABEL = "挂载帮助"@@ -436,6 +436,7 @@ async def setup_submit_json(request: Request):raise HTTPException(status_code=409, detail="settings file already exists")try:applied = onboarding.apply(resolved, answers, windows=windows, access_password=password)+ settings_file.remember_data_root(settings_file.active(), applied.config)except (OSError, RuntimeError) as exc:errors = {"data_root": str(exc)}if errors:diff --git a/src/peach/settings_file.py b/src/peach/settings_file.pyindex a7d9cecb4..1ba5b7925 100644--- a/src/peach/settings_file.py+++ b/src/peach/settings_file.py@@ -33,6 +33,7 @@ from . import distribution#: 设置文件名。位置固定为数据根下,不做多候选路径搜索。SETTINGS_FILENAME = "config.toml"DATA_ROOT_ENV = "PEACH_DATA_ROOT"+DATA_ROOT_LOCATION = "data-root.txt"#: ADR-0017 的顶层布局里这两个目录名是固定的,不随机器变化。DATA_ROOT_DIRNAME = "peach-data"SHARED_ROOT_DIRNAME = "peach-sync"@@ -102,7 +103,7 @@ SEARCH_ANCHOR = _search_anchor()_SEARCH_DEPTH = 4-def discover_data_root(+def _bootstrap_data_root(project_root: Path = SEARCH_ANCHOR, environ: dict[str, str] | None = None,) -> tuple[Path, bool]:"""返回 (数据根, 是否真的找到了)。找不到时第一项是 `peach init` 的默认落点。@@ -123,6 +124,43 @@ def discover_data_root(return project_root.parent / DATA_ROOT_DIRNAME, False+def _selected_data_root(root: Path) -> Path:+ """读取本机首次设置保存的位置;最多跟随八次,并拒绝循环与相对路径。"""+ visited = {root}+ for _ in range(9):+ locator = root / "state" / DATA_ROOT_LOCATION+ try:+ text = locator.read_text(encoding="utf-8").strip()+ except FileNotFoundError:+ return root+ except (OSError, UnicodeError) as exc:+ raise SettingsFileError(f"无法读取数据目录位置:{locator}:{exc}") from exc+ selected = Path(text)+ if not text or not selected.is_absolute() or selected in visited:+ raise SettingsFileError(f"数据目录位置无效或循环:{locator}")+ visited.add(selected)+ root = selected+ raise SettingsFileError("数据目录位置的跳转次数超过八次")+++def discover_data_root(+ project_root: Path = SEARCH_ANCHOR, environ: dict[str, str] | None = None,+) -> tuple[Path, bool]:+ """从启动落点读取已保存的数据目录位置,返回实际数据根及发现状态。"""+ root, found = _bootstrap_data_root(project_root, environ)+ selected = _selected_data_root(root)+ return selected, found or (selected / SETTINGS_FILENAME).is_file()+++def remember_data_root(bootstrap: PeachConfig, selected: PeachConfig) -> None:+ """将首次设置选定的位置原子记录在启动落点,不复制账本或其他数据。"""+ if bootstrap.data_root.resolve() == selected.data_root.resolve():+ return+ from .fsutil import atomic_write_text+ atomic_write_text(bootstrap.data_root / "state" / DATA_ROOT_LOCATION,+ str(selected.data_root.resolve()))++@dataclass(frozen=True)class ServerSettings:host: str = "127.0.0.1"diff --git a/src/peach/tray.py b/src/peach/tray.pyindex 91df553d8..2d69f2c06 100644--- a/src/peach/tray.py+++ b/src/peach/tray.py@@ -213,6 +213,16 @@ class SingleInstance:self._handle.close()self._handle = None+ def relocate(self, path: Path) -> None:+ """先取得目标目录的锁,再释放当前目录的锁。"""+ if self.path == path:+ return+ replacement = SingleInstance(path)+ replacement.acquire()+ self.close()+ self.path, self._handle = replacement.path, replacement._handle+ replacement._handle = None+class ServiceManager:def __init__(@@ -835,6 +845,7 @@ class SetupGate:config,*,waiting: bool,+ instance: SingleInstance | None = None,load: Callable[[], object] = settings_file.load_config,popen: Callable[..., subprocess.Popen] = subprocess.Popen,open_browser: Callable[[str], object] = webbrowser.open,@@ -842,6 +853,7 @@ class SetupGate:self.manager = managerself.config = configself._waiting = waiting+ self._instance = instanceself._load = loadself._popen = popenself._open_browser = open_browser@@ -883,6 +895,8 @@ class SetupGate:specs = configured_service_specs(config)except FileNotFoundError:return False # CA 还没生成完(或没有 openssl),下一轮再看+ if self._instance is not None:+ self._instance.relocate(config.directory("state") / "peach-tray.lock")self._waiting = Falseself.config = configself.manager.replace_specs(@@ -1163,11 +1177,12 @@ class PeachTray:threading.Thread(target=work, name="PeachLedgerAction", daemon=True).start()def open_logs(self, _icon=None, _item=None) -> None:- LOG_DIR.mkdir(parents=True, exist_ok=True)+ log_dir = self.gate.config.directory("logs")+ log_dir.mkdir(parents=True, exist_ok=True)if os.name == "nt":- os.startfile(LOG_DIR) # type: ignore[attr-defined]+ os.startfile(log_dir) # type: ignore[attr-defined]elif sys.platform == "darwin":- subprocess.run(["open", str(LOG_DIR)], check=False)+ subprocess.run(["open", str(log_dir)], check=False)def export_diagnostics(self, _icon=None, _item=None) -> None:from .support_bundle import save_bundle@@ -1316,7 +1331,8 @@ class PeachTray:if self._stop_event.is_set():return# 先看首次设置有没有完成:切换会换掉 `manager.specs`,采样必须落在换完之后。- self.gate.poll()+ if self.gate.poll() and self.preparation is not None:+ self.preparation = tray_preparation(self.gate.config, self.manager)down = [spec for spec in self.manager.specs if not self.manager.healthy(spec)]if down:self.revive_services()@@ -1716,7 +1732,7 @@ def _main(argv: list[str] | None = None) -> int:lifecycle = Nonespecs = build_setup_service_specs(config) if waiting else configured_service_specs(config)manager = ServiceManager(specs, log_dir=config.directory("logs"))- gate = SetupGate(manager, config, waiting=waiting)+ gate = SetupGate(manager, config, waiting=waiting, instance=instance)if sys.platform == "darwin":manager.start_missing()run_macos_menu_bar(manager, gate, silent=args.silent, show_browser=args.show)diff --git a/tests/test_config.py b/tests/test_config.pyindex 415f272c1..63e131102 100644--- a/tests/test_config.py+++ b/tests/test_config.py@@ -58,6 +58,27 @@ class ProjectRootTests(unittest.TestCase):class DataRootDiscoveryTests(unittest.TestCase):+ def test_saved_data_root_locations_reject_invalid_and_cyclic_paths(self):+ with TempTree() as tree:+ state = tree.data_root / "state"+ state.mkdir()+ locator = state / settings_file.DATA_ROOT_LOCATION+ for destination in ("", "relative", str(tree.data_root)):+ with self.subTest(destination=destination):+ locator.write_text(destination, encoding="utf-8")+ with self.assertRaises(SettingsFileError):+ tree.load()++ def test_a_missing_selected_root_stays_selected(self):+ with TempTree() as tree:+ selected = tree.root / "custom-data"+ state = tree.data_root / "state"+ state.mkdir()+ (state / settings_file.DATA_ROOT_LOCATION).write_text(str(selected), encoding="utf-8")+ loaded = tree.load()+ self.assertEqual(loaded.data_root, selected)+ self.assertFalse(loaded.present)+def test_environment_variable_wins_over_the_sibling_directory(self):with TempTree() as tree:elsewhere = tree.root / "elsewhere"diff --git a/tests/test_configuration_sources.py b/tests/test_configuration_sources.pyindex 5a5f179cb..95f628233 100644--- a/tests/test_configuration_sources.py+++ b/tests/test_configuration_sources.py@@ -52,6 +52,21 @@ class MediaConfigurationTests(unittest.TestCase):self.assertEqual(roots["115"], ("B:\\Movies", "B:\\Photos"))self.assertEqual(mounts["115"], ("/Volumes/115/Movies", "/Volumes/115/Photos"))+ def test_windows_network_shares_require_a_mapped_drive(self):+ roots, mounts, errors = media_config.validate([+ {"location": "115", "path": r"\\nas\media\115"},+ ], windows=True)+ self.assertEqual(roots, {})+ self.assertEqual(mounts, {})+ self.assertIn("映射为 Windows 盘符", errors[0])+ with patch.object(media_config, "mount_dependencies", return_value=[]):+ roots, mounts, errors = media_config.validate([+ {"location": "115", "path": r"Z:\视频"},+ ], windows=True)+ self.assertFalse(errors)+ self.assertEqual(roots, {"115": ("Z:\\视频",)})+ self.assertEqual(mounts, {})+def test_invalid_and_overlapping_roots_return_row_errors(self):for rows in ([{"location": "bad", "path": "B:/"}],[{"location": [], "path": "B:/"}],diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.pyindex 1ba92b3a9..8920042a6 100644--- a/tests/test_fastapi_api.py+++ b/tests/test_fastapi_api.py@@ -3141,6 +3141,16 @@ class UnconfiguredMachineTests(unittest.IsolatedAsyncioTestCase):self.assertFalse(body["configured"])self.assertEqual(body["db"], "missing")+ async def test_setup_lifespan_keeps_ledger_workers_stopped(self):+ async with self.app.router.lifespan_context(self.app):+ self.assertIsNone(self.app.state.web_contract.downloads._thread)+ self.assertFalse(self.app.state.follow_scheduler._started)+ self.assertFalse(self.app.state.web_contract.feed_scheduler._started)+ response = await self.client.get("/healthz")+ self.assertEqual(response.status_code, 200)+ self.assertFalse(response.json()["configured"])+ self.assertFalse(self.settings.db_path.exists())+async def test_the_page_serves_the_first_run_shell(self):response = await self.client.get("/")self.assertEqual(response.status_code, 200)diff --git a/tests/test_onboarding.py b/tests/test_onboarding.pyindex 8b9448322..6e97c5410 100644--- a/tests/test_onboarding.py+++ b/tests/test_onboarding.py@@ -489,6 +489,62 @@ class SetupJsonContractTests(_SetupHttpCase):self.assertEqual((loaded.server.host, loaded.server.port), ("127.0.0.1", 8900))self.assertFalse(loaded.replication.enabled)+ def test_a_custom_data_root_is_loaded_by_the_tray_and_a_fresh_launch(self):+ import json+ import socket+ import subprocess+ import sys+ from urllib.request import ProxyHandler, build_opener+ from peach.tray import AlreadyRunning, ServiceManager, SetupGate, SingleInstance, _peach_executable++ selected = self.root / "自选数据目录"+ executable = _peach_executable()+ environment = {"PEACH_DATA_ROOT": str(self.config.data_root)}++ def launch_service(command, **kwargs):+ python = sys.executable+ if os.name == "nt":+ python = sys._base_executable+ kwargs["env"]["__PYVENV_LAUNCHER__"] = sys.executable+ return subprocess.Popen([python, "-m", "peach", *command[1:]], **kwargs)++ manager = ServiceManager((), log_dir=self.config.directory("logs"), popen=launch_service)+ self.addCleanup(manager.stop_owned)+ instance = SingleInstance(self.config.directory("state") / "peach-tray.lock")+ instance.acquire()+ self.addCleanup(instance.close)+ gate = SetupGate(manager, self.config, waiting=True,+ instance=instance,+ load=lambda: settings_file.load_config(environ=environment))+ with socket.socket() as holder:+ holder.bind(("127.0.0.1", 0))+ port = holder.getsockname()[1]+ with mock.patch.object(distribution, "standalone", return_value=True), \+ mock.patch("peach.tray._peach_executable", return_value=executable):+ response = self._send("POST", self.SUBMIT,+ json=self._body(data_root=str(selected), port=str(port), scan_now=False),+ base_url="http://127.0.0.1:8900")+ self.assertEqual(response.status_code, 200, response.text)+ self.assertTrue(gate.poll())+ self.assertFalse(gate.waiting)+ self.assertEqual(gate.config.data_root, selected)+ self.assertTrue(manager.wait_until_ready(), "切换后的服务必须能访问")+ opener = build_opener(ProxyHandler({}))+ with opener.open(f"http://127.0.0.1:{port}/healthz", timeout=5) as ready:+ self.assertTrue(json.load(ready)["configured"])+ with opener.open(f"http://127.0.0.1:{port}/", timeout=5) as page:+ self.assertNotIn('data-page="setup"', page.read().decode("utf-8"))+ with mock.patch.object(distribution, "user_data_root", return_value=self.config.data_root):+ fresh = settings_file.load_config(environ={})+ self.assertTrue(fresh.present)+ self.assertEqual(fresh.data_root, selected)+ self.assertEqual(instance.path.parent, fresh.directory("state"))+ with self.assertRaises(AlreadyRunning):+ SingleInstance(instance.path).acquire()+ self.assertTrue((selected / "database" / "ledger.db").is_file())+ self.assertFalse((self.config.data_root / "database" / "ledger.db").exists())+ self.assertEqual(manager.child_environment()["PEACH_DATA_ROOT"], str(selected))+def test_two_directories_are_declared_together(self):second = self.root / "more"second.mkdir()