Debian Codegraph @

tests/test_ext_intersphinx/test_ext_intersphinx.py

raw
1 """Test the intersphinx extension."""
2
3 from __future__ import annotations
4
5 import http.server
6 import time
7 from typing import TYPE_CHECKING
8 from unittest import mock
9
10 import pytest
11 from docutils import nodes
12
13 from sphinx import addnodes
14 from sphinx._cli.util.errors import strip_escape_sequences
15 from sphinx.builders.html import INVENTORY_FILENAME
16 from sphinx.config import Config
17 from sphinx.errors import ConfigError
18 from sphinx.ext.intersphinx import setup as intersphinx_setup
19 from sphinx.ext.intersphinx._cli import inspect_main
20 from sphinx.ext.intersphinx._load import (
21 _display_failures,
22 _fetch_inventory_data,
23 _fetch_inventory_group,
24 _get_safe_url,
25 _InvConfig,
26 _load_inventory,
27 _strip_basic_auth,
28 load_mappings,
29 validate_intersphinx_mapping,
30 )
31 from sphinx.ext.intersphinx._resolve import missing_reference
32 from sphinx.ext.intersphinx._shared import _IntersphinxProject
33 from sphinx.util.inventory import _Inventory, _InventoryItem
34
35 from tests.test_util.intersphinx_data import (
36 INVENTORY_V2,
37 INVENTORY_V2_AMBIGUOUS_TERMS,
38 INVENTORY_V2_NO_VERSION,
39 INVENTORY_V2_TEXT_VERSION,
40 )
41 from tests.utils import http_server
42
43 if TYPE_CHECKING:
44 from typing import NoReturn
45
46 from sphinx.ext.intersphinx._shared import InventoryCacheEntry
47 from sphinx.testing.util import SphinxTestApp
48 from sphinx.util.typing import Inventory
49
50
51 class FakeList(list[str]): # NoQA: FURB189
52 def __iter__(self) -> NoReturn:
53 raise NotImplementedError
54
55
56 def fake_node(domain, type, target, content, **attrs):
57 contnode = nodes.emphasis(content, content)
58 node = addnodes.pending_xref('')
59 node['reftarget'] = target
60 node['reftype'] = type
61 node['refdomain'] = domain
62 node.attributes.update(attrs)
63 node += contnode
64 return node, contnode
65
66
67 def reference_check(app, *args, **kwds):
68 node, contnode = fake_node(*args, **kwds)
69 return missing_reference(app, app.env, node, contnode)
70
71
72 def set_config(app, mapping):
73 # copy *mapping* so that normalization does not alter it
74 app.config.intersphinx_mapping = mapping.copy()
75 app.config.intersphinx_cache_limit = 0
76 app.config.intersphinx_disabled_reftypes = []
77 app.config.intersphinx_resolve_self = ''
78 app.config.intersphinx_timeout = None
79
80
81 @mock.patch('sphinx.ext.intersphinx._load.InventoryFile')
82 @mock.patch('sphinx.ext.intersphinx._load.requests.get')
83 @pytest.mark.sphinx('html', testroot='root')
84 def test_fetch_inventory_redirection(get_request, InventoryFile, app):
85 mocked_get = get_request.return_value.__enter__.return_value
86 intersphinx_setup(app)
87 mocked_get.content = b'# Sphinx inventory version 2'
88
89 # same uri and inv, not redirected
90 mocked_get.url = 'https://hostname/' + INVENTORY_FILENAME
91 target_uri = 'https://hostname/'
92 raw_data, target_uri = _fetch_inventory_data(
93 target_uri=target_uri,
94 inv_location='https://hostname/' + INVENTORY_FILENAME,
95 config=_InvConfig.from_config(app.config),
96 srcdir=app.srcdir,
97 cache_path=None,
98 )
99 _load_inventory(raw_data, target_uri=target_uri)
100 assert 'intersphinx inventory has moved' not in app.status.getvalue()
101 assert InventoryFile.loads.call_args[1]['uri'] == 'https://hostname/'
102
103 # same uri and inv, redirected
104 app.status.seek(0)
105 app.status.truncate(0)
106 mocked_get.url = 'https://hostname/new/' + INVENTORY_FILENAME
107
108 target_uri = 'https://hostname/'
109 raw_data, target_uri = _fetch_inventory_data(
110 target_uri=target_uri,
111 inv_location='https://hostname/' + INVENTORY_FILENAME,
112 config=_InvConfig.from_config(app.config),
113 srcdir=app.srcdir,
114 cache_path=None,
115 )
116 _load_inventory(raw_data, target_uri=target_uri)
117 assert app.status.getvalue() == (
118 'intersphinx inventory has moved: '
119 'https://hostname/%s -> https://hostname/new/%s\n'
120 % (INVENTORY_FILENAME, INVENTORY_FILENAME)
121 )
122 assert InventoryFile.loads.call_args[1]['uri'] == 'https://hostname/new'
123
124 # different uri and inv, not redirected
125 app.status.seek(0)
126 app.status.truncate(0)
127 mocked_get.url = 'https://hostname/new/' + INVENTORY_FILENAME
128
129 target_uri = 'https://hostname/'
130 raw_data, target_uri = _fetch_inventory_data(
131 target_uri=target_uri,
132 inv_location='https://hostname/new/' + INVENTORY_FILENAME,
133 config=_InvConfig.from_config(app.config),
134 srcdir=app.srcdir,
135 cache_path=None,
136 )
137 _load_inventory(raw_data, target_uri=target_uri)
138 assert 'intersphinx inventory has moved' not in app.status.getvalue()
139 assert InventoryFile.loads.call_args[1]['uri'] == 'https://hostname/'
140
141 # different uri and inv, redirected
142 app.status.seek(0)
143 app.status.truncate(0)
144 mocked_get.url = 'https://hostname/other/' + INVENTORY_FILENAME
145
146 target_uri = 'https://hostname/'
147 raw_data, target_uri = _fetch_inventory_data(
148 target_uri=target_uri,
149 inv_location='https://hostname/new/' + INVENTORY_FILENAME,
150 config=_InvConfig.from_config(app.config),
151 srcdir=app.srcdir,
152 cache_path=None,
153 )
154 _load_inventory(raw_data, target_uri=target_uri)
155 assert app.status.getvalue() == (
156 'intersphinx inventory has moved: '
157 'https://hostname/new/%s -> https://hostname/other/%s\n'
158 % (INVENTORY_FILENAME, INVENTORY_FILENAME)
159 )
160 assert InventoryFile.loads.call_args[1]['uri'] == 'https://hostname/'
161
162
163 @pytest.mark.sphinx('html', testroot='root')
164 def test_missing_reference(tmp_path, app):
165 inv_file = tmp_path / 'inventory'
166 inv_file.write_bytes(INVENTORY_V2)
167 set_config(
168 app,
169 {
170 'python': ('https://docs.python.org/', str(inv_file)),
171 'py3k': ('https://docs.python.org/py3k/', str(inv_file)),
172 'py3krel': ('py3k', str(inv_file)), # relative path
173 'py3krelparent': ('../../py3k', str(inv_file)), # relative path, parent dir
174 },
175 )
176
177 # load the inventory and check if it's done correctly
178 validate_intersphinx_mapping(app, app.config)
179 load_mappings(app)
180 inv: Inventory = app.env.intersphinx_inventory
181
182 assert inv['py:module']['module2'] == _InventoryItem(
183 project_name='foo',
184 project_version='2.0',
185 uri='https://docs.python.org/foo.html#module-module2',
186 display_name='-',
187 )
188
189 # check resolution when a target is found
190 rn = reference_check(app, 'py', 'func', 'module1.func', 'foo')
191 assert isinstance(rn, nodes.reference)
192 assert rn['refuri'] == 'https://docs.python.org/sub/foo.html#module1.func'
193 assert rn['reftitle'] == '(in foo v2.0)'
194 assert rn[0].astext() == 'foo'
195
196 # create unresolvable nodes and check None return value
197 assert reference_check(app, 'py', 'foo', 'module1.func', 'foo') is None
198 assert reference_check(app, 'py', 'func', 'foo', 'foo') is None
199 assert reference_check(app, 'py', 'func', 'foo', 'foo') is None
200
201 # check handling of prefixes
202
203 # prefix given, target found: prefix is stripped
204 rn = reference_check(app, 'py', 'mod', 'py3k:module2', 'py3k:module2')
205 assert rn[0].astext() == 'module2'
206
207 # prefix given, but not in title: nothing stripped
208 rn = reference_check(app, 'py', 'mod', 'py3k:module2', 'module2')
209 assert rn[0].astext() == 'module2'
210
211 # prefix given, but explicit: nothing stripped
212 rn = reference_check(
213 app, 'py', 'mod', 'py3k:module2', 'py3k:module2', refexplicit=True
214 )
215 assert rn[0].astext() == 'py3k:module2'
216
217 # prefix given, target not found and nonexplicit title: prefix is not stripped
218 node, contnode = fake_node(
219 'py', 'mod', 'py3k:unknown', 'py3k:unknown', refexplicit=False
220 )
221 rn = missing_reference(app, app.env, node, contnode)
222 assert rn is None
223 assert contnode[0].astext() == 'py3k:unknown'
224
225 # prefix given, target not found and explicit title: nothing is changed
226 node, contnode = fake_node(
227 'py', 'mod', 'py3k:unknown', 'py3k:unknown', refexplicit=True
228 )
229 rn = missing_reference(app, app.env, node, contnode)
230 assert rn is None
231 assert contnode[0].astext() == 'py3k:unknown'
232
233 # check relative paths
234 rn = reference_check(app, 'py', 'mod', 'py3krel:module1', 'foo')
235 assert rn['refuri'] == 'py3k/foo.html#module-module1'
236
237 rn = reference_check(app, 'py', 'mod', 'py3krelparent:module1', 'foo')
238 assert rn['refuri'] == '../../py3k/foo.html#module-module1'
239
240 rn = reference_check(
241 app, 'py', 'mod', 'py3krel:module1', 'foo', refdoc='sub/dir/test'
242 )
243 assert rn['refuri'] == '../../py3k/foo.html#module-module1'
244
245 rn = reference_check(
246 app, 'py', 'mod', 'py3krelparent:module1', 'foo', refdoc='sub/dir/test'
247 )
248 assert rn['refuri'] == '../../../../py3k/foo.html#module-module1'
249
250 # check refs of standard domain
251 rn = reference_check(app, 'std', 'doc', 'docname', 'docname')
252 assert rn['refuri'] == 'https://docs.python.org/docname.html'
253
254
255 @pytest.mark.sphinx('html', testroot='root')
256 def test_missing_reference_pydomain(tmp_path, app):
257 inv_file = tmp_path / 'inventory'
258 inv_file.write_bytes(INVENTORY_V2)
259 set_config(
260 app,
261 {
262 'python': ('https://docs.python.org/', str(inv_file)),
263 },
264 )
265
266 # load the inventory and check if it's done correctly
267 validate_intersphinx_mapping(app, app.config)
268 load_mappings(app)
269
270 # no context data
271 kwargs = {}
272 node, contnode = fake_node('py', 'func', 'func', 'func()', **kwargs)
273 rn = missing_reference(app, app.env, node, contnode)
274 assert rn is None
275
276 # py:module context helps to search objects
277 kwargs = {'py:module': 'module1'}
278 node, contnode = fake_node('py', 'func', 'func', 'func()', **kwargs)
279 rn = missing_reference(app, app.env, node, contnode)
280 assert rn.astext() == 'func()'
281
282 # py:attr context helps to search objects
283 kwargs = {'py:module': 'module1'}
284 node, contnode = fake_node('py', 'attr', 'Foo.bar', 'Foo.bar', **kwargs)
285 rn = missing_reference(app, app.env, node, contnode)
286 assert rn.astext() == 'Foo.bar'
287
288
289 @pytest.mark.sphinx('html', testroot='root')
290 def test_missing_reference_stddomain(tmp_path, app):
291 inv_file = tmp_path / 'inventory'
292 inv_file.write_bytes(INVENTORY_V2)
293 set_config(
294 app,
295 {
296 'cmd': ('https://docs.python.org/', str(inv_file)),
297 },
298 )
299
300 # load the inventory and check if it's done correctly
301 validate_intersphinx_mapping(app, app.config)
302 load_mappings(app)
303
304 # no context data
305 kwargs = {}
306 node, contnode = fake_node('std', 'option', '-l', '-l', **kwargs)
307 rn = missing_reference(app, app.env, node, contnode)
308 assert rn is None
309
310 # std:program context helps to search objects
311 kwargs = {'std:program': 'ls'}
312 node, contnode = fake_node('std', 'option', '-l', 'ls -l', **kwargs)
313 rn = missing_reference(app, app.env, node, contnode)
314 assert rn.astext() == 'ls -l'
315
316 # refers inventory by name
317 kwargs = {}
318 node, contnode = fake_node('std', 'option', 'cmd:ls -l', '-l', **kwargs)
319 rn = missing_reference(app, app.env, node, contnode)
320 assert rn.astext() == '-l'
321
322 # term reference (normal)
323 node, contnode = fake_node('std', 'term', 'a term', 'a term')
324 rn = missing_reference(app, app.env, node, contnode)
325 assert rn.astext() == 'a term'
326
327 # term reference (case insensitive)
328 node, contnode = fake_node('std', 'term', 'A TERM', 'A TERM')
329 rn = missing_reference(app, app.env, node, contnode)
330 assert rn.astext() == 'A TERM'
331
332 # label reference (normal)
333 node, contnode = fake_node('std', 'ref', 'The-Julia-Domain', 'The-Julia-Domain')
334 rn = missing_reference(app, app.env, node, contnode)
335 assert rn.astext() == 'The Julia Domain'
336
337 # label reference (case insensitive)
338 node, contnode = fake_node('std', 'ref', 'the-julia-domain', 'the-julia-domain')
339 rn = missing_reference(app, app.env, node, contnode)
340 assert rn.astext() == 'The Julia Domain'
341
342
343 @pytest.mark.parametrize(
344 ('term', 'expected_ambiguity'),
345 [
346 ('A TERM', False),
347 ('B TERM', True),
348 ],
349 )
350 @pytest.mark.sphinx('html', testroot='root')
351 def test_ambiguous_reference_handling(term, expected_ambiguity, tmp_path, app, warning):
352 inv_file = tmp_path / 'inventory'
353 inv_file.write_bytes(INVENTORY_V2_AMBIGUOUS_TERMS)
354 set_config(
355 app,
356 {
357 'cmd': ('https://docs.python.org/', str(inv_file)),
358 },
359 )
360
361 # load the inventory
362 validate_intersphinx_mapping(app, app.config)
363 load_mappings(app)
364
365 # term reference (case insensitive)
366 node, contnode = fake_node('std', 'term', term, term)
367 missing_reference(app, app.env, node, contnode)
368
369 ambiguity = f'multiple matches found for std:term:{term}' in warning.getvalue()
370 assert ambiguity is expected_ambiguity
371
372
373 @pytest.mark.sphinx('html', testroot='ext-intersphinx-cppdomain')
374 def test_missing_reference_cppdomain(tmp_path, app):
375 inv_file = tmp_path / 'inventory'
376 inv_file.write_bytes(INVENTORY_V2)
377 set_config(
378 app,
379 {
380 'python': ('https://docs.python.org/', str(inv_file)),
381 },
382 )
383
384 # load the inventory and check if it's done correctly
385 validate_intersphinx_mapping(app, app.config)
386 load_mappings(app)
387
388 app.build()
389 html = (app.outdir / 'index.html').read_text(encoding='utf8')
390 assert (
391 '<a class="reference external"'
392 ' href="https://docs.python.org/index.html#cpp_foo_bar"'
393 ' title="(in foo v2.0)">'
394 '<code class="xref cpp cpp-class docutils literal notranslate">'
395 '<span class="pre">Bar</span></code></a>'
396 ) in html
397 assert (
398 '<a class="reference external"'
399 ' href="https://docs.python.org/index.html#foons"'
400 ' title="(in foo v2.0)"><span class="n"><span class="pre">foons</span></span></a>'
401 ) in html
402 assert (
403 '<a class="reference external"'
404 ' href="https://docs.python.org/index.html#foons_bartype"'
405 ' title="(in foo v2.0)"><span class="n"><span class="pre">bartype</span></span></a>'
406 ) in html
407
408
409 @pytest.mark.sphinx('html', testroot='root')
410 def test_missing_reference_jsdomain(tmp_path, app):
411 inv_file = tmp_path / 'inventory'
412 inv_file.write_bytes(INVENTORY_V2)
413 set_config(
414 app,
415 {
416 'python': ('https://docs.python.org/', str(inv_file)),
417 },
418 )
419
420 # load the inventory and check if it's done correctly
421 validate_intersphinx_mapping(app, app.config)
422 load_mappings(app)
423
424 # no context data
425 kwargs = {}
426 node, contnode = fake_node('js', 'meth', 'baz', 'baz()', **kwargs)
427 rn = missing_reference(app, app.env, node, contnode)
428 assert rn is None
429
430 # js:module and js:object context helps to search objects
431 kwargs = {'js:module': 'foo', 'js:object': 'bar'}
432 node, contnode = fake_node('js', 'meth', 'baz', 'baz()', **kwargs)
433 rn = missing_reference(app, app.env, node, contnode)
434 assert rn.astext() == 'baz()'
435
436
437 @pytest.mark.sphinx('html', testroot='root')
438 def test_missing_reference_disabled_domain(tmp_path, app):
439 inv_file = tmp_path / 'inventory'
440 inv_file.write_bytes(INVENTORY_V2)
441 set_config(
442 app,
443 {
444 'inv': ('https://docs.python.org/', str(inv_file)),
445 },
446 )
447
448 # load the inventory and check if it's done correctly
449 validate_intersphinx_mapping(app, app.config)
450 load_mappings(app)
451
452 def case(*, term, doc, py):
453 def assert_(rn, expected):
454 if expected is None:
455 assert rn is None
456 else:
457 assert rn.astext() == expected
458
459 kwargs = {}
460
461 node, contnode = fake_node('std', 'term', 'a term', 'a term', **kwargs)
462 rn = missing_reference(app, app.env, node, contnode)
463 assert_(rn, 'a term' if term else None)
464
465 node, contnode = fake_node('std', 'term', 'inv:a term', 'a term', **kwargs)
466 rn = missing_reference(app, app.env, node, contnode)
467 assert_(rn, 'a term')
468
469 node, contnode = fake_node('std', 'doc', 'docname', 'docname', **kwargs)
470 rn = missing_reference(app, app.env, node, contnode)
471 assert_(rn, 'docname' if doc else None)
472
473 node, contnode = fake_node('std', 'doc', 'inv:docname', 'docname', **kwargs)
474 rn = missing_reference(app, app.env, node, contnode)
475 assert_(rn, 'docname')
476
477 # an arbitrary ref in another domain
478 node, contnode = fake_node('py', 'func', 'module1.func', 'func()', **kwargs)
479 rn = missing_reference(app, app.env, node, contnode)
480 assert_(rn, 'func()' if py else None)
481
482 node, contnode = fake_node('py', 'func', 'inv:module1.func', 'func()', **kwargs)
483 rn = missing_reference(app, app.env, node, contnode)
484 assert_(rn, 'func()')
485
486 # the base case, everything should resolve
487 assert app.config.intersphinx_disabled_reftypes == []
488 case(term=True, doc=True, py=True)
489
490 # disabled a single ref type
491 app.config.intersphinx_disabled_reftypes = ['std:doc']
492 case(term=True, doc=False, py=True)
493
494 # disabled a whole domain
495 app.config.intersphinx_disabled_reftypes = ['std:*']
496 case(term=False, doc=False, py=True)
497
498 # disabled all domains
499 app.config.intersphinx_disabled_reftypes = ['*']
500 case(term=False, doc=False, py=False)
501
502
503 @pytest.mark.sphinx('html', testroot='root')
504 def test_inventory_not_having_version(tmp_path, app):
505 inv_file = tmp_path / 'inventory'
506 inv_file.write_bytes(INVENTORY_V2_NO_VERSION)
507 set_config(
508 app,
509 {
510 'python': ('https://docs.python.org/', str(inv_file)),
511 },
512 )
513
514 # load the inventory and check if it's done correctly
515 validate_intersphinx_mapping(app, app.config)
516 load_mappings(app)
517
518 rn = reference_check(app, 'py', 'mod', 'module1', 'foo')
519 assert isinstance(rn, nodes.reference)
520 assert rn['refuri'] == 'https://docs.python.org/foo.html#module-module1'
521 assert rn['reftitle'] == '(in foo)'
522 assert rn[0].astext() == 'Long Module desc'
523
524
525 @pytest.mark.sphinx('html', testroot='root')
526 def test_validate_intersphinx_mapping_warnings(app: SphinxTestApp) -> None:
527 """Check warnings in :func:`sphinx.ext.intersphinx.validate_intersphinx_mapping`."""
528 bad_intersphinx_mapping = {
529 '': ('789.example', None), # invalid project name (value)
530 12345: ('456.example', None), # invalid project name (type)
531 None: ('123.example', None), # invalid project name (type)
532 'https://example/': None, # Sphinx 0.5 style value (None)
533 'https://server/': 'inventory', # Sphinx 0.5 style value (str)
534 'bad-dict-item': 0, # invalid dict item type
535 'unpack-except-1': [0], # invalid dict item size (native ValueError)
536 'unpack-except-2': FakeList(), # invalid dict item size (custom exception)
537 'bad-uri-type-1': (123456789, None), # invalid target URI type
538 'bad-uri-type-2': (None, None), # invalid target URI type
539 'bad-uri-value': ('', None), # invalid target URI value
540 'good': ('example.org', None), # duplicated target URI (good entry)
541 'dedup-good': ('example.org', None), # duplicated target URI
542 'bad-location-1': ('a.example', 1), # invalid inventory location (single input, bad type)
543 'bad-location-2': ('b.example', ''), # invalid inventory location (single input, bad string)
544 'bad-location-3': ('c.example', [2, 'x']), # invalid inventory location (sequence input, bad type)
545 'bad-location-4': ('d.example', ['y', '']), # invalid inventory location (sequence input, bad string)
546 'good-target-1': ('e.example', None), # valid inventory location (None)
547 'good-target-2': ('f.example', ('x',)), # valid inventory location (sequence input)
548 } # fmt: skip
549 set_config(app, bad_intersphinx_mapping)
550
551 # normalise the inventory and check if it's done correctly
552 with pytest.raises(
553 ConfigError,
554 match=r'^Invalid `intersphinx_mapping` configuration \(16 errors\).$',
555 ):
556 validate_intersphinx_mapping(app, app.config)
557 warnings = strip_escape_sequences(app.warning.getvalue()).splitlines()
558 assert len(warnings) == len(bad_intersphinx_mapping) - 3
559 assert warnings == [
560 "ERROR: Invalid intersphinx project identifier `''` in intersphinx_mapping. Project identifiers must be non-empty strings.",
561 'ERROR: Invalid intersphinx project identifier `12345` in intersphinx_mapping. Project identifiers must be non-empty strings.',
562 'ERROR: Invalid intersphinx project identifier `None` in intersphinx_mapping. Project identifiers must be non-empty strings.',
563 "ERROR: Invalid value `None` in intersphinx_mapping['https://example/']. Expected a two-element tuple or list.",
564 "ERROR: Invalid value `'inventory'` in intersphinx_mapping['https://server/']. Expected a two-element tuple or list.",
565 "ERROR: Invalid value `0` in intersphinx_mapping['bad-dict-item']. Expected a two-element tuple or list.",
566 "ERROR: Invalid value `[0]` in intersphinx_mapping['unpack-except-1']. Values must be a (target URI, inventory locations) pair.",
567 "ERROR: Invalid value `[]` in intersphinx_mapping['unpack-except-2']. Values must be a (target URI, inventory locations) pair.",
568 "ERROR: Invalid target URI value `123456789` in intersphinx_mapping['bad-uri-type-1'][0]. Target URIs must be unique non-empty strings.",
569 "ERROR: Invalid target URI value `None` in intersphinx_mapping['bad-uri-type-2'][0]. Target URIs must be unique non-empty strings.",
570 "ERROR: Invalid target URI value `''` in intersphinx_mapping['bad-uri-value'][0]. Target URIs must be unique non-empty strings.",
571 "ERROR: Invalid target URI value `'example.org'` in intersphinx_mapping['dedup-good'][0]. Target URIs must be unique (other instance in intersphinx_mapping['good']).",
572 "ERROR: Invalid inventory location value `1` in intersphinx_mapping['bad-location-1'][1]. Inventory locations must be non-empty strings or None.",
573 "ERROR: Invalid inventory location value `''` in intersphinx_mapping['bad-location-2'][1]. Inventory locations must be non-empty strings or None.",
574 "ERROR: Invalid inventory location value `2` in intersphinx_mapping['bad-location-3'][1]. Inventory locations must be non-empty strings or None.",
575 "ERROR: Invalid inventory location value `''` in intersphinx_mapping['bad-location-4'][1]. Inventory locations must be non-empty strings or None.",
576 ]
577
578
579 @pytest.mark.sphinx('html', testroot='root')
580 def test_load_mappings_fallback(tmp_path, app):
581 inv_file = tmp_path / 'inventory'
582 inv_file.write_bytes(INVENTORY_V2)
583 set_config(app, {})
584
585 # connect to invalid path
586 app.config.intersphinx_mapping = {
587 'fallback': ('https://docs.python.org/py3k/', '/invalid/inventory/path'),
588 }
589 validate_intersphinx_mapping(app, app.config)
590 load_mappings(app)
591 assert 'failed to reach any of the inventories' in app.warning.getvalue()
592
593 rn = reference_check(app, 'py', 'func', 'module1.func', 'foo')
594 assert rn is None
595
596 # clear messages
597 app.status.truncate(0)
598 app.warning.truncate(0)
599
600 # add fallbacks to mapping
601 app.config.intersphinx_mapping = {
602 'fallback': (
603 'https://docs.python.org/py3k/',
604 ('/invalid/inventory/path', str(inv_file)),
605 ),
606 }
607 validate_intersphinx_mapping(app, app.config)
608 load_mappings(app)
609 assert (
610 'encountered some issues with some of the inventories'
611 ) in app.status.getvalue()
612 assert app.warning.getvalue() == ''
613
614 rn = reference_check(app, 'py', 'func', 'module1.func', 'foo')
615 assert isinstance(rn, nodes.reference)
616
617
618 class TestStripBasicAuth:
619 """Tests for sphinx.ext.intersphinx._strip_basic_auth()"""
620
621 def test_auth_stripped(self):
622 """Basic auth creds stripped from URL containing creds"""
623 url = 'https://user:[email protected]/project/objects.inv'
624 expected = 'https://domain.com/project/objects.inv'
625 actual = _strip_basic_auth(url)
626 assert actual == expected
627
628 def test_no_auth(self):
629 """Url unchanged if param doesn't contain basic auth creds"""
630 url = 'https://domain.com/project/objects.inv'
631 expected = 'https://domain.com/project/objects.inv'
632 actual = _strip_basic_auth(url)
633 assert actual == expected
634
635 def test_having_port(self):
636 """Basic auth creds correctly stripped from URL containing creds even if URL
637 contains port
638 """
639 url = 'https://user:[email protected]:8080/project/objects.inv'
640 expected = 'https://domain.com:8080/project/objects.inv'
641 actual = _strip_basic_auth(url)
642 assert actual == expected
643
644
645 def test_getsafeurl_authed() -> None:
646 """_get_safe_url() with a url with basic auth"""
647 url = 'https://user:[email protected]/project/objects.inv'
648 expected = 'https://[email protected]/project/objects.inv'
649 actual = _get_safe_url(url)
650 assert actual == expected
651
652
653 def test_getsafeurl_authed_having_port() -> None:
654 """_get_safe_url() with a url with basic auth having port"""
655 url = 'https://user:[email protected]:8080/project/objects.inv'
656 expected = 'https://[email protected]:8080/project/objects.inv'
657 actual = _get_safe_url(url)
658 assert actual == expected
659
660
661 def test_getsafeurl_unauthed() -> None:
662 """_get_safe_url() with a url without basic auth"""
663 url = 'https://domain.com/project/objects.inv'
664 expected = 'https://domain.com/project/objects.inv'
665 actual = _get_safe_url(url)
666 assert actual == expected
667
668
669 def test_inspect_main_noargs(capsys):
670 """inspect_main interface, without arguments"""
671 assert inspect_main([]) == 1
672
673 expected = (
674 'Print out an inventory file.\n'
675 'Error: must specify local path or URL to an inventory file.'
676 )
677 stdout, stderr = capsys.readouterr()
678 assert stdout == ''
679 assert stderr == expected + '\n'
680
681
682 def test_inspect_main_file(capsys, tmp_path):
683 """inspect_main interface, with file argument"""
684 inv_file = tmp_path / 'inventory'
685 inv_file.write_bytes(INVENTORY_V2)
686
687 inspect_main([str(inv_file)])
688
689 stdout, stderr = capsys.readouterr()
690 assert stdout.startswith('c:function\n')
691 assert stderr == ''
692
693
694 def test_inspect_main_url(capsys):
695 """inspect_main interface, with url argument"""
696
697 class InventoryHandler(http.server.BaseHTTPRequestHandler):
698 def do_GET(self):
699 self.send_response(200, 'OK')
700 self.end_headers()
701 self.wfile.write(INVENTORY_V2)
702
703 def log_message(*args, **kwargs):
704 # Silenced.
705 pass
706
707 with http_server(InventoryHandler) as server:
708 url = f'http://localhost:{server.server_port}/{INVENTORY_FILENAME}'
709 inspect_main([url])
710
711 stdout, stderr = capsys.readouterr()
712 assert stdout.startswith('c:function\n')
713 assert stderr == ''
714
715
716 @pytest.mark.sphinx('html', testroot='ext-intersphinx-role', copy_test_root=True)
717 def test_intersphinx_role(app: SphinxTestApp) -> None:
718 inv_file = app.srcdir / 'inventory'
719 inv_file.write_bytes(INVENTORY_V2)
720 app.config.intersphinx_mapping = {
721 'inv': ('https://example.org/', str(inv_file)),
722 }
723 app.config.intersphinx_cache_limit = 0
724 app.config.nitpicky = True
725
726 # load the inventory and check if it's done correctly
727 validate_intersphinx_mapping(app, app.config)
728 load_mappings(app)
729
730 app.build()
731 content = (app.outdir / 'index.html').read_text(encoding='utf8')
732 warnings = strip_escape_sequences(app.warning.getvalue()).splitlines()
733 index_path = app.srcdir / 'index.rst'
734 assert warnings == [
735 f"{index_path}:21: WARNING: role for external cross-reference not found in domain 'py': 'nope' [intersphinx.external]",
736 f"{index_path}:28: WARNING: role for external cross-reference not found in domains 'cpp', 'std': 'nope' [intersphinx.external]",
737 f"{index_path}:39: WARNING: inventory for external cross-reference not found: 'invNope' [intersphinx.external]",
738 f"{index_path}:44: WARNING: role for external cross-reference not found in domain 'c': 'function' (perhaps you meant one of: 'func', 'identifier', 'type') [intersphinx.external]",
739 f"{index_path}:45: WARNING: role for external cross-reference not found in domains 'cpp', 'std': 'function' (perhaps you meant one of: 'cpp:func', 'cpp:identifier', 'cpp:type') [intersphinx.external]",
740 f'{index_path}:9: WARNING: external py:mod reference target not found: module3 [ref.mod]',
741 f'{index_path}:14: WARNING: external py:mod reference target not found: module10 [ref.mod]',
742 f'{index_path}:19: WARNING: external py:meth reference target not found: inv:Foo.bar [ref.meth]',
743 ]
744
745 html = '<a class="reference external" href="https://example.org/{}" title="(in foo v2.0)">'
746 assert html.format('foo.html#module-module1') in content
747 assert html.format('foo.html#module-module2') in content
748
749 assert html.format('sub/foo.html#module1.func') in content
750
751 # default domain
752 assert html.format('index.html#std_uint8_t') in content
753
754 # std roles without domain prefix
755 assert html.format('docname.html') in content
756 assert html.format('index.html#cmdoption-ls-l') in content
757
758 # explicit inventory
759 assert html.format('cfunc.html#CFunc') in content
760
761 # explicit title
762 assert html.format('index.html#foons') in content
763
764
765 @pytest.mark.sphinx('html', testroot='root')
766 @pytest.mark.parametrize(
767 ('cache_limit', 'expected_expired'),
768 [
769 (5, False), # cache for 5 days
770 (1, True), # cache for 1 day
771 (0, True), # cache for 0 days
772 (-1, False), # cache forever
773 ],
774 )
775 def test_intersphinx_cache_limit(app, monkeypatch, cache_limit, expected_expired):
776 url = 'https://example.org/'
777 app.config.intersphinx_cache_limit = cache_limit
778 app.config.intersphinx_mapping = {
779 'inv': (url, None),
780 }
781 app.config.intersphinx_timeout = None
782 # load the inventory and check if it's done correctly
783 intersphinx_cache: dict[str, InventoryCacheEntry] = {
784 url: ('inv', 0, {}), # Timestamp of last cache write is zero.
785 }
786 validate_intersphinx_mapping(app, app.config)
787
788 # The test's `now` is two days after the cache was created.
789 now = 2 * 86400
790 monkeypatch.setattr('time.time', lambda: now)
791
792 # `_fetch_inventory_group` calls `_fetch_inventory_data`.
793 # We replace it with a mock to test whether it has been called.
794 # If it has been called, it means the cache had expired.
795 monkeypatch.setattr(
796 'sphinx.ext.intersphinx._load._fetch_inventory_data',
797 mock.Mock(return_value=(b'', '')),
798 )
799 mock_fetch_inventory = mock.Mock(return_value=_Inventory({}))
800 monkeypatch.setattr(
801 'sphinx.ext.intersphinx._load._load_inventory', mock_fetch_inventory
802 )
803
804 for name, (uri, locations) in app.config.intersphinx_mapping.values():
805 project = _IntersphinxProject(name=name, target_uri=uri, locations=locations)
806 updated = _fetch_inventory_group(
807 project=project,
808 cache=intersphinx_cache,
809 now=now,
810 config=_InvConfig.from_config(app.config),
811 srcdir=app.srcdir,
812 cache_dir=None,
813 )
814 # If we hadn't mocked `_fetch_inventory_data`, it would've made
815 # a request to `https://example.org/` and found no inventory
816 # file. That would've been an error, and `updated` would've been
817 # False even if the cache had expired. The mock makes it behave
818 # "correctly".
819 assert updated is expected_expired
820 # Double-check: If the cache was expired, `mock_fetch_inventory`
821 # must've been called.
822 assert mock_fetch_inventory.called is expected_expired
823
824
825 def test_intersphinx_fetch_inventory_group_url():
826 class InventoryHandler(http.server.BaseHTTPRequestHandler):
827 def do_GET(self):
828 self.send_response(200, 'OK')
829 self.end_headers()
830 self.wfile.write(INVENTORY_V2)
831
832 def log_message(*args, **kwargs):
833 # Silenced.
834 pass
835
836 with http_server(InventoryHandler) as server:
837 url1 = f'http://localhost:{server.server_port}'
838 url2 = f'http://localhost:{server.server_port}/'
839
840 config = Config()
841 config.intersphinx_cache_limit = -1
842 config.intersphinx_mapping = {
843 '1': (url1, None),
844 '2': (url2, None),
845 }
846
847 now = int(time.time())
848 # we can use 'srcdir=None' since we are raising in _fetch_inventory_data
849 kwds = {
850 'cache': {},
851 'now': now,
852 'config': config,
853 'srcdir': None,
854 'cache_dir': None,
855 }
856 # We need an exception with its 'args' attribute set (see error
857 # handling in sphinx.ext.intersphinx._load._fetch_inventory_group).
858 side_effect = ValueError('')
859
860 project1 = _IntersphinxProject(
861 name='1', target_uri=url1, locations=(url1, None)
862 )
863 with mock.patch(
864 'sphinx.ext.intersphinx._load._fetch_inventory_data',
865 side_effect=side_effect,
866 ) as mockfn:
867 assert not _fetch_inventory_group(project=project1, **kwds)
868 mockfn.assert_any_call(
869 target_uri=url1,
870 inv_location=url1,
871 config=config,
872 srcdir=None,
873 cache_path=None,
874 )
875 mockfn.assert_any_call(
876 target_uri=url1,
877 inv_location=url1 + '/' + INVENTORY_FILENAME,
878 config=config,
879 srcdir=None,
880 cache_path=None,
881 )
882
883 project2 = _IntersphinxProject(
884 name='2', target_uri=url2, locations=(url2, None)
885 )
886 with mock.patch(
887 'sphinx.ext.intersphinx._load._fetch_inventory_data',
888 side_effect=side_effect,
889 ) as mockfn:
890 assert not _fetch_inventory_group(project=project2, **kwds)
891 mockfn.assert_any_call(
892 target_uri=url2,
893 inv_location=url2,
894 config=config,
895 srcdir=None,
896 cache_path=None,
897 )
898 mockfn.assert_any_call(
899 target_uri=url2,
900 inv_location=url2 + INVENTORY_FILENAME,
901 config=config,
902 srcdir=None,
903 cache_path=None,
904 )
905
906
907 @pytest.mark.sphinx('html', testroot='root')
908 def test_inventory_text_version(tmp_path, app):
909 inv_file = tmp_path / 'inventory'
910 inv_file.write_bytes(INVENTORY_V2_TEXT_VERSION)
911 set_config(
912 app,
913 {
914 'python': ('https://docs.python.org/', str(inv_file)),
915 },
916 )
917
918 # load the inventory and check if non-numeric version is handled correctly
919 validate_intersphinx_mapping(app, app.config)
920 load_mappings(app)
921
922 rn = reference_check(app, 'py', 'mod', 'module1', 'foo')
923 assert isinstance(rn, nodes.reference)
924 assert rn['refuri'] == 'https://docs.python.org/foo.html#module-module1'
925 assert rn['reftitle'] == '(in foo stable)'
926 assert rn[0].astext() == 'Long Module desc'
927
928
929 def test_display_failures():
930 failures_args = [
931 ('Failed to fetch %s from %s', 'inventory', 'http://example.com'),
932 ('Timeout after %d seconds',), # Only one argument
933 (
934 'intersphinx inventory has moved:',
935 'http://example.com',
936 'http://proxyhost.net',
937 ), # No '%'
938 ]
939 issues = _display_failures(failures_args)
940 assert 'Failed to fetch inventory from http://example.com' in issues
941 assert 'Timeout after %d seconds' in issues
942 assert (
943 'intersphinx inventory has moved: - http://example.com - http://proxyhost.net'
944 in issues
945 )