Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
fix: check documentation links on pull requests
  • Loading branch information
hugosmoreira committed Sep 20, 2026
commit 26a3baa85bdf94779fce40b91fb974da129602c4
1 change: 1 addition & 0 deletions .github/workflows/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ CI/CD workflows for the Stickler project.
| `security.yaml` | push, PR | Bandit + ASH security scans; uploads `security-reports` artifact |
| `security-pr-comment.yaml` | `workflow_run` after Security Scan | Posts/updates the ASH summary as a PR comment |
| `docs.yml` | push to `main` (src/docs paths) | Deploys MkDocs site to GitHub Pages |
| `docs-check.yml` | PR | Builds docs and rejects broken internal links/anchors without deployment |
| `workflow.yml` | release published | Builds and publishes to PyPI and TestPyPI (trusted publishing via OIDC) |

## Conventions
Expand Down
24 changes: 24 additions & 0 deletions .github/workflows/docs-check.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: Check Documentation

on: [pull_request]

permissions:
contents: read

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Set up uv
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1
with:
python-version: "3.12"
- name: Install dependencies
run: uv sync --group docs --frozen
- name: Test documentation check
run: uv run --frozen pytest tests/test_docs_build.py
- name: Build and check documentation links
run: uv run --frozen python docs/check_links.py
15 changes: 14 additions & 1 deletion docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,19 @@ uv run mkdocs build

This generates the static site in `site/` and validates all internal links and references.

To run the pull-request check from the repository root:

```bash
uv run --frozen python docs/check_links.py
uv run --frozen pytest tests/test_docs_build.py
```

The checker builds the site and fails on MkDocs page/navigation warnings,
including missing pages, images, and heading anchors. Existing API-plugin
warnings remain visible but do not fail this check. Fatal build/configuration
errors still fail. External URLs are not fetched. The read-only `docs-check.yml`
workflow runs this check on every pull request; it never deploys the site.

## Deployment

The site is deployed to GitHub Pages automatically via GitHub Actions (`.github/workflows/docs.yml`) on pushes to `main` that modify files in `src/` or `docs/`. This ensures API reference docs stay current when Python source code changes. To deploy manually:
Expand All @@ -68,4 +81,4 @@ Automatic deployment is configured in `.github/workflows/docs.yml`. The workflow

---

> **Note**: A `Makefile` is provided for convenience with targets: `install`, `docs`, `build`, `deploy`, and `clean`.
> **Note**: A `Makefile` is provided for convenience with targets: `install`, `docs`, `build`, `deploy`, and `clean`.
70 changes: 70 additions & 0 deletions docs/check_links.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
"""Build docs, failing on MkDocs page/navigation warnings, not plugin warnings."""

import argparse
import logging
from pathlib import Path

from mkdocs.commands.build import build
from mkdocs.config import load_config
from mkdocs.exceptions import Abort


class _LinkWarnings(logging.Handler):
def __init__(self):
super().__init__(level=logging.WARNING)
self.count = 0

def emit(self, record):
self.count += 1


def check_links(config_file: str, site_dir: str | None = None) -> int:
"""Build a site and return nonzero for broken links; build errors propagate."""
config = load_config(config_file=config_file, site_dir=site_dir)
# Anchors default to INFO, which even a strict build does not reject.
config.validation.links.anchors = logging.WARNING
config.validation.links.not_found = logging.WARNING
config.validation.nav.not_found = logging.WARNING
counter = _LinkWarnings()
loggers = [
logging.getLogger(f"mkdocs.structure.{name}") for name in ("pages", "nav")
]
for logger in loggers:
logger.addHandler(counter)
try:
config.plugins.on_startup(command="build", dirty=False)
try:
build(config)
Comment on lines +59 to +61

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking. This re-creates the CLI's build sequence but skips its _enable_warnings(), so Python DeprecationWarnings from mkdocs or plugins never reach the mkdocs logger and aren't counted. That's a difference from mkdocs build --strict, which counts them, and the module docstring says this fails on MkDocs diagnostics. Worth either routing them the same way or noting the difference.

finally:
config.plugins.on_shutdown()
finally:
for logger in loggers:
logger.removeHandler(counter)
counter.close()
if counter.count:
logging.getLogger("mkdocs").error(
"Documentation link check failed: %d page/navigation warning(s).",
counter.count,
)
return 1
return 0


def main() -> int:
"""Run the same build-only check locally and in pull-request CI."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"-f", "--config-file", default=str(Path(__file__).with_name("mkdocs.yml"))
)
parser.add_argument("-d", "--site-dir")
args = parser.parse_args()
logging.basicConfig(level=logging.INFO, format="%(levelname)s - %(message)s")
try:
return check_links(args.config_file, args.site_dir)
except Abort as error:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should fix. Only Abort is caught, so a ConfigurationError (a missing file, or a YAML parse error) escapes as a raw traceback. check_links.py -f bad.yml, with nav: [ in the file, prints a full Python traceback ending in mkdocs.exceptions.ConfigurationError. Catching mkdocs.exceptions.MkDocsException, the base the CLI handles, gives a clean one-line error.

logging.getLogger("mkdocs").error("%s", error)
return 1


if __name__ == "__main__":
raise SystemExit(main())
1 change: 1 addition & 0 deletions tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ pytest tests/ -n auto
```
tests/
├── test_top_level_exports.py # Top-level package re-exports
├── test_docs_build.py # Real MkDocs link-check acceptance builds
├── structured_object_evaluator/ # Core evaluation tests
│ ├── test_structured_model.py # StructuredModel tests
│ ├── test_comparators.py # Comparator integration
Expand Down
165 changes: 165 additions & 0 deletions tests/test_docs_build.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
"""Exercise the documentation gate with real MkDocs builds (issue #355)."""

import logging
import re
import runpy
import subprocess
import sys
from pathlib import Path

import pytest
import yaml

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit. This module needs yaml, mkdocs and mkdocs-awesome-nav from the docs group, but imports them unconditionally. CI is fine because the default dev group includes docs, but under the documented test group alone it errors at collection instead of skipping. pytest.importorskip("mkdocs") (and the same for yaml) at the top would make it skip cleanly.


ROOT = Path(__file__).resolve().parents[1]
BUILD_COMMAND = [sys.executable, str(ROOT / "docs" / "check_links.py")]


@pytest.fixture
def docs_project(tmp_path):
docs = tmp_path / "docs"
docs.mkdir()
(docs / "other page.md").write_text("# Existing heading\n", encoding="utf-8")
config = {
"site_name": "Link gate fixture",
"theme": {"name": "mkdocs"},
"plugins": [],
}

def build(markdown="# Home\n", *, extra_config=None, hook=None):
(docs / "index.md").write_text(markdown, encoding="utf-8")
settings = {**config, **(extra_config or {})}
if hook:
(tmp_path / "fixture_hook.py").write_text(hook, encoding="utf-8")
settings["hooks"] = ["fixture_hook.py"]
config_file = tmp_path / "mkdocs.yml"
config_file.write_text(yaml.safe_dump(settings), encoding="utf-8")
return subprocess.run(
[*BUILD_COMMAND, "-f", str(config_file), "-d", str(tmp_path / "site")],
cwd=tmp_path,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=60,
)

return build


@pytest.mark.parametrize(
"markdown",
[
"# Home\n",
"# Home\n[Local](#home)",
"# Home\n[Other](other%20page.md#existing-heading)",
"# Home\n[External](https://example.invalid/not-fetched#heading)",
"# Home\n`[Example](missing.md)`",
],
)
def test_valid_docs_build(docs_project, markdown):
result = docs_project(markdown)
assert result.returncode == 0, result.stdout + result.stderr


@pytest.mark.parametrize(
("link", "diagnostic"),
[
("[Missing](missing.md)", "missing.md"),
("![Missing](missing.png)", "missing.png"),
("[Missing](#absent-heading)", "absent-heading"),
("[Missing](other%20page.md#absent-heading)", "absent-heading"),
],
)
def test_broken_links_fail(docs_project, link, diagnostic):
result = docs_project(f"# Home\n{link}\n")
output = result.stdout + result.stderr
assert diagnostic in output, output
assert result.returncode != 0, output


def test_missing_navigation_target_fails(docs_project):
result = docs_project(extra_config={"nav": [{"Home": "missing.md"}]})
output = result.stdout + result.stderr
assert "missing.md" in output, output
assert result.returncode != 0, output


def test_unrelated_warning_remains_visible_without_failing(docs_project):
result = docs_project(
hook="import logging\n"
"def on_pre_build(**kwargs):\n"
" logging.getLogger('mkdocs.plugins.fixture').warning('existing API warning')\n"
)
assert "existing API warning" in result.stdout + result.stderr
assert result.returncode == 0, result.stdout + result.stderr


def test_invalid_configuration_fails(docs_project):
result = docs_project(extra_config={"docs_dir": "not-a-directory"})
assert "not-a-directory" in result.stdout + result.stderr
assert result.returncode != 0


def test_build_exception_fails(docs_project):
result = docs_project(
hook="def on_pre_build(**kwargs):\n"
" raise RuntimeError('fixture build failure')\n"
)
assert "fixture build failure" in result.stdout + result.stderr
assert result.returncode != 0


@pytest.mark.parametrize("fail", [False, True])
def test_plugin_lifecycle_is_preserved(docs_project, fail):
result = docs_project(
hook="def on_startup(**kwargs):\n"
" print('fixture startup')\n"
"def on_shutdown():\n"
" print('fixture shutdown')\n"
"def on_pre_build(**kwargs):\n"
f" if {fail}: raise RuntimeError('fixture build failure')\n"
)
assert "fixture startup" in result.stdout
assert "fixture shutdown" in result.stdout
assert (result.returncode != 0) == fail


def test_repeated_builds_do_not_leak_warning_state(docs_project, tmp_path, caplog):
docs_project("# Home\n[Missing](missing.md)")
checker = runpy.run_path(str(ROOT / "docs" / "check_links.py"))["check_links"]
loggers = [
logging.getLogger(f"mkdocs.structure.{name}") for name in ("pages", "nav")
]
original_handlers = [list(logger.handlers) for logger in loggers]
with caplog.at_level(logging.INFO):
assert checker(str(tmp_path / "mkdocs.yml")) == 1
(tmp_path / "docs" / "index.md").write_text("# Home\n", encoding="utf-8")
assert checker(str(tmp_path / "mkdocs.yml")) == 0
docs_project(
hook="def on_pre_build(**kwargs):\n"
" raise RuntimeError('fixture build failure')\n"
)
with pytest.raises(RuntimeError, match="fixture build failure"):
checker(str(tmp_path / "mkdocs.yml"))
assert [logger.handlers for logger in loggers] == original_handlers


def test_pr_workflow_only_builds_with_read_permissions():
workflow = yaml.load(
(ROOT / ".github" / "workflows" / "docs-check.yml").read_text(encoding="utf-8"),
Loader=yaml.BaseLoader,
)
assert workflow["on"] == ["pull_request"]
assert workflow["permissions"] == {"contents": "read"}
steps = workflow["jobs"]["build"]["steps"]
assert "permissions" not in workflow["jobs"]["build"]
for step in steps:
if "uses" in step:
assert re.fullmatch(r"[\w/-]+@[0-9a-f]{40}", step["uses"])
commands = [step["run"] for step in steps if "run" in step]
assert commands == [
"uv sync --group docs --frozen",
"uv run --frozen pytest tests/test_docs_build.py",
"uv run --frozen python docs/check_links.py",
]
assert steps[0]["with"]["persist-credentials"] == "false"