fileApplicationOpening.test.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. import { EventEmitter } from "node:events";
  2. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  3. const { accessMock, execFileMock, spawnMock, statMock } = vi.hoisted(() => ({
  4. accessMock: vi.fn(),
  5. execFileMock: vi.fn(),
  6. spawnMock: vi.fn(),
  7. statMock: vi.fn(),
  8. }));
  9. vi.mock("node:fs/promises", () => ({ access: accessMock, readdir: vi.fn(), stat: statMock }));
  10. vi.mock("node:child_process", () => ({ execFile: execFileMock, spawn: spawnMock }));
  11. vi.mock("electron", () => ({ shell: { openPath: vi.fn(), showItemInFolder: vi.fn() } }));
  12. vi.mock("@zcode/server/remote/wsl-detect.js", () => ({ listWSLDistros: vi.fn() }));
  13. vi.mock("../src/main/logger.js", () => ({ logger: { warn: vi.fn() } }));
  14. vi.mock("../src/main/editors.js", async () => {
  15. const { getFileApplicationDefs } = await import("../src/main/fileApplications.js");
  16. return {
  17. getEditorDefsForCurrentPlatform: getFileApplicationDefs,
  18. resolveEditorDefAppPath: vi.fn(),
  19. };
  20. });
  21. import { openInEditor } from "../src/main/openInEditor.js";
  22. const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform")!;
  23. beforeEach(() => {
  24. accessMock.mockResolvedValue(undefined);
  25. statMock.mockResolvedValue({ isFile: () => true });
  26. spawnMock.mockImplementation(() => {
  27. const child = Object.assign(new EventEmitter(), { unref: vi.fn() });
  28. queueMicrotask(() => child.emit("spawn"));
  29. return child;
  30. });
  31. execFileMock.mockImplementation(
  32. (_file: string, _args: string[], callback: (error: Error | null) => void) => callback(null),
  33. );
  34. });
  35. afterEach(() => {
  36. Object.defineProperty(process, "platform", platformDescriptor);
  37. vi.resetAllMocks();
  38. });
  39. describe("file application opening", () => {
  40. it.each([
  41. [
  42. "darwin",
  43. "preview",
  44. "/work/报告 文件.PDF",
  45. "open",
  46. ["-a", "/System/Applications/Preview.app", "/work/报告 文件.PDF"],
  47. ],
  48. [
  49. "linux",
  50. "libreoffice-impress",
  51. "/work/演示 文稿.pptx",
  52. "/usr/bin/libreoffice",
  53. ["--impress", "/work/演示 文稿.pptx"],
  54. ],
  55. ])("%s 参数数组保留文件路径", async (platform, id, path, command, args) => {
  56. Object.defineProperty(process, "platform", { value: platform });
  57. expect(await openInEditor(id, path, { pathKind: "file" })).toEqual({ success: true });
  58. if (platform === "darwin") {
  59. expect(execFileMock).toHaveBeenCalledExactlyOnceWith(command, args, expect.any(Function));
  60. } else {
  61. expect(spawnMock).toHaveBeenCalledExactlyOnceWith(command, args, {
  62. detached: true,
  63. stdio: "ignore",
  64. windowsHide: false,
  65. });
  66. expect(execFileMock).not.toHaveBeenCalled();
  67. expect(spawnMock.mock.results[0]?.value.unref).toHaveBeenCalledOnce();
  68. }
  69. });
  70. it("Windows GUI 启动后立即脱离,保留带空格的绝对路径", async () => {
  71. Object.defineProperty(process, "platform", { value: "win32" });
  72. const path = "C:\\work\\报告 文件.docx";
  73. expect(await openInEditor("word", path, { pathKind: "file" })).toEqual({ success: true });
  74. expect(spawnMock).toHaveBeenCalledWith(expect.stringMatching(/WINWORD\.EXE$/iu), [path], {
  75. detached: true,
  76. stdio: "ignore",
  77. windowsHide: false,
  78. });
  79. expect(spawnMock.mock.results[0]?.value.unref).toHaveBeenCalledOnce();
  80. expect(execFileMock).not.toHaveBeenCalled();
  81. });
  82. it("拒绝远端路径、不匹配类型和目录", async () => {
  83. Object.defineProperty(process, "platform", { value: "darwin" });
  84. for (const [path, options] of [
  85. ["/work/a.docx", { pathKind: "file" }],
  86. ["/work/a.pdf", { pathKind: "directory" }],
  87. ["/work/a.pdf", { remoteTarget: { kind: "ssh", host: "example.com", user: "dev" } }],
  88. ] as const) {
  89. expect((await openInEditor("preview", path, options)).success).toBe(false);
  90. }
  91. expect(execFileMock).not.toHaveBeenCalled();
  92. });
  93. it("卸载后不尝试启动应用", async () => {
  94. Object.defineProperty(process, "platform", { value: "darwin" });
  95. accessMock.mockRejectedValue(new Error("ENOENT"));
  96. expect((await openInEditor("preview", "/work/a.pdf")).success).toBe(false);
  97. expect(execFileMock).not.toHaveBeenCalled();
  98. });
  99. });
  100. it("不信任 renderer 的文件类型,也不接受相对路径或选项", async () => {
  101. Object.defineProperty(process, "platform", { value: "linux" });
  102. for (const path of ["--convert-to=x.docx", "report.docx"]) {
  103. expect((await openInEditor("libreoffice-writer", path, { pathKind: "file" })).success).toBe(
  104. false,
  105. );
  106. }
  107. statMock.mockResolvedValue({ isFile: () => false });
  108. expect(
  109. (await openInEditor("libreoffice-writer", "/work/directory.docx", { pathKind: "file" }))
  110. .success,
  111. ).toBe(false);
  112. statMock.mockRejectedValue(new Error("ENOENT"));
  113. expect((await openInEditor("libreoffice-writer", "/work/missing.docx")).success).toBe(false);
  114. expect(spawnMock).not.toHaveBeenCalled();
  115. });
  116. it("启动失败返回错误;spawn 成功不等待应用退出", async () => {
  117. Object.defineProperty(process, "platform", { value: "linux" });
  118. const child = Object.assign(new EventEmitter(), { unref: vi.fn() });
  119. spawnMock.mockImplementation(() => {
  120. queueMicrotask(() => child.emit("error", new Error("EACCES")));
  121. return child;
  122. });
  123. expect(await openInEditor("libreoffice-impress", "/work/slides.pptx")).toEqual({
  124. success: false,
  125. error: "EACCES",
  126. });
  127. expect(child.unref).not.toHaveBeenCalled();
  128. });