test_runtime_resolution.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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 test_unknown_explicit_mode_fails_loud() -> None:
  17. with pytest.raises(ValueError, match="expected 'exe' or 'node'"):
  18. resolve_bundled_launch_args("bogus")
  19. def test_unknown_env_mode_fails_loud(monkeypatch: pytest.MonkeyPatch) -> None:
  20. monkeypatch.setenv(RUNTIME_MODE_ENV_VAR, "bogus")
  21. with pytest.raises(ValueError, match="expected 'exe' or 'node'"):
  22. resolve_bundled_launch_args()
  23. def test_explicit_mode_wins_over_env_mode(monkeypatch: pytest.MonkeyPatch) -> None:
  24. monkeypatch.setenv(RUNTIME_MODE_ENV_VAR, "bogus")
  25. try:
  26. args = resolve_bundled_launch_args("exe")
  27. except FileNotFoundError:
  28. return # explicit 'exe' was honored; only the artifact is missing
  29. assert args[0].endswith(("-x64", "-arm64"))
  30. def test_runtime_requires_spawn_helper_only_on_macos(
  31. tmp_path: Path, monkeypatch: pytest.MonkeyPatch
  32. ) -> None:
  33. runtime_dir = tmp_path / "runtime"
  34. runtime_dir.mkdir()
  35. linux = runtime_dir / "deepseek-harness-sdk-runtime-linux-x64"
  36. linux.touch()
  37. Path(f"{linux}-rg").touch()
  38. macos = runtime_dir / "deepseek-harness-sdk-runtime-macos-arm64"
  39. macos.touch()
  40. Path(f"{macos}-rg").touch()
  41. monkeypatch.setattr(runtime, "bundled_package_dir", lambda: tmp_path)
  42. monkeypatch.setattr(runtime, "_current_platform_tag", lambda: "macos-arm64")
  43. with pytest.raises(FileNotFoundError, match="node-pty spawn helper"):
  44. runtime.bundled_runtime_path()
  45. monkeypatch.setattr(runtime, "_current_platform_tag", lambda: "linux-x64")
  46. assert runtime.bundled_runtime_path() == linux
  47. def test_windows_runtime_uses_exe_payload_and_exe_sidecar(
  48. tmp_path: Path, monkeypatch: pytest.MonkeyPatch
  49. ) -> None:
  50. runtime_dir = tmp_path / "runtime"
  51. runtime_dir.mkdir()
  52. executable = runtime_dir / "deepseek-harness-sdk-runtime-win-x64.exe"
  53. executable.touch()
  54. (runtime_dir / "deepseek-harness-sdk-runtime-win-x64-rg.exe").touch()
  55. monkeypatch.setattr(runtime, "bundled_package_dir", lambda: tmp_path)
  56. monkeypatch.setattr(runtime, "_current_platform_tag", lambda: "win-x64")
  57. assert runtime.bundled_runtime_path() == executable
  58. def test_current_platform_supports_windows_x64_only(monkeypatch: pytest.MonkeyPatch) -> None:
  59. monkeypatch.setattr(runtime.sys, "platform", "win32")
  60. monkeypatch.setattr(runtime.platform, "machine", lambda: "AMD64")
  61. assert runtime._current_platform_tag() == "win-x64"
  62. monkeypatch.setattr(runtime.platform, "machine", lambda: "ARM64")
  63. with pytest.raises(FileNotFoundError, match="Windows x64"):
  64. runtime._current_platform_tag()
  65. def test_current_platform_supports_macos_x64(monkeypatch: pytest.MonkeyPatch) -> None:
  66. monkeypatch.setattr(runtime.sys, "platform", "darwin")
  67. monkeypatch.setattr(runtime.platform, "machine", lambda: "x86_64")
  68. assert runtime._current_platform_tag() == "macos-x64"
  69. def test_runtime_requires_ripgrep_sidecar(
  70. tmp_path: Path, monkeypatch: pytest.MonkeyPatch
  71. ) -> None:
  72. runtime_dir = tmp_path / "runtime"
  73. runtime_dir.mkdir()
  74. (runtime_dir / "deepseek-harness-sdk-runtime-linux-x64").touch()
  75. monkeypatch.setattr(runtime, "bundled_package_dir", lambda: tmp_path)
  76. monkeypatch.setattr(runtime, "_current_platform_tag", lambda: "linux-x64")
  77. with pytest.raises(FileNotFoundError, match="ripgrep sidecar"):
  78. runtime.bundled_runtime_path()
  79. def test_node_mode_runs_the_deployed_dsh_cli(
  80. tmp_path: Path, monkeypatch: pytest.MonkeyPatch
  81. ) -> None:
  82. bin_js = tmp_path / "runtime" / "node" / "node_modules" / "@deepseek-ai" / "dsh" / "lib" / "bin.js"
  83. bin_js.parent.mkdir(parents=True)
  84. bin_js.touch()
  85. monkeypatch.setattr(runtime, "bundled_package_dir", lambda: tmp_path)
  86. monkeypatch.setattr(runtime.shutil, "which", lambda _name: "/node")
  87. assert resolve_bundled_launch_args("node") == ("/node", str(bin_js))
  88. def test_python_dsh_command_requires_explicit_home(
  89. monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
  90. ) -> None:
  91. monkeypatch.delenv("DSH_HOME", raising=False)
  92. with pytest.raises(SystemExit) as excinfo:
  93. main()
  94. assert excinfo.value.code == 2
  95. assert "explicit DSH_HOME" in capsys.readouterr().err
  96. def test_python_dsh_command_executes_the_bundled_cli(
  97. monkeypatch: pytest.MonkeyPatch
  98. ) -> None:
  99. called: dict[str, object] = {}
  100. monkeypatch.setenv("DSH_HOME", "/explicit/home")
  101. monkeypatch.setattr(runtime, "resolve_bundled_launch_args", lambda: ("/runtime",))
  102. monkeypatch.setattr(runtime, "sys", SimpleNamespace(platform="linux", argv=["dsh", "plugin", "--profile", "sdk", "list"]))
  103. def execvpe(file: str, args: tuple[str, ...], env: dict[str, str]) -> None:
  104. called.update(file=file, args=args, home=env.get("DSH_HOME"))
  105. monkeypatch.setattr(runtime.os, "execvpe", execvpe)
  106. main()
  107. assert called == {
  108. "file": "/runtime",
  109. "args": ("/runtime", "plugin", "--profile", "sdk", "list"),
  110. "home": "/explicit/home",
  111. }
  112. @pytest.mark.parametrize("returncode", [0, 37, 513])
  113. def test_windows_console_waits_and_forwards_runtime_status(monkeypatch: pytest.MonkeyPatch, returncode: int) -> None:
  114. monkeypatch.setenv("DSH_HOME", "/explicit/home")
  115. monkeypatch.setattr(runtime, "sys", SimpleNamespace(platform="win32", argv=["dsh", "plugin", "argument with spaces", "中文"]))
  116. monkeypatch.setattr(runtime, "resolve_bundled_launch_args", lambda: ("runtime.exe",))
  117. called = []
  118. def run(args: tuple[str, ...], **kwargs: object) -> subprocess.CompletedProcess[str]:
  119. called.append((args, kwargs))
  120. return subprocess.CompletedProcess(args, returncode)
  121. def forbidden_exec(*args: object) -> None:
  122. pytest.fail("Windows console must wait instead of entering CRT exec")
  123. monkeypatch.setattr(subprocess, "run", run)
  124. monkeypatch.setattr(runtime.os, "execvpe", forbidden_exec)
  125. with pytest.raises(SystemExit) as result:
  126. main()
  127. assert result.value.code == returncode
  128. assert called == [(("runtime.exe", "plugin", "argument with spaces", "中文"), {"env": os.environ})]
  129. @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"))])
  130. def test_windows_console_branch_preserves_real_child_io_and_completion(tmp_path: Path, returncode: int) -> None:
  131. child = tmp_path / "child with spaces.py"
  132. sentinel = tmp_path / "finished"
  133. child.write_text(
  134. "import pathlib,sys\n"
  135. "assert sys.argv[1] == 'argument with spaces'\n"
  136. "assert sys.argv[2] == '中文'\n"
  137. "print('stdout-中文', flush=True)\n"
  138. "print('stderr-中文', file=sys.stderr, flush=True)\n"
  139. f"pathlib.Path({str(sentinel)!r}).write_text('done')\n"
  140. f"raise SystemExit({returncode})\n", encoding="utf-8",
  141. )
  142. driver = (
  143. "import deepseek_harness_runtime as runtime; from types import SimpleNamespace; "
  144. f"runtime.sys = SimpleNamespace(platform='win32', argv=['dsh', 'argument with spaces', '中文']); "
  145. f"runtime.resolve_bundled_launch_args = lambda: ({sys.executable!r}, {str(child)!r}); runtime.main()"
  146. )
  147. result = subprocess.run([sys.executable, "-c", driver], capture_output=True, text=True, encoding="utf-8",
  148. env={**os.environ, "DSH_HOME": str(tmp_path), "PYTHONIOENCODING": "utf-8"}, timeout=15)
  149. assert result.returncode == returncode, result.stderr
  150. assert result.stdout == "stdout-中文\n"
  151. assert result.stderr == "stderr-中文\n"
  152. assert sentinel.read_text() == "done"