|
| 1 | +import json |
| 2 | +import re |
| 3 | +import subprocess |
| 4 | +import sys |
| 5 | +from contextlib import contextmanager |
| 6 | +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 7 | +from pathlib import Path |
| 8 | +from threading import Thread |
| 9 | + |
| 10 | +import pytest |
| 11 | + |
| 12 | +from scripts.linkcheck import ( |
| 13 | + baseline_patterns, |
| 14 | + prepare_baseline, |
| 15 | + read_report, |
| 16 | + summarize, |
| 17 | +) |
| 18 | + |
| 19 | +ROOT = Path(__file__).resolve().parents[1] |
| 20 | + |
| 21 | + |
| 22 | +def write_report(path, records): |
| 23 | + path.write_text("".join(json.dumps(record) + "\n" for record in records)) |
| 24 | + |
| 25 | + |
| 26 | +@pytest.mark.parametrize("status", ["working", "broken", "redirected", "ignored"]) |
| 27 | +def test_exact_external_urls(tmp_path, status): |
| 28 | + url = "https://example.org/docs_(v1)?a=1&b=2" |
| 29 | + report = tmp_path / "output.json" |
| 30 | + write_report( |
| 31 | + report, |
| 32 | + [ |
| 33 | + {"uri": url, "status": status}, |
| 34 | + {"uri": url, "status": status}, |
| 35 | + {"uri": "/local/file", "status": "working"}, |
| 36 | + {"uri": "mailto:docs@example.org", "status": "unchecked"}, |
| 37 | + ], |
| 38 | + ) |
| 39 | + patterns = baseline_patterns(report) |
| 40 | + assert len(patterns) == 1 |
| 41 | + assert re.match(patterns[0], url) |
| 42 | + for other in ( |
| 43 | + url + "#missing-anchor", |
| 44 | + url + "&new=value", |
| 45 | + url + "/new-page", |
| 46 | + url.replace("example.org", "exampleXorg"), |
| 47 | + url + "\n", |
| 48 | + "/local/file", |
| 49 | + ): |
| 50 | + assert not re.match(patterns[0], other) |
| 51 | + |
| 52 | + |
| 53 | +@pytest.mark.parametrize( |
| 54 | + "content", ["not JSON", "[]", "null", "{}", '{"uri": 1, "status": "broken"}'] |
| 55 | +) |
| 56 | +def test_invalid_reports(tmp_path, content): |
| 57 | + report = tmp_path / "output.json" |
| 58 | + report.write_text(content) |
| 59 | + with pytest.raises(ValueError, match="output.json:1:"): |
| 60 | + read_report(report) |
| 61 | + |
| 62 | + |
| 63 | +def test_missing_and_empty_reports(tmp_path): |
| 64 | + report = tmp_path / "output.json" |
| 65 | + with pytest.raises(FileNotFoundError): |
| 66 | + read_report(report) |
| 67 | + report.write_text("\n") |
| 68 | + assert baseline_patterns(report) == [] |
| 69 | + |
| 70 | + |
| 71 | +def test_summary(tmp_path): |
| 72 | + report, summary = tmp_path / "output.json", tmp_path / "summary.md" |
| 73 | + write_report( |
| 74 | + report, |
| 75 | + [ |
| 76 | + {"uri": "https://example.org/ok", "status": "working"}, |
| 77 | + {"uri": "https://example.org/<bad>", "status": "broken", "info": "404"}, |
| 78 | + {"uri": "https://example.org/slow", "status": "timeout"}, |
| 79 | + ], |
| 80 | + ) |
| 81 | + summary.write_text("Existing summary\n") |
| 82 | + summarize(report, summary) |
| 83 | + text = summary.read_text() |
| 84 | + assert text.startswith("Existing summary\n") |
| 85 | + assert "2 failing URLs" in text |
| 86 | + assert "<bad>" in text |
| 87 | + assert "https://example.org/slow" in text |
| 88 | + assert "https://example.org/ok" not in text |
| 89 | + |
| 90 | + |
| 91 | +@pytest.fixture |
| 92 | +def server(): |
| 93 | + requests = [] |
| 94 | + |
| 95 | + class Handler(BaseHTTPRequestHandler): |
| 96 | + def do_HEAD(self): |
| 97 | + requests.append(self.path) |
| 98 | + self.send_response(200 if self.path.startswith("/ok") else 404) |
| 99 | + self.end_headers() |
| 100 | + |
| 101 | + def log_message(self, *args): |
| 102 | + pass |
| 103 | + |
| 104 | + with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as http: |
| 105 | + thread = Thread(target=http.serve_forever, daemon=True) |
| 106 | + thread.start() |
| 107 | + try: |
| 108 | + yield f"http://127.0.0.1:{http.server_port}", requests |
| 109 | + finally: |
| 110 | + http.shutdown() |
| 111 | + thread.join() |
| 112 | + |
| 113 | + |
| 114 | +def documentation(directory, text, *, base=False): |
| 115 | + source = directory / "source" |
| 116 | + source.mkdir() |
| 117 | + configuration = ( |
| 118 | + "import os, sys\n" |
| 119 | + f"sys.path.insert(0, {str(ROOT)!r})\n" |
| 120 | + "from pathlib import Path\n" |
| 121 | + "from scripts.linkcheck import baseline_patterns\n" |
| 122 | + "linkcheck_ignore = []\n" |
| 123 | + "if baseline := os.getenv('LINKCHECK_BASELINE'):\n" |
| 124 | + " linkcheck_ignore = baseline_patterns(Path(baseline))\n" |
| 125 | + "linkcheck_retries = 1\n" |
| 126 | + "linkcheck_timeout = 2\n" |
| 127 | + ) |
| 128 | + if base: |
| 129 | + configuration += ( |
| 130 | + "assert not os.getenv('LINKCHECK_BASELINE')\n" |
| 131 | + "assert not os.getenv('LINKCHECK_BASE_REF')\n" |
| 132 | + ) |
| 133 | + (source / "conf.py").write_text(configuration) |
| 134 | + (source / "index.rst").write_text("Links\n=====\n\n" + text) |
| 135 | + return source |
| 136 | + |
| 137 | + |
| 138 | +def sphinx(source, output): |
| 139 | + return subprocess.run( |
| 140 | + [ |
| 141 | + sys.executable, |
| 142 | + "-m", |
| 143 | + "sphinx", |
| 144 | + "-q", |
| 145 | + "-b", |
| 146 | + "linkcheck", |
| 147 | + "-d", |
| 148 | + str(output / "doctrees"), |
| 149 | + str(source), |
| 150 | + str(output), |
| 151 | + ], |
| 152 | + capture_output=True, |
| 153 | + text=True, |
| 154 | + check=False, |
| 155 | + ) |
| 156 | + |
| 157 | + |
| 158 | +def test_sphinx_checks_only_new_urls(tmp_path, server, monkeypatch): |
| 159 | + url, requests = server |
| 160 | + monkeypatch.delenv("LINKCHECK_BASELINE", raising=False) |
| 161 | + source = documentation(tmp_path, f"{url}/old-broken\n\n{url}/ok\n") |
| 162 | + full = tmp_path / "full" |
| 163 | + assert sphinx(source, full).returncode == 1 |
| 164 | + assert "/old-broken" in requests |
| 165 | + |
| 166 | + monkeypatch.setenv("LINKCHECK_BASELINE", str(full / "output.json")) |
| 167 | + requests.clear() |
| 168 | + with (source / "index.rst").open("a") as stream: |
| 169 | + stream.write(f"\n{url}/ok?new\n") |
| 170 | + result = sphinx(source, tmp_path / "filtered") |
| 171 | + assert result.returncode == 0, result.stdout + result.stderr |
| 172 | + assert requests == ["/ok?new"] |
| 173 | + |
| 174 | + requests.clear() |
| 175 | + with (source / "index.rst").open("a") as stream: |
| 176 | + stream.write(f"\n{url}/new-broken\n") |
| 177 | + assert sphinx(source, tmp_path / "new-broken").returncode == 1 |
| 178 | + assert "/new-broken" in requests |
| 179 | + assert "/old-broken" not in requests |
| 180 | + |
| 181 | + |
| 182 | +def git(*args): |
| 183 | + return subprocess.check_output(["git", *args], text=True).strip() |
| 184 | + |
| 185 | + |
| 186 | +@contextmanager |
| 187 | +def repository(tmp_path, monkeypatch): |
| 188 | + monkeypatch.chdir(tmp_path) |
| 189 | + git("init", "-q") |
| 190 | + git("add", "source") |
| 191 | + git( |
| 192 | + "-c", |
| 193 | + "user.name=Test", |
| 194 | + "-c", |
| 195 | + "user.email=test@example.org", |
| 196 | + "commit", |
| 197 | + "-qm", |
| 198 | + "Docs", |
| 199 | + ) |
| 200 | + yield git("rev-parse", "HEAD") |
| 201 | + assert git("worktree", "list", "--porcelain").count("worktree ") == 1 |
| 202 | + |
| 203 | + |
| 204 | +def test_generate_baseline_and_reuse_cache(tmp_path, server, monkeypatch): |
| 205 | + url, requests = server |
| 206 | + documentation(tmp_path, f"{url}/old-broken\n", base=True) |
| 207 | + report = tmp_path / "cache" / "baseline.jsonl" |
| 208 | + with repository(tmp_path, monkeypatch) as base: |
| 209 | + monkeypatch.setenv("LINKCHECK_BASELINE", "must-not-be-read") |
| 210 | + monkeypatch.setenv("LINKCHECK_BASE_REF", "must-not-be-read") |
| 211 | + prepare_baseline(base, report) |
| 212 | + assert read_report(report)[0]["uri"] == f"{url}/old-broken" |
| 213 | + assert "/old-broken" in requests |
| 214 | + requests.clear() |
| 215 | + prepare_baseline(base, report) |
| 216 | + assert not requests |
| 217 | + |
| 218 | + |
| 219 | +def test_baseline_failure_cleans_up_worktree(tmp_path, monkeypatch): |
| 220 | + source = documentation(tmp_path, "No links.\n") |
| 221 | + (source / "conf.py").write_text("raise RuntimeError('broken configuration')\n") |
| 222 | + with repository(tmp_path, monkeypatch) as base: |
| 223 | + report = tmp_path / "baseline.jsonl" |
| 224 | + with pytest.raises(subprocess.CalledProcessError): |
| 225 | + prepare_baseline(base, report) |
| 226 | + assert not report.exists() |
| 227 | + |
| 228 | + |
| 229 | +def test_fetch_baseline_in_shallow_checkout(tmp_path, server, monkeypatch): |
| 230 | + url, _ = server |
| 231 | + original = tmp_path / "original" |
| 232 | + original.mkdir() |
| 233 | + source = documentation(original, f"{url}/old-broken\n", base=True) |
| 234 | + with repository(original, monkeypatch) as base: |
| 235 | + (source / "index.rst").write_text("Current\n=======\n\nNo links.\n") |
| 236 | + git("add", "source") |
| 237 | + git( |
| 238 | + "-c", |
| 239 | + "user.name=Test", |
| 240 | + "-c", |
| 241 | + "user.email=test@example.org", |
| 242 | + "commit", |
| 243 | + "-qm", |
| 244 | + "Change docs", |
| 245 | + ) |
| 246 | + checkout = tmp_path / "shallow" |
| 247 | + git("clone", "--depth=1", original.as_uri(), str(checkout)) |
| 248 | + with monkeypatch.context() as context: |
| 249 | + context.chdir(checkout) |
| 250 | + with pytest.raises(subprocess.CalledProcessError): |
| 251 | + git("cat-file", "-e", base) |
| 252 | + report = tmp_path / "baseline.jsonl" |
| 253 | + prepare_baseline(base, report) |
| 254 | + assert read_report(report)[0]["uri"] == f"{url}/old-broken" |
| 255 | + assert git("worktree", "list", "--porcelain").count("worktree ") == 1 |
0 commit comments