document-python-entry.test.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. import { execFile } from "node:child_process";
  2. import { promisify } from "node:util";
  3. import { mkdtemp, mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { delimiter, join } from "node:path";
  6. import { fileURLToPath } from "node:url";
  7. import { describe, expect, it } from "vitest";
  8. const exec = promisify(execFile);
  9. const packages = fileURLToPath(new URL("../..", import.meta.url));
  10. const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
  11. const plugins = [
  12. { name: "documents", skill: "docx", variable: "DOCX_SKILL_DIR" },
  13. { name: "pdf", skill: "pdf", variable: "PDF_SKILL_DIR" },
  14. { name: "presentations", skill: "pptx", variable: "PPTX_SKILL_DIR" },
  15. { name: "spreadsheets", skill: "xlsx", variable: "XLSX_SKILL_DIR" },
  16. ];
  17. const shellEntries = plugins
  18. .filter((plugin) => plugin.name !== "presentations")
  19. .flatMap((plugin) =>
  20. [
  21. "env_setup/env_check.sh",
  22. "env_setup/setup_mac_linux.sh",
  23. plugin.name === "pdf" ? "scripts/setup.sh" : "setup.sh",
  24. ].map((entry) => `${plugin.name}-plugin/skills/${plugin.skill}/${entry}`),
  25. );
  26. async function fixture() {
  27. const root = await mkdtemp(join(tmpdir(), "document-python-entry-"));
  28. const bin = join(root, "中文 空格");
  29. const calls = join(root, "calls");
  30. await mkdir(bin);
  31. const interpreter = (source: string) =>
  32. `#!/bin/sh\nprintf '%s|%s\\n' ${quote(source)} "$*" >> ${quote(calls)}\nprintf 'Python 3.12.0\\n'\nexit "\${FAKE_PYTHON_EXIT:-0}"\n`;
  33. await writeFile(join(bin, "python3"), interpreter("system"), { mode: 0o755 });
  34. const installEntry = () =>
  35. writeFile(join(bin, "zcode-python"), interpreter("managed"), { mode: 0o755 });
  36. const env = { ...process.env, PATH: [bin, "/usr/bin", "/bin"].join(delimiter) };
  37. return { root, bin, calls, env, installEntry };
  38. }
  39. describe.skipIf(process.platform === "win32")("document plugin Python entry selection", () => {
  40. it.each(shellEntries)(
  41. "%s stops before downloads when desktop Python is missing",
  42. async (entry) => {
  43. const root = await mkdtemp(join(tmpdir(), "document-python-missing-"));
  44. const bin = join(root, "bin");
  45. const calls = join(root, "unexpected-calls");
  46. await mkdir(bin);
  47. // PATH 只含检测夹具,不修改或卸载宿主 Python;副作用命令只记录,绝不安装。
  48. for (const command of ["curl", "wget", "npm", "brew", "apt", "dnf", "sudo", "mkdir"])
  49. await writeFile(
  50. join(bin, command),
  51. `#!/bin/sh\nprintf '%s\\n' ${quote(command)} >> ${quote(calls)}\nexit 90\n`,
  52. { mode: 0o755 },
  53. );
  54. await writeFile(join(bin, "uname"), '#!/bin/sh\nprintf "Darwin\\n"\n', { mode: 0o755 });
  55. await symlink("/usr/bin/dirname", join(bin, "dirname"));
  56. try {
  57. await expect(
  58. exec("/bin/bash", [join(packages, entry)], {
  59. env: { PATH: bin, HOME: root, ZCODE_PREINSTALLED_TOOLS_AVAILABLE: "1" },
  60. }),
  61. ).rejects.toMatchObject({
  62. code: 1,
  63. stdout: expect.stringContaining("预装版本未就绪或已关闭,请在 帮助 → 预装工具 中查看"),
  64. });
  65. await expect(readFile(calls, "utf8")).rejects.toHaveProperty("code", "ENOENT");
  66. } finally {
  67. await rm(root, { recursive: true, force: true });
  68. }
  69. },
  70. );
  71. it.each(shellEntries)(
  72. "%s retains unmanaged guidance without desktop availability",
  73. async (entry) => {
  74. const root = await mkdtemp(join(tmpdir(), "document-python-unmanaged-"));
  75. const bin = join(root, "bin");
  76. await mkdir(bin);
  77. await writeFile(join(bin, "uname"), '#!/bin/sh\nprintf "Darwin\\n"\n', { mode: 0o755 });
  78. await symlink("/usr/bin/dirname", join(bin, "dirname"));
  79. try {
  80. const result = await exec("/bin/bash", [join(packages, entry)], {
  81. env: { PATH: bin, HOME: root },
  82. }).catch((error: { stdout: string; stderr: string }) => error);
  83. expect(result.stdout).not.toContain("预装版本未就绪或已关闭");
  84. expect(result.stdout).toContain(
  85. entry.endsWith("env_check.sh") ? "python3" : "brew install python3",
  86. );
  87. } finally {
  88. await rm(root, { recursive: true, force: true });
  89. }
  90. },
  91. );
  92. it.each(plugins.filter((plugin) => plugin.name !== "presentations"))(
  93. "$name sourced preflight returns to the caller and accepts system Python after manual installation",
  94. async (plugin) => {
  95. const f = await fixture();
  96. const check = join(
  97. packages,
  98. `${plugin.name}-plugin/skills/${plugin.skill}/env_setup/env_check.sh`,
  99. );
  100. const env = { PATH: f.bin, HOME: f.root, ZCODE_PREINSTALLED_TOOLS_AVAILABLE: "1" };
  101. try {
  102. const interpreter = await readFile(join(f.bin, "python3"), "utf8");
  103. await rm(join(f.bin, "python3"));
  104. await symlink("/usr/bin/dirname", join(f.bin, "dirname"));
  105. await writeFile(join(f.bin, "uname"), '#!/bin/sh\nprintf "Darwin\\n"\n', { mode: 0o755 });
  106. await writeFile(join(f.bin, "node"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
  107. const missing = await exec(
  108. "/bin/bash",
  109. ["-c", `source ${quote(check)}; printf 'CALLER_CONTINUES=%s\\n' "$?"`],
  110. { env },
  111. );
  112. expect(missing.stdout).toContain("预装版本未就绪或已关闭");
  113. expect(missing.stdout).toContain("CALLER_CONTINUES=1");
  114. // 模拟用户按手动步骤安装;桌面可用标记仍保留,不能再次阻塞或要求环境绕过。
  115. await writeFile(join(f.bin, "python3"), interpreter, { mode: 0o755 });
  116. await exec("/bin/bash", [check, "--quiet"], { env });
  117. expect(
  118. (await readFile(f.calls, "utf8"))
  119. .trim()
  120. .split("\n")
  121. .every((line) => line.startsWith("system|")),
  122. ).toBe(true);
  123. } finally {
  124. await rm(f.root, { recursive: true, force: true });
  125. }
  126. },
  127. );
  128. it.each(plugins)(
  129. "$name documented launcher sees an entry added between commands",
  130. async (plugin) => {
  131. const f = await fixture();
  132. try {
  133. const skill = join(packages, `${plugin.name}-plugin/skills/${plugin.skill}`);
  134. const document = await readFile(join(skill, "SKILL.md"), "utf8");
  135. const command = /`([^`\n]*zcode_libreoffice\.py[^`\n]*\bcheck)`/.exec(document)?.[1];
  136. expect(command).toBeTruthy();
  137. const run = (extra: Record<string, string> = {}) =>
  138. exec("/bin/bash", ["--noprofile", "--norc", "-c", command!], {
  139. env: { ...f.env, [plugin.variable]: skill, ...extra },
  140. });
  141. await run();
  142. expect((await readFile(f.calls, "utf8")).trim().split("\n")).toHaveLength(1);
  143. expect(await readFile(f.calls, "utf8")).toMatch(/^system\|/);
  144. await f.installEntry();
  145. await run();
  146. expect((await readFile(f.calls, "utf8")).trim().split("\n")[1]).toMatch(/^managed\|/);
  147. await expect(run({ FAKE_PYTHON_EXIT: "9" })).rejects.toHaveProperty("code", 9);
  148. expect((await readFile(f.calls, "utf8")).trim().split("\n").slice(2)).toEqual([
  149. expect.stringMatching(/^managed\|/),
  150. ]);
  151. } finally {
  152. await rm(f.root, { recursive: true, force: true });
  153. }
  154. },
  155. );
  156. it.each(plugins.filter((plugin) => plugin.name !== "presentations"))(
  157. "$name env_check selects once and never falls back after a managed failure",
  158. async (plugin) => {
  159. const f = await fixture();
  160. try {
  161. await writeFile(join(f.bin, "node"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
  162. await writeFile(join(f.bin, "fc-list"), "#!/bin/sh\nprintf 'noto\\n'\n", { mode: 0o755 });
  163. const check = join(
  164. packages,
  165. `${plugin.name}-plugin/skills/${plugin.skill}/env_setup/env_check.sh`,
  166. );
  167. const run = (extra: Record<string, string> = {}) =>
  168. exec("/bin/bash", [check, "--quiet"], { env: { ...f.env, ...extra } });
  169. await run();
  170. const system = (await readFile(f.calls, "utf8")).trim().split("\n");
  171. expect(system.length).toBeGreaterThan(1);
  172. expect(system.every((line) => line.startsWith("system|"))).toBe(true);
  173. await writeFile(f.calls, "");
  174. await f.installEntry();
  175. await run();
  176. const managed = (await readFile(f.calls, "utf8")).trim().split("\n");
  177. expect(managed.length).toBe(system.length);
  178. expect(managed.every((line) => line.startsWith("managed|"))).toBe(true);
  179. await writeFile(f.calls, "");
  180. await expect(run({ FAKE_PYTHON_EXIT: "9" })).rejects.toHaveProperty("code", 1);
  181. expect(
  182. (await readFile(f.calls, "utf8"))
  183. .trim()
  184. .split("\n")
  185. .every((line) => line.startsWith("managed|")),
  186. ).toBe(true);
  187. } finally {
  188. await rm(f.root, { recursive: true, force: true });
  189. }
  190. },
  191. );
  192. });