editors.test.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. vi.mock("electron", () => ({
  3. app: {
  4. getFileIcon: vi.fn(),
  5. },
  6. nativeImage: {
  7. createFromBuffer: vi.fn(),
  8. },
  9. }));
  10. vi.mock("../src/main/logger.js", () => ({
  11. logger: {
  12. info: vi.fn(),
  13. warn: vi.fn(),
  14. },
  15. }));
  16. const originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, "platform");
  17. function setProcessPlatform(platform: NodeJS.Platform) {
  18. Object.defineProperty(process, "platform", { value: platform });
  19. }
  20. afterEach(() => {
  21. if (originalPlatformDescriptor) {
  22. Object.defineProperty(process, "platform", originalPlatformDescriptor);
  23. }
  24. vi.doUnmock("node:child_process");
  25. vi.doUnmock("node:fs");
  26. vi.doUnmock("../src/main/fileApplications.js");
  27. vi.restoreAllMocks();
  28. vi.resetModules();
  29. });
  30. async function importEditorsWithWindowsCommandMocks(
  31. existingPaths: string[],
  32. whereOutput: string,
  33. whereError?: Error,
  34. ) {
  35. setProcessPlatform("win32");
  36. const existingPathSet = new Set(existingPaths);
  37. vi.doMock("node:fs", async () => {
  38. const actual = await vi.importActual<typeof import("node:fs")>("node:fs");
  39. return {
  40. ...actual,
  41. existsSync: vi.fn((path: string) => existingPathSet.has(path)),
  42. };
  43. });
  44. vi.doMock("node:child_process", async () => {
  45. const actual = await vi.importActual<typeof import("node:child_process")>("node:child_process");
  46. return {
  47. ...actual,
  48. execFileSync: vi.fn((file: string, args: string[]) => {
  49. if (file === "where.exe" && args[0] === "code") {
  50. if (whereError) {
  51. throw whereError;
  52. }
  53. return whereOutput;
  54. }
  55. return "";
  56. }),
  57. };
  58. });
  59. return import("../src/main/editors.js");
  60. }
  61. describe("editors", () => {
  62. it("macOS 应把 VS Code Insiders 识别为可用编辑器", async () => {
  63. setProcessPlatform("darwin");
  64. const { getEditorDefsForCurrentPlatform } = await import("../src/main/editors.js");
  65. expect(getEditorDefsForCurrentPlatform()).toEqual(
  66. expect.arrayContaining([
  67. expect.objectContaining({
  68. id: "vscode-insiders",
  69. name: "VS Code Insiders",
  70. appPath: "/Applications/Visual Studio Code - Insiders.app",
  71. command: "code-insiders",
  72. }),
  73. ]),
  74. );
  75. });
  76. it("macOS 应把 QSpace 和 QSpace Pro 识别为可用的第三方文件管理器", async () => {
  77. setProcessPlatform("darwin");
  78. const { getEditorDefsForCurrentPlatform } = await import("../src/main/editors.js");
  79. expect(getEditorDefsForCurrentPlatform()).toEqual(
  80. expect.arrayContaining([
  81. expect.objectContaining({
  82. id: "qspace",
  83. name: "QSpace",
  84. appPath: "/Applications/QSpace.app",
  85. command: null,
  86. }),
  87. expect.objectContaining({
  88. id: "qspace-pro",
  89. name: "QSpace Pro",
  90. appPath: "/Applications/QSpace Pro.app",
  91. command: null,
  92. }),
  93. ]),
  94. );
  95. });
  96. it("Windows 应把常见 IDE 纳入 workspace 顶部打开菜单候选", async () => {
  97. setProcessPlatform("win32");
  98. const { getEditorDefsForCurrentPlatform } = await import("../src/main/editors.js");
  99. const editorIds = getEditorDefsForCurrentPlatform().map((editor) => editor.id);
  100. expect(editorIds).toEqual(
  101. expect.arrayContaining(["explorer", "vscode", "trae", "idea", "pycharm"]),
  102. );
  103. });
  104. it("Windows requires PATH shims to resolve to a real app exe before showing gui editors", async () => {
  105. const shimPath = "D:\\Microsoft VS Code\\bin\\code";
  106. const { resolveEditorDefAppPath } = await importEditorsWithWindowsCommandMocks(
  107. [shimPath],
  108. `${shimPath}\r\n`,
  109. );
  110. expect(
  111. resolveEditorDefAppPath({
  112. id: "vscode",
  113. name: "VS Code",
  114. appPath: "C:\\missing\\Code.exe",
  115. command: "code",
  116. windowsCommandAppNames: ["Code.exe"],
  117. }),
  118. ).toBeNull();
  119. });
  120. it("Windows derives the real app exe from PATH shims for display and opening", async () => {
  121. const shimPath = "D:\\Microsoft VS Code\\bin\\code";
  122. const appPath = "D:\\Microsoft VS Code\\Code.exe";
  123. const { resolveEditorDefAppPath } = await importEditorsWithWindowsCommandMocks(
  124. [shimPath, appPath],
  125. `${shimPath}\r\n`,
  126. );
  127. expect(
  128. resolveEditorDefAppPath({
  129. id: "vscode",
  130. name: "VS Code",
  131. appPath: "C:\\missing\\Code.exe",
  132. command: "code",
  133. windowsCommandAppNames: ["Code.exe"],
  134. }),
  135. ).toBe(appPath);
  136. });
  137. it("Windows handles missing where.exe without throwing while detecting gui editors", async () => {
  138. const { resolveEditorDefAppPath } = await importEditorsWithWindowsCommandMocks(
  139. [],
  140. "",
  141. Object.assign(new Error("spawn where.exe ENOENT"), { code: "ENOENT" }),
  142. );
  143. expect(() =>
  144. resolveEditorDefAppPath({
  145. id: "vscode",
  146. name: "VS Code",
  147. appPath: "C:\\missing\\Code.exe",
  148. command: "code",
  149. windowsCommandAppNames: ["Code.exe"],
  150. }),
  151. ).not.toThrow();
  152. });
  153. });
  154. describe("file application detection cache", () => {
  155. it.each(["missing", "icon", "error"])(
  156. "retries %s results without restarting and shares pending detection",
  157. async (failure) => {
  158. setProcessPlatform("linux");
  159. const resolveFileApplicationPath = vi.fn();
  160. vi.doMock("../src/main/fileApplications.js", () => ({
  161. getFileApplicationDefs: () => [{ id: "reader", name: "Reader" }],
  162. matchesFileApplication: () => true,
  163. resolveFileApplicationPath,
  164. }));
  165. const { app } = await import("electron");
  166. vi.mocked(app.getFileIcon).mockResolvedValue({ toPNG: () => Buffer.from("icon") } as never);
  167. if (failure === "missing") resolveFileApplicationPath.mockResolvedValueOnce(null);
  168. else if (failure === "error")
  169. resolveFileApplicationPath.mockRejectedValueOnce(new Error("detection failed"));
  170. else {
  171. resolveFileApplicationPath.mockResolvedValueOnce("/usr/bin/reader");
  172. vi.mocked(app.getFileIcon).mockImplementation(async (path) => {
  173. if (path === "/usr/bin/reader") throw new Error("icon unavailable");
  174. return { toPNG: () => Buffer.from("icon") } as never;
  175. });
  176. }
  177. const { getInstalledEditors } = await import("../src/main/editors.js");
  178. if (failure === "error")
  179. await expect(getInstalledEditors("/work/a.pdf")).rejects.toThrow("detection failed");
  180. else
  181. expect(await getInstalledEditors("/work/a.pdf")).not.toEqual(
  182. expect.arrayContaining([expect.objectContaining({ id: "reader" })]),
  183. );
  184. resolveFileApplicationPath.mockResolvedValue("/usr/bin/reader");
  185. vi.mocked(app.getFileIcon).mockResolvedValue({ toPNG: () => Buffer.from("icon") } as never);
  186. const results = await Promise.all([
  187. getInstalledEditors("/work/a.pdf"),
  188. getInstalledEditors("/work/b.pdf"),
  189. ]);
  190. for (const result of results)
  191. expect(result).toEqual(expect.arrayContaining([expect.objectContaining({ id: "reader" })]));
  192. expect(resolveFileApplicationPath).toHaveBeenCalledTimes(2);
  193. await getInstalledEditors("/work/c.pdf");
  194. expect(resolveFileApplicationPath).toHaveBeenCalledTimes(2);
  195. },
  196. );
  197. });