tests/run_tests.py

#!/usr/bin/env python3
"""Resolve a friendly suite selector and execute the persistent pytest suite."""

from __future__ import annotations

import subprocess
import sys
from pathlib import Path

TESTS_DIR = Path(__file__).resolve().parent
SUITES_DIR = TESTS_DIR / "suites"
PREFIX = "test_"
SUFFIX = ".py"


def suites() -> dict[str, Path]:
    return {
        path.stem.removeprefix(PREFIX): path.relative_to(TESTS_DIR)
        for path in sorted(SUITES_DIR.glob(f"{PREFIX}*{SUFFIX}"))
    }


def resolve(selector: str, available: dict[str, Path]) -> tuple[Path, str | None]:
    suite, separator, node = selector.partition("::")
    normalized = suite.replace("-", "_")

    direct = Path(suite)
    if direct.suffix == ".py" or "/" in suite:
        candidates = [direct] if direct.is_absolute() else [TESTS_DIR / direct, TESTS_DIR.parent / direct]
        for candidate in candidates:
            if candidate.is_file():
                return candidate.resolve().relative_to(TESTS_DIR), node if separator else None

    if normalized.startswith(PREFIX) and normalized.endswith(SUFFIX):
        normalized = Path(normalized).stem.removeprefix(PREFIX)
    aliases = {"openai_live": "openai_live_acceptance"}
    normalized = aliases.get(normalized, normalized)
    if normalized in available:
        return available[normalized], node if separator else None

    matches = [name for name in available if name == f"{normalized}_infra"]
    if len(matches) == 1:
        return available[matches[0]], node if separator else None

    names = "\n  ".join(name.replace("_", "-") for name in available)
    kind = "ambiguous" if len(matches) > 1 else "unknown"
    raise SystemExit(f"{kind} test suite {suite!r}. Available suites:\n  {names}")


def main(argv: list[str]) -> int:
    available = suites()
    pytest_args = list(argv)
    target: str | None = None
    live_openai = False

    # A leading option is pytest input, not a suite selector.
    if pytest_args and not pytest_args[0].startswith("-"):
        selector = pytest_args.pop(0)
        path, node = resolve(selector, available)
        target = str(path) + (f"::{node}" if node else "")
        live_openai = path.name == "test_openai_live_acceptance.py"

    command = [sys.executable, "-m", "pytest", "-vv", "--durations=0"]
    if target:
        command.append(target)
    if live_openai and "--live-openai" not in pytest_args:
        command.append("--live-openai")
    command.extend(pytest_args)
    return subprocess.call(command, cwd=TESTS_DIR)


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))