Debian Codegraph @

tests/test_domains/test_domain_py.py

raw
1 """Tests the Python Domain"""
2
3 from __future__ import annotations
4
5 import re
6 from unittest.mock import Mock
7
8 import docutils.utils
9 import pytest
10 from docutils import nodes
11
12 from sphinx import addnodes
13 from sphinx.addnodes import (
14 desc,
15 desc_annotation,
16 desc_content,
17 desc_name,
18 desc_parameter,
19 desc_parameterlist,
20 desc_returns,
21 desc_sig_keyword,
22 desc_sig_literal_number,
23 desc_sig_literal_string,
24 desc_sig_name,
25 desc_sig_operator,
26 desc_sig_punctuation,
27 desc_sig_space,
28 desc_signature,
29 desc_type_parameter,
30 desc_type_parameter_list,
31 pending_xref,
32 )
33 from sphinx.domains import IndexEntry
34 from sphinx.domains.python import PythonDomain, PythonModuleIndex
35 from sphinx.domains.python._annotations import _parse_annotation, _pseudo_parse_arglist
36 from sphinx.domains.python._object import py_sig_re
37 from sphinx.testing import restructuredtext
38 from sphinx.testing.util import assert_node
39 from sphinx.writers.text import STDINDENT
40
41 from tests.utils import extract_node
42
43 TYPE_CHECKING = False
44 if TYPE_CHECKING:
45 from sphinx.application import Sphinx
46 from sphinx.environment import BuildEnvironment
47 from sphinx.testing.util import SphinxTestApp
48
49
50 def parse(sig: str, *, env: BuildEnvironment) -> str:
51 m = py_sig_re.match(sig)
52 if m is None:
53 raise ValueError
54 _name_prefix, _tp_list, _name, arglist, _retann = m.groups()
55 signode = addnodes.desc_signature(sig, '')
56 _pseudo_parse_arglist(signode, arglist, env=env)
57 return signode.astext()
58
59
60 def test_function_signatures(app: Sphinx) -> None:
61 rv = parse("compile(source : string, filename, symbol='file')", env=app.env)
62 assert rv == "(source: string, filename, symbol='file')"
63
64 for params, expect in [
65 ('(a=1)', '(a=1)'),
66 ('(a: int = 1)', '(a: int = 1)'),
67 ('(a=1, [b=None])', '(a=1, [b=None])'),
68 ('(a=1[, b=None])', '(a=1, [b=None])'),
69 ('(a=[], [b=None])', '(a=[], [b=None])'),
70 ('(a=[][, b=None])', '(a=[], [b=None])'),
71 ('(a: Foo[Bar]=[][, b=None])', '(a: Foo[Bar] = [], [b=None])'),
72 ]:
73 rv = parse(f'func{params}', env=app.env)
74 assert rv == expect
75
76 # Note: 'def f[Foo[Bar]]()' is not valid Python but people might write
77 # it in a reST document to convene the intent of a higher-kinded type
78 # variable.
79 for tparams in ['', '[Foo]', '[Foo[Bar]]']:
80 for retann in ['', '-> Foo', '-> Foo[Bar]', '-> anything else']:
81 rv = parse(f'func{tparams}{params} {retann}'.rstrip(), env=app.env)
82 assert rv == expect
83
84
85 @pytest.mark.sphinx('dummy', testroot='domain-py')
86 def test_domain_py_xrefs(app):
87 """Domain objects have correct prefixes when looking up xrefs"""
88 app.build(force_all=True)
89
90 def assert_refnode(
91 node, module_name, class_name, target, reftype=None, domain='py'
92 ):
93 attributes = {
94 'refdomain': domain,
95 'reftarget': target,
96 }
97 if reftype is not None:
98 attributes['reftype'] = reftype
99 if module_name is not False:
100 attributes['py:module'] = module_name
101 if class_name is not False:
102 attributes['py:class'] = class_name
103 assert_node(node, **attributes)
104
105 doctree = app.env.get_doctree('roles')
106 refnodes = list(doctree.findall(pending_xref))
107 assert_refnode(refnodes[0], None, None, 'TopLevel', 'class')
108 assert_refnode(refnodes[1], None, None, 'top_level', 'meth')
109 assert_refnode(refnodes[2], None, None, 'TopLevelType', 'type')
110 assert_refnode(refnodes[3], None, 'NestedParentA', 'child_1', 'meth')
111 assert_refnode(
112 refnodes[4], None, 'NestedParentA', 'NestedChildA.subchild_2', 'meth'
113 )
114 assert_refnode(refnodes[5], None, 'NestedParentA', 'child_2', 'meth')
115 assert_refnode(refnodes[6], False, 'NestedParentA', 'any_child', domain='')
116 assert_refnode(refnodes[7], None, 'NestedParentA', 'NestedChildA', 'class')
117 assert_refnode(
118 refnodes[8], None, 'NestedParentA.NestedChildA', 'subchild_2', 'meth'
119 )
120 assert_refnode(
121 refnodes[9], None, 'NestedParentA.NestedChildA', 'NestedParentA.child_1', 'meth'
122 )
123 assert_refnode(
124 refnodes[10], None, 'NestedParentA', 'NestedChildA.subchild_1', 'meth'
125 )
126 assert_refnode(refnodes[11], None, 'NestedParentB', 'child_1', 'meth')
127 assert_refnode(refnodes[12], None, 'NestedParentB', 'NestedParentB', 'class')
128 assert_refnode(refnodes[13], None, None, 'NestedParentA.NestedChildA', 'class')
129 assert_refnode(refnodes[14], None, None, 'NestedParentA.NestedTypeA', 'type')
130 assert len(refnodes) == 15
131
132 doctree = app.env.get_doctree('module')
133 refnodes = list(doctree.findall(pending_xref))
134 assert_refnode(refnodes[0], 'module_a.submodule', None, 'ModTopLevel', 'class')
135 assert_refnode(
136 refnodes[1], 'module_a.submodule', 'ModTopLevel', 'mod_child_1', 'meth'
137 )
138 assert_refnode(
139 refnodes[2],
140 'module_a.submodule',
141 'ModTopLevel',
142 'ModTopLevel.mod_child_1',
143 'meth',
144 )
145 assert_refnode(
146 refnodes[3], 'module_a.submodule', 'ModTopLevel', 'mod_child_2', 'meth'
147 )
148 assert_refnode(
149 refnodes[4],
150 'module_a.submodule',
151 'ModTopLevel',
152 'module_a.submodule.ModTopLevel.mod_child_1',
153 'meth',
154 )
155 assert_refnode(refnodes[5], 'module_a.submodule', 'ModTopLevel', 'prop', 'attr')
156 assert_refnode(refnodes[6], 'module_a.submodule', 'ModTopLevel', 'prop', 'meth')
157 assert_refnode(refnodes[7], 'module_b.submodule', None, 'ModTopLevel', 'class')
158 assert_refnode(
159 refnodes[8], 'module_b.submodule', 'ModTopLevel', 'ModNoModule', 'class'
160 )
161 assert_refnode(refnodes[9], False, False, 'int', 'class')
162 assert_refnode(refnodes[10], False, False, 'tuple', 'class')
163 assert_refnode(refnodes[11], False, False, 'str', 'class')
164 assert_refnode(refnodes[12], False, False, 'float', 'class')
165 assert_refnode(refnodes[13], False, False, 'list', 'class')
166 assert_refnode(refnodes[14], False, False, 'ModTopLevel', 'class')
167 assert_refnode(refnodes[15], False, False, 'index', 'doc', domain='std')
168 assert_refnode(refnodes[16], False, False, 'typing.Literal', 'obj', domain='py')
169 assert_refnode(refnodes[17], False, False, 'typing.Literal', 'obj', domain='py')
170 assert_refnode(refnodes[18], False, False, 'list', 'class', domain='py')
171 assert_refnode(refnodes[19], False, False, 'int', 'class', domain='py')
172 assert_refnode(refnodes[20], False, False, 'str', 'class', domain='py')
173 assert len(refnodes) == 21
174
175 doctree = app.env.get_doctree('module_option')
176 refnodes = list(doctree.findall(pending_xref))
177 print(refnodes)
178 print(refnodes[0])
179 print(refnodes[1])
180 assert_refnode(refnodes[0], 'test.extra', 'B', 'foo', 'meth')
181 assert_refnode(refnodes[1], 'test.extra', 'B', 'foo', 'meth')
182 assert len(refnodes) == 2
183
184
185 @pytest.mark.sphinx('html', testroot='domain-py')
186 def test_domain_py_xrefs_abbreviations(app):
187 app.build(force_all=True)
188
189 content = (app.outdir / 'abbr.html').read_text(encoding='utf8')
190 assert re.search(
191 r'normal: <a .* href="module.html#module_a.submodule.ModTopLevel.'
192 r'mod_child_1" .*><.*>module_a.submodule.ModTopLevel.mod_child_1\(\)'
193 r'<.*></a>',
194 content,
195 )
196 assert re.search(
197 r'relative: <a .* href="module.html#module_a.submodule.ModTopLevel.'
198 r'mod_child_1" .*><.*>ModTopLevel.mod_child_1\(\)<.*></a>',
199 content,
200 )
201 assert re.search(
202 r'short name: <a .* href="module.html#module_a.submodule.ModTopLevel.'
203 r'mod_child_1" .*><.*>mod_child_1\(\)<.*></a>',
204 content,
205 )
206 assert re.search(
207 r'relative \+ short name: <a .* href="module.html#module_a.submodule.'
208 r'ModTopLevel.mod_child_1" .*><.*>mod_child_1\(\)<.*></a>',
209 content,
210 )
211 assert re.search(
212 r'short name \+ relative: <a .* href="module.html#module_a.submodule.'
213 r'ModTopLevel.mod_child_1" .*><.*>mod_child_1\(\)<.*></a>',
214 content,
215 )
216
217
218 @pytest.mark.sphinx('dummy', testroot='domain-py')
219 def test_domain_py_objects(app):
220 app.build(force_all=True)
221
222 modules = app.env.domains.python_domain.data['modules']
223 objects = app.env.domains.python_domain.data['objects']
224
225 assert 'module_a.submodule' in modules
226 assert 'module_a.submodule' in objects
227 assert 'module_b.submodule' in modules
228 assert 'module_b.submodule' in objects
229
230 assert objects['module_a.submodule.ModTopLevel'][2] == 'class'
231 assert objects['module_a.submodule.ModTopLevel.mod_child_1'][2] == 'method'
232 assert objects['module_a.submodule.ModTopLevel.mod_child_2'][2] == 'method'
233 assert 'ModTopLevel.ModNoModule' not in objects
234 assert objects['ModNoModule'][2] == 'class'
235 assert objects['module_b.submodule.ModTopLevel'][2] == 'class'
236
237 assert objects['TopLevel'][2] == 'class'
238 assert objects['top_level'][2] == 'method'
239 assert objects['TopLevelType'][2] == 'type'
240 assert objects['NestedParentA'][2] == 'class'
241 assert objects['NestedParentA.NestedTypeA'][2] == 'type'
242 assert objects['NestedParentA.child_1'][2] == 'method'
243 assert objects['NestedParentA.any_child'][2] == 'method'
244 assert objects['NestedParentA.NestedChildA'][2] == 'class'
245 assert objects['NestedParentA.NestedChildA.subchild_1'][2] == 'method'
246 assert objects['NestedParentA.NestedChildA.subchild_2'][2] == 'method'
247 assert objects['NestedParentA.child_2'][2] == 'method'
248 assert objects['NestedParentB'][2] == 'class'
249 assert objects['NestedParentB.child_1'][2] == 'method'
250
251
252 @pytest.mark.sphinx('html', testroot='domain-py')
253 def test_resolve_xref_for_properties(app):
254 app.build(force_all=True)
255
256 content = (app.outdir / 'module.html').read_text(encoding='utf8')
257 assert (
258 'Link to <a class="reference internal" href="#module_a.submodule.ModTopLevel.prop"'
259 ' title="module_a.submodule.ModTopLevel.prop">'
260 '<code class="xref py py-attr docutils literal notranslate"><span class="pre">'
261 'prop</span> <span class="pre">attribute</span></code></a>'
262 ) in content
263 assert (
264 'Link to <a class="reference internal" href="#module_a.submodule.ModTopLevel.prop"'
265 ' title="module_a.submodule.ModTopLevel.prop">'
266 '<code class="xref py py-meth docutils literal notranslate"><span class="pre">'
267 'prop</span> <span class="pre">method</span></code></a>'
268 ) in content
269 assert (
270 'Link to <a class="reference internal" href="#module_a.submodule.ModTopLevel.prop"'
271 ' title="module_a.submodule.ModTopLevel.prop">'
272 '<code class="xref py py-attr docutils literal notranslate"><span class="pre">'
273 'prop</span> <span class="pre">attribute</span></code></a>'
274 ) in content
275
276
277 @pytest.mark.sphinx('dummy', testroot='domain-py')
278 def test_domain_py_find_obj(app):
279 def find_obj(modname, prefix, obj_name, obj_type, searchmode=0):
280 return app.env.domains.python_domain.find_obj(
281 app.env, modname, prefix, obj_name, obj_type, searchmode
282 )
283
284 app.build(force_all=True)
285
286 assert find_obj(None, None, 'NONEXISTANT', 'class') == []
287 assert find_obj(None, None, 'NestedParentA', 'class') == [
288 (
289 'NestedParentA',
290 ('roles', 'NestedParentA', 'class', False),
291 )
292 ]
293 assert find_obj(None, None, 'NestedParentA.NestedTypeA', 'type') == [
294 (
295 'NestedParentA.NestedTypeA',
296 ('roles', 'NestedParentA.NestedTypeA', 'type', False),
297 )
298 ]
299 assert find_obj(None, None, 'NestedParentA.NestedChildA', 'class') == [
300 (
301 'NestedParentA.NestedChildA',
302 ('roles', 'NestedParentA.NestedChildA', 'class', False),
303 )
304 ]
305 assert find_obj(None, 'NestedParentA', 'NestedChildA', 'class') == [
306 (
307 'NestedParentA.NestedChildA',
308 ('roles', 'NestedParentA.NestedChildA', 'class', False),
309 )
310 ]
311 assert find_obj(None, None, 'NestedParentA.NestedChildA.subchild_1', 'meth') == [
312 (
313 'NestedParentA.NestedChildA.subchild_1',
314 ('roles', 'NestedParentA.NestedChildA.subchild_1', 'method', False),
315 )
316 ]
317 assert find_obj(None, 'NestedParentA', 'NestedChildA.subchild_1', 'meth') == [
318 (
319 'NestedParentA.NestedChildA.subchild_1',
320 ('roles', 'NestedParentA.NestedChildA.subchild_1', 'method', False),
321 )
322 ]
323 assert find_obj(None, 'NestedParentA.NestedChildA', 'subchild_1', 'meth') == [
324 (
325 'NestedParentA.NestedChildA.subchild_1',
326 ('roles', 'NestedParentA.NestedChildA.subchild_1', 'method', False),
327 )
328 ]
329
330
331 @pytest.mark.sphinx('html', testroot='root')
332 def test_get_full_qualified_name() -> None:
333 env = Mock(domaindata={})
334 domain = PythonDomain(env)
335
336 # non-python references
337 node = nodes.reference()
338 assert domain.get_full_qualified_name(node) is None
339
340 # simple reference
341 node = nodes.reference(reftarget='func')
342 assert domain.get_full_qualified_name(node) == 'func'
343
344 # with py:module context
345 kwargs = {'py:module': 'module1'}
346 node = nodes.reference(reftarget='func', **kwargs)
347 assert domain.get_full_qualified_name(node) == 'module1.func'
348
349 # with py:class context
350 kwargs = {'py:class': 'Class'}
351 node = nodes.reference(reftarget='func', **kwargs)
352 assert domain.get_full_qualified_name(node) == 'Class.func'
353
354 # with both py:module and py:class context
355 kwargs = {'py:module': 'module1', 'py:class': 'Class'}
356 node = nodes.reference(reftarget='func', **kwargs)
357 assert domain.get_full_qualified_name(node) == 'module1.Class.func'
358
359
360 @pytest.mark.sphinx('html', testroot='_blank')
361 def test_parse_annotation(app):
362 doctree = _parse_annotation('int', app.env)
363 assert_node(doctree, ([pending_xref, 'int'],))
364 assert_node(
365 doctree[0], pending_xref, refdomain='py', reftype='class', reftarget='int'
366 )
367
368 doctree = _parse_annotation('List[int]', app.env)
369 assert_node(
370 doctree,
371 (
372 [pending_xref, 'List'],
373 [desc_sig_punctuation, '['],
374 [pending_xref, 'int'],
375 [desc_sig_punctuation, ']'],
376 ),
377 )
378
379 doctree = _parse_annotation('Tuple[int, int]', app.env)
380 assert_node(
381 doctree,
382 (
383 [pending_xref, 'Tuple'],
384 [desc_sig_punctuation, '['],
385 [pending_xref, 'int'],
386 [desc_sig_punctuation, ','],
387 desc_sig_space,
388 [pending_xref, 'int'],
389 [desc_sig_punctuation, ']'],
390 ),
391 )
392
393 doctree = _parse_annotation('Tuple[()]', app.env)
394 assert_node(
395 doctree,
396 (
397 [pending_xref, 'Tuple'],
398 [desc_sig_punctuation, '['],
399 [desc_sig_punctuation, '('],
400 [desc_sig_punctuation, ')'],
401 [desc_sig_punctuation, ']'],
402 ),
403 )
404
405 doctree = _parse_annotation('Tuple[int, ...]', app.env)
406 assert_node(
407 doctree,
408 (
409 [pending_xref, 'Tuple'],
410 [desc_sig_punctuation, '['],
411 [pending_xref, 'int'],
412 [desc_sig_punctuation, ','],
413 desc_sig_space,
414 [desc_sig_punctuation, '...'],
415 [desc_sig_punctuation, ']'],
416 ),
417 )
418
419 doctree = _parse_annotation('Callable[[int, int], int]', app.env)
420 assert_node(
421 doctree,
422 (
423 [pending_xref, 'Callable'],
424 [desc_sig_punctuation, '['],
425 [desc_sig_punctuation, '['],
426 [pending_xref, 'int'],
427 [desc_sig_punctuation, ','],
428 desc_sig_space,
429 [pending_xref, 'int'],
430 [desc_sig_punctuation, ']'],
431 [desc_sig_punctuation, ','],
432 desc_sig_space,
433 [pending_xref, 'int'],
434 [desc_sig_punctuation, ']'],
435 ),
436 )
437
438 doctree = _parse_annotation('Callable[[], int]', app.env)
439 assert_node(
440 doctree,
441 (
442 [pending_xref, 'Callable'],
443 [desc_sig_punctuation, '['],
444 [desc_sig_punctuation, '['],
445 [desc_sig_punctuation, ']'],
446 [desc_sig_punctuation, ','],
447 desc_sig_space,
448 [pending_xref, 'int'],
449 [desc_sig_punctuation, ']'],
450 ),
451 )
452
453 doctree = _parse_annotation('List[None]', app.env)
454 assert_node(
455 doctree,
456 (
457 [pending_xref, 'List'],
458 [desc_sig_punctuation, '['],
459 [pending_xref, 'None'],
460 [desc_sig_punctuation, ']'],
461 ),
462 )
463
464 # None type makes an object-reference (not a class reference)
465 doctree = _parse_annotation('None', app.env)
466 assert_node(doctree, ([pending_xref, 'None'],))
467 assert_node(
468 doctree[0], pending_xref, refdomain='py', reftype='obj', reftarget='None'
469 )
470
471 # Literal type makes an object-reference (not a class reference)
472 doctree = _parse_annotation("typing.Literal['a', 'b']", app.env)
473 assert_node(
474 doctree,
475 (
476 [pending_xref, 'Literal'],
477 [desc_sig_punctuation, '['],
478 [desc_sig_literal_string, "'a'"],
479 [desc_sig_punctuation, ','],
480 desc_sig_space,
481 [desc_sig_literal_string, "'b'"],
482 [desc_sig_punctuation, ']'],
483 ),
484 )
485 assert_node(
486 doctree[0],
487 pending_xref,
488 refdomain='py',
489 reftype='obj',
490 reftarget='typing.Literal',
491 )
492
493 # Annotated type with callable gets parsed
494 doctree = _parse_annotation(
495 'Annotated[Optional[str], annotated_types.MaxLen(max_length=10)]', app.env
496 )
497 assert_node(
498 doctree,
499 (
500 [pending_xref, 'Annotated'],
501 [desc_sig_punctuation, '['],
502 [pending_xref, 'str'],
503 [desc_sig_space, ' '],
504 [desc_sig_punctuation, '|'],
505 [desc_sig_space, ' '],
506 [pending_xref, 'None'],
507 [desc_sig_punctuation, ','],
508 [desc_sig_space, ' '],
509 [pending_xref, 'annotated_types.MaxLen'],
510 [desc_sig_punctuation, '('],
511 [desc_sig_name, 'max_length'],
512 [desc_sig_operator, '='],
513 [desc_sig_literal_number, '10'],
514 [desc_sig_punctuation, ')'],
515 [desc_sig_punctuation, ']'],
516 ),
517 )
518
519 doctree = _parse_annotation('*tuple[str, int]', app.env)
520 assert_node(
521 doctree,
522 (
523 [desc_sig_operator, '*'],
524 [pending_xref, 'tuple'],
525 [desc_sig_punctuation, '['],
526 [pending_xref, 'str'],
527 [desc_sig_punctuation, ','],
528 desc_sig_space,
529 [pending_xref, 'int'],
530 [desc_sig_punctuation, ']'],
531 ),
532 )
533 assert_node(
534 doctree[1],
535 pending_xref,
536 refdomain='py',
537 reftype='class',
538 reftarget='tuple',
539 )
540
541
542 @pytest.mark.sphinx('html', testroot='_blank')
543 def test_parse_annotation_suppress(app):
544 doctree = _parse_annotation('~typing.Dict[str, str]', app.env)
545 assert_node(
546 doctree,
547 (
548 [pending_xref, 'Dict'],
549 [desc_sig_punctuation, '['],
550 [pending_xref, 'str'],
551 [desc_sig_punctuation, ','],
552 desc_sig_space,
553 [pending_xref, 'str'],
554 [desc_sig_punctuation, ']'],
555 ),
556 )
557 assert_node(
558 doctree[0], pending_xref, refdomain='py', reftype='obj', reftarget='typing.Dict'
559 )
560
561
562 @pytest.mark.sphinx('html', testroot='_blank')
563 def test_parse_annotation_Literal(app):
564 doctree = _parse_annotation('Literal[True, False]', app.env)
565 assert_node(
566 doctree,
567 (
568 [pending_xref, 'Literal'],
569 [desc_sig_punctuation, '['],
570 [desc_sig_keyword, 'True'],
571 [desc_sig_punctuation, ','],
572 desc_sig_space,
573 [desc_sig_keyword, 'False'],
574 [desc_sig_punctuation, ']'],
575 ),
576 )
577
578 doctree = _parse_annotation("typing.Literal[0, 1, 'abc']", app.env)
579 assert_node(
580 doctree,
581 (
582 [pending_xref, 'Literal'],
583 [desc_sig_punctuation, '['],
584 [desc_sig_literal_number, '0'],
585 [desc_sig_punctuation, ','],
586 desc_sig_space,
587 [desc_sig_literal_number, '1'],
588 [desc_sig_punctuation, ','],
589 desc_sig_space,
590 [desc_sig_literal_string, "'abc'"],
591 [desc_sig_punctuation, ']'],
592 ),
593 )
594
595
596 @pytest.mark.sphinx('html', testroot='root', freshenv=True)
597 def test_module_index(app):
598 text = (
599 '.. py:module:: docutils\n'
600 '.. py:module:: sphinx\n'
601 '.. py:module:: sphinx.config\n'
602 '.. py:module:: sphinx.builders\n'
603 '.. py:module:: sphinx.builders.html\n'
604 '.. py:module:: sphinx_intl\n'
605 )
606 restructuredtext.parse(app, text)
607 index = PythonModuleIndex(app.env.domains.python_domain)
608 assert index.generate() == (
609 [
610 (
611 'd',
612 [
613 IndexEntry(
614 name='docutils',
615 subtype=0,
616 docname='index',
617 anchor='module-docutils',
618 extra='',
619 qualifier='',
620 descr='',
621 ),
622 ],
623 ),
624 (
625 's',
626 [
627 IndexEntry(
628 name='sphinx',
629 subtype=1,
630 docname='index',
631 anchor='module-sphinx',
632 extra='',
633 qualifier='',
634 descr='',
635 ),
636 IndexEntry(
637 name='sphinx.builders',
638 subtype=2,
639 docname='index',
640 anchor='module-sphinx.builders',
641 extra='',
642 qualifier='',
643 descr='',
644 ),
645 IndexEntry(
646 name='sphinx.builders.html',
647 subtype=2,
648 docname='index',
649 anchor='module-sphinx.builders.html',
650 extra='',
651 qualifier='',
652 descr='',
653 ),
654 IndexEntry(
655 name='sphinx.config',
656 subtype=2,
657 docname='index',
658 anchor='module-sphinx.config',
659 extra='',
660 qualifier='',
661 descr='',
662 ),
663 IndexEntry(
664 name='sphinx_intl',
665 subtype=0,
666 docname='index',
667 anchor='module-sphinx_intl',
668 extra='',
669 qualifier='',
670 descr='',
671 ),
672 ],
673 ),
674 ],
675 False,
676 )
677
678
679 @pytest.mark.sphinx('html', testroot='root', freshenv=True)
680 def test_module_index_submodule(app):
681 text = '.. py:module:: sphinx.config\n'
682 restructuredtext.parse(app, text)
683 index = PythonModuleIndex(app.env.domains.python_domain)
684 assert index.generate() == (
685 [
686 (
687 's',
688 [
689 IndexEntry(
690 name='sphinx',
691 subtype=1,
692 docname='',
693 anchor='',
694 extra='',
695 qualifier='',
696 descr='',
697 ),
698 IndexEntry(
699 name='sphinx.config',
700 subtype=2,
701 docname='index',
702 anchor='module-sphinx.config',
703 extra='',
704 qualifier='',
705 descr='',
706 ),
707 ],
708 )
709 ],
710 False,
711 )
712
713
714 @pytest.mark.sphinx('html', testroot='root', freshenv=True)
715 def test_module_index_not_collapsed(app):
716 text = '.. py:module:: docutils\n.. py:module:: sphinx\n'
717 restructuredtext.parse(app, text)
718 index = PythonModuleIndex(app.env.domains.python_domain)
719 assert index.generate() == (
720 [
721 (
722 'd',
723 [
724 IndexEntry(
725 name='docutils',
726 subtype=0,
727 docname='index',
728 anchor='module-docutils',
729 extra='',
730 qualifier='',
731 descr='',
732 ),
733 ],
734 ),
735 (
736 's',
737 [
738 IndexEntry(
739 name='sphinx',
740 subtype=0,
741 docname='index',
742 anchor='module-sphinx',
743 extra='',
744 qualifier='',
745 descr='',
746 ),
747 ],
748 ),
749 ],
750 True,
751 )
752
753
754 @pytest.mark.sphinx(
755 'html',
756 testroot='root',
757 freshenv=True,
758 confoverrides={'modindex_common_prefix': ['sphinx.']},
759 )
760 def test_modindex_common_prefix(app):
761 text = (
762 '.. py:module:: docutils\n'
763 '.. py:module:: sphinx\n'
764 '.. py:module:: sphinx.config\n'
765 '.. py:module:: sphinx.builders\n'
766 '.. py:module:: sphinx.builders.html\n'
767 '.. py:module:: sphinx_intl\n'
768 )
769 restructuredtext.parse(app, text)
770 index = PythonModuleIndex(app.env.domains.python_domain)
771 assert index.generate() == (
772 [
773 (
774 'b',
775 [
776 IndexEntry(
777 name='sphinx.builders',
778 subtype=1,
779 docname='index',
780 anchor='module-sphinx.builders',
781 extra='',
782 qualifier='',
783 descr='',
784 ),
785 IndexEntry(
786 name='sphinx.builders.html',
787 subtype=2,
788 docname='index',
789 anchor='module-sphinx.builders.html',
790 extra='',
791 qualifier='',
792 descr='',
793 ),
794 ],
795 ),
796 (
797 'c',
798 [
799 IndexEntry(
800 name='sphinx.config',
801 subtype=0,
802 docname='index',
803 anchor='module-sphinx.config',
804 extra='',
805 qualifier='',
806 descr='',
807 ),
808 ],
809 ),
810 (
811 'd',
812 [
813 IndexEntry(
814 name='docutils',
815 subtype=0,
816 docname='index',
817 anchor='module-docutils',
818 extra='',
819 qualifier='',
820 descr='',
821 ),
822 ],
823 ),
824 (
825 's',
826 [
827 IndexEntry(
828 name='sphinx',
829 subtype=0,
830 docname='index',
831 anchor='module-sphinx',
832 extra='',
833 qualifier='',
834 descr='',
835 ),
836 IndexEntry(
837 name='sphinx_intl',
838 subtype=0,
839 docname='index',
840 anchor='module-sphinx_intl',
841 extra='',
842 qualifier='',
843 descr='',
844 ),
845 ],
846 ),
847 ],
848 True,
849 )
850
851
852 @pytest.mark.sphinx('html', testroot='_blank')
853 def test_no_index_entry(app):
854 text = '.. py:function:: f()\n.. py:function:: g()\n :no-index-entry:\n'
855 doctree = restructuredtext.parse(app, text)
856 assert_node(doctree, (addnodes.index, desc, addnodes.index, desc))
857 assert_node(
858 doctree[0],
859 addnodes.index,
860 entries=[('pair', 'built-in function; f()', 'f', '', None)],
861 )
862 assert_node(doctree[2], addnodes.index, entries=[])
863
864 text = '.. py:class:: f\n.. py:class:: g\n :no-index-entry:\n'
865 doctree = restructuredtext.parse(app, text)
866 assert_node(doctree, (addnodes.index, desc, addnodes.index, desc))
867 assert_node(
868 doctree[0],
869 addnodes.index,
870 entries=[('single', 'f (built-in class)', 'f', '', None)],
871 )
872 assert_node(doctree[2], addnodes.index, entries=[])
873
874 text = '.. py:module:: f\n.. py:module:: g\n :no-index-entry:\n'
875 doctree = restructuredtext.parse(app, text)
876 assert_node(doctree, (addnodes.index, nodes.target, nodes.target))
877 assert_node(
878 doctree[0],
879 addnodes.index,
880 entries=[('pair', 'module; f', 'module-f', '', None)],
881 )
882
883
884 @pytest.mark.sphinx('html', testroot='domain-py-python_use_unqualified_type_names')
885 def test_python_python_use_unqualified_type_names(app):
886 app.build()
887 content = (app.outdir / 'index.html').read_text(encoding='utf8')
888 assert (
889 '<span class="n"><a class="reference internal" href="#foo.Name" title="foo.Name">'
890 '<span class="pre">Name</span></a></span>'
891 ) in content
892 assert '<span class="n"><span class="pre">foo.Age</span></span>' in content
893 assert (
894 '<p><strong>name</strong> (<a class="reference internal" href="#foo.Name" '
895 'title="foo.Name"><em>Name</em></a>) – blah blah</p>'
896 ) in content
897 assert '<p><strong>age</strong> (<em>foo.Age</em>) – blah blah</p>' in content
898
899
900 @pytest.mark.sphinx(
901 'html',
902 testroot='domain-py-python_use_unqualified_type_names',
903 confoverrides={'python_use_unqualified_type_names': False},
904 )
905 def test_python_python_use_unqualified_type_names_disabled(app):
906 app.build()
907 content = (app.outdir / 'index.html').read_text(encoding='utf8')
908 assert (
909 '<span class="n"><a class="reference internal" href="#foo.Name" title="foo.Name">'
910 '<span class="pre">foo.Name</span></a></span>'
911 ) in content
912 assert '<span class="n"><span class="pre">foo.Age</span></span>' in content
913 assert (
914 '<p><strong>name</strong> (<a class="reference internal" href="#foo.Name" '
915 'title="foo.Name"><em>foo.Name</em></a>) – blah blah</p>'
916 ) in content
917 assert '<p><strong>age</strong> (<em>foo.Age</em>) – blah blah</p>' in content
918
919
920 @pytest.mark.sphinx('dummy', testroot='domain-py-xref-warning')
921 def test_warn_missing_reference(app):
922 app.build()
923 assert "index.rst:6: WARNING: undefined label: 'no-label'" in app.warning.getvalue()
924 assert (
925 'index.rst:6: WARNING: Failed to create a cross reference. '
926 "A title or caption not found: 'existing-label'"
927 ) in app.warning.getvalue()
928
929
930 @pytest.mark.parametrize('include_options', [True, False])
931 @pytest.mark.sphinx('html', testroot='root', confoverrides={'nitpicky': True})
932 def test_signature_line_number(app, include_options):
933 text = '.. py:function:: foo(bar : string)\n' + (
934 ' :no-index-entry:\n' if include_options else ''
935 )
936 doc = restructuredtext.parse(app, text)
937 xrefs = list(doc.findall(condition=addnodes.pending_xref))
938 assert len(xrefs) == 1
939 source, line = docutils.utils.get_source_line(xrefs[0])
940 assert 'index.rst' in source
941 assert line == 1
942
943
944 @pytest.mark.sphinx(
945 'html',
946 testroot='root',
947 confoverrides={
948 'python_maximum_signature_line_length': len('hello(name: str) -> str'),
949 'maximum_signature_line_length': 1,
950 },
951 )
952 def test_python_maximum_signature_line_length_overrides_global(app):
953 text = '.. py:function:: hello(name: str) -> str'
954 doctree = restructuredtext.parse(app, text)
955 expected_doctree = (
956 addnodes.index,
957 [
958 desc,
959 (
960 [
961 desc_signature,
962 (
963 [desc_name, 'hello'],
964 desc_parameterlist,
965 [desc_returns, pending_xref, 'str'],
966 ),
967 ],
968 desc_content,
969 ),
970 ],
971 )
972 assert_node(doctree, expected_doctree)
973 assert_node(
974 doctree[1],
975 addnodes.desc,
976 desctype='function',
977 domain='py',
978 objtype='function',
979 no_index=False,
980 )
981 signame_node = [desc_sig_name, 'name']
982 expected_sig = [
983 desc_parameterlist,
984 desc_parameter,
985 (
986 signame_node,
987 [desc_sig_punctuation, ':'],
988 desc_sig_space,
989 [nodes.inline, pending_xref, 'str'],
990 ),
991 ]
992 assert_node(extract_node(doctree, 1, 0, 1), expected_sig)
993 assert_node(
994 extract_node(doctree, 1, 0, 1),
995 desc_parameterlist,
996 multi_line_parameter_list=False,
997 )
998
999
1000 @pytest.mark.sphinx(
1001 'html',
1002 testroot='domain-py-python_maximum_signature_line_length',
1003 )
1004 def test_domain_py_python_maximum_signature_line_length_in_html(app):
1005 app.build()
1006 content = (app.outdir / 'index.html').read_text(encoding='utf8')
1007 expected_parameter_list_hello = """\
1008
1009 <dl>
1010 <dd>\
1011 <em class="sig-param">\
1012 <span class="n"><span class="pre">name</span></span>\
1013 <span class="p"><span class="pre">:</span></span>\
1014 <span class="w"> </span>\
1015 <span class="n"><span class="pre">str</span></span>\
1016 </em>,\
1017 </dd>
1018 </dl>
1019
1020 <span class="sig-paren">)</span> \
1021 <span class="sig-return">\
1022 <span class="sig-return-icon">&#x2192;</span> \
1023 <span class="sig-return-typehint"><span class="pre">str</span></span>\
1024 </span>\
1025 <a class="headerlink" href="#hello" title="Link to this definition">¶</a>\
1026 </dt>\
1027 """
1028 assert expected_parameter_list_hello in content
1029
1030 param_line_fmt = '<dd>{}</dd>\n'
1031 param_name_fmt = (
1032 '<em class="sig-param"><span class="n"><span class="pre">{}</span></span></em>'
1033 )
1034 optional_fmt = '<span class="optional">{}</span>'
1035
1036 expected_a = param_line_fmt.format(
1037 optional_fmt.format('[')
1038 + param_name_fmt.format('a')
1039 + ','
1040 + optional_fmt.format('['),
1041 )
1042 assert expected_a in content
1043
1044 expected_b = param_line_fmt.format(
1045 param_name_fmt.format('b')
1046 + ','
1047 + optional_fmt.format(']')
1048 + optional_fmt.format(']'),
1049 )
1050 assert expected_b in content
1051
1052 expected_c = param_line_fmt.format(param_name_fmt.format('c') + ',')
1053 assert expected_c in content
1054
1055 expected_d = param_line_fmt.format(
1056 param_name_fmt.format('d') + optional_fmt.format('[') + ','
1057 )
1058 assert expected_d in content
1059
1060 expected_e = param_line_fmt.format(param_name_fmt.format('e') + ',')
1061 assert expected_e in content
1062
1063 expected_f = param_line_fmt.format(
1064 param_name_fmt.format('f') + ',' + optional_fmt.format(']')
1065 )
1066 assert expected_f in content
1067
1068 expected_parameter_list_foo = """\
1069
1070 <dl>
1071 {}{}{}{}{}{}</dl>
1072
1073 <span class="sig-paren">)</span>\
1074 <a class="headerlink" href="#foo" title="Link to this definition">¶</a>\
1075 </dt>\
1076 """.format(expected_a, expected_b, expected_c, expected_d, expected_e, expected_f)
1077 assert expected_parameter_list_foo in content
1078
1079
1080 @pytest.mark.sphinx(
1081 'text',
1082 testroot='domain-py-python_maximum_signature_line_length',
1083 )
1084 def test_domain_py_python_maximum_signature_line_length_in_text(app):
1085 app.build()
1086 content = (app.outdir / 'index.txt').read_text(encoding='utf8')
1087 param_line_fmt = STDINDENT * ' ' + '{}\n'
1088
1089 expected_parameter_list_hello = '(\n{}) -> str'.format(
1090 param_line_fmt.format('name: str,')
1091 )
1092
1093 assert expected_parameter_list_hello in content
1094
1095 expected_a = param_line_fmt.format('[a,[')
1096 assert expected_a in content
1097
1098 expected_b = param_line_fmt.format('b,]]')
1099 assert expected_b in content
1100
1101 expected_c = param_line_fmt.format('c,')
1102 assert expected_c in content
1103
1104 expected_d = param_line_fmt.format('d[,')
1105 assert expected_d in content
1106
1107 expected_e = param_line_fmt.format('e,')
1108 assert expected_e in content
1109
1110 expected_f = param_line_fmt.format('f,]')
1111 assert expected_f in content
1112
1113 expected_parameter_list_foo = '(\n{}{}{}{}{}{})'.format(
1114 expected_a,
1115 expected_b,
1116 expected_c,
1117 expected_d,
1118 expected_e,
1119 expected_f,
1120 )
1121 assert expected_parameter_list_foo in content
1122
1123
1124 @pytest.mark.sphinx(
1125 'html',
1126 testroot='domain-py-python_maximum_signature_line_length',
1127 confoverrides={'python_trailing_comma_in_multi_line_signatures': False},
1128 )
1129 def test_domain_py_python_trailing_comma_in_multi_line_signatures_in_html(app):
1130 app.build()
1131 content = (app.outdir / 'index.html').read_text(encoding='utf8')
1132 expected_parameter_list_hello = """\
1133
1134 <dl>
1135 <dd>\
1136 <em class="sig-param">\
1137 <span class="n"><span class="pre">name</span></span>\
1138 <span class="p"><span class="pre">:</span></span>\
1139 <span class="w"> </span>\
1140 <span class="n"><span class="pre">str</span></span>\
1141 </em>\
1142 </dd>
1143 </dl>
1144
1145 <span class="sig-paren">)</span> \
1146 <span class="sig-return">\
1147 <span class="sig-return-icon">&#x2192;</span> \
1148 <span class="sig-return-typehint"><span class="pre">str</span></span>\
1149 </span>\
1150 <a class="headerlink" href="#hello" title="Link to this definition">¶</a>\
1151 </dt>\
1152 """
1153 assert expected_parameter_list_hello in content
1154
1155 param_line_fmt = '<dd>{}</dd>\n'
1156 param_name_fmt = (
1157 '<em class="sig-param"><span class="n"><span class="pre">{}</span></span></em>'
1158 )
1159 optional_fmt = '<span class="optional">{}</span>'
1160
1161 expected_a = param_line_fmt.format(
1162 optional_fmt.format('[')
1163 + param_name_fmt.format('a')
1164 + ','
1165 + optional_fmt.format('['),
1166 )
1167 assert expected_a in content
1168
1169 expected_b = param_line_fmt.format(
1170 param_name_fmt.format('b')
1171 + ','
1172 + optional_fmt.format(']')
1173 + optional_fmt.format(']'),
1174 )
1175 assert expected_b in content
1176
1177 expected_c = param_line_fmt.format(param_name_fmt.format('c') + ',')
1178 assert expected_c in content
1179
1180 expected_d = param_line_fmt.format(
1181 param_name_fmt.format('d') + optional_fmt.format('[') + ','
1182 )
1183 assert expected_d in content
1184
1185 expected_e = param_line_fmt.format(param_name_fmt.format('e') + ',')
1186 assert expected_e in content
1187
1188 expected_f = param_line_fmt.format(
1189 param_name_fmt.format('f') + optional_fmt.format(']')
1190 )
1191 assert expected_f in content
1192
1193 expected_parameter_list_foo = """\
1194
1195 <dl>
1196 {}{}{}{}{}{}</dl>
1197
1198 <span class="sig-paren">)</span>\
1199 <a class="headerlink" href="#foo" title="Link to this definition">¶</a>\
1200 </dt>\
1201 """.format(expected_a, expected_b, expected_c, expected_d, expected_e, expected_f)
1202 assert expected_parameter_list_foo in content
1203
1204
1205 @pytest.mark.sphinx(
1206 'text',
1207 testroot='domain-py-python_maximum_signature_line_length',
1208 freshenv=True,
1209 confoverrides={'python_trailing_comma_in_multi_line_signatures': False},
1210 )
1211 def test_domain_py_python_trailing_comma_in_multi_line_signatures_in_text(app):
1212 app.build()
1213 content = (app.outdir / 'index.txt').read_text(encoding='utf8')
1214 param_line_fmt = STDINDENT * ' ' + '{}\n'
1215
1216 expected_parameter_list_hello = '(\n{}) -> str'.format(
1217 param_line_fmt.format('name: str')
1218 )
1219
1220 assert expected_parameter_list_hello in content
1221
1222 expected_a = param_line_fmt.format('[a,[')
1223 assert expected_a in content
1224
1225 expected_b = param_line_fmt.format('b,]]')
1226 assert expected_b in content
1227
1228 expected_c = param_line_fmt.format('c,')
1229 assert expected_c in content
1230
1231 expected_d = param_line_fmt.format('d[,')
1232 assert expected_d in content
1233
1234 expected_e = param_line_fmt.format('e,')
1235 assert expected_e in content
1236
1237 expected_f = param_line_fmt.format('f]')
1238 assert expected_f in content
1239
1240 expected_parameter_list_foo = '(\n{}{}{}{}{}{})'.format(
1241 expected_a,
1242 expected_b,
1243 expected_c,
1244 expected_d,
1245 expected_e,
1246 expected_f,
1247 )
1248 assert expected_parameter_list_foo in content
1249
1250
1251 @pytest.mark.sphinx('html', testroot='_blank')
1252 def test_module_content_line_number(app):
1253 text = '.. py:module:: foo\n\n Some link here: :ref:`abc`\n'
1254 doc = restructuredtext.parse(app, text)
1255 xrefs = list(doc.findall(condition=addnodes.pending_xref))
1256 assert len(xrefs) == 1
1257 source, line = docutils.utils.get_source_line(xrefs[0])
1258 assert 'index.rst' in source
1259 assert line == 3
1260
1261
1262 @pytest.mark.sphinx(
1263 'html',
1264 testroot='root',
1265 freshenv=True,
1266 confoverrides={'python_display_short_literal_types': True},
1267 )
1268 def test_short_literal_types(app):
1269 text = """\
1270 .. py:function:: literal_ints(x: Literal[1, 2, 3] = 1) -> None
1271 .. py:function:: literal_union(x: Union[Literal["a"], Literal["b"], Literal["c"]]) -> None
1272 """
1273 doctree = restructuredtext.parse(app, text)
1274 assert_node(
1275 doctree,
1276 (
1277 addnodes.index,
1278 [
1279 desc,
1280 (
1281 [
1282 desc_signature,
1283 (
1284 [desc_name, 'literal_ints'],
1285 [
1286 desc_parameterlist,
1287 (
1288 [
1289 desc_parameter,
1290 (
1291 [desc_sig_name, 'x'],
1292 [desc_sig_punctuation, ':'],
1293 desc_sig_space,
1294 [
1295 desc_sig_name,
1296 (
1297 [desc_sig_literal_number, '1'],
1298 desc_sig_space,
1299 [desc_sig_punctuation, '|'],
1300 desc_sig_space,
1301 [desc_sig_literal_number, '2'],
1302 desc_sig_space,
1303 [desc_sig_punctuation, '|'],
1304 desc_sig_space,
1305 [desc_sig_literal_number, '3'],
1306 ),
1307 ],
1308 desc_sig_space,
1309 [desc_sig_operator, '='],
1310 desc_sig_space,
1311 [nodes.inline, '1'],
1312 ),
1313 ],
1314 ),
1315 ],
1316 [desc_returns, pending_xref, 'None'],
1317 ),
1318 ],
1319 [desc_content, ()],
1320 ),
1321 ],
1322 addnodes.index,
1323 [
1324 desc,
1325 (
1326 [
1327 desc_signature,
1328 (
1329 [desc_name, 'literal_union'],
1330 [
1331 desc_parameterlist,
1332 (
1333 [
1334 desc_parameter,
1335 (
1336 [desc_sig_name, 'x'],
1337 [desc_sig_punctuation, ':'],
1338 desc_sig_space,
1339 [
1340 desc_sig_name,
1341 (
1342 [desc_sig_literal_string, "'a'"],
1343 desc_sig_space,
1344 [desc_sig_punctuation, '|'],
1345 desc_sig_space,
1346 [desc_sig_literal_string, "'b'"],
1347 desc_sig_space,
1348 [desc_sig_punctuation, '|'],
1349 desc_sig_space,
1350 [desc_sig_literal_string, "'c'"],
1351 ),
1352 ],
1353 ),
1354 ],
1355 ),
1356 ],
1357 [desc_returns, pending_xref, 'None'],
1358 ),
1359 ],
1360 [desc_content, ()],
1361 ),
1362 ],
1363 ),
1364 )
1365
1366
1367 @pytest.mark.sphinx('html', testroot='_blank')
1368 def test_function_pep_695(app):
1369 text = """.. py:function:: func[\
1370 S,\
1371 T: int,\
1372 U: (int, str),\
1373 R: int | str,\
1374 A: int | Annotated[int, ctype("char")],\
1375 *V,\
1376 **P\
1377 ]
1378 """
1379 doctree = restructuredtext.parse(app, text)
1380 assert_node(
1381 doctree,
1382 (
1383 addnodes.index,
1384 [
1385 desc,
1386 (
1387 [
1388 desc_signature,
1389 (
1390 [desc_name, 'func'],
1391 [
1392 desc_type_parameter_list,
1393 (
1394 [desc_type_parameter, ([desc_sig_name, 'S'])],
1395 [
1396 desc_type_parameter,
1397 (
1398 [desc_sig_name, 'T'],
1399 [desc_sig_punctuation, ':'],
1400 desc_sig_space,
1401 [desc_sig_name, ([pending_xref, 'int'])],
1402 ),
1403 ],
1404 [
1405 desc_type_parameter,
1406 (
1407 [desc_sig_name, 'U'],
1408 [desc_sig_punctuation, ':'],
1409 desc_sig_space,
1410 [desc_sig_punctuation, '('],
1411 [
1412 desc_sig_name,
1413 (
1414 [pending_xref, 'int'],
1415 [desc_sig_punctuation, ','],
1416 desc_sig_space,
1417 [pending_xref, 'str'],
1418 ),
1419 ],
1420 [desc_sig_punctuation, ')'],
1421 ),
1422 ],
1423 [
1424 desc_type_parameter,
1425 (
1426 [desc_sig_name, 'R'],
1427 [desc_sig_punctuation, ':'],
1428 desc_sig_space,
1429 [
1430 desc_sig_name,
1431 (
1432 [pending_xref, 'int'],
1433 desc_sig_space,
1434 [desc_sig_punctuation, '|'],
1435 desc_sig_space,
1436 [pending_xref, 'str'],
1437 ),
1438 ],
1439 ),
1440 ],
1441 [
1442 desc_type_parameter,
1443 (
1444 [desc_sig_name, 'A'],
1445 [desc_sig_punctuation, ':'],
1446 desc_sig_space,
1447 [
1448 desc_sig_name,
1449 (
1450 [pending_xref, 'int'],
1451 [desc_sig_space, ' '],
1452 [desc_sig_punctuation, '|'],
1453 [desc_sig_space, ' '],
1454 [pending_xref, 'Annotated'],
1455 [desc_sig_punctuation, '['],
1456 [pending_xref, 'int'],
1457 [desc_sig_punctuation, ','],
1458 [desc_sig_space, ' '],
1459 [pending_xref, 'ctype'],
1460 [desc_sig_punctuation, '('],
1461 [desc_sig_literal_string, "'char'"],
1462 [desc_sig_punctuation, ')'],
1463 [desc_sig_punctuation, ']'],
1464 ),
1465 ],
1466 ),
1467 ],
1468 [
1469 desc_type_parameter,
1470 (
1471 [desc_sig_operator, '*'],
1472 [desc_sig_name, 'V'],
1473 ),
1474 ],
1475 [
1476 desc_type_parameter,
1477 (
1478 [desc_sig_operator, '**'],
1479 [desc_sig_name, 'P'],
1480 ),
1481 ],
1482 ),
1483 ],
1484 [desc_parameterlist, ()],
1485 ),
1486 ],
1487 [desc_content, ()],
1488 ),
1489 ],
1490 ),
1491 )
1492
1493
1494 @pytest.mark.sphinx('html', testroot='_blank')
1495 def test_class_def_pep_695(app):
1496 # Non-concrete unbound generics are allowed at runtime but type checkers
1497 # should fail (https://peps.python.org/pep-0695/#type-parameter-scopes)
1498 text = """.. py:class:: Class[S: Sequence[T], T, KT, VT](Dict[KT, VT])"""
1499 doctree = restructuredtext.parse(app, text)
1500 assert_node(
1501 doctree,
1502 (
1503 addnodes.index,
1504 [
1505 desc,
1506 (
1507 [
1508 desc_signature,
1509 (
1510 [
1511 desc_annotation,
1512 ([desc_sig_keyword, 'class'], desc_sig_space),
1513 ],
1514 [desc_name, 'Class'],
1515 [
1516 desc_type_parameter_list,
1517 (
1518 [
1519 desc_type_parameter,
1520 (
1521 [desc_sig_name, 'S'],
1522 [desc_sig_punctuation, ':'],
1523 desc_sig_space,
1524 [
1525 desc_sig_name,
1526 (
1527 [pending_xref, 'Sequence'],
1528 [desc_sig_punctuation, '['],
1529 [pending_xref, 'T'],
1530 [desc_sig_punctuation, ']'],
1531 ),
1532 ],
1533 ),
1534 ],
1535 [desc_type_parameter, ([desc_sig_name, 'T'])],
1536 [desc_type_parameter, ([desc_sig_name, 'KT'])],
1537 [desc_type_parameter, ([desc_sig_name, 'VT'])],
1538 ),
1539 ],
1540 [desc_parameterlist, ([desc_parameter, 'Dict[KT, VT]'])],
1541 ),
1542 ],
1543 [desc_content, ()],
1544 ),
1545 ],
1546 ),
1547 )
1548
1549
1550 @pytest.mark.sphinx('html', testroot='_blank')
1551 def test_class_def_pep_696(app):
1552 # test default values for type variables without using PEP 696 AST parser
1553 text = """.. py:class:: Class[\
1554 T, KT, VT,\
1555 J: int,\
1556 K = list,\
1557 S: str = str,\
1558 L: (T, tuple[T, ...], collections.abc.Iterable[T]) = set[T],\
1559 Q: collections.abc.Mapping[KT, VT] = dict[KT, VT],\
1560 *V = *tuple[*Ts, bool],\
1561 **P = [int, Annotated[int, ValueRange(3, 10), ctype("char")]]\
1562 ](Other[T, KT, VT, J, S, L, Q, *V, **P])
1563 """
1564 doctree = restructuredtext.parse(app, text)
1565 assert_node(
1566 doctree,
1567 (
1568 addnodes.index,
1569 [
1570 desc,
1571 (
1572 [
1573 desc_signature,
1574 (
1575 [
1576 desc_annotation,
1577 ([desc_sig_keyword, 'class'], desc_sig_space),
1578 ],
1579 [desc_name, 'Class'],
1580 [
1581 desc_type_parameter_list,
1582 (
1583 [desc_type_parameter, ([desc_sig_name, 'T'])],
1584 [desc_type_parameter, ([desc_sig_name, 'KT'])],
1585 [desc_type_parameter, ([desc_sig_name, 'VT'])],
1586 # J: int
1587 [
1588 desc_type_parameter,
1589 (
1590 [desc_sig_name, 'J'],
1591 [desc_sig_punctuation, ':'],
1592 desc_sig_space,
1593 [desc_sig_name, ([pending_xref, 'int'])],
1594 ),
1595 ],
1596 # K = list
1597 [
1598 desc_type_parameter,
1599 (
1600 [desc_sig_name, 'K'],
1601 desc_sig_space,
1602 [desc_sig_operator, '='],
1603 desc_sig_space,
1604 [nodes.inline, 'list'],
1605 ),
1606 ],
1607 # S: str = str
1608 [
1609 desc_type_parameter,
1610 (
1611 [desc_sig_name, 'S'],
1612 [desc_sig_punctuation, ':'],
1613 desc_sig_space,
1614 [desc_sig_name, ([pending_xref, 'str'])],
1615 desc_sig_space,
1616 [desc_sig_operator, '='],
1617 desc_sig_space,
1618 [nodes.inline, 'str'],
1619 ),
1620 ],
1621 [
1622 desc_type_parameter,
1623 (
1624 [desc_sig_name, 'L'],
1625 [desc_sig_punctuation, ':'],
1626 desc_sig_space,
1627 [desc_sig_punctuation, '('],
1628 [
1629 desc_sig_name,
1630 (
1631 # T
1632 [pending_xref, 'T'],
1633 [desc_sig_punctuation, ','],
1634 desc_sig_space,
1635 # tuple[T, ...]
1636 [pending_xref, 'tuple'],
1637 [desc_sig_punctuation, '['],
1638 [pending_xref, 'T'],
1639 [desc_sig_punctuation, ','],
1640 desc_sig_space,
1641 [desc_sig_punctuation, '...'],
1642 [desc_sig_punctuation, ']'],
1643 [desc_sig_punctuation, ','],
1644 desc_sig_space,
1645 # collections.abc.Iterable[T]
1646 [
1647 pending_xref,
1648 'collections.abc.Iterable',
1649 ],
1650 [desc_sig_punctuation, '['],
1651 [pending_xref, 'T'],
1652 [desc_sig_punctuation, ']'],
1653 ),
1654 ],
1655 [desc_sig_punctuation, ')'],
1656 desc_sig_space,
1657 [desc_sig_operator, '='],
1658 desc_sig_space,
1659 [nodes.inline, 'set[T]'],
1660 ),
1661 ],
1662 [
1663 desc_type_parameter,
1664 (
1665 [desc_sig_name, 'Q'],
1666 [desc_sig_punctuation, ':'],
1667 desc_sig_space,
1668 [
1669 desc_sig_name,
1670 (
1671 [
1672 pending_xref,
1673 'collections.abc.Mapping',
1674 ],
1675 [desc_sig_punctuation, '['],
1676 [pending_xref, 'KT'],
1677 [desc_sig_punctuation, ','],
1678 desc_sig_space,
1679 [pending_xref, 'VT'],
1680 [desc_sig_punctuation, ']'],
1681 ),
1682 ],
1683 desc_sig_space,
1684 [desc_sig_operator, '='],
1685 desc_sig_space,
1686 [nodes.inline, 'dict[KT, VT]'],
1687 ),
1688 ],
1689 [
1690 desc_type_parameter,
1691 (
1692 [desc_sig_operator, '*'],
1693 [desc_sig_name, 'V'],
1694 desc_sig_space,
1695 [desc_sig_operator, '='],
1696 desc_sig_space,
1697 [nodes.inline, '*tuple[*Ts, bool]'],
1698 ),
1699 ],
1700 [
1701 desc_type_parameter,
1702 (
1703 [desc_sig_operator, '**'],
1704 [desc_sig_name, 'P'],
1705 desc_sig_space,
1706 [desc_sig_operator, '='],
1707 desc_sig_space,
1708 [
1709 nodes.inline,
1710 '[int, Annotated[int, ValueRange(3, 10), ctype("char")]]',
1711 ],
1712 ),
1713 ],
1714 ),
1715 ],
1716 [
1717 desc_parameterlist,
1718 (
1719 [
1720 desc_parameter,
1721 'Other[T, KT, VT, J, S, L, Q, *V, **P]',
1722 ],
1723 ),
1724 ],
1725 ),
1726 ],
1727 [desc_content, ()],
1728 ),
1729 ],
1730 ),
1731 )
1732
1733
1734 @pytest.mark.parametrize(
1735 ('tp_list', 'tptext'),
1736 [
1737 ('[T:int]', '[T: int]'),
1738 ('[T:*Ts]', '[T: *Ts]'),
1739 ('[T:int|(*Ts)]', '[T: int | (*Ts)]'),
1740 ('[T:(*Ts)|int]', '[T: (*Ts) | int]'),
1741 ('[T:(int|(*Ts))]', '[T: (int | (*Ts))]'),
1742 ('[T:((*Ts)|int)]', '[T: ((*Ts) | int)]'),
1743 ("[T:Annotated[int,ctype('char')]]", "[T: Annotated[int, ctype('char')]]"),
1744 ],
1745 )
1746 @pytest.mark.sphinx('html', testroot='root')
1747 def test_pep_695_and_pep_696_whitespaces_in_bound(app, tp_list, tptext):
1748 text = f'.. py:function:: f{tp_list}()'
1749 doctree = restructuredtext.parse(app, text)
1750 assert doctree.astext() == f'\n\nf{tptext}()\n\n'
1751
1752 text = f'.. py:function:: f{tp_list}() -> Annotated[T, Qux[int]()]'
1753 doctree = restructuredtext.parse(app, text)
1754 assert doctree.astext() == f'\n\nf{tptext}() -> Annotated[T, Qux[int]()]\n\n'
1755
1756
1757 @pytest.mark.parametrize(
1758 ('tp_list', 'tptext'),
1759 [
1760 ('[T:(int,str)]', '[T: (int, str)]'),
1761 ('[T:(int|str,*Ts)]', '[T: (int | str, *Ts)]'),
1762 ],
1763 )
1764 @pytest.mark.sphinx('html', testroot='root')
1765 def test_pep_695_and_pep_696_whitespaces_in_constraints(app, tp_list, tptext):
1766 text = f'.. py:function:: f{tp_list}()'
1767 doctree = restructuredtext.parse(app, text)
1768 assert doctree.astext() == f'\n\nf{tptext}()\n\n'
1769
1770 text = f'.. py:function:: f{tp_list}() -> Annotated[T, Qux[int]()]'
1771 doctree = restructuredtext.parse(app, text)
1772 assert doctree.astext() == f'\n\nf{tptext}() -> Annotated[T, Qux[int]()]\n\n'
1773
1774
1775 @pytest.mark.parametrize(
1776 ('tp_list', 'tptext'),
1777 [
1778 ('[T=int]', '[T = int]'),
1779 ('[T:int=int]', '[T: int = int]'),
1780 ('[*V=*Ts]', '[*V = *Ts]'),
1781 ('[*V=(*Ts)]', '[*V = (*Ts)]'),
1782 ('[*V=*tuple[str,...]]', '[*V = *tuple[str, ...]]'),
1783 ('[*V=*tuple[*Ts,...]]', '[*V = *tuple[*Ts, ...]]'),
1784 ('[*V=*tuple[int,*Ts]]', '[*V = *tuple[int, *Ts]]'),
1785 ('[*V=*tuple[*Ts,int]]', '[*V = *tuple[*Ts, int]]'),
1786 ('[**P=[int,*Ts]]', '[**P = [int, *Ts]]'),
1787 ('[**P=[int, int*3]]', '[**P = [int, int * 3]]'),
1788 ('[**P=[int, *Ts*3]]', '[**P = [int, *Ts * 3]]'),
1789 ('[**P=[int,A[int,ctype("char")]]]', '[**P = [int, A[int, ctype("char")]]]'),
1790 ],
1791 )
1792 @pytest.mark.sphinx('html', testroot='root')
1793 def test_pep_695_and_pep_696_whitespaces_in_default(app, tp_list, tptext):
1794 text = f'.. py:function:: f{tp_list}()'
1795 doctree = restructuredtext.parse(app, text)
1796 assert doctree.astext() == f'\n\nf{tptext}()\n\n'
1797
1798 text = f'.. py:function:: f{tp_list}() -> Annotated[T, Qux[int]()]'
1799 doctree = restructuredtext.parse(app, text)
1800 assert doctree.astext() == f'\n\nf{tptext}() -> Annotated[T, Qux[int]()]\n\n'
1801
1802
1803 def test_deco_role(app):
1804 text = """\
1805 .. py:decorator:: foo.bar
1806 :no-contents-entry:
1807 :no-index-entry:
1808 :no-typesetting:
1809 """
1810
1811 doctree = restructuredtext.parse(app, text + '\n:py:deco:`foo.bar`')
1812 assert doctree.astext() == '\n\n\n\[email protected]'
1813
1814 doctree = restructuredtext.parse(app, text + '\n:py:deco:`~foo.bar`')
1815 assert doctree.astext() == '\n\n\n\n@bar'
1816
1817
1818 def test_pytype_canonical(app):
1819 text = """\
1820 .. py:type:: A
1821 :canonical: int
1822
1823 .. py:type:: B
1824 :canonical: int
1825 """
1826
1827 doctree = restructuredtext.parse(app, text)
1828 assert not app.warning.getvalue()
1829
1830
1831 @pytest.mark.sphinx('html', testroot='domain-py-xref-type-alias')
1832 def test_type_alias_xref_resolution(app: SphinxTestApp) -> None:
1833 """Test that type aliases in function signatures can be cross-referenced.
1834
1835 This tests the fix for issue https://github.com/sphinx-doc/sphinx/issues/10785
1836 where type aliases documented as :py:data: but referenced as :py:class: in
1837 function signatures would not resolve properly.
1838
1839 Tests both a Union type alias and a generic type alias to ensure our
1840 domain fallback mechanism works for various type alias patterns.
1841 """
1842 app.config.nitpicky = True
1843 app.build()
1844
1845 # In nitpicky mode, check that no warnings were generated for type alias cross-references
1846 warnings_text = app.warning.getvalue()
1847 assert 'py:class reference target not found: pathlike' not in warnings_text, (
1848 f'Type alias cross-reference failed in nitpicky mode. Warnings: {warnings_text}'
1849 )
1850 assert 'py:class reference target not found: Handler' not in warnings_text, (
1851 f'Type alias cross-reference failed for Handler. Warnings: {warnings_text}'
1852 )
1853
1854 # Core functionality test: Verify type alias links are generated in function signatures
1855 html_content = (app.outdir / 'index.html').read_text(encoding='utf8')
1856
1857 # Both type aliases should be documented and have anchors
1858 assert 'id="alias_module.pathlike"' in html_content, (
1859 'pathlike type alias definition anchor not found in HTML'
1860 )
1861 assert 'id="alias_module.Handler"' in html_content, (
1862 'Handler type alias definition anchor not found in HTML'
1863 )
1864
1865 # The critical test: type aliases in function signatures should be clickable links
1866 # This tests the original issue - function signature type annotations should resolve
1867 assert (
1868 '<a class="reference internal" href="#alias_module.pathlike"' in html_content
1869 ), 'pathlike type alias not linked in function signature'
1870
1871 assert (
1872 '<a class="reference internal" href="#alias_module.Handler"' in html_content
1873 ), 'Handler type alias not linked in function signature'
1874
1875 # Verify the links are specifically in the function signature contexts
1876 # Test pathlike in read_file function signature
1877 read_file_match = re.search(
1878 r'<span class="pre">read_file</span>.*?</dt>', html_content, re.DOTALL
1879 )
1880 assert read_file_match is not None, 'Could not find read_file function signature'
1881 read_file_signature = read_file_match.group(0)
1882 assert (
1883 '<a class="reference internal" href="#alias_module.pathlike"'
1884 in read_file_signature
1885 ), 'pathlike type alias link not found in read_file function signature'
1886
1887 # Test Handler in process_error function signature
1888 process_error_match = re.search(
1889 r'<span class="pre">process_error</span>.*?</dt>', html_content, re.DOTALL
1890 )
1891 assert process_error_match is not None, (
1892 'Could not find process_error function signature'
1893 )
1894 process_error_signature = process_error_match.group(0)
1895 assert (
1896 '<a class="reference internal" href="#alias_module.Handler"'
1897 in process_error_signature
1898 ), 'Handler type alias link not found in process_error function signature'
1899 assert (
1900 '<a class="reference internal" href="#alias_module.HandlerType"'
1901 in process_error_signature
1902 ), 'HandlerType type alias link not found in process_error function signature'