|
| 1 | +import shlex |
| 2 | +import subprocess |
| 3 | +import tempfile |
| 4 | +import threading |
| 5 | +import time |
| 6 | +from pathlib import Path |
| 7 | +from typing import IO, Any, Generator |
| 8 | + |
| 9 | +import pytest |
| 10 | + |
| 11 | +from tests._process_utils import get_kwargs_for_process_group, terminate_process_group |
| 12 | + |
| 13 | +REPO_ROOT = Path(__file__).resolve().parent.parent.parent |
| 14 | +EXAMPLES_DIR = REPO_ROOT / 'examples' |
| 15 | + |
| 16 | + |
| 17 | +def pytest_configure(config: pytest.Config) -> None: |
| 18 | + config.addinivalue_line('markers', 'example_dir(name): set the example directory for a test') |
| 19 | + |
| 20 | + |
| 21 | +class DaprRunner: |
| 22 | + """Helper to run `dapr run` commands and capture output.""" |
| 23 | + |
| 24 | + def __init__(self, cwd: Path) -> None: |
| 25 | + self._cwd = cwd |
| 26 | + self._bg_process: subprocess.Popen[str] | None = None |
| 27 | + self._bg_output_file: IO[str] | None = None |
| 28 | + |
| 29 | + @staticmethod |
| 30 | + def _terminate(proc: subprocess.Popen[str]) -> None: |
| 31 | + if proc.poll() is not None: |
| 32 | + return |
| 33 | + |
| 34 | + terminate_process_group(proc) |
| 35 | + try: |
| 36 | + proc.wait(timeout=10) |
| 37 | + except subprocess.TimeoutExpired: |
| 38 | + terminate_process_group(proc, force=True) |
| 39 | + proc.wait() |
| 40 | + |
| 41 | + def run(self, args: str, *, timeout: int = 30, until: list[str] | None = None) -> str: |
| 42 | + """Run a foreground command, block until it finishes, and return output. |
| 43 | +
|
| 44 | + Use this for short-lived processes (e.g. a publisher that exits on its |
| 45 | + own). For long-lived background services, use ``start()``/``stop()``. |
| 46 | +
|
| 47 | + Args: |
| 48 | + args: Arguments passed to ``dapr run``. |
| 49 | + timeout: Maximum seconds to wait before killing the process. |
| 50 | + until: If provided, the process is terminated as soon as every |
| 51 | + string in this list has appeared in the accumulated output. |
| 52 | + """ |
| 53 | + proc = subprocess.Popen( |
| 54 | + args=('dapr', 'run', *shlex.split(args)), |
| 55 | + cwd=self._cwd, |
| 56 | + stdout=subprocess.PIPE, |
| 57 | + stderr=subprocess.STDOUT, |
| 58 | + text=True, |
| 59 | + **get_kwargs_for_process_group(), |
| 60 | + ) |
| 61 | + lines: list[str] = [] |
| 62 | + assert proc.stdout is not None |
| 63 | + |
| 64 | + # Kill the process if it exceeds the timeout. A background timer is |
| 65 | + # needed because `for line in proc.stdout` blocks indefinitely when |
| 66 | + # the child never exits. |
| 67 | + timer = threading.Timer( |
| 68 | + interval=timeout, function=lambda: terminate_process_group(proc, force=True) |
| 69 | + ) |
| 70 | + timer.start() |
| 71 | + |
| 72 | + try: |
| 73 | + for line in proc.stdout: |
| 74 | + print(line, end='', flush=True) |
| 75 | + lines.append(line) |
| 76 | + if until and all(exp in ''.join(lines) for exp in until): |
| 77 | + break |
| 78 | + finally: |
| 79 | + timer.cancel() |
| 80 | + self._terminate(proc) |
| 81 | + |
| 82 | + return ''.join(lines) |
| 83 | + |
| 84 | + def start(self, args: str, *, wait: int = 5) -> None: |
| 85 | + """Start a long-lived background service. |
| 86 | +
|
| 87 | + Use this for servers/subscribers that must stay alive while a second |
| 88 | + process runs via ``run()``. Call ``stop()`` to terminate and collect |
| 89 | + output. Stdout is written to a temp file to avoid pipe-buffer deadlocks. |
| 90 | + """ |
| 91 | + output_file = tempfile.NamedTemporaryFile(mode='w+', suffix='.log') |
| 92 | + proc = subprocess.Popen( |
| 93 | + args=('dapr', 'run', *shlex.split(args)), |
| 94 | + cwd=self._cwd, |
| 95 | + stdout=output_file, |
| 96 | + stderr=subprocess.STDOUT, |
| 97 | + text=True, |
| 98 | + **get_kwargs_for_process_group(), |
| 99 | + ) |
| 100 | + self._bg_process = proc |
| 101 | + self._bg_output_file = output_file |
| 102 | + time.sleep(wait) |
| 103 | + |
| 104 | + def stop(self) -> str: |
| 105 | + """Stop the background service and return its captured output.""" |
| 106 | + if self._bg_process is None: |
| 107 | + return '' |
| 108 | + self._terminate(self._bg_process) |
| 109 | + self._bg_process = None |
| 110 | + return self._read_and_close_output() |
| 111 | + |
| 112 | + def _read_and_close_output(self) -> str: |
| 113 | + if self._bg_output_file is None: |
| 114 | + return '' |
| 115 | + self._bg_output_file.seek(0) |
| 116 | + output = self._bg_output_file.read() |
| 117 | + self._bg_output_file.close() |
| 118 | + self._bg_output_file = None |
| 119 | + print(output, end='', flush=True) |
| 120 | + return output |
| 121 | + |
| 122 | + |
| 123 | +@pytest.fixture |
| 124 | +def dapr(request: pytest.FixtureRequest) -> Generator[DaprRunner, Any, None]: |
| 125 | + """Provides a DaprRunner scoped to an example directory. |
| 126 | +
|
| 127 | + Use the ``example_dir`` marker to select which example: |
| 128 | +
|
| 129 | + @pytest.mark.example_dir('state_store') |
| 130 | + def test_something(dapr): |
| 131 | + ... |
| 132 | +
|
| 133 | + Defaults to the examples root if no marker is set. |
| 134 | + """ |
| 135 | + marker = request.node.get_closest_marker('example_dir') |
| 136 | + cwd = EXAMPLES_DIR / marker.args[0] if marker else EXAMPLES_DIR |
| 137 | + |
| 138 | + runner = DaprRunner(cwd) |
| 139 | + yield runner |
| 140 | + runner.stop() |
0 commit comments