Debian Codegraph @

tests/test_builders/test_build_linkcheck.py

raw
1 """Test the build process with manpage builder with the test root."""
2
3 from __future__ import annotations
4
5 import json
6 import re
7 import sys
8 import textwrap
9 import time
10 import wsgiref.handlers
11 from base64 import b64encode
12 from http.server import BaseHTTPRequestHandler
13 from io import StringIO
14 from queue import Queue
15 from typing import TYPE_CHECKING
16 from unittest import mock
17
18 import pytest
19 from urllib3.poolmanager import PoolManager
20
21 import sphinx.util.http_date
22 from sphinx._cli.util.errors import strip_escape_sequences
23 from sphinx.builders.linkcheck import (
24 CheckRequest,
25 Hyperlink,
26 HyperlinkAvailabilityCheckWorker,
27 RateLimit,
28 compile_linkcheck_allowed_redirects,
29 )
30 from sphinx.errors import ConfigError
31 from sphinx.testing.util import SphinxTestApp
32 from sphinx.util import requests
33 from sphinx.util._pathlib import _StrPath
34
35 from tests.utils import CERT_FILE, serve_application
36
37 ts_re = re.compile(r'.*\[(?P<ts>.*)\].*')
38
39 if TYPE_CHECKING:
40 from collections.abc import Callable, Iterable
41 from pathlib import Path
42 from typing import Any, Self
43
44 from urllib3 import HTTPConnectionPool
45
46 from sphinx.builders.linkcheck import (
47 CheckResult,
48 )
49 from sphinx.testing.util import SphinxTestApp
50
51
52 class DefaultsHandler(BaseHTTPRequestHandler):
53 protocol_version = 'HTTP/1.1'
54
55 def do_HEAD(self) -> None:
56 if self.path[1:].rstrip() in {'', 'anchor.html'}:
57 self.send_response(200, 'OK')
58 self.send_header('Content-Length', '0')
59 self.end_headers()
60 else:
61 self.send_response(404, 'Not Found')
62 self.send_header('Content-Length', '0')
63 self.end_headers()
64
65 def do_GET(self) -> None:
66 if self.path[1:].rstrip() == '':
67 content = b'ok\n\n'
68 elif self.path[1:].rstrip() == 'anchor.html':
69 doc = '<!DOCTYPE html><html><body><a id="found"></a></body></html>'
70 content = doc.encode('utf-8')
71 else:
72 content = b''
73
74 if content:
75 self.send_response(200, 'OK')
76 self.send_header('Content-Length', str(len(content)))
77 self.end_headers()
78 self.wfile.write(content)
79 else:
80 self.send_response(404, 'Not Found')
81 self.send_header('Content-Length', '0')
82 self.end_headers()
83
84
85 class ConnectionMeasurement:
86 """Measure the number of distinct host connections created during linkchecking"""
87
88 def __init__(self) -> None:
89 self.connections: set[HTTPConnectionPool] = set()
90 self.urllib3_connection_from_url = PoolManager.connection_from_url
91 self.patcher = mock.patch.object(
92 target=PoolManager,
93 attribute='connection_from_url',
94 new=self._collect_connections(),
95 )
96
97 def _collect_connections(self) -> Callable[[PoolManager, str], HTTPConnectionPool]:
98 def connection_collector(obj: PoolManager, url: str) -> HTTPConnectionPool:
99 connection = self.urllib3_connection_from_url(obj, url) # type: ignore[no-untyped-call]
100 self.connections.add(connection)
101 return connection
102
103 return connection_collector
104
105 def __enter__(self) -> Self:
106 self.patcher.start()
107 return self
108
109 def __exit__(self, *args: object, **kwargs: Any) -> None:
110 for connection in self.connections:
111 connection.close()
112 self.patcher.stop()
113
114 @property
115 def connection_count(self) -> int:
116 return len(self.connections)
117
118
119 @pytest.mark.sphinx(
120 'linkcheck',
121 testroot='linkcheck',
122 freshenv=True,
123 )
124 def test_defaults(app: SphinxTestApp) -> None:
125 with serve_application(app, DefaultsHandler) as address:
126 with ConnectionMeasurement() as m:
127 app.build()
128 assert m.connection_count <= 5
129
130 # Text output
131 assert (app.outdir / 'output.txt').exists()
132 content = (app.outdir / 'output.txt').read_text(encoding='utf8')
133
134 # looking for '#top' and '#does-not-exist' not found should fail
135 assert "Anchor 'top' not found" in content
136 assert "Anchor 'does-not-exist' not found" in content
137 # images should fail
138 assert f'Not Found for url: http://{address}/image.png' in content
139 assert f'Not Found for url: http://{address}/image2.png' in content
140 # looking for missing local file should fail
141 assert '[broken] path/to/notfound' in content
142 assert len(content.splitlines()) == 5
143
144 # JSON output
145 assert (app.outdir / 'output.json').exists()
146 content = (app.outdir / 'output.json').read_text(encoding='utf8')
147
148 rows = [json.loads(x) for x in content.splitlines()]
149 row = rows[0]
150 for attr in ('filename', 'lineno', 'status', 'code', 'uri', 'info'):
151 assert attr in row
152
153 assert len(content.splitlines()) == 10
154 assert len(rows) == 10
155 # the output order of the rows is not stable
156 # due to possible variance in network latency
157 rowsby = {row['uri']: row for row in rows}
158 # looking for local file that exists should succeed
159 assert rowsby['conf.py']['status'] == 'working'
160 assert rowsby[f'http://{address}#!bar'] == {
161 'filename': 'links.rst',
162 'lineno': 5,
163 'status': 'working',
164 'code': 0,
165 'uri': f'http://{address}#!bar',
166 'info': '',
167 }
168
169 def _missing_resource(filename: str, lineno: int) -> dict[str, str | int]:
170 return {
171 'filename': 'links.rst',
172 'lineno': lineno,
173 'status': 'broken',
174 'code': 0,
175 'uri': f'http://{address}/{filename}',
176 'info': f'404 Client Error: Not Found for url: http://{address}/{filename}',
177 }
178
179 assert rowsby[f'http://{address}/image2.png'] == _missing_resource('image2.png', 12)
180 # looking for '#top' and '#does-not-exist' not found should fail
181 assert rowsby[f'http://{address}/#top']['info'] == "Anchor 'top' not found"
182 assert rowsby[f'http://{address}/#top']['status'] == 'broken'
183 assert (
184 rowsby[f'http://{address}#does-not-exist']['info']
185 == "Anchor 'does-not-exist' not found"
186 )
187 # images should fail
188 assert (
189 f'Not Found for url: http://{address}/image.png'
190 in rowsby[f'http://{address}/image.png']['info']
191 )
192 # anchor should be found
193 assert rowsby[f'http://{address}/anchor.html#found'] == {
194 'filename': 'links.rst',
195 'lineno': 14,
196 'status': 'working',
197 'code': 0,
198 'uri': f'http://{address}/anchor.html#found',
199 'info': '',
200 }
201
202
203 @pytest.mark.sphinx(
204 'linkcheck',
205 testroot='linkcheck',
206 freshenv=True,
207 confoverrides={'linkcheck_anchors': False},
208 )
209 def test_check_link_response_only(app: SphinxTestApp) -> None:
210 with serve_application(app, DefaultsHandler) as address:
211 app.build()
212
213 # JSON output
214 assert (app.outdir / 'output.json').exists()
215 content = (app.outdir / 'output.json').read_text(encoding='utf8')
216
217 rows = [json.loads(x) for x in content.splitlines()]
218 rowsby = {row['uri']: row for row in rows}
219 assert rowsby[f'http://{address}/#top']['status'] == 'working'
220
221
222 @pytest.mark.sphinx(
223 'linkcheck',
224 testroot='linkcheck-too-many-retries',
225 freshenv=True,
226 )
227 def test_too_many_retries(app: SphinxTestApp) -> None:
228 with serve_application(app, DefaultsHandler) as address:
229 app.build()
230
231 # Text output
232 assert (app.outdir / 'output.txt').exists()
233 content = (app.outdir / 'output.txt').read_text(encoding='utf8')
234
235 # looking for non-existent URL should fail
236 assert ' Max retries exceeded with url: /doesnotexist' in content
237
238 # JSON output
239 assert (app.outdir / 'output.json').exists()
240 content = (app.outdir / 'output.json').read_text(encoding='utf8')
241
242 assert len(content.splitlines()) == 1
243 row = json.loads(content)
244 # the output order of the rows is not stable
245 # due to possible variance in network latency
246
247 # looking for non-existent URL should fail
248 assert row['filename'] == 'index.rst'
249 assert row['lineno'] == 1
250 assert row['status'] == 'broken'
251 assert row['code'] == 0
252 assert row['uri'] == f'https://{address}/doesnotexist'
253
254
255 @pytest.mark.sphinx(
256 'linkcheck',
257 testroot='linkcheck-raw-node',
258 freshenv=True,
259 copy_test_root=True,
260 )
261 def test_raw_node(app: SphinxTestApp) -> None:
262 with serve_application(app, OKHandler) as address:
263 # write an index file that contains a link back to this webserver's root
264 # URL. docutils will replace the raw node with the contents retrieved..
265 # ..and then the linkchecker will check that the root URL is available.
266 index = app.srcdir / 'index.rst'
267 index.write_text(
268 f".. raw:: 'html'\n :url: http://{address}/",
269 encoding='utf-8',
270 )
271 app.build()
272
273 # JSON output
274 assert (app.outdir / 'output.json').exists()
275 content = (app.outdir / 'output.json').read_text(encoding='utf8')
276
277 assert len(content.splitlines()) == 1
278 row = json.loads(content)
279
280 # raw nodes' url should be checked too
281 assert row == {
282 'filename': 'index.rst',
283 'lineno': 1,
284 'status': 'working',
285 'code': 0,
286 'uri': f'http://{address}/', # the received rST contains a link to its' own URL
287 'info': '',
288 }
289
290
291 @pytest.mark.sphinx(
292 'linkcheck',
293 testroot='linkcheck-anchors-ignore',
294 freshenv=True,
295 confoverrides={'linkcheck_anchors_ignore': ['^!', '^top$']},
296 )
297 def test_anchors_ignored(app: SphinxTestApp) -> None:
298 with serve_application(app, OKHandler):
299 app.build()
300
301 assert (app.outdir / 'output.txt').exists()
302 content = (app.outdir / 'output.txt').read_text(encoding='utf8')
303
304 # expect all ok when excluding #top
305 assert not content
306
307
308 class AnchorsIgnoreForUrlHandler(BaseHTTPRequestHandler):
309 protocol_version = 'HTTP/1.1'
310
311 def _chunk_content(self, content: str, *, max_chunk_size: int) -> Iterable[bytes]:
312 def _encode_chunk(chunk: bytes) -> Iterable[bytes]:
313 """Encode a bytestring into a format suitable for HTTP chunked-transfer.
314
315 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding
316 """
317 yield f'{len(chunk):X}'.encode('ascii')
318 yield b'\r\n'
319 yield chunk
320 yield b'\r\n'
321
322 buffer = b''
323 for char in content:
324 buffer += char.encode('utf-8')
325 if len(buffer) >= max_chunk_size:
326 chunk, buffer = buffer[:max_chunk_size], buffer[max_chunk_size:]
327 yield from _encode_chunk(chunk)
328
329 # Flush remaining bytes, if any
330 if buffer:
331 yield from _encode_chunk(buffer)
332
333 # Emit a final empty chunk to close the stream
334 yield from _encode_chunk(b'')
335
336 def _send_chunked(self, content: str) -> bool:
337 for chunk in self._chunk_content(content, max_chunk_size=20):
338 try:
339 self.wfile.write(chunk)
340 except (BrokenPipeError, ConnectionResetError) as e:
341 self.log_message(str(e))
342 return False
343 return True
344
345 def do_HEAD(self) -> None:
346 if self.path in {'/valid', '/ignored'}:
347 self.send_response(200, 'OK')
348 else:
349 self.send_response(404, 'Not Found')
350 self.end_headers()
351
352 def do_GET(self) -> None:
353 if self.path == '/valid':
354 self.send_response(200, 'OK')
355 content = "<h1 id='valid-anchor'>valid anchor</h1>\n"
356 elif self.path == '/ignored':
357 self.send_response(200, 'OK')
358 content = 'no anchor but page exists\n'
359 else:
360 self.send_response(404, 'Not Found')
361 content = 'not found\n'
362 self.send_header('Transfer-Encoding', 'chunked')
363 self.end_headers()
364 self._send_chunked(content)
365
366
367 @pytest.mark.sphinx(
368 'linkcheck',
369 testroot='linkcheck-anchors-ignore-for-url',
370 freshenv=True,
371 )
372 def test_anchors_ignored_for_url(app: SphinxTestApp) -> None:
373 with serve_application(app, AnchorsIgnoreForUrlHandler) as address:
374 app.config.linkcheck_anchors_ignore_for_url = [
375 f'http://{address}/ignored', # existing page
376 f'http://{address}/invalid', # unknown page
377 ]
378 app.build()
379
380 assert (app.outdir / 'output.txt').exists()
381 content = (app.outdir / 'output.json').read_text(encoding='utf8')
382
383 attrs = ('filename', 'lineno', 'status', 'code', 'uri', 'info')
384 data = [json.loads(x) for x in content.splitlines()]
385 assert len(data) == 8
386 assert all(all(attr in row for attr in attrs) for row in data)
387
388 # rows may be unsorted due to network latency or
389 # the order the threads are processing the links
390 rows = {r['uri']: {'status': r['status'], 'info': r['info']} for r in data}
391
392 assert rows[f'http://{address}/valid']['status'] == 'working'
393 assert rows[f'http://{address}/valid#valid-anchor']['status'] == 'working'
394 assert rows[f'http://{address}/valid#py:module::urllib.parse']['status'] == 'broken'
395 assert rows[f'http://{address}/valid#invalid-anchor'] == {
396 'status': 'broken',
397 'info': "Anchor 'invalid-anchor' not found",
398 }
399
400 assert rows[f'http://{address}/ignored']['status'] == 'working'
401 assert rows[f'http://{address}/ignored#invalid-anchor']['status'] == 'working'
402
403 assert rows[f'http://{address}/invalid'] == {
404 'status': 'broken',
405 'info': f'404 Client Error: Not Found for url: http://{address}/invalid',
406 }
407 assert rows[f'http://{address}/invalid#anchor'] == {
408 'status': 'broken',
409 'info': f'404 Client Error: Not Found for url: http://{address}/invalid',
410 }
411
412
413 @pytest.mark.sphinx(
414 'linkcheck',
415 testroot='linkcheck-localserver-anchor',
416 freshenv=True,
417 )
418 def test_raises_for_invalid_status(app: SphinxTestApp) -> None:
419 class InternalServerErrorHandler(BaseHTTPRequestHandler):
420 protocol_version = 'HTTP/1.1'
421
422 def do_GET(self) -> None:
423 self.send_error(500, 'Internal Server Error')
424
425 with serve_application(app, InternalServerErrorHandler) as address:
426 app.build()
427 content = (app.outdir / 'output.txt').read_text(encoding='utf8')
428 assert content == (
429 f'index.rst:1: [broken] http://{address}/#anchor: '
430 '500 Server Error: Internal Server Error '
431 f'for url: http://{address}/\n'
432 )
433
434
435 @pytest.mark.sphinx(
436 'linkcheck',
437 testroot='linkcheck-localserver-anchor',
438 freshenv=True,
439 )
440 def test_incomplete_html_anchor(app: SphinxTestApp) -> None:
441 class IncompleteHTMLDocumentHandler(BaseHTTPRequestHandler):
442 protocol_version = 'HTTP/1.1'
443
444 def do_GET(self) -> None:
445 content = b'this is <div id="anchor">not</div> a valid HTML document'
446 self.send_response(200, 'OK')
447 self.send_header('Content-Length', str(len(content)))
448 self.end_headers()
449 self.wfile.write(content)
450
451 with serve_application(app, IncompleteHTMLDocumentHandler):
452 app.build()
453
454 content = (app.outdir / 'output.json').read_text(encoding='utf8')
455 assert len(content.splitlines()) == 1
456
457 row = json.loads(content)
458 assert row['status'] == 'working'
459
460
461 @pytest.mark.sphinx(
462 'linkcheck',
463 testroot='linkcheck-localserver-anchor',
464 freshenv=True,
465 )
466 def test_decoding_error_anchor_ignored(app: SphinxTestApp) -> None:
467 class NonASCIIHandler(BaseHTTPRequestHandler):
468 protocol_version = 'HTTP/1.1'
469
470 def do_GET(self) -> None:
471 content = b'\x80\x00\x80\x00' # non-ASCII byte-string
472 self.send_response(200, 'OK')
473 self.send_header('Content-Length', str(len(content)))
474 self.end_headers()
475 self.wfile.write(content)
476
477 with serve_application(app, NonASCIIHandler):
478 app.build()
479
480 content = (app.outdir / 'output.json').read_text(encoding='utf8')
481 assert len(content.splitlines()) == 1
482
483 row = json.loads(content)
484 assert row['status'] == 'ignored'
485
486
487 def custom_handler(
488 valid_credentials: tuple[str, str] | None = None,
489 success_criteria: Callable[[BaseHTTPRequestHandler], bool] = lambda _: True,
490 ) -> type[BaseHTTPRequestHandler]:
491 """Returns an HTTP request handler that authenticates the client and then determines
492 an appropriate HTTP response code, based on caller-provided credentials and optional
493 success criteria, respectively.
494 """
495 expected_token = None
496 if valid_credentials:
497 assert len(valid_credentials) == 2, 'expected a pair of strings as credentials'
498 expected_token = b64encode(':'.join(valid_credentials).encode()).decode('utf-8')
499 del valid_credentials
500
501 def authenticated(
502 method: Callable[[CustomHandler], None],
503 ) -> Callable[[CustomHandler], None]:
504 def method_if_authenticated(self: CustomHandler) -> None:
505 if expected_token is None:
506 return method(self)
507 elif not self.headers['Authorization']:
508 self.send_response(401, 'Unauthorized')
509 self.end_headers()
510 elif self.headers['Authorization'] == f'Basic {expected_token}':
511 return method(self)
512 else:
513 self.send_response(403, 'Forbidden')
514 self.send_header('Content-Length', '0')
515 self.end_headers()
516 return None
517
518 return method_if_authenticated
519
520 class CustomHandler(BaseHTTPRequestHandler):
521 protocol_version = 'HTTP/1.1'
522
523 @authenticated
524 def do_HEAD(self) -> None:
525 self.do_GET()
526
527 @authenticated
528 def do_GET(self) -> None:
529 if success_criteria(self):
530 self.send_response(200, 'OK')
531 self.send_header('Content-Length', '0')
532 else:
533 self.send_response(400, 'Bad Request')
534 self.send_header('Content-Length', '0')
535 self.end_headers()
536
537 return CustomHandler
538
539
540 @pytest.mark.sphinx(
541 'linkcheck',
542 testroot='linkcheck-localserver',
543 freshenv=True,
544 )
545 def test_auth_header_uses_first_match(app: SphinxTestApp) -> None:
546 with serve_application(
547 app, custom_handler(valid_credentials=('user1', 'password'))
548 ) as address:
549 app.config.linkcheck_auth = [
550 (r'^$', ('no', 'match')),
551 (rf'^http://{re.escape(address)}/$', ('user1', 'password')),
552 (r'.*local.*', ('user2', 'hunter2')),
553 ]
554 app.build()
555
556 with open(app.outdir / 'output.json', encoding='utf-8') as fp:
557 content = json.load(fp)
558
559 assert content['status'] == 'working'
560
561
562 @pytest.mark.sphinx(
563 'linkcheck',
564 testroot='linkcheck-localserver',
565 freshenv=True,
566 confoverrides={'linkcheck_allow_unauthorized': False},
567 )
568 def test_unauthorized_broken(app: SphinxTestApp) -> None:
569 with serve_application(
570 app, custom_handler(valid_credentials=('user1', 'password'))
571 ):
572 app.build()
573
574 with open(app.outdir / 'output.json', encoding='utf-8') as fp:
575 content = json.load(fp)
576
577 assert content['info'] == 'unauthorized'
578 assert content['status'] == 'broken'
579
580
581 @pytest.mark.sphinx(
582 'linkcheck',
583 testroot='linkcheck-localserver',
584 freshenv=True,
585 confoverrides={'linkcheck_auth': [(r'^$', ('user1', 'password'))]},
586 )
587 def test_auth_header_no_match(app: SphinxTestApp) -> None:
588 with serve_application(
589 app, custom_handler(valid_credentials=('user1', 'password'))
590 ):
591 app.build()
592
593 with open(app.outdir / 'output.json', encoding='utf-8') as fp:
594 content = json.load(fp)
595
596 assert content['info'] == 'unauthorized'
597 assert content['status'] == 'broken'
598
599
600 @pytest.mark.sphinx(
601 'linkcheck',
602 testroot='linkcheck-localserver',
603 freshenv=True,
604 )
605 def test_linkcheck_request_headers(app: SphinxTestApp) -> None:
606 def check_headers(self: BaseHTTPRequestHandler) -> bool:
607 if 'X-Secret' in self.headers:
608 return False
609 return self.headers['Accept'] == 'text/html'
610
611 with serve_application(
612 app, custom_handler(success_criteria=check_headers)
613 ) as address:
614 app.config.linkcheck_request_headers = {
615 f'http://{address}/': {'Accept': 'text/html'},
616 '*': {'X-Secret': 'open sesami'},
617 }
618 app.build()
619
620 with open(app.outdir / 'output.json', encoding='utf-8') as fp:
621 content = json.load(fp)
622
623 assert content['status'] == 'working'
624
625
626 @pytest.mark.sphinx(
627 'linkcheck',
628 testroot='linkcheck-localserver',
629 freshenv=True,
630 )
631 def test_linkcheck_request_headers_no_slash(app: SphinxTestApp) -> None:
632 def check_headers(self: BaseHTTPRequestHandler) -> bool:
633 if 'X-Secret' in self.headers:
634 return False
635 return self.headers['Accept'] == 'application/json'
636
637 with serve_application(
638 app, custom_handler(success_criteria=check_headers)
639 ) as address:
640 app.config.linkcheck_request_headers = {
641 f'http://{address}': {'Accept': 'application/json'},
642 '*': {'X-Secret': 'open sesami'},
643 }
644 app.build()
645
646 with open(app.outdir / 'output.json', encoding='utf-8') as fp:
647 content = json.load(fp)
648
649 assert content['status'] == 'working'
650
651
652 @pytest.mark.sphinx(
653 'linkcheck',
654 testroot='linkcheck-localserver',
655 freshenv=True,
656 confoverrides={
657 'linkcheck_request_headers': {
658 'http://do.not.match.org': {'Accept': 'application/json'},
659 '*': {'X-Secret': 'open sesami'},
660 }
661 },
662 )
663 def test_linkcheck_request_headers_default(app: SphinxTestApp) -> None:
664 def check_headers(self: BaseHTTPRequestHandler) -> bool:
665 if self.headers['X-Secret'] != 'open sesami':
666 return False
667 return self.headers['Accept'] != 'application/json'
668
669 with serve_application(app, custom_handler(success_criteria=check_headers)):
670 app.build()
671
672 with open(app.outdir / 'output.json', encoding='utf-8') as fp:
673 content = json.load(fp)
674
675 assert content['status'] == 'working'
676
677
678 def make_redirect_handler(*, support_head: bool = True) -> type[BaseHTTPRequestHandler]:
679 class RedirectOnceHandler(BaseHTTPRequestHandler):
680 protocol_version = 'HTTP/1.1'
681
682 def do_HEAD(self) -> None:
683 if support_head:
684 self.do_GET()
685 else:
686 self.send_response(405, 'Method Not Allowed')
687 self.send_header('Content-Length', '0')
688 self.end_headers()
689
690 def do_GET(self) -> None:
691 if self.path == '/?redirected=1':
692 self.send_response(204, 'No content')
693 else:
694 self.send_response(302, 'Found')
695 self.send_header('Location', '/?redirected=1')
696 self.send_header('Content-Length', '0')
697 self.end_headers()
698
699 def log_date_time_string(self) -> str:
700 """Strip date and time from logged messages for assertions."""
701 return ''
702
703 return RedirectOnceHandler
704
705
706 @pytest.mark.sphinx(
707 'linkcheck',
708 testroot='linkcheck-localserver',
709 freshenv=True,
710 )
711 def test_follows_redirects_on_HEAD(
712 app: SphinxTestApp, capsys: pytest.CaptureFixture[str]
713 ) -> None:
714 with serve_application(app, make_redirect_handler(support_head=True)) as address:
715 compile_linkcheck_allowed_redirects(app, app.config)
716 app.build()
717 _stdout, stderr = capsys.readouterr()
718 content = (app.outdir / 'output.txt').read_text(encoding='utf8')
719 assert content == (
720 'index.rst:1: [redirected with Found] '
721 f'http://{address}/ to http://{address}/?redirected=1\n'
722 )
723 assert stderr == textwrap.dedent(
724 """\
725 127.0.0.1 - - [] "HEAD / HTTP/1.1" 302 -
726 127.0.0.1 - - [] "HEAD /?redirected=1 HTTP/1.1" 204 -
727 """,
728 )
729 assert (
730 f'redirect http://{address}/ - with Found to http://{address}/?redirected=1\n'
731 ) in strip_escape_sequences(app.status.getvalue())
732 assert app.warning.getvalue() == ''
733
734
735 @pytest.mark.sphinx(
736 'linkcheck',
737 testroot='linkcheck-localserver',
738 freshenv=True,
739 )
740 def test_follows_redirects_on_GET(
741 app: SphinxTestApp, capsys: pytest.CaptureFixture[str]
742 ) -> None:
743 with serve_application(app, make_redirect_handler(support_head=False)) as address:
744 compile_linkcheck_allowed_redirects(app, app.config)
745 app.build()
746 _stdout, stderr = capsys.readouterr()
747 content = (app.outdir / 'output.txt').read_text(encoding='utf8')
748 assert content == (
749 'index.rst:1: [redirected with Found] '
750 f'http://{address}/ to http://{address}/?redirected=1\n'
751 )
752 assert stderr == textwrap.dedent(
753 """\
754 127.0.0.1 - - [] "HEAD / HTTP/1.1" 405 -
755 127.0.0.1 - - [] "GET / HTTP/1.1" 302 -
756 127.0.0.1 - - [] "GET /?redirected=1 HTTP/1.1" 204 -
757 """,
758 )
759 assert (
760 f'redirect http://{address}/ - with Found to http://{address}/?redirected=1\n'
761 ) in strip_escape_sequences(app.status.getvalue())
762 assert app.warning.getvalue() == ''
763
764
765 @pytest.mark.sphinx(
766 'linkcheck',
767 testroot='linkcheck-localserver',
768 freshenv=True,
769 confoverrides={'linkcheck_allowed_redirects': {}}, # warn about any redirects
770 )
771 def test_warns_disallowed_redirects(
772 app: SphinxTestApp, capsys: pytest.CaptureFixture[str]
773 ) -> None:
774 with serve_application(app, make_redirect_handler()) as address:
775 compile_linkcheck_allowed_redirects(app, app.config)
776 app.build()
777 _stdout, stderr = capsys.readouterr()
778 content = (app.outdir / 'output.txt').read_text(encoding='utf8')
779 assert content == (
780 'index.rst:1: [redirected with Found] '
781 f'http://{address}/ to http://{address}/?redirected=1\n'
782 )
783 assert stderr == textwrap.dedent(
784 """\
785 127.0.0.1 - - [] "HEAD / HTTP/1.1" 302 -
786 127.0.0.1 - - [] "HEAD /?redirected=1 HTTP/1.1" 204 -
787 """,
788 )
789 assert len(app.warning.getvalue().splitlines()) == 1
790
791
792 def test_linkcheck_allowed_redirects_config(
793 make_app: Callable[..., SphinxTestApp], tmp_path: Path
794 ) -> None:
795 tmp_path.joinpath('conf.py').touch()
796 tmp_path.joinpath('index.rst').touch()
797
798 # ``linkcheck_allowed_redirects = None`` is rejected
799 warning_stream = StringIO()
800 with pytest.raises(ConfigError):
801 make_app(
802 'linkcheck',
803 srcdir=tmp_path,
804 confoverrides={'linkcheck_allowed_redirects': None},
805 warning=warning_stream,
806 )
807 assert strip_escape_sequences(warning_stream.getvalue()).splitlines() == [
808 "WARNING: The config value `linkcheck_allowed_redirects' has type `NoneType'; expected `dict'."
809 ]
810
811 # ``linkcheck_allowed_redirects = {}`` is permitted
812 app = make_app(
813 'linkcheck',
814 srcdir=tmp_path,
815 confoverrides={'linkcheck_allowed_redirects': {}},
816 )
817 assert strip_escape_sequences(app.warning.getvalue()) == ''
818
819
820 @pytest.mark.sphinx('linkcheck', testroot='linkcheck-localserver-warn-redirects')
821 def test_linkcheck_allowed_redirects(app: SphinxTestApp) -> None:
822 with serve_application(app, make_redirect_handler(support_head=False)) as address:
823 app.config.linkcheck_allowed_redirects = {f'http://{address}/.*1': '.*'}
824 compile_linkcheck_allowed_redirects(app, app.config)
825 app.build()
826
827 with open(app.outdir / 'output.json', encoding='utf-8') as fp:
828 rows = [json.loads(l) for l in fp]
829
830 assert len(rows) == 2
831 records = {row['uri']: row for row in rows}
832 assert records[f'http://{address}/path1']['status'] == 'working'
833 assert records[f'http://{address}/path2'] == {
834 'filename': 'index.rst',
835 'lineno': 3,
836 'status': 'redirected',
837 'code': 302,
838 'uri': f'http://{address}/path2',
839 'info': f'http://{address}/?redirected=1',
840 }
841
842 assert (
843 f'index.rst:3: WARNING: redirect http://{address}/path2 - with Found to '
844 f'http://{address}/?redirected=1\n'
845 ) in strip_escape_sequences(app.warning.getvalue())
846 assert len(app.warning.getvalue().splitlines()) == 1
847
848
849 class OKHandler(BaseHTTPRequestHandler):
850 protocol_version = 'HTTP/1.1'
851
852 def do_HEAD(self) -> None:
853 self.send_response(200, 'OK')
854 self.send_header('Content-Length', '0')
855 self.end_headers()
856
857 def do_GET(self) -> None:
858 content = b'ok\n'
859 self.send_response(200, 'OK')
860 self.send_header('Content-Length', str(len(content)))
861 self.end_headers()
862 self.wfile.write(content)
863
864
865 @mock.patch('sphinx.builders.linkcheck.requests.get', wraps=requests.get)
866 @pytest.mark.sphinx(
867 'linkcheck',
868 testroot='linkcheck-localserver-https',
869 freshenv=True,
870 )
871 def test_invalid_ssl(get_request: mock.Mock, app: SphinxTestApp) -> None:
872 # Link indicates SSL should be used (https) but the server does not handle it.
873 with serve_application(app, OKHandler) as address:
874 app.build()
875 assert not get_request.called
876
877 with open(app.outdir / 'output.json', encoding='utf-8') as fp:
878 content = json.load(fp)
879 assert content['status'] == 'broken'
880 assert content['filename'] == 'index.rst'
881 assert content['lineno'] == 1
882 assert content['uri'] == f'https://{address}/'
883 assert 'SSLError' in content['info']
884
885
886 @pytest.mark.sphinx(
887 'linkcheck',
888 testroot='linkcheck-localserver-https',
889 freshenv=True,
890 )
891 def test_connect_to_selfsigned_fails(app: SphinxTestApp) -> None:
892 with serve_application(app, OKHandler, tls_enabled=True) as address:
893 app.build()
894
895 with open(app.outdir / 'output.json', encoding='utf-8') as fp:
896 content = json.load(fp)
897 assert content['status'] == 'broken'
898 assert content['filename'] == 'index.rst'
899 assert content['lineno'] == 1
900 assert content['uri'] == f'https://{address}/'
901 assert '[SSL: CERTIFICATE_VERIFY_FAILED]' in content['info']
902
903
904 @pytest.mark.sphinx(
905 'linkcheck',
906 testroot='linkcheck-localserver-https',
907 freshenv=True,
908 confoverrides={'tls_verify': False},
909 )
910 def test_connect_to_selfsigned_with_tls_verify_false(app: SphinxTestApp) -> None:
911 with serve_application(app, OKHandler, tls_enabled=True) as address:
912 app.build()
913
914 with open(app.outdir / 'output.json', encoding='utf-8') as fp:
915 content = json.load(fp)
916 assert content == {
917 'code': 0,
918 'status': 'working',
919 'filename': 'index.rst',
920 'lineno': 1,
921 'uri': f'https://{address}/',
922 'info': '',
923 }
924
925
926 @pytest.mark.sphinx(
927 'linkcheck',
928 testroot='linkcheck-localserver-https',
929 freshenv=True,
930 confoverrides={'tls_cacerts': CERT_FILE},
931 )
932 def test_connect_to_selfsigned_with_tls_cacerts(app: SphinxTestApp) -> None:
933 with serve_application(app, OKHandler, tls_enabled=True) as address:
934 app.build()
935
936 with open(app.outdir / 'output.json', encoding='utf-8') as fp:
937 content = json.load(fp)
938 assert content == {
939 'code': 0,
940 'status': 'working',
941 'filename': 'index.rst',
942 'lineno': 1,
943 'uri': f'https://{address}/',
944 'info': '',
945 }
946
947
948 @pytest.mark.sphinx(
949 'linkcheck',
950 testroot='linkcheck-localserver-https',
951 freshenv=True,
952 )
953 def test_connect_to_selfsigned_with_requests_env_var(
954 monkeypatch: pytest.MonkeyPatch, app: SphinxTestApp
955 ) -> None:
956 monkeypatch.setenv('REQUESTS_CA_BUNDLE', CERT_FILE)
957 with serve_application(app, OKHandler, tls_enabled=True) as address:
958 app.build()
959
960 with open(app.outdir / 'output.json', encoding='utf-8') as fp:
961 content = json.load(fp)
962 assert content == {
963 'code': 0,
964 'status': 'working',
965 'filename': 'index.rst',
966 'lineno': 1,
967 'uri': f'https://{address}/',
968 'info': '',
969 }
970
971
972 @pytest.mark.sphinx(
973 'linkcheck',
974 testroot='linkcheck-localserver-https',
975 freshenv=True,
976 confoverrides={'tls_cacerts': 'does/not/exist'},
977 )
978 def test_connect_to_selfsigned_nonexistent_cert_file(app: SphinxTestApp) -> None:
979 with serve_application(app, OKHandler, tls_enabled=True) as address:
980 app.build()
981
982 with open(app.outdir / 'output.json', encoding='utf-8') as fp:
983 content = json.load(fp)
984 assert content == {
985 'code': 0,
986 'status': 'broken',
987 'filename': 'index.rst',
988 'lineno': 1,
989 'uri': f'https://{address}/',
990 'info': 'Could not find a suitable TLS CA certificate bundle, invalid path: does/not/exist',
991 }
992
993
994 class InfiniteRedirectOnHeadHandler(BaseHTTPRequestHandler):
995 protocol_version = 'HTTP/1.1'
996
997 def do_HEAD(self) -> None:
998 self.send_response(302, 'Found')
999 self.send_header('Location', '/redirected')
1000 self.send_header('Content-Length', '0')
1001 self.end_headers()
1002
1003 def do_GET(self) -> None:
1004 content = b'ok\n'
1005 self.send_response(200, 'OK')
1006 self.send_header('Content-Length', str(len(content)))
1007 self.end_headers()
1008 self.wfile.write(content)
1009 self.close_connection = (
1010 True # we don't expect the client to read this response body
1011 )
1012
1013
1014 @pytest.mark.sphinx(
1015 'linkcheck',
1016 testroot='linkcheck-localserver',
1017 freshenv=True,
1018 )
1019 def test_TooManyRedirects_on_HEAD(
1020 app: SphinxTestApp, monkeypatch: pytest.MonkeyPatch
1021 ) -> None:
1022 import requests.sessions
1023
1024 monkeypatch.setattr(requests.sessions, 'DEFAULT_REDIRECT_LIMIT', 5)
1025
1026 with serve_application(app, InfiniteRedirectOnHeadHandler) as address:
1027 app.build()
1028
1029 with open(app.outdir / 'output.json', encoding='utf-8') as fp:
1030 content = json.load(fp)
1031 assert content == {
1032 'code': 0,
1033 'status': 'working',
1034 'filename': 'index.rst',
1035 'lineno': 1,
1036 'uri': f'http://{address}/',
1037 'info': '',
1038 }
1039
1040
1041 @pytest.mark.sphinx('linkcheck', testroot='linkcheck-localserver')
1042 def test_ignore_local_redirection(app: SphinxTestApp) -> None:
1043 with serve_application(app, InfiniteRedirectOnHeadHandler) as address:
1044 app.config.linkcheck_ignore = [f'http://{address}/redirected']
1045 app.build()
1046
1047 with open(app.outdir / 'output.json', encoding='utf-8') as fp:
1048 content = json.load(fp)
1049 assert content == {
1050 'code': 302,
1051 'status': 'ignored',
1052 'filename': 'index.rst',
1053 'lineno': 1,
1054 'uri': f'http://{address}/',
1055 'info': f'ignored redirect: http://{address}/redirected',
1056 }
1057
1058
1059 class RemoteDomainRedirectHandler(InfiniteRedirectOnHeadHandler):
1060 protocol_version = 'HTTP/1.1'
1061
1062 def do_GET(self) -> None:
1063 self.send_response(301, 'Found')
1064 if self.path == '/':
1065 self.send_header('Location', '/local')
1066 elif self.path == '/local':
1067 self.send_header('Location', 'http://example.test/migrated')
1068 self.send_header('Content-Length', '0')
1069 self.end_headers()
1070
1071
1072 @pytest.mark.sphinx('linkcheck', testroot='linkcheck-localserver')
1073 def test_ignore_remote_redirection(app: SphinxTestApp) -> None:
1074 with serve_application(app, RemoteDomainRedirectHandler) as address:
1075 app.config.linkcheck_ignore = ['http://example.test']
1076 app.build()
1077
1078 with open(app.outdir / 'output.json', encoding='utf-8') as fp:
1079 content = json.load(fp)
1080 assert content == {
1081 'code': 301,
1082 'status': 'ignored',
1083 'filename': 'index.rst',
1084 'lineno': 1,
1085 'uri': f'http://{address}/',
1086 'info': 'ignored redirect: http://example.test/migrated',
1087 }
1088
1089
1090 def make_retry_after_handler(
1091 responses: list[tuple[int, str | None]],
1092 ) -> type[BaseHTTPRequestHandler]:
1093 class RetryAfterHandler(BaseHTTPRequestHandler):
1094 protocol_version = 'HTTP/1.1'
1095
1096 def do_HEAD(self) -> None:
1097 status, retry_after = responses.pop(0)
1098 self.send_response(status)
1099 if retry_after:
1100 self.send_header('Retry-After', retry_after)
1101 self.send_header('Content-Length', '0')
1102 self.end_headers()
1103
1104 def log_date_time_string(self) -> str:
1105 """Strip date and time from logged messages for assertions."""
1106 return ''
1107
1108 return RetryAfterHandler
1109
1110
1111 @pytest.mark.sphinx(
1112 'linkcheck',
1113 testroot='linkcheck-localserver',
1114 freshenv=True,
1115 )
1116 def test_too_many_requests_retry_after_int_delay(
1117 app: SphinxTestApp, capsys: pytest.CaptureFixture[str]
1118 ) -> None:
1119 with (
1120 serve_application(
1121 app, make_retry_after_handler([(429, '0'), (200, None)])
1122 ) as address,
1123 mock.patch('sphinx.builders.linkcheck.DEFAULT_DELAY', 0),
1124 mock.patch('sphinx.builders.linkcheck.QUEUE_POLL_SECS', 0.01),
1125 ):
1126 app.build()
1127 content = (app.outdir / 'output.json').read_text(encoding='utf8')
1128 assert json.loads(content) == {
1129 'filename': 'index.rst',
1130 'lineno': 1,
1131 'status': 'working',
1132 'code': 0,
1133 'uri': f'http://{address}/',
1134 'info': '',
1135 }
1136 rate_limit_log = f'-rate limited- http://{address}/ | sleeping...\n'
1137 assert rate_limit_log in strip_escape_sequences(app.status.getvalue())
1138 _stdout, stderr = capsys.readouterr()
1139 assert stderr == textwrap.dedent(
1140 """\
1141 127.0.0.1 - - [] "HEAD / HTTP/1.1" 429 -
1142 127.0.0.1 - - [] "HEAD / HTTP/1.1" 200 -
1143 """,
1144 )
1145
1146
1147 @pytest.mark.parametrize('tz', [None, 'GMT', 'GMT+3', 'GMT-3'])
1148 @pytest.mark.sphinx(
1149 'linkcheck',
1150 testroot='linkcheck-localserver',
1151 freshenv=True,
1152 )
1153 def test_too_many_requests_retry_after_HTTP_date(
1154 tz: str | None,
1155 app: SphinxTestApp,
1156 monkeypatch: pytest.MonkeyPatch,
1157 capsys: pytest.CaptureFixture[str],
1158 ) -> None:
1159 retry_after = wsgiref.handlers.format_date_time(time.time())
1160
1161 with monkeypatch.context() as m:
1162 if tz is not None:
1163 m.setenv('TZ', tz)
1164 if sys.platform != 'win32':
1165 time.tzset()
1166 m.setattr(
1167 sphinx.util.http_date, '_GMT_OFFSET', float(time.localtime().tm_gmtoff)
1168 )
1169
1170 with serve_application(
1171 app, make_retry_after_handler([(429, retry_after), (200, None)])
1172 ) as address:
1173 app.build()
1174
1175 # Undo side-effects: the monkeypatch context manager clears the TZ environment
1176 # variable, but we also need to reset Python's internal notion of the current
1177 # timezone.
1178 if sys.platform != 'win32':
1179 time.tzset()
1180
1181 content = (app.outdir / 'output.json').read_text(encoding='utf8')
1182 assert json.loads(content) == {
1183 'filename': 'index.rst',
1184 'lineno': 1,
1185 'status': 'working',
1186 'code': 0,
1187 'uri': f'http://{address}/',
1188 'info': '',
1189 }
1190 _stdout, stderr = capsys.readouterr()
1191 assert stderr == textwrap.dedent(
1192 """\
1193 127.0.0.1 - - [] "HEAD / HTTP/1.1" 429 -
1194 127.0.0.1 - - [] "HEAD / HTTP/1.1" 200 -
1195 """,
1196 )
1197
1198
1199 @pytest.mark.sphinx(
1200 'linkcheck',
1201 testroot='linkcheck-localserver',
1202 freshenv=True,
1203 )
1204 def test_too_many_requests_retry_after_without_header(
1205 app: SphinxTestApp, capsys: pytest.CaptureFixture[str]
1206 ) -> None:
1207 with (
1208 serve_application(
1209 app, make_retry_after_handler([(429, None), (200, None)])
1210 ) as address,
1211 mock.patch('sphinx.builders.linkcheck.DEFAULT_DELAY', 0),
1212 ):
1213 app.build()
1214 content = (app.outdir / 'output.json').read_text(encoding='utf8')
1215 assert json.loads(content) == {
1216 'filename': 'index.rst',
1217 'lineno': 1,
1218 'status': 'working',
1219 'code': 0,
1220 'uri': f'http://{address}/',
1221 'info': '',
1222 }
1223 _stdout, stderr = capsys.readouterr()
1224 assert stderr == textwrap.dedent(
1225 """\
1226 127.0.0.1 - - [] "HEAD / HTTP/1.1" 429 -
1227 127.0.0.1 - - [] "HEAD / HTTP/1.1" 200 -
1228 """,
1229 )
1230
1231
1232 @pytest.mark.sphinx(
1233 'linkcheck',
1234 testroot='linkcheck-localserver',
1235 freshenv=True,
1236 confoverrides={
1237 'linkcheck_report_timeouts_as_broken': False,
1238 'linkcheck_timeout': 0.01,
1239 },
1240 )
1241 def test_requests_timeout(app: SphinxTestApp) -> None:
1242 class DelayedResponseHandler(BaseHTTPRequestHandler):
1243 protocol_version = 'HTTP/1.1'
1244
1245 def do_GET(self) -> None:
1246 time.sleep(0.2) # wait before sending any response data
1247 self.send_response(200, 'OK')
1248 self.send_header('Content-Length', '0')
1249 self.end_headers()
1250
1251 with serve_application(app, DelayedResponseHandler):
1252 app.build()
1253
1254 with open(app.outdir / 'output.json', encoding='utf-8') as fp:
1255 content = json.load(fp)
1256
1257 assert content['status'] == 'timeout'
1258
1259
1260 @pytest.mark.sphinx(
1261 'linkcheck',
1262 testroot='linkcheck-localserver',
1263 freshenv=True,
1264 confoverrides={'linkcheck_rate_limit_timeout': 0.0},
1265 )
1266 def test_too_many_requests_user_timeout(app: SphinxTestApp) -> None:
1267 with serve_application(app, make_retry_after_handler([(429, None)])) as address:
1268 app.build()
1269 content = (app.outdir / 'output.json').read_text(encoding='utf8')
1270 assert json.loads(content) == {
1271 'filename': 'index.rst',
1272 'lineno': 1,
1273 'status': 'broken',
1274 'code': 0,
1275 'uri': f'http://{address}/',
1276 'info': f'429 Client Error: Too Many Requests for url: http://{address}/',
1277 }
1278
1279
1280 class FakeResponse:
1281 headers: dict[str, str] = {}
1282 url = 'http://localhost/'
1283
1284
1285 @pytest.mark.sphinx('html', testroot='root')
1286 def test_limit_rate_default_sleep(app: SphinxTestApp) -> None:
1287 worker = HyperlinkAvailabilityCheckWorker(app.config, Queue(), Queue(), {})
1288 with mock.patch('time.time', return_value=0.0):
1289 next_check = worker.limit_rate(
1290 FakeResponse.url, FakeResponse.headers.get('Retry-After')
1291 )
1292 assert next_check == 60.0
1293
1294
1295 @pytest.mark.sphinx(
1296 'html', testroot='root', confoverrides={'linkcheck_rate_limit_timeout': 0.0}
1297 )
1298 def test_limit_rate_user_max_delay(app: SphinxTestApp) -> None:
1299 worker = HyperlinkAvailabilityCheckWorker(app.config, Queue(), Queue(), {})
1300 next_check = worker.limit_rate(
1301 FakeResponse.url, FakeResponse.headers.get('Retry-After')
1302 )
1303 assert next_check is None
1304
1305
1306 @pytest.mark.sphinx('html', testroot='root')
1307 def test_limit_rate_doubles_previous_wait_time(app: SphinxTestApp) -> None:
1308 rate_limits = {'localhost': RateLimit(60.0, 0.0)}
1309 worker = HyperlinkAvailabilityCheckWorker(app.config, Queue(), Queue(), rate_limits)
1310 with mock.patch('time.time', return_value=0.0):
1311 next_check = worker.limit_rate(
1312 FakeResponse.url, FakeResponse.headers.get('Retry-After')
1313 )
1314 assert next_check == 120.0
1315
1316
1317 @pytest.mark.sphinx(
1318 'html', testroot='root', confoverrides={'linkcheck_rate_limit_timeout': 90}
1319 )
1320 def test_limit_rate_clips_wait_time_to_max_time(app: SphinxTestApp) -> None:
1321 rate_limits = {'localhost': RateLimit(60.0, 0.0)}
1322 worker = HyperlinkAvailabilityCheckWorker(app.config, Queue(), Queue(), rate_limits)
1323 with mock.patch('time.time', return_value=0.0):
1324 next_check = worker.limit_rate(
1325 FakeResponse.url, FakeResponse.headers.get('Retry-After')
1326 )
1327 assert next_check == 90.0
1328 assert app.warning.getvalue() == ''
1329
1330
1331 @pytest.mark.sphinx(
1332 'html', testroot='root', confoverrides={'linkcheck_rate_limit_timeout': 90.0}
1333 )
1334 def test_limit_rate_bails_out_after_waiting_max_time(app: SphinxTestApp) -> None:
1335 rate_limits = {'localhost': RateLimit(90.0, 0.0)}
1336 worker = HyperlinkAvailabilityCheckWorker(app.config, Queue(), Queue(), rate_limits)
1337 next_check = worker.limit_rate(
1338 FakeResponse.url, FakeResponse.headers.get('Retry-After')
1339 )
1340 assert next_check is None
1341 assert app.warning.getvalue() == ''
1342
1343
1344 @mock.patch('sphinx.util.requests.requests.Session.get_adapter')
1345 @pytest.mark.sphinx('html', testroot='root')
1346 def test_connection_contention(
1347 get_adapter: mock.Mock, app: SphinxTestApp, capsys: pytest.CaptureFixture[str]
1348 ) -> None:
1349 # Create a shared, but limited-size, connection pool
1350 import requests
1351
1352 get_adapter.return_value = requests.adapters.HTTPAdapter(pool_maxsize=1)
1353
1354 # Set an upper-bound on socket timeouts globally
1355 import socket
1356
1357 socket.setdefaulttimeout(5)
1358
1359 # Create parallel consumer threads
1360 with serve_application(app, make_redirect_handler(support_head=True)) as address:
1361 # Place a workload into the linkcheck queue
1362 link_count = 10
1363 wqueue: Queue[CheckRequest] = Queue()
1364 rqueue: Queue[CheckResult] = Queue()
1365 for _ in range(link_count):
1366 wqueue.put(
1367 CheckRequest(
1368 0, Hyperlink(f'http://{address}', 'test', _StrPath('test.rst'), 1)
1369 )
1370 )
1371
1372 begin = time.time()
1373 checked: list[CheckResult] = []
1374 threads = [
1375 HyperlinkAvailabilityCheckWorker(
1376 config=app.config,
1377 rqueue=rqueue,
1378 wqueue=wqueue,
1379 rate_limits={},
1380 )
1381 for _ in range(10)
1382 ]
1383 for thread in threads:
1384 thread.start()
1385 while time.time() < begin + 5 and len(checked) < link_count:
1386 checked.append(rqueue.get(timeout=5))
1387 for thread in threads:
1388 thread.join(timeout=0)
1389
1390 # Ensure that all items were consumed within the time limit
1391 _, stderr = capsys.readouterr()
1392 assert len(checked) == link_count
1393 assert 'TimeoutError' not in stderr
1394
1395
1396 class ConnectionResetHandler(BaseHTTPRequestHandler):
1397 protocol_version = 'HTTP/1.1'
1398
1399 def do_HEAD(self) -> None:
1400 self.close_connection = True
1401
1402 def do_GET(self) -> None:
1403 self.send_response(200, 'OK')
1404 self.send_header('Content-Length', '0')
1405 self.end_headers()
1406
1407
1408 @pytest.mark.sphinx(
1409 'linkcheck',
1410 testroot='linkcheck-localserver',
1411 freshenv=True,
1412 )
1413 def test_get_after_head_raises_connection_error(app: SphinxTestApp) -> None:
1414 with serve_application(app, ConnectionResetHandler) as address:
1415 app.build()
1416 content = (app.outdir / 'output.txt').read_text(encoding='utf8')
1417 assert not content
1418 content = (app.outdir / 'output.json').read_text(encoding='utf8')
1419 assert json.loads(content) == {
1420 'filename': 'index.rst',
1421 'lineno': 1,
1422 'status': 'working',
1423 'code': 0,
1424 'uri': f'http://{address}/',
1425 'info': '',
1426 }
1427
1428
1429 @pytest.mark.sphinx(
1430 'linkcheck',
1431 testroot='linkcheck-documents_exclude',
1432 freshenv=True,
1433 )
1434 def test_linkcheck_exclude_documents(app: SphinxTestApp) -> None:
1435 with serve_application(app, DefaultsHandler):
1436 app.build()
1437
1438 with open(app.outdir / 'output.json', encoding='utf-8') as fp:
1439 content = [json.loads(record) for record in fp]
1440
1441 assert len(content) == 2
1442 assert {
1443 'filename': 'broken_link.rst',
1444 'lineno': 4,
1445 'status': 'ignored',
1446 'code': 0,
1447 'uri': 'https://www.sphinx-doc.org/this-is-a-broken-link',
1448 'info': 'broken_link matched ^broken_link$ from linkcheck_exclude_documents',
1449 } in content
1450 assert {
1451 'filename': 'br0ken_link.rst',
1452 'lineno': 4,
1453 'status': 'ignored',
1454 'code': 0,
1455 'uri': 'https://www.sphinx-doc.org/this-is-another-broken-link',
1456 'info': 'br0ken_link matched br[0-9]ken_link from linkcheck_exclude_documents',
1457 } in content
1458
1459
1460 class CapitalisePathHandler(BaseHTTPRequestHandler):
1461 """Test server that uppercases URL paths via redirects."""
1462
1463 protocol_version = 'HTTP/1.1'
1464
1465 def do_GET(self) -> None:
1466 if self.path.islower():
1467 # Redirect lowercase paths to uppercase versions
1468 self.send_response(301, 'Moved Permanently')
1469 self.send_header('Location', self.path.upper())
1470 self.send_header('Content-Length', '0')
1471 self.end_headers()
1472 else:
1473 # Serve uppercase paths
1474 content = b'ok\n\n'
1475 self.send_response(200, 'OK')
1476 self.send_header('Content-Length', str(len(content)))
1477 self.end_headers()
1478 self.wfile.write(content)
1479
1480
1481 @pytest.mark.sphinx(
1482 'linkcheck',
1483 testroot='linkcheck-case-check',
1484 freshenv=True,
1485 )
1486 @pytest.mark.parametrize(
1487 ('case_insensitive_pattern', 'expected_path1', 'expected_path2', 'expected_path3'),
1488 [
1489 ([], 'redirected', 'redirected', 'working'), # default: case-sensitive
1490 (
1491 [r'http://localhost:\d+/.*'],
1492 'working',
1493 'working',
1494 'working',
1495 ), # all URLs case-insensitive
1496 (
1497 [r'http://localhost:\d+/path1'],
1498 'working',
1499 'redirected',
1500 'working',
1501 ), # only path1 case-insensitive
1502 ],
1503 )
1504 def test_linkcheck_case_sensitivity(
1505 app: SphinxTestApp,
1506 case_insensitive_pattern: list[str],
1507 expected_path1: str,
1508 expected_path2: str,
1509 expected_path3: str,
1510 ) -> None:
1511 """Test case-sensitive and case-insensitive URL checking."""
1512 app.config.linkcheck_case_insensitive_urls = case_insensitive_pattern
1513
1514 with serve_application(app, CapitalisePathHandler) as address:
1515 app.build()
1516
1517 content = (app.outdir / 'output.json').read_text(encoding='utf8')
1518 rows = [json.loads(x) for x in content.splitlines()]
1519 rowsby = {row['uri']: row for row in rows}
1520
1521 # Verify expected status for each path
1522 assert rowsby[f'http://{address}/path1']['status'] == expected_path1
1523 assert rowsby[f'http://{address}/path2']['status'] == expected_path2
1524 assert rowsby[f'http://{address}/PATH3']['status'] == expected_path3