"""Tests for .github/convert_html_docs.py — pdoc3 HTML to markdown converter.""" from __future__ import annotations import importlib import sys from pathlib import Path import pytest pytestmark = pytest.mark.docs # The module lives at .github/convert_html_docs.py which isn't a regular # package, so we load it by file path. _SCRIPT_PATH = Path(__file__).resolve().parents[2] / ".github" / "convert_html_docs.py" _spec = importlib.util.spec_from_file_location("convert_html_docs", _SCRIPT_PATH) assert _spec and _spec.loader _mod = importlib.util.module_from_spec(_spec) sys.modules["convert_html_docs"] = _mod _spec.loader.exec_module(_mod) ContentFingerprint = _mod.ContentFingerprint PageConverter = _mod.PageConverter convert_directory = _mod.convert_directory extract_fingerprint = _mod.extract_fingerprint map_link = _mod.map_link validate_links = _mod.validate_links validate_markdown = _mod.validate_markdown MINIMAL_MODULE_HTML = """\

Module livekit.agents.vad

""" NAMESPACE_HTML = """\

Namespace livekit

Sub-modules

livekit.agents

LiveKit Agents for Python

livekit.rtc
""" FUNCTION_HTML = """\

Module livekit.agents

LiveKit Agents for Python

Functions

def get_job_context() ‑ livekit.agents.job.JobContext
Expand source code
def get_job_context() -> JobContext:
    ctx = _JobContextVar.get(None)
    if ctx is None:
        raise RuntimeError(
            "no job context found"
        )
    return ctx

Get the current job context.

""" CLASS_HTML = """\

Module livekit.agents.vad

Classes

class VAD (*, capabilities: VADCapabilities)
Expand source code
class VAD(ABC):
    def __init__(self, *, capabilities: VADCapabilities) -> None:
        self._capabilities = capabilities

Base class for voice activity detection.

Ancestors

  • abc.ABC

Subclasses

  • livekit.plugins.silero.vad.VAD

Instance variables

prop capabilities : VADCapabilities
Expand source code
@property
def capabilities(self) -> VADCapabilities:
    return self._capabilities

Methods

def stream(self) ‑ VADStream
Expand source code
@abstractmethod
def stream(self) -> VADStream: ...

Inherited members

""" CLASS_VARIABLES_HTML = """\

Module livekit.agents

Classes

class APIError (message: str, *, body: object | None = None)

Raised when an API request failed.

Class variables

var message : str

The error message returned by the API.

var body : object | None

The API response body.

""" MULTILINE_SIG_HTML = """\

Module livekit.agents

Functions

def create_api_error(message: str = '',
*,
status: int,
request_id: str | None = None) ‑ APIStatusError

Create an error from HTTP status.

""" ADMONITION_HTML = """\

Module livekit.agents

Functions

def my_func()

Some description.

Note

This is an important note.

""" class TestMapLink: def test_with_fragment(self) -> None: assert map_link("llm.html#ChatContext") == "llm.md#ChatContext" def test_absolute_url_unchanged(self) -> None: assert map_link("https://docs.livekit.io") == "https://docs.livekit.io" def test_fragment_only_unchanged(self) -> None: assert map_link("#section") == "#section" def test_parent_index(self) -> None: assert map_link("../agents/index.html") == "../agents.md" def test_bare_index_html(self) -> None: """index.html alone (no directory prefix).""" result = map_link("index.html") assert result == "../index.md" class TestPageConverter: def test_minimal_module(self) -> None: """Empty module produces just a heading.""" md = PageConverter(MINIMAL_MODULE_HTML).convert() assert md.startswith("# Module `livekit.agents.vad`") # Should not have any section headings assert "## " not in md def test_submodules(self) -> None: """Sub-modules section renders as bullet list.""" md = PageConverter(NAMESPACE_HTML).convert() assert "## Sub-modules" in md assert "[`livekit.agents`]" in md assert "LiveKit Agents for Python" in md # Module without description should still be listed assert "[`livekit.rtc`]" in md def test_function_basic(self) -> None: """Function with source and description.""" md = PageConverter(FUNCTION_HTML).convert() assert "## Functions" in md assert "### `get_job_context`" in md assert "def get_job_context" in md assert "Get the current job context." in md # Source should be in details assert "
Source" in md assert "def get_job_context() -> JobContext:" in md def test_function_source_html_unescape(self) -> None: """HTML entities in source code are unescaped.""" md = PageConverter(FUNCTION_HTML).convert() # " should become " assert '"no job context found"' in md # > should become > assert "-> JobContext:" in md def test_multiline_signature(self) -> None: """Multi-line signatures with
tags.""" md = PageConverter(MULTILINE_SIG_HTML).convert() assert "### `create_api_error`" in md assert "def create_api_error" in md # Non-breaking hyphen ‑ (U+2011) should be normalized to - assert "- APIStatusError" in md def test_class_ancestors(self) -> None: md = PageConverter(CLASS_HTML).convert() assert "#### Ancestors" in md assert "- abc.ABC" in md def test_class_subclasses(self) -> None: md = PageConverter(CLASS_HTML).convert() assert "#### Subclasses" in md assert "- livekit.plugins.silero.vad.VAD" in md def test_class_instance_variables(self) -> None: md = PageConverter(CLASS_HTML).convert() assert "#### Instance variables" in md assert "`capabilities`" in md # Property source should be included assert "@property" in md def test_class_methods(self) -> None: md = PageConverter(CLASS_HTML).convert() assert "#### Methods" in md assert "`stream`" in md assert "@abstractmethod" in md def test_class_inherited_members(self) -> None: md = PageConverter(CLASS_HTML).convert() assert "#### Inherited members" in md assert "**EventEmitter**" in md assert "emit" in md assert "on" in md def test_class_variables(self) -> None: """Class variables section renders properly.""" md = PageConverter(CLASS_VARIABLES_HTML).convert() assert "#### Class variables" in md assert "`message`" in md assert "The error message returned by the API." in md assert "`body`" in md def test_admonition(self) -> None: """Admonitions convert to blockquotes.""" md = PageConverter(ADMONITION_HTML).convert() assert "> **Note:**" in md assert "important note" in md class TestValidation: def test_valid_markdown(self) -> None: """Converted markdown from same HTML should validate.""" md = PageConverter(FUNCTION_HTML).convert() fp = extract_fingerprint(FUNCTION_HTML) vr = validate_markdown(fp, md) assert vr.is_valid assert vr.score == 1.0 def test_class_validates(self) -> None: """Complex class HTML validates after conversion.""" md = PageConverter(CLASS_HTML).convert() fp = extract_fingerprint(CLASS_HTML) vr = validate_markdown(fp, md) assert vr.is_valid assert vr.score >= 0.9 def test_missing_identifier_fails(self) -> None: """Missing identifiers cause validation failure.""" fp = ContentFingerprint( identifiers=["livekit.agents.missing_func"], source_blocks=[], signatures=[], description_texts=[], ) vr = validate_markdown(fp, "# Some markdown without the identifier") assert not vr.is_valid assert "livekit.agents.missing_func" in vr.missing_identifiers def test_missing_signature_fails(self) -> None: """Missing signatures cause validation failure (gate).""" fp = ContentFingerprint( identifiers=[], source_blocks=[], signatures=["nonexistent_function"], description_texts=[], ) vr = validate_markdown(fp, "# No such function here") assert not vr.is_valid assert "nonexistent_function" in vr.missing_signatures def test_description_warning_only(self) -> None: """Low description overlap produces warnings but does NOT fail validation.""" fp = ContentFingerprint( identifiers=[], source_blocks=[], signatures=[], description_texts=[ "This is a very specific description about quantum computing algorithms" ], ) vr = validate_markdown(fp, "# Completely unrelated content about cooking recipes") # Should still be valid (descriptions are warning-only) assert vr.is_valid assert len(vr.description_warnings) > 0 def test_directory_conversion_preserves_api_content_and_internal_links(tmp_path: Path) -> None: input_dir = tmp_path / "html" output_dir = tmp_path / "markdown" pages = { "livekit/index.html": NAMESPACE_HTML, "livekit/agents/index.html": FUNCTION_HTML.replace( "Get the current job context.", 'Get the current job context. See voice detection.', ), "livekit/agents/vad.html": CLASS_HTML, "livekit/rtc/index.html": MINIMAL_MODULE_HTML.replace("livekit.agents.vad", "livekit.rtc"), } for relative_path, html in pages.items(): path = input_dir / relative_path path.parent.mkdir(parents=True, exist_ok=True) path.write_text(html, encoding="utf-8") assert convert_directory(input_dir, output_dir) == (len(pages), len(pages), 0) assert {str(path.relative_to(output_dir)) for path in output_dir.rglob("*.md")} == { "livekit.md", "livekit/agents.md", "livekit/agents/vad.md", "livekit/rtc.md", } functions = (output_dir / "livekit/agents.md").read_text(encoding="utf-8") assert "def get_job_context() -> JobContext:" in functions assert "Get the current job context." in functions assert "vad.md" in functions classes = (output_dir / "livekit/agents/vad.md").read_text(encoding="utf-8") assert "Base class for voice activity detection." in classes assert "@abstractmethod" in classes and "def stream(self) -> VADStream:" in classes result = validate_links(output_dir) assert result.broken == [] assert result.external == [] class TestValidateLinks: def test_broken_link_detected(self, tmp_path: Path) -> None: """A link to a missing file is detected.""" (tmp_path / "a.md").write_text("[link](missing.md)\n") result = validate_links(tmp_path) assert len(result.broken) == 1 assert result.broken[0][1] == "missing.md" def test_external_links_ignored(self, tmp_path: Path) -> None: """External URLs and anchors are not checked.""" (tmp_path / "a.md").write_text( "[ext](https://example.com) [anchor](#foo) [mailto](mailto:a@b.com)\n" ) result = validate_links(tmp_path) assert result.broken == [] assert result.external == [] def test_fragment_links(self, tmp_path: Path) -> None: """Links with fragments still check the file exists.""" (tmp_path / "a.md").write_text("[link](b.md#section)\n") (tmp_path / "b.md").write_text("# B\n") result = validate_links(tmp_path) assert result.broken == [] def test_known_external_href_classified(self, tmp_path: Path) -> None: """The exact known Pydantic href is classified as external when missing.""" # Nest source so ../concepts/models.md resolves inside the output tree # but points to a non-existent file. sub = tmp_path / "sub" sub.mkdir() (sub / "a.md").write_text("[Models](../concepts/models.md)\n") result = validate_links(tmp_path) assert result.broken == [] assert len(result.external) == 1 assert result.external[0][1] == "../concepts/models.md" def test_known_external_href_valid_if_exists(self, tmp_path: Path) -> None: """If a known-external href actually resolves to an existing file, it's valid.""" sub = tmp_path / "sub" sub.mkdir() concepts = tmp_path / "concepts" concepts.mkdir() (concepts / "models.md").write_text("# Models\n") (sub / "a.md").write_text("[Models](../concepts/models.md)\n") result = validate_links(tmp_path) assert result.broken == [] assert result.external == [] def test_escape_above_root_is_broken(self, tmp_path: Path) -> None: """Links resolving above the output root are broken, not external.""" (tmp_path / "a.md").write_text("[oops](../../oops.md)\n") result = validate_links(tmp_path) assert len(result.broken) == 1 assert result.broken[0][1] == "../../oops.md" assert result.external == [] def test_similar_but_not_exact_external_is_broken(self, tmp_path: Path) -> None: """A href similar to the known external but not exact is still broken.""" (tmp_path / "a.md").write_text("[link](../concepts/other.md)\n") result = validate_links(tmp_path) assert len(result.broken) == 1 assert result.external == []