test_runtime_resolution.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. """Keyless runtime-resolution tests; launch coverage lives in test_bundled_runtime.py."""
  2. from __future__ import annotations
  3. import os
  4. import subprocess
  5. import sys
  6. from pathlib import Path
  7. from types import SimpleNamespace
  8. import deepseek_harness_runtime as runtime
  9. import pytest
  10. from deepseek_harness_runtime import (
  11. RUNTIME_MODE_ENV_VAR,
  12. bundled_package_dir,
  13. main,
  14. resolve_bundled_launch_args,
  15. )
  16. def _office_sidecar(executable: Path) -> Path:
  17. office = executable.with_name(f"{executable.name.removesuffix('.exe')}-office")
  18. tag = executable.name.removeprefix("deepseek-harness-sdk-runtime-").removesuffix(".exe")
  19. engine = "wasm" if tag.startswith("linux-") else tag.replace("win-", "win32-").replace("macos-", "darwin-")
  20. for required in ("@deepseek-ai/libreoffice-kit/package.json", f"@deepseek-ai/libreoffice-kit-{engine}/prebuilds.json"):
  21. path = office / "node_modules" / required
  22. path.parent.mkdir(parents=True, exist_ok=True)
  23. path.write_text("{}")
  24. return office
  25. def test_unknown_explicit_mode_fails_loud() -> None:
  26. with pytest.raises(ValueError, match="expected 'exe' or 'node'"):
  27. resolve_bundled_launch_args("bogus")
  28. def test_unknown_env_mode_fails_loud(monkeypatch: pytest.MonkeyPatch) -> None:
  29. monkeypatch.setenv(RUNTIME_MODE_ENV_VAR, "bogus")
  30. with pytest.raises(ValueError, match="expected 'exe' or 'node'"):
  31. resolve_bundled_launch_args()
  32. def test_explicit_mode_wins_over_env_mode(monkeypatch: pytest.MonkeyPatch) -> None:
  33. monkeypatch.setenv(RUNTIME_MODE_ENV_VAR, "bogus")
  34. try:
  35. args = resolve_bundled_launch_args("exe")
  36. except FileNotFoundError:
  37. return # explicit 'exe' was honored; only the artifact is missing
  38. assert args[0].endswith(("-x64", "-arm64"))
  39. def test_runtime_requires_spawn_helper_only_on_macos(
  40. tmp_path: Path, monkeypatch: pytest.MonkeyPatch
  41. ) -> None:
  42. runtime_dir = tmp_path / "runtime"
  43. runtime_dir.mkdir()
  44. linux = runtime_dir / "deepseek-harness-sdk-runtime-linux-x64"
  45. linux.touch()
  46. Path(f"{linux}-rg").touch()
  47. _office_sidecar(linux)
  48. macos = runtime_dir / "deepseek-harness-sdk-runtime-macos-arm64"
  49. macos.touch()
  50. Path(f"{macos}-rg").touch()
  51. monkeypatch.setattr(runtime, "bundled_package_dir", lambda: tmp_path)
  52. monkeypatch.setattr(runtime, "_current_platform_tag", lambda: "macos-arm64")
  53. with pytest.raises(FileNotFoundError, match="node-pty spawn helper"):
  54. runtime.bundled_runtime_path()
  55. monkeypatch.setattr(runtime, "_current_platform_tag", lambda: "linux-x64")
  56. assert runtime.bundled_runtime_path() == linux
  57. def test_windows_runtime_uses_exe_payload_and_exe_sidecar(
  58. tmp_path: Path, monkeypatch: pytest.MonkeyPatch
  59. ) -> None:
  60. runtime_dir = tmp_path / "runtime"
  61. runtime_dir.mkdir()
  62. executable = runtime_dir / "deepseek-harness-sdk-runtime-win-x64.exe"
  63. executable.touch()
  64. (runtime_dir / "deepseek-harness-sdk-runtime-win-x64-rg.exe").touch()
  65. _office_sidecar(executable)
  66. monkeypatch.setattr(runtime, "bundled_package_dir", lambda: tmp_path)
  67. monkeypatch.setattr(runtime, "_current_platform_tag", lambda: "win-x64")
  68. assert runtime.bundled_runtime_path() == executable
  69. def test_current_platform_supports_windows_x64_only(monkeypatch: pytest.MonkeyPatch) -> None:
  70. monkeypatch.setattr(runtime.sys, "platform", "win32")
  71. monkeypatch.setattr(runtime.platform, "machine", lambda: "AMD64")
  72. assert runtime._current_platform_tag() == "win-x64"
  73. monkeypatch.setattr(runtime.platform, "machine", lambda: "ARM64")
  74. with pytest.raises(FileNotFoundError, match="Windows x64"):
  75. runtime._current_platform_tag()
  76. def test_current_platform_supports_macos_x64(monkeypatch: pytest.MonkeyPatch) -> None:
  77. monkeypatch.setattr(runtime.sys, "platform", "darwin")
  78. monkeypatch.setattr(runtime.platform, "machine", lambda: "x86_64")
  79. assert runtime._current_platform_tag() == "macos-x64"
  80. def test_runtime_requires_ripgrep_sidecar(
  81. tmp_path: Path, monkeypatch: pytest.MonkeyPatch
  82. ) -> None:
  83. runtime_dir = tmp_path / "runtime"
  84. runtime_dir.mkdir()
  85. (runtime_dir / "deepseek-harness-sdk-runtime-linux-x64").touch()
  86. monkeypatch.setattr(runtime, "bundled_package_dir", lambda: tmp_path)
  87. monkeypatch.setattr(runtime, "_current_platform_tag", lambda: "linux-x64")
  88. with pytest.raises(FileNotFoundError, match="ripgrep sidecar"):
  89. runtime.bundled_runtime_path()
  90. def test_runtime_requires_complete_office_sidecar(
  91. tmp_path: Path, monkeypatch: pytest.MonkeyPatch
  92. ) -> None:
  93. executable = tmp_path / "runtime" / "deepseek-harness-sdk-runtime-linux-x64"
  94. executable.parent.mkdir()
  95. executable.touch()
  96. Path(f"{executable}-rg").touch()
  97. monkeypatch.setattr(runtime, "bundled_package_dir", lambda: tmp_path)
  98. monkeypatch.setattr(runtime, "_current_platform_tag", lambda: "linux-x64")
  99. with pytest.raises(FileNotFoundError, match="Office sidecar"):
  100. runtime.bundled_runtime_path()
  101. office = _office_sidecar(executable)
  102. assert runtime.bundled_runtime_path() == executable
  103. (office / "node_modules/@deepseek-ai/libreoffice-kit-wasm/prebuilds.json").unlink()
  104. with pytest.raises(FileNotFoundError, match="Office sidecar"):
  105. runtime.bundled_runtime_path()
  106. def test_node_mode_runs_the_deployed_dsh_cli(
  107. tmp_path: Path, monkeypatch: pytest.MonkeyPatch
  108. ) -> None:
  109. bin_js = tmp_path / "runtime" / "node" / "node_modules" / "@deepseek-ai" / "dsh" / "lib" / "bin.js"
  110. bin_js.parent.mkdir(parents=True)
  111. bin_js.touch()
  112. monkeypatch.setattr(runtime, "bundled_package_dir", lambda: tmp_path)
  113. monkeypatch.setattr(runtime.shutil, "which", lambda _name: "/node")
  114. assert resolve_bundled_launch_args("node") == ("/node", str(bin_js))
  115. def test_python_dsh_command_requires_explicit_home(
  116. monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
  117. ) -> None:
  118. monkeypatch.delenv("DSH_HOME", raising=False)
  119. with pytest.raises(SystemExit) as excinfo:
  120. main()
  121. assert excinfo.value.code == 2
  122. assert "explicit DSH_HOME" in capsys.readouterr().err
  123. def test_python_dsh_command_executes_the_bundled_cli(
  124. monkeypatch: pytest.MonkeyPatch
  125. ) -> None:
  126. called: dict[str, object] = {}
  127. monkeypatch.setenv("DSH_HOME", "/explicit/home")
  128. monkeypatch.setattr(runtime, "resolve_bundled_launch_args", lambda: ("/runtime",))
  129. monkeypatch.setattr(runtime, "sys", SimpleNamespace(platform="linux", argv=["dsh", "plugin", "--profile", "sdk", "list"]))
  130. def execvpe(file: str, args: tuple[str, ...], env: dict[str, str]) -> None:
  131. called.update(file=file, args=args, home=env.get("DSH_HOME"))
  132. monkeypatch.setattr(runtime.os, "execvpe", execvpe)
  133. main()
  134. assert called == {
  135. "file": "/runtime",
  136. "args": ("/runtime", "plugin", "--profile", "sdk", "list"),
  137. "home": "/explicit/home",
  138. }
  139. @pytest.mark.parametrize("returncode", [0, 37, 513])
  140. def test_windows_console_waits_and_forwards_runtime_status(monkeypatch: pytest.MonkeyPatch, returncode: int) -> None:
  141. monkeypatch.setenv("DSH_HOME", "/explicit/home")
  142. monkeypatch.setattr(runtime, "sys", SimpleNamespace(platform="win32", argv=["dsh", "plugin", "argument with spaces", "中文"]))
  143. monkeypatch.setattr(runtime, "resolve_bundled_launch_args", lambda: ("runtime.exe",))
  144. called = []
  145. def run(args: tuple[str, ...], **kwargs: object) -> subprocess.CompletedProcess[str]:
  146. called.append((args, kwargs))
  147. return subprocess.CompletedProcess(args, returncode)
  148. def forbidden_exec(*args: object) -> None:
  149. pytest.fail("Windows console must wait instead of entering CRT exec")
  150. monkeypatch.setattr(subprocess, "run", run)
  151. monkeypatch.setattr(runtime.os, "execvpe", forbidden_exec)
  152. with pytest.raises(SystemExit) as result:
  153. main()
  154. assert result.value.code == returncode
  155. assert called == [(("runtime.exe", "plugin", "argument with spaces", "中文"), {"env": os.environ})]
  156. @pytest.mark.parametrize("returncode", [0, 37, pytest.param(513, marks=pytest.mark.skipif(sys.platform != "win32", reason="POSIX truncates process exit codes to eight bits"))])
  157. def test_windows_console_branch_preserves_real_child_io_and_completion(tmp_path: Path, returncode: int) -> None:
  158. child = tmp_path / "child with spaces.py"
  159. sentinel = tmp_path / "finished"
  160. child.write_text(
  161. "import pathlib,sys\n"
  162. "assert sys.argv[1] == 'argument with spaces'\n"
  163. "assert sys.argv[2] == '中文'\n"
  164. "print('stdout-中文', flush=True)\n"
  165. "print('stderr-中文', file=sys.stderr, flush=True)\n"
  166. f"pathlib.Path({str(sentinel)!r}).write_text('done')\n"
  167. f"raise SystemExit({returncode})\n", encoding="utf-8",
  168. )
  169. driver = (
  170. "import deepseek_harness_runtime as runtime; from types import SimpleNamespace; "
  171. f"runtime.sys = SimpleNamespace(platform='win32', argv=['dsh', 'argument with spaces', '中文']); "
  172. f"runtime.resolve_bundled_launch_args = lambda: ({sys.executable!r}, {str(child)!r}); runtime.main()"
  173. )
  174. result = subprocess.run([sys.executable, "-c", driver], capture_output=True, text=True, encoding="utf-8",
  175. env={**os.environ, "DSH_HOME": str(tmp_path), "PYTHONIOENCODING": "utf-8"}, timeout=15)
  176. assert result.returncode == returncode, result.stderr
  177. assert result.stdout == "stdout-中文\n"
  178. assert result.stderr == "stderr-中文\n"
  179. assert sentinel.read_text() == "done"
  180. @pytest.mark.parametrize("target", ["linux-x64", "linux-arm64", "macos-arm64", "macos-x64", "win-x64"])
  181. def test_runtime_requires_its_platform_office_engine(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, target: str) -> None:
  182. extension = ".exe" if target.startswith("win-") else ""
  183. executable = tmp_path / "runtime" / f"deepseek-harness-sdk-runtime-{target}{extension}"
  184. executable.parent.mkdir()
  185. executable.touch()
  186. executable.with_name(f"{executable.stem}-rg{extension}").touch()
  187. if target.startswith("macos-"):
  188. Path(f"{executable}-spawn-helper").touch()
  189. office = _office_sidecar(executable)
  190. monkeypatch.setattr(runtime, "bundled_package_dir", lambda: tmp_path)
  191. monkeypatch.setattr(runtime, "_current_platform_tag", lambda: target)
  192. assert runtime.bundled_runtime_path() == executable
  193. engine = next(office.glob("node_modules/@deepseek-ai/libreoffice-kit-*/prebuilds.json"))
  194. engine.unlink()
  195. foreign = office / "node_modules/@deepseek-ai" / ("libreoffice-kit-darwin-arm64" if target.startswith("linux-") else "libreoffice-kit-wasm") / "prebuilds.json"
  196. foreign.parent.mkdir(parents=True, exist_ok=True)
  197. foreign.write_text("{}")
  198. with pytest.raises(FileNotFoundError, match="Office sidecar"):
  199. runtime.bundled_runtime_path()