from __future__ import annotations import json import os import queue import subprocess import sys import threading from pathlib import Path from typing import Any import pytest WORKER_DIR = Path(__file__).resolve().parent.parent FIXTURES = Path(__file__).resolve().parent / "fixtures" HF_TINY = Path.home() / ".cache/huggingface/hub/models--Systran--faster-whisper-tiny/snapshots" sys.path.insert(0, str(WORKER_DIR)) class WorkerProc: """python -m gvr_worker 를 자식 프로세스로 띄워 JSON Lines 로 대화한다.""" def __init__(self, env: dict[str, str]) -> None: self.proc = subprocess.Popen( [sys.executable, "-m", "gvr_worker"], cwd=WORKER_DIR, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", ) self.lines: queue.Queue[dict[str, Any]] = queue.Queue() self.raw: list[str] = [] self.stderr: list[str] = [] threading.Thread(target=self._read, daemon=True).start() threading.Thread(target=self._drain_stderr, daemon=True).start() def _drain_stderr(self) -> None: for line in self.proc.stderr: # type: ignore[union-attr] self.stderr.append(line) def _read(self) -> None: for line in self.proc.stdout: # type: ignore[union-attr] self.raw.append(line) self.lines.put(json.loads(line)) # stdout 은 항상 유효한 JSON 이어야 한다 def send(self, obj: dict[str, Any] | str) -> None: text = obj if isinstance(obj, str) else json.dumps(obj, ensure_ascii=False) self.proc.stdin.write(text + "\n") # type: ignore[union-attr] self.proc.stdin.flush() # type: ignore[union-attr] def recv(self, timeout: float = 60) -> dict[str, Any]: return self.lines.get(timeout=timeout) def request(self, obj: dict[str, Any], timeout: float = 120) -> tuple[dict[str, Any], list[dict[str, Any]]]: """응답과 그 사이에 온 같은 id 의 이벤트들을 돌려준다.""" self.send(obj) events = [] while True: msg = self.recv(timeout) if msg.get("id") != obj.get("id"): continue if "event" in msg: events.append(msg) continue return msg, events def close(self) -> int: if self.proc.poll() is None: try: self.send({"id": "bye", "op": "shutdown"}) except (BrokenPipeError, OSError): pass try: return self.proc.wait(timeout=30) except subprocess.TimeoutExpired: self.proc.kill() return self.proc.wait() @pytest.fixture(scope="session") def models_dir(tmp_path_factory: pytest.TempPathFactory) -> Path: """tiny 모델을 HF 캐시에서 링크하거나 (없으면 테스트 중 download 로 받음).""" d = tmp_path_factory.mktemp("models") snaps = sorted(HF_TINY.glob("*/model.bin")) if HF_TINY.is_dir() else [] if snaps: (d / "tiny").symlink_to(snaps[0].parent, target_is_directory=True) return d @pytest.fixture(scope="session") def worker(models_dir: Path, tmp_path_factory: pytest.TempPathFactory): env = {**os.environ, "GVR_DATA_DIR": str(tmp_path_factory.mktemp("data")), "GVR_MODELS_DIR": str(models_dir), "PYTHONIOENCODING": "utf-8"} w = WorkerProc(env) yield w w.close()