fallback_checks.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. """以真实分发入口验证一次回退、取消收尾和桌面引导。"""
  2. import asyncio
  3. import importlib.util
  4. import json
  5. import os
  6. from pathlib import Path
  7. import shlex
  8. import shutil
  9. import subprocess
  10. import sys
  11. import time
  12. from urllib.parse import unquote, urlparse
  13. ROOT = Path(__file__).parent
  14. # 修复原因:预装 Python 不设 PYTHONUTF8,Windows 上 read_text/write_text 默认用系统代码页(如 936);
  15. # 测试用 UTF-8 读写这些 JSON,路径或提示含中文时会解码错。读写测试交换的文件一律显式用 UTF-8。
  16. CONFIG = json.loads((ROOT / "config.json").read_text(encoding="utf8"))
  17. DOCS = ROOT / "中文 空格"
  18. PLUGINS = json.loads((ROOT / "plugins.json").read_text(encoding="utf8"))
  19. HELPER = Path(PLUGINS["documents"]["path"]) / "scripts/zcode_libreoffice.py"
  20. WINDOWS = sys.platform == "win32"
  21. def quoted(value):
  22. return shlex.quote(str(value))
  23. def fake_soffice(mode):
  24. """Windows 夹具:入口 shim 的配置把调用转给本脚本,路径经环境变量传入。"""
  25. arguments = sys.argv[2:]
  26. if mode == "managed":
  27. if "--version" in arguments:
  28. sys.exit(subprocess.run([os.environ["ZCODE_FALLBACK_ORIGINAL"], *arguments]).returncode)
  29. with open(os.environ["ZCODE_FALLBACK_MANAGED_LOG"], "a", encoding="utf8") as log:
  30. for argument in arguments:
  31. if argument.startswith("-env:UserInstallation="):
  32. log.write(argument + "\n")
  33. if os.environ["ZCODE_FALLBACK_MODE"] == "sleep":
  34. time.sleep(60)
  35. sys.exit(0)
  36. Path(os.environ["ZCODE_FALLBACK_PARTIAL"]).write_text("failed partial output")
  37. sys.exit(78)
  38. actual = os.environ["ZCODE_FALLBACK_SYSTEM"]
  39. if "--version" in arguments:
  40. sys.exit(subprocess.run([actual, *arguments]).returncode)
  41. with open(os.environ["ZCODE_FALLBACK_SYSTEM_LOG"], "a", encoding="utf8") as log:
  42. log.write("run\n")
  43. if Path(os.environ["ZCODE_FALLBACK_PARTIAL"]).exists():
  44. sys.exit(91)
  45. sys.exit(subprocess.run([actual, *arguments]).returncode)
  46. if __name__ == "__main__" and sys.argv[1:2] in (["managed"], ["system"]):
  47. fake_soffice(sys.argv[1])
  48. spec = importlib.util.spec_from_file_location("acceptance_libreoffice", HELPER)
  49. helper = importlib.util.module_from_spec(spec)
  50. sys.modules[spec.name] = helper
  51. spec.loader.exec_module(helper)
  52. def shim_config(mode):
  53. # shim 配置只接受绝对路径;目标是当前解释器,由它运行本脚本的假入口分支,调用方参数接在后面。
  54. return json.dumps({
  55. "schemaVersion": 1, "target": sys.executable,
  56. "args": [str(Path(__file__).resolve()), mode], "env": [],
  57. }, ensure_ascii=False)
  58. async def main():
  59. bin_dir = Path(CONFIG["root"]) / "bin"
  60. # Windows 入口是 shim:exe 不变,改写同名 .shim 配置即可换目标;其他平台替换 sh 脚本。
  61. entry = bin_dir / ("zcode-soffice.shim" if WINDOWS else "zcode-soffice")
  62. original = entry.read_bytes()
  63. backup = ROOT / ("original-soffice-entry.exe" if WINDOWS else "original-soffice-entry")
  64. if WINDOWS:
  65. # 备份是完整入口(shim 副本加原配置);配置写的是绝对路径,放在夹具目录也能运行。
  66. shutil.copyfile(bin_dir / "zcode-soffice.exe", backup)
  67. backup.with_suffix(".shim").write_bytes(original)
  68. else:
  69. backup.write_bytes(original)
  70. backup.chmod(0o755)
  71. managed_log, system_log = ROOT / "managed-failure.log", ROOT / "system-retry.log"
  72. output = DOCS / "Fallback PDF"
  73. output.mkdir(exist_ok=True)
  74. partial = output / "中文 字体验收.pdf"
  75. if WINDOWS:
  76. actual_system = Path(CONFIG["systemApplication"]) / "program/soffice.com"
  77. else:
  78. actual_system = Path(CONFIG["systemApplication"]) / "Contents/MacOS/soffice"
  79. system_dir = ROOT / "system-probe"
  80. system_dir.mkdir(exist_ok=True)
  81. # 系统 shim 只记录次数并委托真实系统应用;不修改官方应用目录。
  82. if WINDOWS:
  83. shutil.copyfile(bin_dir / "zcode-soffice.exe", system_dir / "soffice.exe")
  84. (system_dir / "soffice.shim").write_text(shim_config("system"), encoding="utf-8")
  85. else:
  86. system_entry = system_dir / "soffice"
  87. system_entry.write_text(f'''#!/bin/sh
  88. for arg do
  89. if [ "$arg" = "--version" ]; then exec {quoted(actual_system)} "$@"; fi
  90. done
  91. printf 'run\\n' >> {quoted(system_log)}
  92. if [ -e {quoted(partial)} ]; then exit 91; fi
  93. export SAL_USE_VCLPLUGIN=osx
  94. exec {quoted(actual_system)} "$@"
  95. ''')
  96. system_entry.chmod(0o755)
  97. env = dict(os.environ, PATH=str(system_dir) + os.pathsep + os.environ["PATH"])
  98. if WINDOWS:
  99. env.update({
  100. "ZCODE_FALLBACK_ORIGINAL": str(backup),
  101. "ZCODE_FALLBACK_MANAGED_LOG": str(managed_log),
  102. "ZCODE_FALLBACK_SYSTEM_LOG": str(system_log),
  103. "ZCODE_FALLBACK_PARTIAL": str(partial),
  104. "ZCODE_FALLBACK_SYSTEM": str(actual_system),
  105. })
  106. header = f'''#!/bin/sh
  107. for arg do
  108. if [ "$arg" = "--version" ]; then exec {quoted(backup)} "$@"; fi
  109. done
  110. for arg do
  111. case "$arg" in -env:UserInstallation=*) printf '%s\\n' "$arg" >> {quoted(managed_log)};; esac
  112. done
  113. '''
  114. def install_entry(mode):
  115. if WINDOWS:
  116. env["ZCODE_FALLBACK_MODE"] = mode
  117. entry.write_text(shim_config("managed"), encoding="utf-8")
  118. else:
  119. body = "sleep 60\n" if mode == "sleep" else f"printf 'failed partial output' > {quoted(partial)}\nexit 78\n"
  120. entry.write_text(header + body)
  121. entry.chmod(0o755)
  122. try:
  123. install_entry("fail")
  124. result = await helper.run_libreoffice(
  125. ["--convert-to", "pdf", "--outdir", str(output), str(DOCS / "中文 字体验收.docx")],
  126. environment=env, temporary_outputs=[partial],
  127. )
  128. assert result.source == "system"
  129. assert system_log.read_text().splitlines() == ["run"]
  130. from pypdf import PdfReader
  131. assert "文档转换与中文显示" in PdfReader(partial).pages[0].extract_text()
  132. profile_urls = [line.split("=", 1)[1] for line in managed_log.read_text().splitlines()]
  133. assert all(not Path(unquote(urlparse(url).path).lstrip("/" if WINDOWS else "")).exists() for url in profile_urls)
  134. managed_log.unlink()
  135. system_log.unlink()
  136. install_entry("sleep")
  137. task = asyncio.create_task(helper.run_libreoffice(["--convert-to", "pdf", str(DOCS / "中文 字体验收.docx")], environment=env))
  138. # 等真实调用写出配置参数后取消,避免在子进程尚未启动前制造假通过。
  139. async with asyncio.timeout(30):
  140. while not managed_log.exists():
  141. await asyncio.sleep(0.02)
  142. task.cancel()
  143. try:
  144. await task
  145. raise AssertionError("Cancelled call unexpectedly completed")
  146. except asyncio.CancelledError:
  147. pass
  148. assert not system_log.exists()
  149. cancelled_profiles = [line.split("=", 1)[1] for line in managed_log.read_text().splitlines()]
  150. assert all(not Path(unquote(urlparse(url).path).lstrip("/" if WINDOWS else "")).exists() for url in cancelled_profiles)
  151. finally:
  152. entry.write_bytes(original)
  153. entry.chmod(0o755)
  154. # 用正常发现链隔离系统候选,不删除宿主安装,也不注入候选列表绕过查找。
  155. empty_home = ROOT / "no-tools-home"
  156. empty_home.mkdir(exist_ok=True)
  157. if WINDOWS:
  158. system_root = os.environ["SYSTEMROOT"]
  159. no_tools = dict(os.environ, HOME=str(empty_home), USERPROFILE=str(empty_home),
  160. PATH=os.pathsep.join([str(Path(system_root) / "System32"), system_root]))
  161. # Windows 按 Program Files 发现系统版本;指向空目录即可隔离已安装的系统 LibreOffice。
  162. for name in ("PROGRAMFILES", "PROGRAMFILES(X86)"):
  163. no_tools[name] = str(empty_home)
  164. else:
  165. assert not Path("/Applications/LibreOffice.app").exists()
  166. no_tools = dict(os.environ, HOME=str(empty_home), PATH="/usr/bin:/bin")
  167. try:
  168. await helper.run_libreoffice(["--version"], environment=no_tools)
  169. raise AssertionError("Missing tools unexpectedly succeeded")
  170. except helper.LibreOfficeUnavailable as error:
  171. guidance = str(error)
  172. assert "帮助" in guidance and "预装工具" in guidance
  173. (ROOT / "fallback-results.json").write_text(json.dumps({
  174. "source": result.source, "fallbackActualRuns": 1, "managedFailureCode": 78,
  175. "managedProfilesRemoved": profile_urls, "cancelledProfilesRemoved": cancelled_profiles,
  176. "cancelDidNotRetry": True, "guidance": guidance, "entryRestored": entry.read_bytes() == original,
  177. "realSystemApplication": str(actual_system),
  178. }, ensure_ascii=False, indent=2), encoding="utf8")
  179. if __name__ == "__main__":
  180. asyncio.run(main())