| 1 |
"""Test the autodoc extension. This mainly tests the signature utilities.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from typing import Generic, TypeVar |
| 6 |
|
| 7 |
import pytest |
| 8 |
|
| 9 |
from sphinx.ext.autodoc._directive_options import _AutoDocumenterOptions |
| 10 |
from sphinx.ext.autodoc._dynamic._docstrings import _get_docstring_lines |
| 11 |
from sphinx.ext.autodoc._dynamic._signatures import _format_signatures |
| 12 |
from sphinx.ext.autodoc._property_types import ( |
| 13 |
_ClassDefProperties, |
| 14 |
_FunctionDefProperties, |
| 15 |
) |
| 16 |
from sphinx.ext.autodoc._shared import _AutodocConfig |
| 17 |
from sphinx.util.inspect import safe_getattr |
| 18 |
|
| 19 |
from tests.test_ext_autodoc.autodoc_util import FakeEvents |
| 20 |
|
| 21 |
TYPE_CHECKING = False |
| 22 |
if TYPE_CHECKING: |
| 23 |
from typing import Any |
| 24 |
|
| 25 |
from sphinx.application import Sphinx |
| 26 |
from sphinx.events import EventManager |
| 27 |
from sphinx.ext.autodoc._property_types import _AutodocObjType |
| 28 |
|
| 29 |
processed_signatures = [] |
| 30 |
|
| 31 |
|
| 32 |
def format_sig( |
| 33 |
obj_type: _AutodocObjType, |
| 34 |
name: str, |
| 35 |
obj: Any, |
| 36 |
*, |
| 37 |
config: _AutodocConfig | None = None, |
| 38 |
events: EventManager | None = None, |
| 39 |
args: str | None = None, |
| 40 |
retann: str | None = None, |
| 41 |
) -> tuple[str, str] | tuple[()]: |
| 42 |
if config is None: |
| 43 |
config = _AutodocConfig() |
| 44 |
if events is None: |
| 45 |
events = FakeEvents() |
| 46 |
options = _AutoDocumenterOptions() |
| 47 |
|
| 48 |
parent = object # dummy |
| 49 |
props = _ClassDefProperties( |
| 50 |
obj_type=obj_type, # type: ignore[arg-type] |
| 51 |
module_name='', |
| 52 |
parts=(name,), |
| 53 |
docstring_lines=(), |
| 54 |
bases=getattr(obj, '__bases__', None), |
| 55 |
_obj=obj, |
| 56 |
_obj___module__=getattr(obj, '__module__', None), |
| 57 |
_obj___qualname__=getattr(obj, '__qualname__', None), |
| 58 |
_obj___name__=name, |
| 59 |
_obj_bases=(), |
| 60 |
_obj_is_new_type=False, |
| 61 |
_obj_is_typevar=False, |
| 62 |
) |
| 63 |
docstrings = _get_docstring_lines( |
| 64 |
props, |
| 65 |
class_doc_from=config.autoclass_content, |
| 66 |
get_attr=safe_getattr, |
| 67 |
inherit_docstrings=config.autodoc_inherit_docstrings, |
| 68 |
parent=parent, |
| 69 |
tab_width=8, |
| 70 |
) |
| 71 |
signatures = _format_signatures( |
| 72 |
autodoc_annotations={}, |
| 73 |
config=config, |
| 74 |
docstrings=docstrings, |
| 75 |
events=events, |
| 76 |
get_attr=safe_getattr, |
| 77 |
options=options, |
| 78 |
parent=parent, |
| 79 |
props=props, |
| 80 |
args=args, |
| 81 |
retann=retann, |
| 82 |
) |
| 83 |
if not signatures: |
| 84 |
return () |
| 85 |
assert len(signatures) == 1 |
| 86 |
return signatures[0] |
| 87 |
|
| 88 |
|
| 89 |
def _process_signature( |
| 90 |
_app: Sphinx, |
| 91 |
what: str, |
| 92 |
name: str, |
| 93 |
_obj: Any, |
| 94 |
_options: Any, |
| 95 |
_args: str, |
| 96 |
_retann: str, |
| 97 |
) -> tuple[str | None, str | None] | None: |
| 98 |
processed_signatures.append((what, name)) |
| 99 |
if name == '.bar': |
| 100 |
return '42', None |
| 101 |
return None |
| 102 |
|
| 103 |
|
| 104 |
def test_format_module_signatures() -> None: |
| 105 |
# no signatures for modules |
| 106 |
assert format_sig('module', 'test', None) == () |
| 107 |
|
| 108 |
|
| 109 |
def test_format_function_signatures() -> None: |
| 110 |
# test for functions |
| 111 |
def f(a, b, c=1, **d): # type: ignore[no-untyped-def] |
| 112 |
pass |
| 113 |
|
| 114 |
def g(a='\n'): # type: ignore[no-untyped-def] |
| 115 |
pass |
| 116 |
|
| 117 |
assert format_sig('function', 'f', f) == ('(a, b, c=1, **d)', '') |
| 118 |
assert format_sig('function', 'f', f, args='(a, b, c, d)') == ('(a, b, c, d)', '') |
| 119 |
assert format_sig('function', 'g', g) == (r"(a='\n')", '') |
| 120 |
|
| 121 |
|
| 122 |
@pytest.mark.parametrize( |
| 123 |
('params', 'expect'), |
| 124 |
[ |
| 125 |
('(a=1)', '(a=1)'), |
| 126 |
('(a: int=1)', '(a: int = 1)'), # auto whitespace formatting |
| 127 |
('(a:list[T] =[], b=None)', '(a: list[T] = [], b=None)'), # idem |
| 128 |
], |
| 129 |
) |
| 130 |
def test_format_function_signatures_pep695(params: str, expect: str) -> None: |
| 131 |
ns: dict[str, Any] = {} |
| 132 |
exec(f'def f[T]{params}: pass', ns) # NoQA: S102 |
| 133 |
f = ns['f'] |
| 134 |
assert format_sig('function', 'f', f) == (expect, '') |
| 135 |
assert format_sig('function', 'f', f, args='(...)') == ('(...)', '') |
| 136 |
assert format_sig('function', 'f', f, args='(...)', retann='...') == ( |
| 137 |
'(...)', |
| 138 |
'...', |
| 139 |
) |
| 140 |
|
| 141 |
exec(f'def f[T]{params} -> list[T]: return []', ns) # NoQA: S102 |
| 142 |
f = ns['f'] |
| 143 |
assert format_sig('function', 'f', f) == (expect, 'list[T]') |
| 144 |
assert format_sig('function', 'f', f, args='(...)') == ('(...)', '') |
| 145 |
assert format_sig('function', 'f', f, args='(...)', retann='...') == ( |
| 146 |
'(...)', |
| 147 |
'...', |
| 148 |
) |
| 149 |
|
| 150 |
# TODO(picnixz): add more test cases for PEP-695 classes as well (though |
| 151 |
# complex cases are less likely to appear and are painful to test). |
| 152 |
|
| 153 |
|
| 154 |
def test_format_class_signatures() -> None: |
| 155 |
# test for classes |
| 156 |
class D: |
| 157 |
pass |
| 158 |
|
| 159 |
class E: |
| 160 |
def __init__(self): # type: ignore[no-untyped-def] |
| 161 |
pass |
| 162 |
|
| 163 |
# an empty init and no init are the same |
| 164 |
for C in (D, E): |
| 165 |
assert format_sig('class', 'D', C) == ('()', '') |
| 166 |
|
| 167 |
class SomeMeta(type): |
| 168 |
def __call__(cls, a, b=None): # type: ignore[no-untyped-def] |
| 169 |
return type.__call__(cls, a, b) |
| 170 |
|
| 171 |
# these three are all equivalent |
| 172 |
class F: |
| 173 |
def __init__(self, a, b=None): # type: ignore[no-untyped-def] |
| 174 |
pass |
| 175 |
|
| 176 |
class FNew: |
| 177 |
def __new__(cls, a, b=None): # type: ignore[no-untyped-def] # NoQA: ARG004 |
| 178 |
return super().__new__(cls) |
| 179 |
|
| 180 |
class FMeta(metaclass=SomeMeta): |
| 181 |
pass |
| 182 |
|
| 183 |
# and subclasses should always inherit |
| 184 |
class G(F): |
| 185 |
pass |
| 186 |
|
| 187 |
class GNew(FNew): |
| 188 |
pass |
| 189 |
|
| 190 |
class GMeta(FMeta): |
| 191 |
pass |
| 192 |
|
| 193 |
# subclasses inherit |
| 194 |
assert format_sig('class', 'C', F) == ('(a, b=None)', '') |
| 195 |
assert format_sig('class', 'C', FNew) == ('(a, b=None)', '') |
| 196 |
assert format_sig('class', 'C', FMeta) == ('(a, b=None)', '') |
| 197 |
assert format_sig('class', 'C', G) == ('(a, b=None)', '') |
| 198 |
assert format_sig('class', 'C', GNew) == ('(a, b=None)', '') |
| 199 |
assert format_sig('class', 'C', GMeta) == ('(a, b=None)', '') |
| 200 |
assert format_sig('class', 'C', D, args='(a, b)', retann='X') == ('(a, b)', 'X') |
| 201 |
|
| 202 |
|
| 203 |
def test_format_class_signatures_text_signature() -> None: |
| 204 |
class ListSubclass(list): # type: ignore[type-arg] # NoQA: FURB189 |
| 205 |
pass |
| 206 |
|
| 207 |
# only supported if the python implementation decides to document it |
| 208 |
if getattr(list, '__text_signature__', None) is not None: |
| 209 |
assert format_sig('class', 'C', ListSubclass) == ('(iterable=(), /)', '') |
| 210 |
else: |
| 211 |
assert format_sig('class', 'C', ListSubclass) == () |
| 212 |
|
| 213 |
|
| 214 |
def test_format_class_signatures_no_text_signature() -> None: |
| 215 |
class ExceptionSubclass(Exception): |
| 216 |
pass |
| 217 |
|
| 218 |
# Exception has no __text_signature__ as at Python 3.14 |
| 219 |
if getattr(Exception, '__text_signature__', None) is not None: |
| 220 |
pytest.xfail('Exception.__text_signature__ exists!') |
| 221 |
assert format_sig('class', 'C', ExceptionSubclass) == () |
| 222 |
|
| 223 |
|
| 224 |
def test_format_class_signatures_init_both() -> None: |
| 225 |
# __init__ have signature at first line of docstring |
| 226 |
config = _AutodocConfig(autoclass_content='both') |
| 227 |
|
| 228 |
class F2: |
| 229 |
"""some docstring for F2.""" |
| 230 |
|
| 231 |
def __init__(self, *args, **kw): # type: ignore[no-untyped-def] |
| 232 |
""" |
| 233 |
__init__(a1, a2, kw1=True, kw2=False) |
| 234 |
|
| 235 |
some docstring for __init__. |
| 236 |
""" # NoQA: D212 |
| 237 |
|
| 238 |
class G2(F2): |
| 239 |
pass |
| 240 |
|
| 241 |
assert format_sig('class', 'F2', F2, config=config) == ( |
| 242 |
'(a1, a2, kw1=True, kw2=False)', |
| 243 |
'', |
| 244 |
) |
| 245 |
assert format_sig('class', 'G2', G2, config=config) == ( |
| 246 |
'(a1, a2, kw1=True, kw2=False)', |
| 247 |
'', |
| 248 |
) |
| 249 |
|
| 250 |
|
| 251 |
def test_format_method_signatures() -> None: |
| 252 |
# test for methods |
| 253 |
class H: |
| 254 |
def foo1(self, b, *c): # type: ignore[no-untyped-def] |
| 255 |
pass |
| 256 |
|
| 257 |
def foo2(b, *c): # type: ignore[no-untyped-def] # NoQA: N805 |
| 258 |
pass |
| 259 |
|
| 260 |
def foo3(self, d='\n'): # type: ignore[no-untyped-def] |
| 261 |
pass |
| 262 |
|
| 263 |
assert format_sig('method', 'H.foo', H.foo1) == ('(b, *c)', '') |
| 264 |
assert format_sig('method', 'H.foo', H.foo1, args='(a)') == ('(a)', '') |
| 265 |
assert format_sig('method', 'H.foo', H.foo2) == ('(*c)', '') |
| 266 |
assert format_sig('method', 'H.foo', H.foo3) == (r"(d='\n')", '') |
| 267 |
|
| 268 |
# test bound methods interpreted as functions |
| 269 |
assert format_sig('function', 'foo', H().foo1) == ('(b, *c)', '') |
| 270 |
assert format_sig('function', 'foo', H().foo2) == ('(*c)', '') |
| 271 |
assert format_sig('function', 'foo', H().foo3) == (r"(d='\n')", '') |
| 272 |
|
| 273 |
|
| 274 |
def test_format_method_signatures_error_handling() -> None: |
| 275 |
# test exception handling (exception is caught and args is '') |
| 276 |
config = _AutodocConfig(autodoc_docstring_signature=False) |
| 277 |
assert format_sig('function', 'int', int, config=config) == () |
| 278 |
|
| 279 |
|
| 280 |
def test_format_signatures_event_handler() -> None: |
| 281 |
events = FakeEvents() |
| 282 |
events.connect('autodoc-process-signature', _process_signature) |
| 283 |
|
| 284 |
class H: |
| 285 |
def foo1(self, b, *c): # type: ignore[no-untyped-def] |
| 286 |
pass |
| 287 |
|
| 288 |
# test processing by event handler |
| 289 |
assert format_sig('method', 'bar', H.foo1, events=events) == ('42', '') |
| 290 |
|
| 291 |
|
| 292 |
def test_format_functools_partial_signatures() -> None: |
| 293 |
# test functions created via functools.partial |
| 294 |
from functools import partial |
| 295 |
|
| 296 |
curried1 = partial(lambda a, b, c: None, 'A') |
| 297 |
assert format_sig('function', 'curried1', curried1) == ('(b, c)', '') |
| 298 |
curried2 = partial(lambda a, b, c=42: None, 'A') |
| 299 |
assert format_sig('function', 'curried2', curried2) == ('(b, c=42)', '') |
| 300 |
curried3 = partial(lambda a, b, *c: None, 'A') |
| 301 |
assert format_sig('function', 'curried3', curried3) == ('(b, *c)', '') |
| 302 |
curried4 = partial(lambda a, b, c=42, *d, **e: None, 'A') |
| 303 |
assert format_sig('function', 'curried4', curried4) == ('(b, c=42, *d, **e)', '') |
| 304 |
|
| 305 |
|
| 306 |
def test_autodoc_process_signature_typing_generic() -> None: |
| 307 |
T = TypeVar('T') |
| 308 |
|
| 309 |
class A(Generic[T]): |
| 310 |
def __init__(self, a, b=None): # type: ignore[no-untyped-def] |
| 311 |
pass |
| 312 |
|
| 313 |
# Test that typing.Generic's __new__ method does not mask |
| 314 |
# the class's __init__ signature. |
| 315 |
assert format_sig('class', 'A', A) == ('(a, b=None)', '') |
| 316 |
|
| 317 |
|
| 318 |
def test_autodoc_process_signature_typehints() -> None: |
| 319 |
captured = [] |
| 320 |
|
| 321 |
def process_signature(*args: Any) -> None: |
| 322 |
captured.append(args) |
| 323 |
|
| 324 |
events = FakeEvents() |
| 325 |
events.connect('autodoc-process-signature', process_signature) |
| 326 |
|
| 327 |
def func(x: int, y: int) -> int: # type: ignore[empty-body] |
| 328 |
pass |
| 329 |
|
| 330 |
props = _FunctionDefProperties( |
| 331 |
obj_type='function', |
| 332 |
module_name='', |
| 333 |
parts=('func',), |
| 334 |
docstring_lines=(), |
| 335 |
_obj=func, |
| 336 |
_obj___module__=None, |
| 337 |
_obj___qualname__=None, |
| 338 |
_obj___name__=None, |
| 339 |
properties=frozenset(), |
| 340 |
) |
| 341 |
|
| 342 |
options = _AutoDocumenterOptions() |
| 343 |
_format_signatures( |
| 344 |
autodoc_annotations={}, |
| 345 |
config=_AutodocConfig(), |
| 346 |
docstrings=None, |
| 347 |
events=events, |
| 348 |
get_attr=safe_getattr, |
| 349 |
options=options, |
| 350 |
parent=None, |
| 351 |
props=props, |
| 352 |
) |
| 353 |
|
| 354 |
app = events._app |
| 355 |
assert captured == [ |
| 356 |
(app, 'function', '.func', func, options, '(x: int, y: int)', 'int') |
| 357 |
] |