Files
video-analyse/tests/test_cli.py
T
alex 151d60a861 cli: import the MCP server entry point directly (code-review F8)
_mcp_server probed the module for run/run_server/mcp/server with a getattr
ladder, plus a second server.run branch - names mcp_server always exports (or
never will), so most of the ladder was unreachable and the failure messages
described a situation that cannot occur.

- cli: one lazy `from .mcp_server import DEFAULT_HTTP_HOST, run` inside a
  try/except that keeps the actionable install message; importlib is gone
- tests: the serve-mcp dispatch stub provides the two names the entry point
  uses
2026-11-24 12:54:35 +00:00

858 lines
30 KiB
Python

"""CLI tests: typer wiring, help text, JSON output and error mapping.
No network and no model is touched. The media tests use the synthetic ``sample_video``
fixture; every model-dependent command runs against one stub of the analysis module
(patched at ``cli.analysis``) that returns hand-built outcomes and records options.
"""
from __future__ import annotations
import json
import shutil
import sys
import types
from pathlib import Path
from typing import Any
import pytest
from click.testing import Result
from typer.testing import CliRunner
from video_analyse import __version__, cli
from video_analyse.analysis import AnalysisOptions
from video_analyse.config import Settings
from video_analyse.diarize import DIARIZE_BACKENDS
from video_analyse.ingest import IngestResult
from video_analyse.models import (
Artifacts,
Segment,
Shot,
ShotDescription,
SpeakerTurn,
Transcript,
VideoReport,
Word,
)
from video_analyse.synthesis import AnswerResult
from video_analyse.transcribe import STT_BACKENDS
FFMPEG = shutil.which("ffmpeg")
FFPROBE = shutil.which("ffprobe")
needs_ffprobe = pytest.mark.skipif(FFPROBE is None, reason="ffprobe not on PATH")
needs_ffmpeg_tools = pytest.mark.skipif(
FFMPEG is None or FFPROBE is None, reason="ffmpeg/ffprobe not on PATH"
)
VA_ENV_VARS = (
"VA_PROFILE",
"VA_CACHE_DIR",
"VA_LANGUAGE",
"VA_STT_BACKEND",
"VA_STT_API_BASE_URL",
"VA_STT_API_MODEL",
"VA_STT_MAX_UPLOAD_BYTES",
"VA_WHISPER_MODEL",
"VA_DIARIZE",
"VA_DIARIZE_BACKEND",
"VA_DIARIZE_CLUSTER_THRESHOLD",
"VA_DIARIZE_MIN_DURATION_ON",
"VA_DIARIZE_MIN_DURATION_OFF",
"VA_VLM_MODEL",
"VA_LLAMA_SERVER_URL",
"VA_SYNTHESIS_MODEL",
)
COMMANDS = (
"version",
"fetch",
"probe",
"transcribe",
"diarize",
"shots",
"describe",
"analyse",
"moment",
"ask",
"doctor",
"serve-mcp",
)
COMMAND_OPTIONS: dict[str, tuple[str, ...]] = {
"fetch": ("--quality", "--json"),
"probe": ("--json",),
"transcribe": ("--backend", "--lang", "--diarize", "--no-diarize", "--format", "--json"),
"diarize": ("--backend", "--json"),
"shots": ("--max-shots", "--json"),
"describe": ("--model", "--json"),
"analyse": ("--no-diarize", "--no-describe", "--max-shots", "--out", "--force", "--json"),
"moment": (
"--start",
"--end",
"--describe",
"--no-describe",
"--max-frames",
"--width",
"--out",
"--json",
),
"ask": ("--json",),
"doctor": ("--json",),
"serve-mcp": ("--transport", "--port"),
}
@pytest.fixture(autouse=True)
def _isolated_environment(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
"""Keep tests independent of the developer's environment and real cache."""
for name in VA_ENV_VARS:
monkeypatch.delenv(name, raising=False)
monkeypatch.setenv("VA_CACHE_DIR", str(tmp_path / "cache"))
def _invoke(*args: str) -> Result:
"""Invoke the CLI with a fixed terminal width so rich help text does not wrap."""
runner = CliRunner()
return runner.invoke(cli.app, list(args), env={"COLUMNS": "120", "TERM": "dumb"})
def _install_stub_analysis(
monkeypatch: pytest.MonkeyPatch,
*,
artifacts: Artifacts | None = None,
transcript: Transcript | None = None,
shots: list[Shot] | None = None,
answer: AnswerResult | None = None,
failure: BaseException | None = None,
) -> Any:
"""Patch ``cli.analysis`` with one outcome-shaped stub; return the recorded calls."""
class StubAnalysis:
def __init__(self) -> None:
self.calls: list[dict[str, Any]] = []
def _record(self, operation: str, source: str, **values: Any) -> None:
self.calls.append({"operation": operation, "source": source, **values})
async def probe(
self, source: str, *, settings: Settings, progress: Any = None
) -> Artifacts:
self._record("probe", source, settings=settings, progress=progress)
assert artifacts is not None
return artifacts
async def transcript(
self,
source: str,
options: AnalysisOptions,
*,
settings: Settings,
progress: Any = None,
) -> Transcript:
self._record(
"transcript", source, options=options, settings=settings, progress=progress
)
if failure is not None:
raise failure
assert transcript is not None
return transcript
def _outcome_artifacts(self, source: str) -> Artifacts:
"""The narrow outcomes return the whole run's artifacts (B2's one run)."""
assert artifacts is not None
return artifacts.model_copy(update={"source": source, "shots": list(shots or [])})
async def shots(
self,
source: str,
options: AnalysisOptions,
*,
settings: Settings,
progress: Any = None,
) -> Artifacts:
self._record("shots", source, options=options, settings=settings, progress=progress)
if failure is not None:
raise failure
return self._outcome_artifacts(source)
async def describe(
self,
source: str,
options: AnalysisOptions,
*,
settings: Settings,
progress: Any = None,
) -> Artifacts:
self._record("describe", source, options=options, settings=settings, progress=progress)
if failure is not None:
raise failure
return self._outcome_artifacts(source)
async def analyse(
self,
source: str,
options: AnalysisOptions,
*,
settings: Settings,
progress: Any = None,
) -> Artifacts:
self._record("analyse", source, options=options, settings=settings, progress=progress)
if failure is not None:
raise failure
assert artifacts is not None
return artifacts
async def ask(
self,
source: str,
question: str,
options: AnalysisOptions,
*,
settings: Settings,
allow_analysis: bool = False,
) -> AnswerResult:
self._record(
"ask",
source,
question=question,
options=options,
settings=settings,
allow_analysis=allow_analysis,
)
if failure is not None:
raise failure
assert answer is not None
return answer
stub = StubAnalysis()
monkeypatch.setattr(cli, "analysis", stub)
return stub
def _sample_transcript() -> Transcript:
"""A two-speaker transcript with word timings and speaker turns."""
return Transcript(
language="en",
duration=3.0,
backend="stub",
model="stub-model",
segments=[
Segment(
start=0.0,
end=1.5,
text="Hello there.",
speaker="S1",
words=[
Word(text="Hello", start=0.0, end=0.6),
Word(text="there.", start=0.6, end=1.4),
],
),
Segment(start=1.5, end=3.0, text="General Kenobi.", speaker="S2"),
],
speaker_turns=[
SpeakerTurn(start=0.0, end=1.5, speaker="S1"),
SpeakerTurn(start=1.5, end=3.0, speaker="S2"),
],
)
def _sample_shots() -> list[Shot]:
"""Two shots, the first one described."""
return [
Shot(
index=0,
start=0.0,
end=4.0,
description=ShotDescription(
summary="A test pattern fills the frame.", shot_type="other"
),
),
Shot(index=1, start=4.0, end=10.0),
]
def _sample_report(source: str) -> VideoReport:
"""A minimal validated report used by the analyse/ask stubs."""
return VideoReport(
source=source,
title="Sample analysis",
duration=10.0,
summary="A synthetic test pattern with a tone.",
topics=["testing"],
people=[],
highlights=[],
shots=[Shot(index=0, start=0.0, end=10.0)],
transcript=None,
metadata={},
)
def _stub_artifacts(tmp_path: Path, *, transcript: Transcript | None = None) -> Artifacts:
"""Artifacts shell rooted in ``tmp_path`` for the stub pipeline."""
return Artifacts(
source=str(tmp_path / "clip.mp4"),
workdir=tmp_path / "work",
transcript=transcript,
shots=_sample_shots(),
)
# --------------------------------------------------------------------------- #
# help, version, argument parsing
# --------------------------------------------------------------------------- #
def test_root_help_lists_every_command() -> None:
result = _invoke("--help")
assert result.exit_code == 0, result.output
assert "Usage" in result.stdout
for command in COMMANDS:
assert command in result.stdout
def test_bare_invocation_prints_help() -> None:
result = _invoke()
assert result.exit_code == 0, result.output
assert "Usage" in result.stdout
@pytest.mark.parametrize(("command", "options"), sorted(COMMAND_OPTIONS.items()))
def test_command_help_lists_its_options(command: str, options: tuple[str, ...]) -> None:
result = _invoke(command, "--help")
assert result.exit_code == 0, result.output
for option in options:
assert option in result.stdout, f"{option} missing from `va {command} --help`"
def test_version_is_available_as_flag_and_command() -> None:
flagged = _invoke("--version")
assert flagged.exit_code == 0, flagged.output
assert flagged.stdout.strip() == __version__
command = _invoke("version")
assert command.exit_code == 0, command.output
assert command.stdout.strip() == __version__
def test_transcribe_rejects_unknown_format(tmp_path: Path) -> None:
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
result = _invoke("transcribe", str(media), "--format", "vtt")
assert result.exit_code != 0
assert "--format" in result.output
def test_shots_rejects_removed_detector_option(tmp_path: Path) -> None:
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
result = _invoke("shots", str(media), "--detector", "adaptive")
assert result.exit_code == 2, result.output
assert "No such option" in result.output
assert "--detector" in result.output
@pytest.mark.parametrize(
("command", "registry"), [("transcribe", STT_BACKENDS), ("diarize", DIARIZE_BACKENDS)]
)
def test_backend_options_come_from_the_stage_registries(
command: str, registry: tuple[str, ...]
) -> None:
"""--backend help and rejection both list exactly the stage registry's names."""
help_result = _invoke(command, "--help")
assert help_result.exit_code == 0, help_result.output
for name in registry:
assert name in help_result.stdout, f"{name} missing from `va {command} --help`"
rejected = _invoke(command, "--backend", "not-a-backend", "clip.mp4")
assert rejected.exit_code == 2, rejected.output
assert "not-a-backend" in rejected.output
def test_serve_mcp_rejects_unknown_transport() -> None:
result = _invoke("serve-mcp", "--transport", "websocket")
assert result.exit_code != 0
assert "--transport" in result.output
@pytest.mark.parametrize(
("extra_args", "expected"),
[
((), {"transport": "stdio", "host": "127.0.0.1", "port": 8000}),
(
("--transport", "http", "--port", "9100"),
{"transport": "http", "host": "127.0.0.1", "port": 9100},
),
],
)
def test_serve_mcp_dispatches_to_the_server_entry_point(
monkeypatch: pytest.MonkeyPatch, extra_args: tuple[str, ...], expected: dict[str, Any]
) -> None:
calls: list[dict[str, Any]] = []
fake_module = types.ModuleType("video_analyse.mcp_server")
fake_module.run = lambda **kwargs: calls.append(kwargs) # type: ignore[attr-defined]
fake_module.DEFAULT_HTTP_HOST = "127.0.0.1" # type: ignore[attr-defined]
monkeypatch.setitem(sys.modules, "video_analyse.mcp_server", fake_module)
result = _invoke("serve-mcp", *extra_args)
assert result.exit_code == 0, result.output
assert calls == [expected]
# --------------------------------------------------------------------------- #
# real media: probe (ffprobe only, no models)
# --------------------------------------------------------------------------- #
@needs_ffprobe
def test_probe_json_on_sample_video(sample_video: Path) -> None:
result = _invoke("probe", str(sample_video), "--json")
assert result.exit_code == 0, result.output
payload = json.loads(result.stdout) # stdout is exactly one JSON document
for key in (
"path",
"source",
"duration",
"width",
"height",
"fps",
"has_audio",
"size_bytes",
"extra",
):
assert key in payload
assert Path(payload["path"]) == sample_video.resolve()
assert payload["duration"] == pytest.approx(10.0, abs=0.5)
assert payload["width"] == 640
assert payload["height"] == 360
assert payload["has_audio"] is True
# The global --json flag (before the subcommand) produces the same document.
global_result = _invoke("--json", "probe", str(sample_video))
assert global_result.exit_code == 0, global_result.output
assert json.loads(global_result.stdout)["has_audio"] is True
@needs_ffprobe
def test_probe_human_output_on_sample_video(sample_video: Path) -> None:
result = _invoke("probe", str(sample_video))
assert result.exit_code == 0, result.output
assert "Media info" in result.stdout
assert "640x360" in result.stdout
assert "00:10" in result.stdout
@pytest.mark.parametrize("command", ["probe", "transcribe", "diarize", "shots", "analyse"])
def test_missing_file_exits_nonzero_with_message(command: str, tmp_path: Path) -> None:
missing = tmp_path / "missing.mp4"
result = _invoke(command, str(missing))
assert result.exit_code == 1, result.output
assert "missing.mp4" in result.output
assert "not found" in result.output.lower()
# --------------------------------------------------------------------------- #
# model-dependent commands against one analysis stub
# --------------------------------------------------------------------------- #
def test_transcribe_json_and_srt_from_stub_analysis(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
transcript = _sample_transcript()
artifacts = Artifacts(source=str(media), workdir=tmp_path / "work", transcript=transcript)
stub = _install_stub_analysis(monkeypatch, artifacts=artifacts, transcript=transcript)
json_result = _invoke(
"transcribe",
str(media),
"--diarize",
"--lang",
"en",
"--backend",
"whisper",
"--json",
)
assert json_result.exit_code == 0, json_result.output
payload = json.loads(json_result.stdout)
assert payload["language"] == "en"
assert [segment["text"] for segment in payload["segments"]] == [
"Hello there.",
"General Kenobi.",
]
assert payload["segments"][0]["speaker"] == "S1"
call = stub.calls[0]
assert call["operation"] == "transcript"
assert call["options"].diarize is True
assert call["options"].language == "en"
assert call["settings"].resolved_stt() == "whisper"
srt_result = _invoke("transcribe", str(media), "--format", "srt")
assert srt_result.exit_code == 0, srt_result.output
assert srt_result.stdout.startswith("1\n00:00:00,000 --> 00:00:01,500\n[S1] Hello there.")
assert "[S2] General Kenobi." in srt_result.stdout
assert stub.calls[1]["options"].diarize is None
def test_transcribe_honours_va_language_unless_lang_is_passed(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""Omitting --lang passes no override; an explicit 'auto' asks analysis to clear it."""
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
stub = _install_stub_analysis(
monkeypatch,
artifacts=Artifacts(source=str(media), workdir=tmp_path / "work"),
transcript=_sample_transcript(),
)
monkeypatch.setenv("VA_LANGUAGE", "en")
assert _invoke("transcribe", str(media), "--json").exit_code == 0
assert stub.calls[-1]["options"].language is None
assert stub.calls[-1]["settings"].language == "en"
assert _invoke("transcribe", str(media), "--lang", "auto", "--json").exit_code == 0
assert stub.calls[-1]["options"].language == "auto"
def test_shots_and_describe_json_from_stub_analysis(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
artifacts = _stub_artifacts(tmp_path)
stub = _install_stub_analysis(monkeypatch, artifacts=artifacts, shots=artifacts.shots)
shots_result = _invoke("shots", str(media), "--max-shots", "8", "--json")
assert shots_result.exit_code == 0, shots_result.output
payload = json.loads(shots_result.stdout)
assert [shot["index"] for shot in payload["shots"]] == [0, 1]
shots_call = [call for call in stub.calls if call["operation"] == "shots"][-1]
assert shots_call["options"].max_shots == 8
describe_result = _invoke("describe", str(media), "--model", "stub:vlm", "--json")
assert describe_result.exit_code == 0, describe_result.output
payload = json.loads(describe_result.stdout)
assert payload["shots"][0]["description"]["summary"].startswith("A test pattern")
describe_call = [call for call in stub.calls if call["operation"] == "describe"][-1]
assert describe_call["settings"].vlm_model == "stub:vlm"
def test_shots_and_describe_run_the_scheduler_once(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""Each narrow command is one scheduler run: the outcome operation owns the artifacts."""
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
artifacts = _stub_artifacts(tmp_path)
stub = _install_stub_analysis(monkeypatch, artifacts=artifacts, shots=artifacts.shots)
shots_result = _invoke("shots", str(media), "--json")
assert shots_result.exit_code == 0, shots_result.output
assert [call["operation"] for call in stub.calls] == ["shots"]
payload = json.loads(shots_result.stdout)
assert payload["source"] == str(media)
assert payload["workdir"] == str(artifacts.workdir)
assert [shot["index"] for shot in payload["shots"]] == [0, 1]
stub.calls.clear()
describe_result = _invoke("describe", str(media), "--json")
assert describe_result.exit_code == 0, describe_result.output
assert [call["operation"] for call in stub.calls] == ["describe"]
assert json.loads(describe_result.stdout)["shots"][0]["index"] == 0
def test_diarize_json_from_stub_analysis(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
transcript = _sample_transcript()
stub = _install_stub_analysis(
monkeypatch,
artifacts=Artifacts(source=str(media), workdir=tmp_path / "work", transcript=transcript),
transcript=transcript,
)
result = _invoke("diarize", str(media), "--backend", "sherpa", "--json")
assert result.exit_code == 0, result.output
payload = json.loads(result.stdout)
assert payload["speaker_turns"][0]["speaker"] == "S1"
call = stub.calls[0]
assert call["operation"] == "transcript"
assert call["options"].diarize is True
assert call["settings"].diarize_backend == "sherpa"
def test_analyse_writes_markdown_and_maps_options(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
report = _sample_report(str(media))
artifacts = Artifacts(
source=str(media),
workdir=tmp_path / "work",
shots=report.shots,
report=report,
)
stub = _install_stub_analysis(monkeypatch, artifacts=artifacts)
out = tmp_path / "out" / "report.md"
result = _invoke(
"analyse",
str(media),
"--no-diarize",
"--no-describe",
"--max-shots",
"8",
"--out",
str(out),
"--force",
)
assert result.exit_code == 0, result.output
assert out.is_file()
assert out.with_suffix(".json").is_file()
written = json.loads(out.with_suffix(".json").read_text(encoding="utf-8"))
assert written["title"] == "Sample analysis"
assert "JSON report written to" in result.stdout
markdown = out.read_text(encoding="utf-8")
assert markdown.startswith("# Sample analysis")
assert "A synthetic test pattern with a tone." in markdown
assert "Markdown report written to" in result.stdout
options = stub.calls[0]["options"]
assert options.diarize is False
assert options.describe is False
assert options.max_shots == 8
assert options.force is True
json_result = _invoke("analyse", str(media), "--out", str(out.parent / "again.md"), "--json")
assert json_result.exit_code == 0, json_result.output
payload = json.loads(json_result.stdout)
assert payload["title"] == "Sample analysis"
assert payload["topics"] == ["testing"]
defaults = stub.calls[-1]["options"]
assert defaults.diarize is None and defaults.describe is True
assert defaults.max_shots == 64
def test_behavioural_flags_travel_in_analysis_options_not_settings(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""--no-diarize/--no-describe/--max-shots/--force never rewrite the settings profile."""
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
report = _sample_report(str(media))
artifacts = Artifacts(
source=str(media), workdir=tmp_path / "work", shots=report.shots, report=report
)
stub = _install_stub_analysis(monkeypatch, artifacts=artifacts)
monkeypatch.setenv("VA_DIARIZE", "true")
monkeypatch.setenv("VA_LANGUAGE", "en")
result = _invoke(
"analyse",
str(media),
"--no-diarize",
"--no-describe",
"--max-shots",
"8",
"--force",
"--out",
str(tmp_path / "out" / "report.md"),
)
assert result.exit_code == 0, result.output
call = stub.calls[-1]
assert (call["options"].diarize, call["options"].describe) == (False, False)
assert (call["options"].max_shots, call["options"].force) == (8, True)
assert call["settings"].diarize is True # the profile still says diarize on
assert call["settings"].language == "en" # ... and the language is untouched
def test_profile_flags_override_the_environment_at_the_entry_point(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""--backend / --model are profile fields: they override VA_* once, at the entry point."""
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
transcript = _sample_transcript()
artifacts = _stub_artifacts(tmp_path, transcript=transcript)
stub = _install_stub_analysis(
monkeypatch, artifacts=artifacts, transcript=transcript, shots=artifacts.shots
)
monkeypatch.setenv("VA_STT_BACKEND", "parakeet")
monkeypatch.setenv("VA_VLM_MODEL", "env:vlm")
assert _invoke("transcribe", str(media), "--backend", "whisper", "--json").exit_code == 0
assert stub.calls[-1]["settings"].resolved_stt() == "whisper"
assert _invoke("describe", str(media), "--model", "flag:vlm", "--json").exit_code == 0
assert stub.calls[-1]["settings"].vlm_model == "flag:vlm"
def test_analyse_writes_the_srt_artifact_when_a_transcript_exists(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
report = _sample_report(str(media)).model_copy(update={"transcript": _sample_transcript()})
artifacts = Artifacts(
source=str(media), workdir=tmp_path / "work", report=report, transcript=report.transcript
)
_install_stub_analysis(monkeypatch, artifacts=artifacts)
out = tmp_path / "out" / "report.md"
result = _invoke("analyse", str(media), "--out", str(out))
assert result.exit_code == 0, result.output
srt = out.with_suffix(".srt")
assert srt.is_file()
assert srt.read_text(encoding="utf-8").startswith("1\n00:00:00,000 --> 00:00:01,500")
assert "Transcript written to" in result.stdout
@needs_ffmpeg_tools
def test_moment_on_sample_video_writes_frames(sample_video: Path, tmp_path: Path) -> None:
"""``va moment`` runs the analysis frame path against the real fixture."""
out = tmp_path / "frames"
result = _invoke(
"moment",
str(sample_video),
"--start",
"0.5",
"--end",
"4",
"--out",
str(out),
"--json",
)
assert result.exit_code == 0, result.output
payload = json.loads(result.stdout)
assert payload["t_start"] == 0.5
assert payload["t_end"] == 4.0
assert len(payload["frame_timestamps"]) == 4
assert "frames" not in payload
assert len(payload["frame_paths"]) == 4
for path in payload["frame_paths"]:
assert Path(path).read_bytes()[:2] == b"\xff\xd8"
def test_ask_prints_grounded_answer(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
stub = _install_stub_analysis(
monkeypatch,
answer=AnswerResult(answer="Answer to: what happens?", cached=False),
)
result = _invoke("ask", str(media), "what", "happens?", "--json")
assert result.exit_code == 0, result.output
payload = json.loads(result.stdout)
assert payload["question"] == "what happens?"
assert payload["answer"] == "Answer to: what happens?"
call = stub.calls[0]
assert call["operation"] == "ask"
assert call["question"] == "what happens?"
assert call["options"].no_cache is False
def test_ask_honours_no_cache(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
stub = _install_stub_analysis(monkeypatch, answer=AnswerResult(answer="fresh", cached=False))
result = _invoke("ask", str(media), "why?", "--no-cache", "--json")
assert result.exit_code == 0, result.output
assert stub.calls[0]["options"].no_cache is True
def test_ask_without_cached_report_exits_nonzero(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
_install_stub_analysis(
monkeypatch,
failure=RuntimeError(
f"ask: no cached analysis report for {media!s}. Run analyze_video first, or "
f"'va analyse {media!s}' from the CLI."
),
)
result = _invoke("ask", str(media), "why?")
assert result.exit_code == 1, result.output
assert "va analyse" in result.output
def test_analysis_failure_maps_to_exit_code_1(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
_install_stub_analysis(
monkeypatch,
artifacts=Artifacts(source=str(media), workdir=tmp_path / "work"),
shots=_sample_shots(),
failure=RuntimeError("llama-server is not reachable at http://127.0.0.1:8080/v1"),
)
result = _invoke("describe", str(media))
assert result.exit_code == 1, result.output
assert "llama-server is not reachable" in result.output
def test_fetch_reports_downloaded_file(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
downloaded = tmp_path / "downloads" / "demo.mp4"
downloaded.parent.mkdir(parents=True)
downloaded.write_bytes(b"video bytes")
async def fake_fetch(url: str, *, cache_dir: Path, quality: int) -> IngestResult:
assert url == "https://example.invalid/v"
assert quality == 720
return IngestResult(path=downloaded, info={"id": "abc"}, downloaded=True, title="Demo")
monkeypatch.setattr(cli, "_fetch_source", fake_fetch)
result = _invoke("fetch", "https://example.invalid/v", "--quality", "720", "--json")
assert result.exit_code == 0, result.output
payload = json.loads(result.stdout)
assert payload["title"] == "Demo"
assert payload["downloaded"] is True
assert Path(payload["path"]) == downloaded
# --------------------------------------------------------------------------- #
# doctor
# --------------------------------------------------------------------------- #
@needs_ffmpeg_tools
def test_doctor_exits_zero_and_prints_profile_line() -> None:
result = _invoke("doctor")
assert result.exit_code == 0, result.output
assert "profile" in result.stdout.lower()
assert "local" in result.stdout
assert "ffmpeg" in result.stdout
assert "ffprobe" in result.stdout
assert "cache dir" in result.stdout
assert "GROQ_API_KEY" in result.stdout
@needs_ffmpeg_tools
def test_doctor_warns_about_missing_ollama_key(monkeypatch: pytest.MonkeyPatch) -> None:
"""Ollama-cloud specs without a key warn with the config.toml hint."""
monkeypatch.setenv("VA_VLM_MODEL", "ollama:deepseek-v4.1-flash:1017")
monkeypatch.setenv("VA_SYNTHESIS_MODEL", "ollama:deepseek-v4.1-flash:1017")
result = _invoke("doctor")
assert result.exit_code == 0, result.output
assert "config.toml" in result.stdout
monkeypatch.setenv("VA_OLLAMA_API_KEY", "sk-test")
result = _invoke("doctor")
assert result.exit_code == 0, result.output
assert "ollama_api_key" in result.stdout
@needs_ffmpeg_tools
def test_doctor_json_payload_has_check_list() -> None:
result = _invoke("doctor", "--json")
assert result.exit_code == 0, result.output
payload = json.loads(result.stdout)
assert payload["profile"] == "local"
names = {check["name"] for check in payload["checks"]}
assert {"python", "profile", "ffmpeg", "ffprobe", "cache dir", "free disk"} <= names
assert {"ok", "warn", "fail", "info"} >= {check["status"] for check in payload["checks"]}
assert payload["llama_server_command"] is None or isinstance(
payload["llama_server_command"], str
)