Skip to content

Commit

Permalink
doc: have tighter control on what autodoc shows
Browse files Browse the repository at this point in the history
New versions of sphinx starting showing `__init__` parameters even when
we don't want them to show because they are private (have `_ispytest`
argument).

The only working solution I found was to switch to
`autodoc_typehints_description_target = "documented"` and explicitly
document parameters for which we want to show the types. It's a little
tedious and repetitive in some simple cases, but overall it results in
nicer API docs.
  • Loading branch information
bluetech committed Aug 13, 2022
1 parent cb7f5ed commit 7431750
Show file tree
Hide file tree
Showing 16 changed files with 335 additions and 168 deletions.
1 change: 1 addition & 0 deletions doc/en/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@

autodoc_member_order = "bysource"
autodoc_typehints = "description"
autodoc_typehints_description_target = "documented"
todo_include_todos = 1

latex_engine = "lualatex"
Expand Down
2 changes: 1 addition & 1 deletion doc/en/reference/reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ pytest.deprecated_call

**Tutorial**: :ref:`ensuring_function_triggers`

.. autofunction:: pytest.deprecated_call()
.. autofunction:: pytest.deprecated_call([match])
:with:

pytest.register_assert_rewrite
Expand Down
2 changes: 1 addition & 1 deletion src/_pytest/assertion/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def register_assert_rewrite(*names: str) -> None:
actually imported, usually in your __init__.py if you are a plugin
using a package.
:raises TypeError: If the given module names are not strings.
:param names: The module names to register.
"""
for name in names:
if not isinstance(name, str):
Expand Down
54 changes: 35 additions & 19 deletions src/_pytest/config/argparsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,15 @@ def getgroup(
) -> "OptionGroup":
"""Get (or create) a named option Group.
:name: Name of the option group.
:description: Long description for --help output.
:after: Name of another group, used for ordering --help output.
:param name: Name of the option group.
:param description: Long description for --help output.
:param after: Name of another group, used for ordering --help output.
:returns: The option group.
The returned group object has an ``addoption`` method with the same
signature as :func:`parser.addoption <pytest.Parser.addoption>` but
will be shown in the respective group in the output of
``pytest. --help``.
``pytest --help``.
"""
for group in self._groups:
if group.name == name:
Expand All @@ -89,10 +90,11 @@ def getgroup(
def addoption(self, *opts: str, **attrs: Any) -> None:
"""Register a command line option.
:opts: Option names, can be short or long options.
:attrs: Same attributes which the ``add_argument()`` function of the
`argparse library <https://docs.python.org/library/argparse.html>`_
accepts.
:param opts:
Option names, can be short or long options.
:param attrs:
Same attributes as the argparse library's :py:func:`add_argument()
<argparse.ArgumentParser.add_argument>` function accepts.
After command line parsing, options are available on the pytest config
object via ``config.option.NAME`` where ``NAME`` is usually set
Expand Down Expand Up @@ -148,16 +150,24 @@ def parse_known_args(
args: Sequence[Union[str, "os.PathLike[str]"]],
namespace: Optional[argparse.Namespace] = None,
) -> argparse.Namespace:
"""Parse and return a namespace object with known arguments at this point."""
"""Parse the known arguments at this point.
:returns: An argparse namespace object.
"""
return self.parse_known_and_unknown_args(args, namespace=namespace)[0]

def parse_known_and_unknown_args(
self,
args: Sequence[Union[str, "os.PathLike[str]"]],
namespace: Optional[argparse.Namespace] = None,
) -> Tuple[argparse.Namespace, List[str]]:
"""Parse and return a namespace object with known arguments, and
the remaining arguments unknown at this point."""
"""Parse the known arguments at this point, and also return the
remaining unknown arguments.
:returns:
A tuple containing an argparse namespace object for the known
arguments, and a list of the unknown arguments.
"""
optparser = self._getparser()
strargs = [os.fspath(x) for x in args]
return optparser.parse_known_args(strargs, namespace=namespace)
Expand All @@ -173,9 +183,9 @@ def addini(
) -> None:
"""Register an ini-file option.
:name:
:param name:
Name of the ini-variable.
:type:
:param type:
Type of the variable. Can be:
* ``string``: a string
Expand All @@ -189,7 +199,7 @@ def addini(
The ``paths`` variable type.
Defaults to ``string`` if ``None`` or not passed.
:default:
:param default:
Default value if no ini-file option exists but is queried.
The value of ini-variables can be retrieved via a call to
Expand Down Expand Up @@ -354,24 +364,30 @@ def __init__(
self.options: List[Argument] = []
self.parser = parser

def addoption(self, *optnames: str, **attrs: Any) -> None:
def addoption(self, *opts: str, **attrs: Any) -> None:
"""Add an option to this group.
If a shortened version of a long option is specified, it will
be suppressed in the help. ``addoption('--twowords', '--two-words')``
results in help showing ``--two-words`` only, but ``--twowords`` gets
accepted **and** the automatic destination is in ``args.twowords``.
:param opts:
Option names, can be short or long options.
:param attrs:
Same attributes as the argparse library's :py:func:`add_argument()
<argparse.ArgumentParser.add_argument>` function accepts.
"""
conflict = set(optnames).intersection(
conflict = set(opts).intersection(
name for opt in self.options for name in opt.names()
)
if conflict:
raise ValueError("option names %s already added" % conflict)
option = Argument(*optnames, **attrs)
option = Argument(*opts, **attrs)
self._addoption_instance(option, shortupper=False)

def _addoption(self, *optnames: str, **attrs: Any) -> None:
option = Argument(*optnames, **attrs)
def _addoption(self, *opts: str, **attrs: Any) -> None:
option = Argument(*opts, **attrs)
self._addoption_instance(option, shortupper=True)

def _addoption_instance(self, option: "Argument", shortupper: bool = False) -> None:
Expand Down
19 changes: 12 additions & 7 deletions src/_pytest/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -513,8 +513,8 @@ def session(self) -> "Session":
return self._pyfuncitem.session # type: ignore[no-any-return]

def addfinalizer(self, finalizer: Callable[[], object]) -> None:
"""Add finalizer/teardown function to be called after the last test
within the requesting test context finished execution."""
"""Add finalizer/teardown function to be called without arguments after
the last test within the requesting test context finished execution."""
# XXX usually this method is shadowed by fixturedef specific ones.
self._addfinalizer(finalizer, scope=self.scope)

Expand All @@ -529,13 +529,16 @@ def applymarker(self, marker: Union[str, MarkDecorator]) -> None:
on all function invocations.
:param marker:
A :class:`pytest.MarkDecorator` object created by a call
to ``pytest.mark.NAME(...)``.
An object created by a call to ``pytest.mark.NAME(...)``.
"""
self.node.add_marker(marker)

def raiseerror(self, msg: Optional[str]) -> NoReturn:
"""Raise a FixtureLookupError with the given message."""
"""Raise a FixtureLookupError exception.
:param msg:
An optional custom error message.
"""
raise self._fixturemanager.FixtureLookupError(None, self, msg)

def _fillfixtures(self) -> None:
Expand All @@ -557,6 +560,8 @@ def getfixturevalue(self, argname: str) -> Any:
phase, but during the test teardown phase a fixture's value may not
be available.
:param argname:
The fixture name.
:raises pytest.FixtureLookupError:
If the given fixture could not be found.
"""
Expand Down Expand Up @@ -768,8 +773,8 @@ def __repr__(self) -> str:
return f"<SubRequest {self.fixturename!r} for {self._pyfuncitem!r}>"

def addfinalizer(self, finalizer: Callable[[], object]) -> None:
"""Add finalizer/teardown function to be called after the last test
within the requesting test context finished execution."""
"""Add finalizer/teardown function to be called without arguments after
the last test within the requesting test context finished execution."""
self._fixturedef.addfinalizer(finalizer)

def _schedule_finalizers(
Expand Down

0 comments on commit 7431750

Please sign in to comment.