forked from tox-dev/sphinx-autodoc-typehints
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_pep695.py
More file actions
1011 lines (815 loc) · 30.8 KB
/
Copy pathtest_pep695.py
File metadata and controls
1011 lines (815 loc) · 30.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import sys
import types
from pathlib import Path
from textwrap import dedent
from typing import TYPE_CHECKING, Any, Union
from unittest.mock import create_autospec
import pytest
from conftest import normalize_sphinx_text
from sphinx.config import Config
from sphinx_autodoc_typehints import format_annotation
if TYPE_CHECKING:
from io import StringIO
from sphinx.testing.util import SphinxTestApp
_mod_pep695 = types.ModuleType("mod")
_mod_pep695.__file__ = __file__
exec( # ruff:ignore[exec-builtin]
dedent("""\
from __future__ import annotations
type IntList = list[int]
type StringOrInt = str | int
def type_alias_func(x: IntList) -> StringOrInt:
\"\"\"Function using PEP 695 type aliases.
:param x: List of integers
:return: String or integer
\"\"\"
...
class Foo[T]:
\"\"\"A generic class.\"\"\"
def __init__(self, thing: T) -> None:
\"\"\"Init.
:param thing: the thing
\"\"\"
def get(self) -> T:
\"\"\"Get the thing.
:return: the thing
\"\"\"
...
class FooStringOrInt(Foo[StringOrInt]):
\"\"\"A subclass of Foo with StringOrInt type param.\"\"\"
def set(self, thing: StringOrInt) -> StringOrInt:
\"\"\"Set the thing.
:param thing: the thing
:return: the thing
\"\"\"
...
class Multi[K, V]:
\"\"\"A class with multiple type params.\"\"\"
def lookup(self, key: K) -> V:
\"\"\"Look up.
:param key: the key
\"\"\"
...
def identity[U](x: U) -> U:
\"\"\"Identity function.
:param x: input
\"\"\"
return x
"""),
_mod_pep695.__dict__,
)
@pytest.mark.sphinx("text", testroot="integration")
def test_pep695_class_type_params(
app: SphinxTestApp, status: StringIO, warning: StringIO, monkeypatch: pytest.MonkeyPatch
) -> None:
(Path(app.srcdir) / "index.rst").write_text(
dedent("""\
Test
====
.. autoclass:: mod.Foo
:members:
""")
)
monkeypatch.setitem(sys.modules, "mod", _mod_pep695)
app.build()
assert "build succeeded" in status.getvalue()
assert "Cannot resolve forward reference" not in warning.getvalue()
@pytest.mark.sphinx("text", testroot="integration")
def test_pep695_class_multiple_type_params(
app: SphinxTestApp, status: StringIO, warning: StringIO, monkeypatch: pytest.MonkeyPatch
) -> None:
(Path(app.srcdir) / "index.rst").write_text(
dedent("""\
Test
====
.. autoclass:: mod.Multi
:members:
""")
)
monkeypatch.setitem(sys.modules, "mod", _mod_pep695)
app.build()
assert "build succeeded" in status.getvalue()
assert "Cannot resolve forward reference" not in warning.getvalue()
@pytest.mark.sphinx("text", testroot="integration")
def test_pep695_function_type_params(
app: SphinxTestApp, status: StringIO, warning: StringIO, monkeypatch: pytest.MonkeyPatch
) -> None:
(Path(app.srcdir) / "index.rst").write_text(
dedent("""\
Test
====
.. autofunction:: mod.identity
""")
)
monkeypatch.setitem(sys.modules, "mod", _mod_pep695)
app.build()
assert "build succeeded" in status.getvalue()
assert "Cannot resolve forward reference" not in warning.getvalue()
@pytest.mark.sphinx("text", testroot="integration")
def test_pep695_type_alias_in_function_undocumented(
app: SphinxTestApp,
status: StringIO,
warning: StringIO,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test that PEP 695 type aliases in function signatures
are rendered as their literal types when the type aliases are
not documented."""
(Path(app.srcdir) / "index.rst").write_text(".. autofunction:: mod.type_alias_func")
monkeypatch.setitem(sys.modules, "mod", _mod_pep695)
app.build()
assert "build succeeded" in status.getvalue()
assert not warning.getvalue().strip()
result = normalize_sphinx_text((Path(app.srcdir) / "_build/text/index.txt").read_text())
expected = dedent("""\
mod.type_alias_func(x)
Function using PEP 695 type aliases.
Parameters:
**x** ("list"["int"]) -- List of integers
Return type:
"str" | "int"
Returns:
String or integer
""").strip()
assert result.strip() == normalize_sphinx_text(expected)
@pytest.mark.sphinx("text", testroot="integration")
def test_pep695_type_alias_in_function_documented(
app: SphinxTestApp,
status: StringIO,
warning: StringIO,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test that PEP 695 type aliases in function signatures
are rendered as their documented type names when the type aliases
are documented."""
(Path(app.srcdir) / "index.rst").write_text(
dedent("""\
.. py:type:: mod.IntList
List of integers
.. py:type:: mod.StringOrInt
String or integer
.. autofunction:: mod.type_alias_func
""")
)
monkeypatch.setitem(sys.modules, "mod", _mod_pep695)
app.build()
assert "build succeeded" in status.getvalue()
assert not warning.getvalue().strip()
result = normalize_sphinx_text((Path(app.srcdir) / "_build/text/index.txt").read_text())
expected = dedent("""\
type mod.IntList
List of integers
type mod.StringOrInt
String or integer
mod.type_alias_func(x)
Function using PEP 695 type aliases.
Parameters:
**x** ("IntList") -- List of integers
Return type:
"StringOrInt"
Returns:
String or integer
""").strip()
assert result.strip() == normalize_sphinx_text(expected)
@pytest.mark.sphinx("text", testroot="integration")
def test_pep695_type_alias_in_method_undocumented(
app: SphinxTestApp,
status: StringIO,
warning: StringIO,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test that PEP 695 type aliases in method signatures are
rendered as their literal types when the type aliases are not
documented."""
(Path(app.srcdir) / "index.rst").write_text(".. autoclass:: mod.FooStringOrInt\n :members:")
monkeypatch.setitem(sys.modules, "mod", _mod_pep695)
app.build()
assert "build succeeded" in status.getvalue()
assert not warning.getvalue().strip()
result = normalize_sphinx_text((Path(app.srcdir) / "_build/text/index.txt").read_text())
expected = dedent("""\
class mod.FooStringOrInt(thing)
A subclass of Foo with StringOrInt type param.
set(thing)
Set the thing.
Parameters:
**thing** ("str" | "int") -- the thing
Return type:
"str" | "int"
Returns:
the thing
""").strip()
assert result.strip() == normalize_sphinx_text(expected)
@pytest.mark.sphinx("text", testroot="integration")
def test_pep695_type_alias_in_method_documented(
app: SphinxTestApp,
status: StringIO,
warning: StringIO,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test that PEP 695 type aliases in method signatures are
rendered as their documented type names when the type aliases
are documented."""
(Path(app.srcdir) / "index.rst").write_text(
dedent("""\
.. py:type:: mod.StringOrInt
String or integer
.. autoclass:: mod.FooStringOrInt
:members:
""")
)
monkeypatch.setitem(sys.modules, "mod", _mod_pep695)
app.build()
assert "build succeeded" in status.getvalue()
assert not warning.getvalue().strip()
result = normalize_sphinx_text((Path(app.srcdir) / "_build/text/index.txt").read_text())
expected = dedent("""\
type mod.StringOrInt
String or integer
class mod.FooStringOrInt(thing)
A subclass of Foo with StringOrInt type param.
set(thing)
Set the thing.
Parameters:
**thing** ("StringOrInt") -- the thing
Return type:
"StringOrInt"
Returns:
the thing
""").strip()
assert result.strip() == normalize_sphinx_text(expected)
@pytest.mark.sphinx("text", testroot="integration")
def test_pep695_external_type_alias(
app: SphinxTestApp,
status: StringIO,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test that external TypeAliasType renders as the alias name, not the expanded value."""
# Define an external type alias in a private module
ext_priv_mod = types.ModuleType("extpkg._priv")
exec("type ExtAlias = str | int", ext_priv_mod.__dict__) # ruff:ignore[exec-builtin]
ext_alias = ext_priv_mod.__dict__["ExtAlias"]
# Reexport the type alias in a public module
ext_pub_mod = types.ModuleType("extpkg")
ext_pub_mod.ExtAlias = ext_alias # type: ignore[attr-defined]
# Import and use the external type alias in user module
user_mod = types.ModuleType("user_mod")
user_mod.__dict__["ExtAlias"] = ext_alias
exec( # ruff:ignore[exec-builtin]
dedent("""\
from __future__ import annotations
def ext_alias_func(x: ExtAlias) -> ExtAlias:
\"\"\"Function using external type alias.
:param x: the value
:return: the value
\"\"\"
...
"""),
user_mod.__dict__,
)
(Path(app.srcdir) / "index.rst").write_text(".. autofunction:: user_mod.ext_alias_func")
monkeypatch.setitem(sys.modules, "user_mod", user_mod)
app.build()
assert "build succeeded" in status.getvalue()
result = normalize_sphinx_text((Path(app.srcdir) / "_build/text/index.txt").read_text())
assert '"ExtAlias"' in result
assert '"str" | "int"' not in result
@pytest.mark.skipif(sys.version_info < (3, 14), reason="PEP 649 lazy annotation evaluation is Python 3.14+")
@pytest.mark.sphinx("text", testroot="integration")
def test_pep695_type_checking_only_annotation(
app: SphinxTestApp,
status: StringIO,
warning: StringIO,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Regression test for #703: PEP 695 generic functions with TYPE_CHECKING-only annotations
must not raise NameError during Sphinx processing."""
mod = types.ModuleType("mod_703")
mod.__file__ = __file__
exec( # ruff:ignore[exec-builtin]
dedent("""\
import functools
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Callable
def my_customizable_decorator[**P, R]() -> Callable[[Callable[P, R]], Callable[P, R]]:
\"\"\"Return a decorator that wraps functions.\"\"\"
def decorator[**P, R](func: Callable[P, R]) -> Callable[P, R]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
return func(*args, **kwargs)
return wrapper
return decorator
"""),
mod.__dict__,
)
(Path(app.srcdir) / "index.rst").write_text(".. autofunction:: mod_703.my_customizable_decorator")
monkeypatch.setitem(sys.modules, "mod_703", mod)
app.build()
assert "build succeeded" in status.getvalue()
# The fix prevents process_signature from throwing — a forward_reference warning
# for unresolvable TYPE_CHECKING imports in exec'd modules is acceptable.
assert "threw an exception" not in warning.getvalue()
UserId = Union[int, str]
RequestData = dict[str, Any]
_TYPE_ALIAS_PREAMBLE = """\
.. py:type:: mod.UserId
A user identifier that can be either an integer or a string.
.. py:type:: mod.RequestData
Request data dictionary.
.. autofunction:: mod.{}
"""
_TYPE_ALIAS_EXPECTED = """\
type mod.UserId
A user identifier that can be either an integer or a string.
type mod.RequestData
Request data dictionary.
{}
"""
def get_user(user_id: UserId) -> str:
"""
Get a user by ID.
Args:
user_id: The user identifier
"""
def process_request(data: RequestData) -> bool:
"""
Process a request.
Args:
data: The request data
"""
@pytest.mark.parametrize(
("documented", "expected_body"),
[
pytest.param(
get_user,
"""\
mod.get_user(user_id)
Get a user by ID.
Parameters:
**user_id** ("UserId") -- The user identifier
Return type:
"str"
""",
id="get-user",
),
pytest.param(
process_request,
"""\
mod.process_request(data)
Process a request.
Parameters:
**data** ("RequestData") -- The request data
Return type:
"bool"
""",
id="process-request",
),
],
)
@pytest.mark.sphinx("text", testroot="integration")
def test_documented_type_alias_crossref(
app: SphinxTestApp,
status: StringIO,
warning: StringIO,
monkeypatch: pytest.MonkeyPatch,
documented: Any,
expected_body: str,
) -> None:
(Path(app.srcdir) / "index.rst").write_text(_TYPE_ALIAS_PREAMBLE.format(documented.__name__))
monkeypatch.setitem(sys.modules, "mod", sys.modules[__name__])
app.build()
assert "build succeeded" in status.getvalue()
value = warning.getvalue().strip()
assert not value or "Inline strong start-string without end-string" in value
result = normalize_sphinx_text((Path(app.srcdir) / "_build/text/index.txt").read_text())
expected = dedent(normalize_sphinx_text(_TYPE_ALIAS_EXPECTED.format(expected_body))).strip()
assert result.strip() == expected
@pytest.mark.sphinx("text", testroot="integration")
def test_recursive_type_alias_does_not_recurse_forever(
app: SphinxTestApp,
status: StringIO,
warning: StringIO,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A self-referential PEP 695 alias builds cleanly and renders as a self cross-reference (#720)."""
mod = types.ModuleType("mod_720")
mod.__file__ = __file__
exec( # ruff:ignore[exec-builtin]
dedent("""\
from __future__ import annotations
type RecType = int | list[RecType]
\"\"\"A recursive type alias.\"\"\"
def some_func(some_param: RecType) -> None:
\"\"\"Describe.
:param some_param: some description
\"\"\"
...
"""),
mod.__dict__,
)
(Path(app.srcdir) / "index.rst").write_text(".. autofunction:: mod_720.some_func")
monkeypatch.setitem(sys.modules, "mod_720", mod)
app.build()
assert "build succeeded" in status.getvalue()
assert not warning.getvalue().strip()
result = normalize_sphinx_text((Path(app.srcdir) / "_build/text/index.txt").read_text())
assert '"RecType"' in result
@pytest.mark.sphinx("text", testroot="integration")
def test_recursive_type_alias_from_other_module(
app: SphinxTestApp,
status: StringIO,
warning: StringIO,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A recursive alias imported from another module resolves to that module's target (#723)."""
pkg = Path(app.srcdir) / "pkg_723"
pkg.mkdir()
(pkg / "other.py").write_text('type RecType = int | list[RecType]\n"""A recursive type alias."""\n')
(pkg / "__init__.py").write_text(
dedent("""\
from pkg_723.other import RecType
def some_func(some_param: RecType) -> None:
\"\"\"Describe.
:param some_param: some description
\"\"\"
...
""")
)
(Path(app.srcdir) / "index.rst").write_text(
".. automodule:: pkg_723\n :members:\n\n.. automodule:: pkg_723.other\n :members:\n"
)
monkeypatch.syspath_prepend(str(app.srcdir))
app.config.nitpicky = True
app.build()
assert "build succeeded" in status.getvalue()
assert "reference target not found" not in warning.getvalue()
result = normalize_sphinx_text((Path(app.srcdir) / "_build/text/index.txt").read_text())
# documented further down the same document, which only the resolve phase can know
assert '**some_param** ("RecType")' in result
@pytest.mark.parametrize(
("package", "alias", "annotation", "expected"),
[
pytest.param(
"pkg_764",
"type Alias = int | Sequence[str]",
"Alias | None",
'"int" | "Sequence"["str"] | "None"',
id="plain",
),
pytest.param(
"pkg_764_generic",
"type Alias[T] = Sequence[T]",
"Alias[int]",
'"Sequence"["int"]',
id="generic",
),
],
)
@pytest.mark.sphinx("text", testroot="integration")
def test_type_alias_value_needs_guarded_import(
app: SphinxTestApp,
status: StringIO,
warning: StringIO,
monkeypatch: pytest.MonkeyPatch,
package: str,
alias: str,
annotation: str,
expected: str,
) -> None:
"""An alias expands even when its value needs the guarded imports of the module defining it (#764)."""
pkg = Path(app.srcdir) / package
pkg.mkdir()
(pkg / "__init__.py").touch()
(pkg / "_types.py").write_text(
dedent(f"""\
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Sequence
{alias}
""")
)
(pkg / "api.py").write_text(
dedent(f"""\
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ._types import Alias
def f(x: {annotation}) -> None:
\"\"\"Do nothing.
:param x: an argument.
\"\"\"
""")
)
(Path(app.srcdir) / "index.rst").write_text(f".. autofunction:: {package}.api.f\n")
monkeypatch.syspath_prepend(str(app.srcdir))
app.build()
assert "build succeeded" in status.getvalue()
assert not warning.getvalue().strip()
result = normalize_sphinx_text((Path(app.srcdir) / "_build/text/index.txt").read_text())
assert expected in result
_mod_unresolvable = types.ModuleType("mod_unresolvable")
_mod_unresolvable.__file__ = __file__
exec("type Broken = Missing\n", _mod_unresolvable.__dict__) # ruff:ignore[exec-builtin]
def test_alias_whose_value_never_evaluates_renders_as_its_name() -> None:
"""An alias nothing can evaluate falls back to a reference to its own name (#764)."""
formatted = format_annotation(_mod_unresolvable.Broken, create_autospec(Config))
assert formatted == ":py:type:`~mod_unresolvable.Broken`"
@pytest.mark.sphinx("text", testroot="integration")
def test_eager_annotations(
app: SphinxTestApp,
status: StringIO,
warning: StringIO,
) -> None:
"""Non-deferred annotations (no ``from __future__ import annotations``) also resolve."""
template = """\
.. py:type:: mod_eager.UserId
A user identifier.
.. autofunction:: mod_eager.get_user_eager
"""
(Path(app.srcdir) / "index.rst").write_text(template)
app.build()
assert "build succeeded" in status.getvalue()
value = warning.getvalue().strip()
assert not value or "Inline strong start-string without end-string" in value
result = normalize_sphinx_text((Path(app.srcdir) / "_build/text/index.txt").read_text())
assert '"UserId"' in result
@pytest.mark.sphinx("text", testroot="integration")
def test_alias_documented_in_a_later_document(
app: SphinxTestApp,
status: StringIO,
warning: StringIO,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""An alias documented in a document read after the one using it cross-references, not expands."""
(Path(app.srcdir) / "index.rst").write_text(
".. autofunction:: mod.type_alias_func\n\n.. toctree::\n\n zz_aliases\n"
)
(Path(app.srcdir) / "zz_aliases.rst").write_text(".. py:type:: mod.IntList\n\n List of integers.\n")
monkeypatch.setitem(sys.modules, "mod", _mod_pep695)
app.build()
assert "build succeeded" in status.getvalue()
value = warning.getvalue().strip()
assert not value or "Inline strong start-string without end-string" in value
result = normalize_sphinx_text((Path(app.srcdir) / "_build/text/index.txt").read_text())
assert '"IntList"' in result
assert '"list"["int"]' not in result
_mod_nested = types.ModuleType("mod_nested")
_mod_nested.__file__ = __file__
exec( # ruff:ignore[exec-builtin]
dedent("""\
from __future__ import annotations
type Inner = int | str
type Outer = Inner | bytes
type Documented = float
type Mixed = Documented | Inner
def nested_func(x: Mixed) -> Outer:
\"\"\"Describe.
:param x: the value
:return: the result
\"\"\"
...
"""),
_mod_nested.__dict__,
)
@pytest.mark.sphinx("text", testroot="integration")
def test_alias_expansion_recurses_into_further_aliases(
app: SphinxTestApp,
status: StringIO,
warning: StringIO,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""An expanded value naming further aliases links the documented ones and expands the rest."""
(Path(app.srcdir) / "index.rst").write_text(
".. autofunction:: mod_nested.nested_func\n\n.. toctree::\n\n zz_aliases\n"
)
(Path(app.srcdir) / "zz_aliases.rst").write_text(".. py:type:: mod_nested.Documented\n\n A documented alias.\n")
monkeypatch.setitem(sys.modules, "mod_nested", _mod_nested)
app.build()
assert "build succeeded" in status.getvalue()
value = warning.getvalue().strip()
assert not value or "Inline strong start-string without end-string" in value
result = normalize_sphinx_text((Path(app.srcdir) / "_build/text/index.txt").read_text())
assert '**x** ("Documented" | "int" | "str")' in result # Mixed = Documented | Inner
assert '"int" | "str" | "bytes"' in result # Outer = Inner | bytes
@pytest.mark.skipif(sys.version_info < (3, 14), reason="annotationlib requires Python 3.14+")
@pytest.mark.sphinx("text", testroot="integration")
def test_forward_ref_builds_without_errors( # pragma: >=3.14 cover
app: SphinxTestApp,
status: StringIO,
) -> None:
"""Forward-referencing module builds cleanly on 3.14+ using annotationlib."""
(Path(app.srcdir) / "index.rst").write_text(".. autoclass:: mod_forward_ref.Tree\n :members:\n")
app.build()
assert "build succeeded" in status.getvalue()
result = normalize_sphinx_text((Path(app.srcdir) / "_build/text/index.txt").read_text())
assert "Tree" in result
@pytest.mark.skipif(sys.version_info < (3, 14), reason="PEP 649 lazy annotation evaluation is Python 3.14+")
@pytest.mark.sphinx("text", testroot="integration")
def test_non_subscriptable_generic_annotation( # pragma: >=3.14 cover
app: SphinxTestApp,
status: StringIO,
warning: StringIO,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Regression test for #712: annotations whose lazy evaluation raises (here TypeError from
subscripting a non-generic class) must not crash the build; the hint degrades to its source text."""
mod = types.ModuleType("mod_712")
mod.__file__ = __file__
source = dedent("""\
class DiGraph:
pass
def add_node_between_nodes(g: DiGraph[int]) -> None:
\"\"\"Stub.\"\"\"
""")
# dont_inherit keeps this file's `from __future__ import annotations` (PEP 563) out of the
# compiled module so its annotations stay lazily evaluated (PEP 649)
exec(compile(source, "<mod_712>", "exec", dont_inherit=True), mod.__dict__) # ruff:ignore[exec-builtin]
(Path(app.srcdir) / "index.rst").write_text(".. autofunction:: mod_712.add_node_between_nodes")
monkeypatch.setitem(sys.modules, "mod_712", mod)
app.config.__dict__["always_document_param_types"] = True
app.build()
assert "build succeeded" in status.getvalue()
assert "threw an exception" not in warning.getvalue()
result = normalize_sphinx_text((Path(app.srcdir) / "_build/text/index.txt").read_text())
assert "DiGraph[int]" in result
@pytest.mark.sphinx("text", testroot="integration")
def test_pep695_generic_type_alias_undocumented(
app: SphinxTestApp,
status: StringIO,
warning: StringIO,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A subscripted generic alias expands to its value with the type params substituted."""
mod = types.ModuleType("mod_generic_alias")
mod.__file__ = __file__
exec( # ruff:ignore[exec-builtin]
dedent("""\
from __future__ import annotations
type Pair[T] = tuple[T, T]
def pair_func(x: Pair[int]) -> None:
\"\"\"Describe.
:param x: a pair
\"\"\"
...
"""),
mod.__dict__,
)
(Path(app.srcdir) / "index.rst").write_text(".. autofunction:: mod_generic_alias.pair_func")
monkeypatch.setitem(sys.modules, "mod_generic_alias", mod)
app.build()
assert "build succeeded" in status.getvalue()
assert not warning.getvalue().strip()
result = normalize_sphinx_text((Path(app.srcdir) / "_build/text/index.txt").read_text())
assert '"tuple"["int", "int"]' in result
@pytest.mark.sphinx("text", testroot="integration")
def test_pep695_generic_type_alias_documented(
app: SphinxTestApp,
status: StringIO,
warning: StringIO,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A subscripted generic alias cross-references the alias and keeps its args."""
mod = types.ModuleType("mod_generic_alias_doc")
mod.__file__ = __file__
exec( # ruff:ignore[exec-builtin]
dedent("""\
from __future__ import annotations
type Pair[T] = tuple[T, T]
\"\"\"A pair of things.\"\"\"
def pair_func(x: Pair[int]) -> None:
\"\"\"Describe.
:param x: a pair
\"\"\"
...
"""),
mod.__dict__,
)
(Path(app.srcdir) / "index.rst").write_text(
dedent("""\
.. py:type:: mod_generic_alias_doc.Pair
A pair of things
.. autofunction:: mod_generic_alias_doc.pair_func
""")
)
monkeypatch.setitem(sys.modules, "mod_generic_alias_doc", mod)
app.config.nitpicky = True
app.build()
assert "build succeeded" in status.getvalue()
assert "reference target not found" not in warning.getvalue()
result = normalize_sphinx_text((Path(app.srcdir) / "_build/text/index.txt").read_text())
assert '"Pair"["int"]' in result
@pytest.mark.sphinx("text", testroot="integration")
def test_pep695_external_generic_type_alias(
app: SphinxTestApp,
status: StringIO,
warning: StringIO,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A subscripted generic alias from another package resolves to its canonical public name.
This is ``numpy.typing.NDArray[np.void]``: an alias defined in a private module, re-exported from a
public one, used subscripted. Without unwrapping the subscription it renders as ``GenericAlias``.
"""
ext_priv_mod = types.ModuleType("extpkg2._priv")
exec("type ExtPair[T] = tuple[T, T]", ext_priv_mod.__dict__) # ruff:ignore[exec-builtin]
ext_alias = ext_priv_mod.__dict__["ExtPair"]
ext_pub_mod = types.ModuleType("extpkg2")
ext_pub_mod.ExtPair = ext_alias # type: ignore[attr-defined]
monkeypatch.setitem(sys.modules, "extpkg2._priv", ext_priv_mod)
monkeypatch.setitem(sys.modules, "extpkg2", ext_pub_mod)
user_mod = types.ModuleType("user_mod_generic")
user_mod.__dict__["ExtPair"] = ext_alias
exec( # ruff:ignore[exec-builtin]
dedent("""\
from __future__ import annotations
def ext_pair_func(x: ExtPair[int]) -> None:
\"\"\"Describe.
:param x: a pair
\"\"\"
...
"""),
user_mod.__dict__,
)
(Path(app.srcdir) / "index.rst").write_text(".. autofunction:: user_mod_generic.ext_pair_func")
monkeypatch.setitem(sys.modules, "user_mod_generic", user_mod)
app.build()
assert "build succeeded" in status.getvalue()
assert "GenericAlias" not in warning.getvalue()
result = normalize_sphinx_text((Path(app.srcdir) / "_build/text/index.txt").read_text())
assert '"ExtPair"["int"]' in result
assert "GenericAlias" not in result
@pytest.mark.sphinx("text", testroot="integration")
def test_recursive_generic_type_alias_does_not_recurse_forever(
app: SphinxTestApp,
status: StringIO,
warning: StringIO,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A generic alias that references itself through its subscripted form builds cleanly."""
mod = types.ModuleType("mod_rec_generic")
mod.__file__ = __file__
exec( # ruff:ignore[exec-builtin]
dedent("""\
from __future__ import annotations
type RecPair[T] = T | list[RecPair[T]]
\"\"\"A recursive generic type alias.\"\"\"
def some_func(some_param: RecPair[int]) -> None:
\"\"\"Describe.
:param some_param: some description
\"\"\"
...
"""),
mod.__dict__,
)
(Path(app.srcdir) / "index.rst").write_text(".. autofunction:: mod_rec_generic.some_func")
monkeypatch.setitem(sys.modules, "mod_rec_generic", mod)
app.build()
assert "build succeeded" in status.getvalue()
assert not warning.getvalue().strip()
result = normalize_sphinx_text((Path(app.srcdir) / "_build/text/index.txt").read_text())
assert '"RecPair"' in result
_mod_generic_edge = types.ModuleType("mod_generic_edge")
_mod_generic_edge.__file__ = __file__
exec( # ruff:ignore[exec-builtin]
dedent("""\
type Ident[X] = X
type Count[X] = int
type Nested[X] = list[Ident[X]]
type Pair[A, B] = tuple[A, B]
type Star[*Ts] = tuple[*Ts]
"""),
_mod_generic_edge.__dict__,
)
_ALIAS_XREF = r":py:type:`~mod_generic_edge.Pair`"
@pytest.mark.parametrize(
("annotation", "expected"),
[
pytest.param(_mod_generic_edge.Ident[int], r":py:class:`int`", id="value_is_a_bare_type_param"),
pytest.param(_mod_generic_edge.Count[int], r":py:class:`int`", id="value_ignores_its_type_param"),
pytest.param(
_mod_generic_edge.Nested[int],
r":py:class:`list`\ \[:py:class:`int`]",
id="value_wraps_another_alias",
),
pytest.param(
_mod_generic_edge.Star[int, str],
r":py:class:`tuple`\ \[:py:class:`int`, :py:class:`str`]",
id="variadic_type_param",
),
pytest.param(
_mod_generic_edge.Pair[int],
_ALIAS_XREF + r"\ \[:py:class:`int`]",
id="too_few_args",