#!/usr/bin/env python3 from __future__ import annotations import contextlib import importlib.util import io from pathlib import Path import socket import sys import tempfile import unittest from unittest import mock MODULE_PATH = Path(__file__).with_name("check-docs-links.py") SPEC = importlib.util.spec_from_file_location("check_docs_links", MODULE_PATH) if SPEC is None or SPEC.loader is None: raise ImportError(f"cannot load {MODULE_PATH}") check_docs_links = importlib.util.module_from_spec(SPEC) sys.modules[SPEC.name] = check_docs_links SPEC.loader.exec_module(check_docs_links) class DocsLinkCheckerTest(unittest.TestCase): def setUp(self) -> None: self.temporary_directory = tempfile.TemporaryDirectory() self.addCleanup(self.temporary_directory.cleanup) self.root = Path(self.temporary_directory.name) def write(self, relative: str, contents: str = "") -> Path: path = self.root / relative path.parent.mkdir(parents=True, exist_ok=True) path.write_text(contents, encoding="utf-8") return path def check(self, *paths: str, allowlist=None): selected = [Path(path) for path in paths] return check_docs_links.check(self.root, selected, allowlist) def run_main(self, *arguments: str) -> tuple[int, str]: output = io.StringIO() with contextlib.redirect_stdout(output): result = check_docs_links.main(list(arguments)) return result, output.getvalue() def test_relative_dot_parent_url_decoding_and_external_links(self) -> None: self.write("docs/guide/start.md", "[a](./next.md) [b](../other.md)\n") self.write("docs/guide/next.md", "[up](../guide/start.md)\n") self.write("docs/other.md", "[space]()\n") self.write("docs/space file.md", "") self.write( "docs/external.md", "[web](https://example.invalid/missing) [http](http://example.invalid) " "[mail](mailto:test@example.invalid) [old](/tmp/evidence.txt)\n", ) diagnostics, file_count, link_count = self.check("docs") self.assertEqual([], diagnostics) self.assertEqual(5, file_count) self.assertEqual(8, link_count) def test_percent_encoded_cyrillic_path_and_anchors(self) -> None: encoded_name = "%D0%BF%D0%BB%D0%B0%D0%BD%20%D1%80%D0%B0%D0%B1%D0%BE%D1%82.md" encoded_anchor = "#%D1%86%D0%B5%D0%BB%D1%8C-%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82%D0%B0" self.write("docs/index.md", f"[plan]({encoded_name}{encoded_anchor})\n") self.write("docs/план работ.md", "# Цель проекта\n") diagnostics, _, _ = self.check() self.assertEqual([], diagnostics) def test_heading_slugs_duplicates_and_inline_markup(self) -> None: self.write( "docs/target.md", "# Hello, *world*!\n# Hello, world!\n# Раздел с пробелами\n", ) self.write( "docs/source.md", "[first](target.md#hello-world) [second](target.md#hello-world-1) " "[cyrillic](target.md#раздел-с-пробелами)\n", ) diagnostics, _, _ = self.check() self.assertEqual([], diagnostics) def test_broken_file_has_precise_diagnostic_and_exit_one(self) -> None: self.write("docs/source.md", "prefix\n[broken](../missing.md)\n") result, output = self.run_main("--root", str(self.root), "docs") self.assertEqual(1, result) self.assertIn("docs/source.md:2 → ../missing.md (target does not exist)", output) self.assertIn("1 broken links", output) def test_broken_anchor_is_distinct_from_broken_file(self) -> None: self.write("docs/target.md", "# Existing heading\n") self.write("docs/source.md", "[broken](target.md#missing-heading)\n") diagnostics, _, _ = self.check() self.assertEqual(1, len(diagnostics)) self.assertEqual("anchor does not exist", diagnostics[0].reason) self.assertEqual(1, diagnostics[0].line) def test_source_line_anchor_only_requires_existing_file(self) -> None: self.write("apps/desktop/src/lib.rs", "pub fn example() {}\n") self.write("docs/source.md", "[line](../apps/desktop/src/lib.rs#L1)\n") diagnostics, _, _ = self.check() self.assertEqual([], diagnostics) def test_allowlist_requires_exact_source_and_target(self) -> None: self.write( "docs/source.md", "[old](/not-checked.md) [bad](missing.md) [different](other-missing.md)\n", ) self.write("docs/other.md", "[bad](missing.md)\n") allowed = {("docs/source.md", "missing.md")} diagnostics, _, _ = self.check(allowlist=allowed) self.assertEqual(2, len(diagnostics)) self.assertEqual( { (self.root / "docs/source.md", "other-missing.md"), (self.root / "docs/other.md", "missing.md"), }, {(item.source, item.target) for item in diagnostics}, ) def test_public_mode_rejects_all_allowlist_entries(self) -> None: self.write("README.md", "[bad](missing.md)\n") error_output = io.StringIO() with contextlib.redirect_stderr(error_output), self.assertRaises(SystemExit) as raised: check_docs_links.main( ["--root", str(self.root), "--public", "--allow", "README.md=missing.md"] ) self.assertEqual(2, raised.exception.code) self.assertIn("does not permit --allow", error_output.getvalue()) def test_malformed_links_do_not_crash(self) -> None: self.write( "docs/source.md", "[unclosed](target.md\n[unclosed bracket](x[y]\n" "[bad percent](bad%ZZ.md) [bad url](relative.md#[) " "[bad title]( junk)\n", ) diagnostics, _, _ = self.check() self.assertEqual(2, len(diagnostics)) self.assertTrue(all(item.line == 3 for item in diagnostics)) def test_code_fences_inline_code_and_unknown_references_are_ignored(self) -> None: self.write( "docs/source.md", "```md\n[broken](missing.md)\n```\n" "`[broken](inline.md)`\n[not a reference][unknown]\n", ) diagnostics, _, link_count = self.check() self.assertEqual([], diagnostics) self.assertEqual(0, link_count) def test_reference_links_and_titles_are_checked(self) -> None: self.write("docs/target file.md", "# Heading\n") self.write( "docs/source.md", "[inline]( \"title\")\n" "[reference][target]\n[target]: 'title'\n", ) diagnostics, _, link_count = self.check() self.assertEqual([], diagnostics) self.assertEqual(2, link_count) def test_external_links_never_open_a_socket(self) -> None: self.write("README.md", "[web](https://example.invalid) [mail](mailto:a@example.invalid)\n") with mock.patch.object(socket, "socket", side_effect=AssertionError("network access")): diagnostics, _, link_count = self.check() self.assertEqual([], diagnostics) self.assertEqual(2, link_count) def test_link_cannot_escape_explicit_root(self) -> None: outside = self.root.parent / "outside-check-docs-links.md" outside.write_text("", encoding="utf-8") self.addCleanup(outside.unlink) self.write("docs/source.md", "[outside](../../outside-check-docs-links.md)\n") diagnostics, _, _ = self.check() self.assertEqual(1, len(diagnostics)) self.assertIn("outside root", diagnostics[0].reason) if __name__ == "__main__": unittest.main()