|
| 1 | +"""Helpers for spawning fixture plugins as real subprocesses. |
| 2 | +
|
| 3 | +These tests exercise the exact process boundary Flow Launcher uses: |
| 4 | +V1 plugins get one JSON-RPC request as argv[1] and answer on stdout in a |
| 5 | +fresh process per request; V2 plugins are a single long-lived process |
| 6 | +speaking newline-delimited JSON-RPC over stdin/stdout. |
| 7 | +""" |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import json |
| 11 | +import os |
| 12 | +import queue |
| 13 | +import subprocess |
| 14 | +import sys |
| 15 | +import threading |
| 16 | +from pathlib import Path |
| 17 | +from typing import Any, Optional |
| 18 | + |
| 19 | +import pytest |
| 20 | + |
| 21 | +REPO_ROOT = Path(__file__).resolve().parents[2] |
| 22 | +FIXTURES = Path(__file__).resolve().parent / 'fixtures' |
| 23 | +V1_PLUGIN = FIXTURES / 'v1_plugin' / 'main.py' |
| 24 | +V2_PLUGIN = FIXTURES / 'v2_plugin' / 'main.py' |
| 25 | + |
| 26 | +READ_TIMEOUT = 15.0 |
| 27 | + |
| 28 | + |
| 29 | +def plugin_env() -> dict: |
| 30 | + """Subprocess environment with the repo importable even without install.""" |
| 31 | + env = os.environ.copy() |
| 32 | + env['PYTHONPATH'] = str(REPO_ROOT) + os.pathsep + env.get('PYTHONPATH', '') |
| 33 | + return env |
| 34 | + |
| 35 | + |
| 36 | +@pytest.fixture |
| 37 | +def run_v1(tmp_path): |
| 38 | + """Spawn the V1 fixture exactly as Flow Launcher does: fresh process, |
| 39 | + request JSON in argv[1], response read from stdout.""" |
| 40 | + def _run(request: dict) -> str: |
| 41 | + completed = subprocess.run( |
| 42 | + [sys.executable, str(V1_PLUGIN), json.dumps(request)], |
| 43 | + capture_output=True, text=True, encoding='utf-8', |
| 44 | + cwd=tmp_path, env=plugin_env(), timeout=READ_TIMEOUT, |
| 45 | + ) |
| 46 | + assert completed.returncode == 0, completed.stderr |
| 47 | + return completed.stdout |
| 48 | + return _run |
| 49 | + |
| 50 | + |
| 51 | +class V2PluginProcess: |
| 52 | + """A persistent V2 plugin subprocess with a line-reader thread so tests |
| 53 | + never block forever on a plugin that stops responding.""" |
| 54 | + |
| 55 | + def __init__(self, tmp_path: Path) -> None: |
| 56 | + self.proc = subprocess.Popen( |
| 57 | + [sys.executable, str(V2_PLUGIN)], |
| 58 | + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 59 | + text=True, encoding='utf-8', bufsize=1, |
| 60 | + cwd=tmp_path, env=plugin_env(), |
| 61 | + ) |
| 62 | + self._lines: queue.Queue = queue.Queue() |
| 63 | + self._reader = threading.Thread(target=self._pump, daemon=True) |
| 64 | + self._reader.start() |
| 65 | + |
| 66 | + def _pump(self) -> None: |
| 67 | + for line in self.proc.stdout: |
| 68 | + if line.strip(): |
| 69 | + self._lines.put(line) |
| 70 | + |
| 71 | + def send(self, message: dict) -> None: |
| 72 | + self.proc.stdin.write(json.dumps(message) + '\n') |
| 73 | + self.proc.stdin.flush() |
| 74 | + |
| 75 | + def read_message(self, timeout: float = READ_TIMEOUT) -> dict: |
| 76 | + try: |
| 77 | + return json.loads(self._lines.get(timeout=timeout)) |
| 78 | + except queue.Empty: |
| 79 | + raise AssertionError( |
| 80 | + f"No response from V2 plugin within {timeout}s; " |
| 81 | + f"stderr: {self._drain_stderr()}" |
| 82 | + ) |
| 83 | + |
| 84 | + def request(self, request_id: int, method: str, params: Optional[list] = None, |
| 85 | + **extra: Any) -> dict: |
| 86 | + """Send a request and return the response bearing the same id.""" |
| 87 | + message = {'jsonrpc': '2.0', 'id': request_id, 'method': method, |
| 88 | + 'params': params or [], **extra} |
| 89 | + self.send(message) |
| 90 | + response = self.read_message() |
| 91 | + assert response.get('id') == request_id, ( |
| 92 | + f"Expected response to id={request_id}, got: {response}") |
| 93 | + return response |
| 94 | + |
| 95 | + def assert_no_output(self, wait: float = 0.5) -> None: |
| 96 | + try: |
| 97 | + line = self._lines.get(timeout=wait) |
| 98 | + except queue.Empty: |
| 99 | + return |
| 100 | + raise AssertionError(f"Expected silence, but plugin wrote: {line!r}") |
| 101 | + |
| 102 | + def _drain_stderr(self) -> str: |
| 103 | + if self.proc.poll() is None: |
| 104 | + return '<process still running>' |
| 105 | + return self.proc.stderr.read() |
| 106 | + |
| 107 | + def close(self) -> None: |
| 108 | + if self.proc.poll() is None: |
| 109 | + self.proc.kill() |
| 110 | + self.proc.wait(timeout=5) |
| 111 | + for stream in (self.proc.stdin, self.proc.stdout, self.proc.stderr): |
| 112 | + if stream: |
| 113 | + stream.close() |
| 114 | + |
| 115 | + |
| 116 | +@pytest.fixture |
| 117 | +def v2_plugin(tmp_path): |
| 118 | + process = V2PluginProcess(tmp_path) |
| 119 | + yield process |
| 120 | + process.close() |
0 commit comments