Files
video-analyse/tests/test_analysis.py
T
alex dca19074f4 tests: cover the cached-turns guard and the analyse cross-door parity (code-review B6)
Two verification gaps from the review:

- the `transcript is not None` guard added in d94188e had no test. The stage skip
  policy normally keeps a transcript-less diarize apply out of the scheduler's way,
  so the test calls the apply callable the scheduler invokes (RunContext with no
  transcript) and asserts the load leaves the run untouched; removing the guard
  makes it fail with NoneType.model_copy inside attribute_speakers
- the third #9 divergence (va analyse --max-shots / --no-describe) was only
  asserted CLI-side. The new parity test runs both doors against the same fake
  pipeline and asserts identical stage calls *and* that max_shots=8 reaches the
  shots stage from both (shown red against an MCP tool that dropped max_shots)
2026-11-24 12:56:40 +00:00

639 lines
22 KiB
Python

"""Tests for the analysis module: outcomes, progress, diagnosis and front-door parity.
Most tests run the real :class:`~video_analyse.pipeline.Pipeline` over injected fake
stages, so they exercise analysis policy (want-sets, option overrides, cache reads,
progress events) without ffmpeg, a model or the network. The frame tests use the real
``sample_video`` fixture because frame extraction is the one cheap media path involved.
"""
from __future__ import annotations
import asyncio
import shutil
from pathlib import Path
from typing import Any
import pytest
from pydantic import ValidationError
from typer.testing import CliRunner
import video_analyse.analysis as analysis_module
import video_analyse.synthesis as synthesis_module
from video_analyse import analysis, cli, mcp_server
from video_analyse.analysis import AnalysisOptions, checked_int
from video_analyse.cache import StageCache
from video_analyse.config import Settings
from video_analyse.models import (
MediaFacts,
Segment,
Shot,
ShotDescription,
SpeakerTurn,
Transcript,
VideoReport,
Word,
)
from video_analyse.pipeline import Pipeline, ProgressEvent
from video_analyse.synthesis import AnswerResult
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",
)
@pytest.fixture(autouse=True)
def clean_va_env(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 _settings(tmp_path: Path, **overrides: Any) -> Settings:
"""Settings rooted in ``tmp_path`` with only the test's own knobs overridden."""
values: dict[str, Any] = {"cache_dir": tmp_path / "cache"}
values.update(overrides)
return Settings(**values)
def _source(tmp_path: Path, name: str = "clip.mp4") -> Path:
"""Create a local file whose bytes are the source identity."""
path = tmp_path / "media" / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b"fake video bytes")
return path
class FakeStages:
"""Deterministic stand-ins for every analysis stage, recording every call."""
def __init__(self, *, has_audio: bool = True, has_video: bool = True) -> None:
self.has_audio = has_audio
self.has_video = has_video
self.calls: list[str] = []
self.shot_options: list[Any] = []
self.transcribe_options: list[Any] = []
def _transcript(self) -> Transcript:
return Transcript(
duration=10.0,
language="en",
backend="fake",
model="fake-model",
segments=[
Segment(
start=0.0,
end=5.0,
text="Hello there.",
words=[Word(text="Hello", start=0.0, end=1.0)],
),
Segment(start=5.0, end=10.0, text="General Kenobi."),
],
)
async def probe(self, path: Path) -> MediaFacts:
self.calls.append("probe")
return MediaFacts(
duration=10.0,
width=640 if self.has_video else None,
height=360 if self.has_video else None,
fps=12.0 if self.has_video else None,
has_audio=self.has_audio,
size_bytes=path.stat().st_size,
format="mp4",
)
async def audio(self, path: Path, workdir: Path) -> Path:
self.calls.append("audio")
wav = workdir / "audio.wav"
wav.parent.mkdir(parents=True, exist_ok=True)
wav.write_bytes(b"fake wav bytes")
return wav
async def transcribe(self, wav: Path, *, options: Any) -> Transcript:
self.calls.append("transcribe")
self.transcribe_options.append(options)
return self._transcript()
async def diarize(self, wav: Path, *, options: Any) -> list[SpeakerTurn]:
self.calls.append("diarize")
return [
SpeakerTurn(start=0.0, end=5.0, speaker="S1"),
SpeakerTurn(start=5.0, end=10.0, speaker="S2"),
]
async def shots(
self, path: Path, info: MediaFacts, *, workdir: Path, options: Any
) -> list[Shot]:
self.calls.append("shots")
self.shot_options.append(options)
frames = workdir / "keyframes"
frames.mkdir(parents=True, exist_ok=True)
shots = [Shot(index=0, start=0.0, end=5.0), Shot(index=1, start=5.0, end=10.0)]
for shot in shots:
frame = frames / f"shot-{shot.index}.jpg"
frame.write_bytes(b"\xff\xd8fake-jpeg")
shot.keyframe = frame
return shots
async def describe(
self, shots: list[Shot], transcript: Transcript | None, *, options: Any
) -> list[Shot]:
self.calls.append("describe")
return [
shot.model_copy(
update={
"description": ShotDescription(summary=f"Shot {shot.index}", shot_type="other")
}
)
for shot in shots
]
async def report(
self,
shots: list[Shot],
transcript: Transcript | None,
info: MediaFacts,
*,
source: str,
options: Any,
) -> VideoReport:
self.calls.append("report")
return VideoReport(
source=source,
title="Fake report",
duration=info.duration,
summary="A fake report.",
topics=["fake"],
people=[],
highlights=[],
shots=[shot.model_copy(deep=True) for shot in shots],
transcript=transcript,
metadata={"has_audio": info.has_audio},
)
def mapping(self) -> dict[str, Any]:
"""The stage-callable mapping accepted by ``Pipeline``."""
return {
"probe": self.probe,
"audio": self.audio,
"transcribe": self.transcribe,
"diarize": self.diarize,
"shots": self.shots,
"describe": self.describe,
"report": self.report,
}
def _patch_pipeline(monkeypatch: pytest.MonkeyPatch, fake: FakeStages) -> None:
"""Make analysis construct the real pipeline with this test's fake stages."""
class FakePipeline(Pipeline):
def __init__(self, settings: Settings, **options: Any) -> None:
super().__init__(settings, fake.mapping(), **options)
monkeypatch.setattr(analysis_module, "Pipeline", FakePipeline)
# --------------------------------------------------------------------------- #
# options and outcome policy
# --------------------------------------------------------------------------- #
def test_max_shots_is_validated_once_in_analysis_options() -> None:
assert AnalysisOptions().max_shots == 64
with pytest.raises(ValidationError):
AnalysisOptions(max_shots=0)
async def test_transcript_follows_settings_diarize_unless_the_option_overrides_it(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
source = _source(tmp_path)
fake = FakeStages()
_patch_pipeline(monkeypatch, fake)
settings = _settings(tmp_path, diarize=True)
transcript = await analysis.transcript(str(source), AnalysisOptions(), settings=settings)
assert isinstance(transcript, Transcript)
assert fake.calls == ["probe", "audio", "transcribe", "diarize"]
shutil.rmtree(settings.cache_dir, ignore_errors=True)
fake.calls.clear()
transcript = await analysis.transcript(
str(source), AnalysisOptions(diarize=False), settings=settings
)
assert isinstance(transcript, Transcript)
assert fake.calls == ["probe", "audio", "transcribe"]
async def test_transcript_language_option_overrides_va_language(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
source = _source(tmp_path)
fake = FakeStages()
_patch_pipeline(monkeypatch, fake)
settings = _settings(tmp_path, language="en")
await analysis.transcript(str(source), AnalysisOptions(), settings=settings)
assert fake.transcribe_options[-1].language == "en"
shutil.rmtree(settings.cache_dir, ignore_errors=True)
fake.calls.clear()
await analysis.transcript(str(source), AnalysisOptions(language="auto"), settings=settings)
assert fake.transcribe_options[-1].language is None
async def test_transcript_raises_the_no_audio_diagnosis_once(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
source = _source(tmp_path)
fake = FakeStages(has_audio=False)
_patch_pipeline(monkeypatch, fake)
with pytest.raises(RuntimeError, match="no audio stream") as excinfo:
await analysis.transcript(str(source), AnalysisOptions(), settings=_settings(tmp_path))
message = str(excinfo.value)
assert "VA_STT_BACKEND" in message
assert fake.calls == ["probe"]
async def test_analyse_progress_events_have_the_exact_stage_total(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
source = _source(tmp_path)
fake = FakeStages()
_patch_pipeline(monkeypatch, fake)
events: list[ProgressEvent] = []
artifacts = await analysis.analyse(
str(source),
AnalysisOptions(),
settings=_settings(tmp_path),
progress=events.append,
)
assert artifacts.report is not None
assert events
assert {event.total for event in events} == {7}
assert [event.index for event in events if event.stage == "report"] == [7, 7]
assert events[-1] == ProgressEvent(stage="report", state="done", index=7, total=7)
assert [event.stage for event in events if event.state == "start"] == [
"probe",
"audio",
"transcribe",
"diarize",
"shots",
"describe",
"report",
]
# --------------------------------------------------------------------------- #
# cache reads: current keys only, never a stale variant
# --------------------------------------------------------------------------- #
async def test_cached_never_serves_a_shots_variant_from_other_options(tmp_path: Path) -> None:
source = _source(tmp_path)
fake = FakeStages()
settings = _settings(tmp_path)
await Pipeline(settings, fake.mapping(), max_shots=8).run(str(source))
narrow = await analysis.cached(
str(source), settings=settings, options=AnalysisOptions(max_shots=8)
)
assert narrow is not None
assert [shot.index for shot in narrow.shots] == [0, 1]
assert narrow.transcript is not None
wide = await analysis.cached(
str(source), settings=settings, options=AnalysisOptions(max_shots=64)
)
assert wide is not None
assert wide.shots == [] # the max_shots=8 artifact is a different key, never served
assert wide.transcript is not None # transcript keys are independent of max_shots
async def test_moment_reads_context_through_cached_at_the_current_keys(
monkeypatch: pytest.MonkeyPatch, sample_video: Path, tmp_path: Path
) -> None:
fake = FakeStages()
settings = _settings(tmp_path)
await Pipeline(settings, fake.mapping()).run(str(sample_video))
_patch_pipeline(monkeypatch, fake)
result = await analysis.moment(
str(sample_video),
0.5,
4.0,
AnalysisOptions(describe=False),
settings=settings,
max_frames=2,
width=320,
)
assert [segment.text for segment in result.transcript] == ["Hello"]
assert result.shots and result.shots[0].description is not None
assert len(result.frames) == 2
assert all(frame[:2] == b"\xff\xd8" for frame in result.frames)
async def test_moment_clips_words_at_the_window_edges(
monkeypatch: pytest.MonkeyPatch, sample_video: Path, tmp_path: Path
) -> None:
"""moment's transcript slice uses the same half-open word-midpoint rule as shots."""
fake = FakeStages()
settings = _settings(tmp_path)
await Pipeline(settings, fake.mapping()).run(str(sample_video))
_patch_pipeline(monkeypatch, fake)
inside = await analysis.moment(
str(sample_video),
0.4,
1.0,
AnalysisOptions(describe=False),
settings=settings,
max_frames=1,
width=320,
)
assert [segment.text for segment in inside.transcript] == ["Hello"]
# "Hello" is 0.0-1.0 s, midpoint 0.5: the window end is exclusive.
edge = await analysis.moment(
str(sample_video),
0.0,
0.5,
AnalysisOptions(describe=False),
settings=settings,
max_frames=1,
width=320,
)
assert edge.transcript == []
async def test_moment_never_serves_shots_from_another_max_shots_variant(
monkeypatch: pytest.MonkeyPatch, sample_video: Path, tmp_path: Path
) -> None:
fake = FakeStages()
settings = _settings(tmp_path)
await Pipeline(settings, fake.mapping(), max_shots=8).run(str(sample_video))
_patch_pipeline(monkeypatch, fake)
result = await analysis.moment(
str(sample_video),
0.5,
4.0,
AnalysisOptions(max_shots=64, describe=False),
settings=settings,
max_frames=1,
width=320,
)
assert result.shots == []
assert any("No cached shots" in note for note in result.notes)
async def test_cached_url_without_a_downloaded_source_returns_none(tmp_path: Path) -> None:
"""An uncached URL has no resolved source hash, so cached() reports nothing cached."""
url = "https://example.invalid/lecture.mp4"
assert await analysis.cached(url, settings=_settings(tmp_path)) is None
async def test_ask_uncached_url_raises_the_documented_diagnosis(tmp_path: Path) -> None:
"""A cache-only ask on an uncached URL names the front doors instead of leaking internals."""
url = "https://example.invalid/lecture.mp4"
with pytest.raises(RuntimeError) as excinfo:
await analysis.ask(url, "What happens?", AnalysisOptions(), settings=_settings(tmp_path))
message = str(excinfo.value)
assert "no cached analysis report" in message
assert "va analyse" in message
async def test_ask_without_a_cached_report_names_both_front_doors(tmp_path: Path) -> None:
source = _source(tmp_path)
with pytest.raises(RuntimeError) as excinfo:
await analysis.ask(
str(source), "What happens?", AnalysisOptions(), settings=_settings(tmp_path)
)
message = str(excinfo.value)
assert "Run analyze_video first" in message
assert "va analyse" in message
async def test_ask_no_cache_bypasses_the_answer_cache(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
source = _source(tmp_path)
fake = FakeStages()
settings = _settings(tmp_path)
await Pipeline(settings, fake.mapping()).run(str(source))
seen: list[Any] = []
async def fake_answer(
report: VideoReport,
question: str,
*,
settings: Settings,
cache: StageCache | None = None,
) -> AnswerResult:
seen.append(cache)
return AnswerResult(answer="answer", cached=cache is not None)
monkeypatch.setattr(synthesis_module, "answer_question_result", fake_answer)
await analysis.ask(str(source), "Why?", AnalysisOptions(no_cache=True), settings=settings)
await analysis.ask(str(source), "Why?", AnalysisOptions(no_cache=False), settings=settings)
assert seen[0] is None
assert isinstance(seen[1], StageCache)
# --------------------------------------------------------------------------- #
# explicit front-door parity (same options -> same behaviour)
# --------------------------------------------------------------------------- #
def test_transcribe_parity_follows_settings_diarize_in_both_doors(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
source = _source(tmp_path)
fake = FakeStages()
_patch_pipeline(monkeypatch, fake)
monkeypatch.setenv("VA_DIARIZE", "false")
result = CliRunner().invoke(
cli.app, ["transcribe", str(source), "--json"], env={"COLUMNS": "120", "TERM": "dumb"}
)
assert result.exit_code == 0, result.output
cli_calls = list(fake.calls)
assert "diarize" not in cli_calls
shutil.rmtree(tmp_path / "cache", ignore_errors=True)
fake.calls.clear()
async def call_mcp() -> Any:
from fastmcp import Client
async with Client(mcp_server.mcp) as client:
return await client.call_tool("transcribe_video", {"source": str(source)})
tool_result = asyncio.run(call_mcp())
assert tool_result.structured_content["speaker_turns"] == []
assert fake.calls == cli_calls
def test_ask_no_cache_parity_across_both_doors(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
source = _source(tmp_path)
fake = FakeStages()
settings = _settings(tmp_path)
asyncio.run(Pipeline(settings, fake.mapping()).run(str(source)))
seen: list[Any] = []
async def fake_answer(
report: VideoReport,
question: str,
*,
settings: Settings,
cache: StageCache | None = None,
) -> AnswerResult:
seen.append(cache)
return AnswerResult(answer="answer", cached=False)
monkeypatch.setattr(synthesis_module, "answer_question_result", fake_answer)
cli_result = CliRunner().invoke(
cli.app,
["ask", str(source), "Why?", "--no-cache", "--json"],
env={"COLUMNS": "120", "TERM": "dumb"},
)
assert cli_result.exit_code == 0, cli_result.output
assert seen[-1] is None
async def call_mcp() -> None:
from fastmcp import Client
async with Client(mcp_server.mcp) as client:
await client.call_tool(
"ask_video",
{"source": str(source), "question": "Why?", "no_cache": True},
)
asyncio.run(call_mcp())
assert seen[-1] is None
assert seen == [None, None]
def test_analyse_max_shots_and_no_describe_parity_across_both_doors(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""The third #9 divergence: --max-shots/--no-describe behave identically in both doors."""
source = _source(tmp_path)
fake = FakeStages()
_patch_pipeline(monkeypatch, fake)
cli_result = CliRunner().invoke(
cli.app,
[
"analyse",
str(source),
"--max-shots",
"8",
"--no-describe",
"--out",
str(tmp_path / "report.md"),
"--json",
],
env={"COLUMNS": "120", "TERM": "dumb"},
)
assert cli_result.exit_code == 0, cli_result.output
cli_calls = list(fake.calls)
assert "describe" not in cli_calls
assert fake.shot_options[-1].max_shots == 8
shutil.rmtree(tmp_path / "cache", ignore_errors=True)
fake.calls.clear()
async def call_mcp() -> Any:
from fastmcp import Client
async with Client(mcp_server.mcp) as client:
return await client.call_tool(
"analyze_video",
{"source": str(source), "max_shots": 8, "describe": False},
)
tool_result = asyncio.run(call_mcp())
assert tool_result.structured_content["source"] == str(source)
assert "describe" not in fake.calls
assert fake.shot_options[-1].max_shots == 8
assert fake.calls == cli_calls
# --------------------------------------------------------------------------- #
# real frame extraction (cheap media path, no model)
# --------------------------------------------------------------------------- #
def test_checked_int_is_the_one_bounded_integer_guard() -> None:
"""The guard rejects bools and out-of-range values with one message shape."""
assert checked_int(3, "count", minimum=1, maximum=8) == 3
assert checked_int(0, "count", minimum=0) == 0
with pytest.raises(ValueError, match="count must be an integer between 1 and 8"):
checked_int(9, "count", minimum=1, maximum=8)
with pytest.raises(ValueError, match="count must be an integer >= 0"):
checked_int(-1, "count", minimum=0)
with pytest.raises(ValueError, match="count must be an integer"):
checked_int(True, "count", minimum=0)
with pytest.raises(ValueError, match="count must be an integer"):
checked_int(1.5, "count", minimum=0)
async def test_moment_and_frame_reject_out_of_range_arguments(
sample_video: Path, tmp_path: Path
) -> None:
"""The public operations share the bounded-integer guard for their numeric knobs."""
settings = _settings(tmp_path)
options = AnalysisOptions(describe=False)
with pytest.raises(ValueError, match="max_frames must be an integer between 1 and 8"):
await analysis.moment(str(sample_video), 0.0, 1.0, options, settings=settings, max_frames=0)
with pytest.raises(ValueError, match="width must be an integer between 64 and 2048"):
await analysis.moment(str(sample_video), 0.0, 1.0, options, settings=settings, width=10)
with pytest.raises(ValueError, match="width must be an integer between 64 and 2048"):
await analysis.frame(str(sample_video), 1.0, settings=settings, width=4096)
async def test_frame_and_moment_use_real_ffmpeg_on_the_fixture(sample_video: Path) -> None:
single = await analysis.frame(str(sample_video), 2.5, settings=_settings(sample_video.parent))
assert single.timestamp == pytest.approx(2.5)
assert single.data[:2] == b"\xff\xd8"
result = await analysis.moment(
str(sample_video),
0.5,
4.0,
AnalysisOptions(describe=False),
settings=_settings(sample_video.parent),
max_frames=3,
width=320,
)
assert len(result.frames) == 3
assert result.frame_timestamps == sorted(result.frame_timestamps)
assert all(frame[:2] == b"\xff\xd8" for frame in result.frames)