libreoffice-entry.test.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import { execFile } from "node:child_process";
  2. import { promisify } from "node:util";
  3. import { mkdtemp, mkdir, writeFile, readFile, readdir, rm } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { fileURLToPath } from "node:url";
  7. import { describe, expect, it } from "vitest";
  8. const exec = promisify(execFile);
  9. const helper = fileURLToPath(new URL("../../documents-plugin/scripts", import.meta.url));
  10. const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
  11. async function fixture(mode: string, systemVersion = "printf 'LibreOfficeDev 7.6.0.0\\n'") {
  12. const root = await mkdtemp(join(tmpdir(), "zcode-office-entry-"));
  13. const bin = join(root, "中文 空格");
  14. await mkdir(bin);
  15. const system = join(root, "system-office");
  16. const systemCalls = join(root, "system-calls");
  17. await writeFile(system, `#!/bin/sh\nprintf '%s\\n' "$*" >> ${quote(systemCalls)}\n${systemVersion}\n`, { mode: 0o755 });
  18. if (mode !== "missing") {
  19. const entry = join(bin, "zcode-soffice");
  20. const action = mode === "vanish" ? '/bin/rm -- "$0"; exit 0' : mode === "failure" ? 'exit 7' : 'printf "managed-output\\n"';
  21. await writeFile(entry, `#!/bin/sh\ncase "$*" in *--version*) printf 'LibreOffice 26.8.1\\n'; ${mode === "vanish" ? action : 'exit 0'};; esac\n${action}\n`, { mode: 0o755 });
  22. }
  23. const driver = join(root, "invoke.py");
  24. await writeFile(driver, `import asyncio, dataclasses, json, sys\nfrom pathlib import Path\nsys.path.insert(0, ${JSON.stringify(helper)})\nfrom zcode_libreoffice import run_libreoffice\nasync def main():\n try:\n recalculate = Path(sys.argv[4]) if len(sys.argv) > 4 else None\n value = await run_libreoffice(json.loads(sys.argv[1]), environment=json.loads(sys.argv[2]), candidate_paths=[Path(p) for p in json.loads(sys.argv[3])], timeout=2, recalculate=recalculate)\n print(json.dumps(dataclasses.asdict(value)))\n except Exception as error:\n print(json.dumps({'error':str(error), 'type':type(error).__name__}))\nasyncio.run(main())\n`);
  25. const run = async (args: string[], available = true, systemAvailable = true, recalculate?: string) => {
  26. const env = { PATH: bin, TMPDIR: root, ...(available ? { ZCODE_PREINSTALLED_TOOLS_AVAILABLE: "1" } : {}) };
  27. // -B:导入插件源码目录下的统一入口时不写 __pycache__。
  28. const { stdout } = await exec("python3", ["-B", driver, JSON.stringify(args), JSON.stringify(env), JSON.stringify(systemAvailable ? [system] : []), ...(recalculate ? [recalculate] : [])]);
  29. return JSON.parse(stdout);
  30. };
  31. return { root, bin, run, systemCalls };
  32. }
  33. describe.skipIf(process.platform === "win32")("LibreOffice PATH entry boundary", () => {
  34. it.each(["missing", "failure", "vanish"])("uses system once when managed entry is %s", async (mode) => {
  35. const f = await fixture(mode);
  36. try {
  37. const result = await f.run(["--convert-to", "pdf"]);
  38. expect(result.source).toBe("system");
  39. expect(result.stderr).toContain(mode === "missing" ? "未就绪或已关闭" : "运行失败");
  40. expect(result.notice).toMatch(new RegExp(`^Using system LibreOffice 7\\.6\\.0\\.0\\. 受管版本未使用:${mode === "missing" ? "未就绪或已关闭" : "运行失败"}`));
  41. expect((await readFile(f.systemCalls, "utf8")).trim().split("\n")).toHaveLength(2);
  42. expect((await readdir(f.root)).filter((name) => name.startsWith("zcode-libreoffice-"))).toEqual([]);
  43. } finally { await rm(f.root, { recursive: true, force: true }); }
  44. });
  45. it("selects guidance from availability without reading an installation record", async () => {
  46. const f = await fixture("missing");
  47. try {
  48. expect((await f.run(["--version"], true, false)).error).toContain("帮助 → 预装工具");
  49. const standalone = await f.run(["--version"], false, false);
  50. expect(standalone.error).not.toContain("帮助 → 预装工具");
  51. expect(standalone.error).toContain("env_setup/setup.md");
  52. } finally { await rm(f.root, { recursive: true, force: true }); }
  53. });
  54. it("rejects caller profile overrides without starting the system program", async () => {
  55. const f = await fixture("failure");
  56. try {
  57. expect((await f.run(["-env:UserInstallation=file:///tmp/override"])).error).toContain("调用参数不能覆盖");
  58. await expect(readFile(f.systemCalls)).rejects.toHaveProperty("code", "ENOENT");
  59. } finally { await rm(f.root, { recursive: true, force: true }); }
  60. });
  61. it.each([
  62. ["exits non-zero", "printf 'missing libfoo.so\\n' >&2; exit 127", "missing libfoo.so"],
  63. ["times out", "/bin/sleep 5", "timed out"],
  64. ])("reports a system program that %s instead of installation guidance", async (_name, systemVersion, cause) => {
  65. const f = await fixture("missing", systemVersion);
  66. try {
  67. const result = await f.run(["--version"]);
  68. expect(result.type).toBe("LibreOfficeInvocationError");
  69. expect(result.error).toContain("系统 LibreOffice 无法运行");
  70. expect(result.error).toContain(cause);
  71. expect(result.error).toContain("帮助 → 预装工具");
  72. expect(result.error).not.toContain("LibreOffice not found");
  73. } finally { await rm(f.root, { recursive: true, force: true }); }
  74. });
  75. it("reports a missing recalculation input without starting any program", async () => {
  76. const f = await fixture("ready");
  77. try {
  78. const result = await f.run([], true, true, join(f.root, "missing.xlsx"));
  79. expect(result.type).toBe("LibreOfficeInvocationError");
  80. expect(result.error).toContain("重算输入不是文件");
  81. expect(result.error).not.toContain("受管版本未使用");
  82. expect(result.error).not.toContain("setup.md");
  83. await expect(readFile(f.systemCalls)).rejects.toHaveProperty("code", "ENOENT");
  84. } finally { await rm(f.root, { recursive: true, force: true }); }
  85. });
  86. it("does not rerun the system program after cancellation", async () => {
  87. const f = await fixture("ready");
  88. try {
  89. const entry = join(f.bin, "zcode-soffice");
  90. const driver = join(f.root, "cancel.py");
  91. await writeFile(entry, `#!${process.execPath}\nif(process.argv.includes('--version'))console.log('LibreOffice 26.8.1');else {process.stdout.write('started');setInterval(()=>{},1000)}\n`, { mode: 0o755 });
  92. await writeFile(driver, `import asyncio, sys\nsys.path.insert(0, ${JSON.stringify(helper)})\nfrom zcode_libreoffice import run_libreoffice\nfrom pathlib import Path\nasync def main():\n task=asyncio.create_task(run_libreoffice(['--convert-to','pdf'], environment={'PATH':${JSON.stringify(f.bin)},'TMPDIR':${JSON.stringify(f.root)}}, candidate_paths=[Path(${JSON.stringify(join(f.root, 'system-office'))})]))\n await asyncio.sleep(.2)\n task.cancel()\n try: await task\n except asyncio.CancelledError: print('cancelled')\nasyncio.run(main())\n`);
  93. const result = await exec("python3", ["-B", driver]);
  94. expect(result.stdout.trim()).toBe("cancelled");
  95. await expect(readFile(f.systemCalls)).rejects.toHaveProperty("code", "ENOENT");
  96. expect((await readdir(f.root)).filter((name) => name.startsWith("zcode-libreoffice-"))).toEqual([]);
  97. } finally { await rm(f.root, { recursive: true, force: true }); }
  98. });
  99. });