test_process_manager.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from __future__ import annotations
  2. import subprocess
  3. import sys
  4. from pathlib import Path
  5. from core import process_manager
  6. def test_process_manager_stops_pid_file_process(tmp_path, monkeypatch) -> None:
  7. monkeypatch.setattr(process_manager, "PID_DIR", tmp_path)
  8. proc = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
  9. pid_file = tmp_path / "zhuce6-worker.pid"
  10. pid_file.write_text(str(proc.pid), encoding="utf-8")
  11. try:
  12. assert process_manager.read_pid("worker") == proc.pid
  13. assert process_manager.is_running(proc.pid) is True
  14. assert process_manager.stop_process("worker", timeout=1.0) is True
  15. proc.wait(timeout=5)
  16. assert not pid_file.exists()
  17. finally:
  18. if proc.poll() is None:
  19. proc.kill()
  20. proc.wait(timeout=5)
  21. def test_process_manager_status_all_reports_pid_files(tmp_path, monkeypatch) -> None:
  22. monkeypatch.setattr(process_manager, "PID_DIR", tmp_path)
  23. (tmp_path / "zhuce6-main.pid").write_text("999999", encoding="utf-8")
  24. statuses = process_manager.status_all()
  25. assert len(statuses) == 1
  26. assert statuses[0]["name"] == "main"
  27. assert statuses[0]["pid"] == 999999
  28. assert statuses[0]["pid_file"] == str(tmp_path / "zhuce6-main.pid")
  29. def test_process_manager_stop_all_also_stops_orphan_repo_processes(tmp_path, monkeypatch) -> None:
  30. monkeypatch.setattr(process_manager, "PID_DIR", tmp_path)
  31. (tmp_path / "zhuce6-main.pid").write_text("111", encoding="utf-8")
  32. stopped: list[tuple[int, str | None]] = []
  33. monkeypatch.setattr(process_manager, "_list_repo_process_pids", lambda: [222, 333])
  34. monkeypatch.setattr(
  35. process_manager,
  36. "_stop_pid",
  37. lambda pid, timeout=5.0, remove_name=None: stopped.append((pid, remove_name)) or True,
  38. )
  39. result = process_manager.stop_all(timeout=1.0)
  40. assert result == {"main": True, "orphan_pids": [222, 333]}
  41. assert stopped == [
  42. (111, "main"),
  43. (222, None),
  44. (333, None),
  45. ]