help-client-config.test.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. import { readFile, writeFile, rm } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { readSettings, seedSettings, waitForDefaultWorkspaceReady } from "./helpers/desktop-app.js";
  4. import { writeE2EJsonFileAtomically } from "./helpers/e2e-atomic-json-file.js";
  5. import {
  6. buildHelpBrowserFixture,
  7. readHelpFixture,
  8. startHelpConfigFixture,
  9. } from "./helpers/help-client-config-fixture.js";
  10. type DesktopBridge = {
  11. executeDesktopCommand(command: string): Promise<void>;
  12. canOpenCommunity(locale: "zh-CN" | "en-US"): Promise<boolean>;
  13. setApplicationLocale(locale: "zh-CN" | "en-US"): Promise<void>;
  14. };
  15. async function command(command: string) {
  16. await browser.execute(async (value) => {
  17. await (window as unknown as { zcode: DesktopBridge }).zcode.executeDesktopCommand(value);
  18. }, command);
  19. }
  20. async function available(locale: "zh-CN" | "en-US") {
  21. return browser.execute(
  22. async (value) => (window as unknown as { zcode: DesktopBridge }).zcode.canOpenCommunity(value),
  23. locale,
  24. );
  25. }
  26. async function english() {
  27. await browser.execute(async () => {
  28. await (window as unknown as { zcode: DesktopBridge }).zcode.setApplicationLocale("en-US");
  29. });
  30. }
  31. describe("帮助配置 client/configs", () => {
  32. let originalSettings: Awaited<ReturnType<typeof readSettings>>;
  33. let localPath: string;
  34. let originalLocal: string | undefined;
  35. let fixture: Awaited<ReturnType<typeof readHelpFixture>>;
  36. let server: Awaited<ReturnType<typeof startHelpConfigFixture>>;
  37. let external: Awaited<ReturnType<typeof browser.electron.mock>>;
  38. before(async () => {
  39. await waitForDefaultWorkspaceReady(30000);
  40. originalSettings = await readSettings();
  41. fixture = await readHelpFixture();
  42. const appPath = await browser.electron.execute((electron) => electron.app.getAppPath());
  43. // E2E 必须只改 worker 的隔离默认配置,绝不写开发者的真实安装目录。
  44. if (!appPath.includes(".e2e-cache")) throw new Error(`Unexpected E2E app path: ${appPath}`);
  45. localPath = join(appPath, "../../config/default.json");
  46. originalLocal = await readFile(localPath, "utf8").catch(() => undefined);
  47. // Main 的 setApplicationLocale 只更新原生菜单,不修改 Renderer 的持久语言。
  48. // 先为隔离副本设置界面语言再加载,避免中文系统下用英文选择器误报帮助入口缺失。
  49. await seedSettings({ locale: "en-US", localePreference: "en-US" });
  50. await browser.refresh();
  51. await waitForDefaultWorkspaceReady(30000);
  52. });
  53. beforeEach(async () => {
  54. await english();
  55. await writeE2EJsonFileAtomically(localPath, fixture.local);
  56. external = await browser.electron.mock("shell", "openExternal");
  57. await external.mockResolvedValue(undefined);
  58. server = await startHelpConfigFixture(fixture.remote);
  59. await seedSettings({ zcodeEndpointOrigin: server.origin });
  60. });
  61. afterEach(async () => {
  62. await browser.keys("Escape");
  63. await browser.electron.restoreAllMocks();
  64. await seedSettings({ zcodeEndpointOrigin: originalSettings.zcodeEndpointOrigin });
  65. await server?.close();
  66. });
  67. after(async () => {
  68. if (originalLocal === undefined) await rm(localPath, { force: true });
  69. else await writeFile(localPath, originalLocal, "utf8");
  70. await seedSettings(originalSettings);
  71. await browser.execute(async (locale) => {
  72. await (window as unknown as { zcode: DesktopBridge }).zcode.setApplicationLocale(locale);
  73. }, originalSettings.locale ?? "en-US");
  74. });
  75. async function expectExternal(url: string) {
  76. await browser.waitUntil(
  77. async () => {
  78. try {
  79. await expect(external).toHaveBeenCalledWith(url);
  80. return true;
  81. } catch {
  82. return false;
  83. }
  84. },
  85. { timeout: 10000, timeoutMsg: `未打开外链 ${url}` },
  86. );
  87. }
  88. it("HC-01: 真实帮助菜单、语言与成功缓存", async () => {
  89. expect(await available("en-US")).toBe(true);
  90. await $('button[aria-label="Help"]').click();
  91. await $('//*[@role="menuitem" and contains(.,"User community")]').click();
  92. await expectExternal(fixture.remote.community_urls!["en-US"]!);
  93. expect(await available("zh-CN")).toBe(true);
  94. await browser.execute(async () => {
  95. await (window as unknown as { zcode: DesktopBridge }).zcode.setApplicationLocale("zh-CN");
  96. });
  97. await command("openCommunity");
  98. await expectExternal(fixture.remote.community_urls!["zh-CN"]!);
  99. expect(server.requests).toHaveLength(1);
  100. const query = new URL(server.requests[0]!.url, server.origin).searchParams;
  101. expect(query.get("app_version")).toBeTruthy();
  102. expect(query.get("platform")).toBe(`${process.platform}-${process.arch}`);
  103. expect(server.requests[0]!.headers.authorization).toBeUndefined();
  104. });
  105. it("HC-02: 英文缺失只回退英文内置值", async () => {
  106. server.setConfig({ community_urls: { "zh-CN": fixture.remote.community_urls!["zh-CN"] } });
  107. expect(await available("en-US")).toBe(true);
  108. await command("openCommunity");
  109. await expectExternal(fixture.local.community_urls!["en-US"]!);
  110. });
  111. it("HC-03: false 覆盖本地 true 并显示弹窗;新 endpoint 的 true 打开表单", async () => {
  112. await command("openFeedback");
  113. await $('[role="dialog"]').waitForDisplayed({ timeout: 10000 });
  114. await expect($('[role="dialog"]')).toHaveText(expect.stringContaining("Submit feedback"));
  115. if (process.platform === "linux") {
  116. const overlayTop = await browser.execute(() => {
  117. const overlay = document.querySelector<HTMLElement>('[data-slot="dialog-overlay"]');
  118. if (!overlay) throw new Error("反馈弹窗遮罩不存在");
  119. return overlay.getBoundingClientRect().top;
  120. });
  121. expect(overlayTop).toBe(0);
  122. }
  123. await expect(external).not.toHaveBeenCalled();
  124. await browser.keys("Escape");
  125. const other = await startHelpConfigFixture({
  126. ...fixture.remote,
  127. feedback_use_external_form: true,
  128. });
  129. try {
  130. await seedSettings({ zcodeEndpointOrigin: other.origin });
  131. await command("openFeedback");
  132. await expectExternal(fixture.remote.feedback_url!);
  133. expect(other.requests).toHaveLength(1);
  134. } finally {
  135. await other.close();
  136. }
  137. });
  138. for (const failure of ["http", "business", "json"] as const) {
  139. it(`HC-04-${failure}: 失败回退、不缓存失败、同 endpoint 恢复`, async () => {
  140. server.setFailure(failure);
  141. expect(await available("en-US")).toBe(true);
  142. await command("openCommunity");
  143. await expectExternal(fixture.local.community_urls!["en-US"]!);
  144. expect(server.requests.length).toBeGreaterThanOrEqual(2);
  145. server.setConfig(fixture.remote);
  146. await command("openCommunity");
  147. await expectExternal(fixture.remote.community_urls!["en-US"]!);
  148. });
  149. }
  150. it("HC-04-empty: 远端和内置均无当前语言时平台不可用", async () => {
  151. await writeE2EJsonFileAtomically(localPath, {});
  152. server.setConfig({});
  153. expect(await available("en-US")).toBe(false);
  154. expect(await available("zh-CN")).toBe(false);
  155. });
  156. it("HC-05: 窄屏 Chromium Web 解析、并发缓存与页面重载重新请求", async () => {
  157. const webServer = await startHelpConfigFixture(fixture.remote, await buildHelpBrowserFixture());
  158. const mainHandle = await browser.getWindowHandle();
  159. const existing = await browser.getWindowHandles();
  160. const id = await browser.electron.execute(async (electron, url) => {
  161. const win = new electron.BrowserWindow({
  162. width: 390,
  163. height: 844,
  164. show: false,
  165. webPreferences: { sandbox: true, nodeIntegration: false },
  166. });
  167. await win.loadURL(url);
  168. return win.id;
  169. }, webServer.origin);
  170. try {
  171. await browser.waitUntil(
  172. async () => (await browser.getWindowHandles()).length > existing.length,
  173. { timeout: 10000 },
  174. );
  175. const handle = (await browser.getWindowHandles()).find((item) => !existing.includes(item))!;
  176. await browser.switchToWindow(handle);
  177. const read = async () =>
  178. browser.execute(async () => {
  179. const help = (
  180. window as unknown as {
  181. helpFixture: {
  182. resolveWebCommunityUrl(
  183. locale: string,
  184. options: { endpointOrigin: string },
  185. ): Promise<string>;
  186. };
  187. }
  188. ).helpFixture;
  189. return Promise.all(
  190. ["zh-CN", "en-US"].map((locale) =>
  191. help.resolveWebCommunityUrl(locale, { endpointOrigin: location.origin }),
  192. ),
  193. );
  194. });
  195. expect(await read()).toEqual([
  196. fixture.remote.community_urls!["zh-CN"],
  197. fixture.remote.community_urls!["en-US"],
  198. ]);
  199. expect(webServer.requests).toHaveLength(1);
  200. expect(
  201. new URL(webServer.requests[0]!.url, webServer.origin).searchParams.has("platform"),
  202. ).toBe(false);
  203. webServer.setConfig({ community_urls: { "en-US": "https://example.com/E2E_WEB_CHANGED" } });
  204. expect((await read())[1]).toBe(fixture.remote.community_urls!["en-US"]);
  205. await browser.refresh();
  206. expect((await read())[1]).toBe("https://example.com/E2E_WEB_CHANGED");
  207. expect(webServer.requests).toHaveLength(2);
  208. } finally {
  209. await browser.electron.execute(
  210. (electron, windowId) => electron.BrowserWindow.fromId(windowId)?.destroy(),
  211. id,
  212. );
  213. await browser.switchToWindow(mainHandle);
  214. await webServer.close();
  215. }
  216. });
  217. });