From 8a90d5725be01ecfdc77d55b1c44038f7dce6bce Mon Sep 17 00:00:00 2001 From: Hood Chatham Date: Thu, 12 Sep 2024 15:59:25 +0200 Subject: [PATCH] Fix placement of return type when there is a doctest (#482) Resolves #480 --- src/sphinx_autodoc_typehints/patches.py | 15 +++++++++++++- tests/test_integration.py | 26 +++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/sphinx_autodoc_typehints/patches.py b/src/sphinx_autodoc_typehints/patches.py index e29a6dc..2307f53 100644 --- a/src/sphinx_autodoc_typehints/patches.py +++ b/src/sphinx_autodoc_typehints/patches.py @@ -5,8 +5,9 @@ from functools import lru_cache from typing import TYPE_CHECKING, Any +from docutils import nodes from docutils.parsers.rst.directives.admonitions import BaseAdmonition -from docutils.parsers.rst.states import Text +from docutils.parsers.rst.states import Body, Text from sphinx.ext.napoleon.docstring import GoogleDocstring from .attributes_patch import patch_attribute_handling @@ -110,6 +111,17 @@ def _patched_text_indent(self: Text, *args: Any) -> Any: return result +def _patched_body_doctest( + self: Body, _match: None, _context: None, next_state: str | None +) -> tuple[list[Any], str | None, list[Any]]: + line = self.document.current_line + 1 + data = "\n".join(self.state_machine.get_text_block()) + n = nodes.doctest_block(data, data) + n.line = line + self.parent += n + return [], next_state, [] + + def _patch_line_numbers() -> None: """ Make the rst parser put line numbers on more nodes. @@ -118,6 +130,7 @@ def _patch_line_numbers() -> None: """ Text.indent = _patched_text_indent BaseAdmonition.run = _patched_base_admonition_run + Body.doctest = _patched_body_doctest def install_patches(app: Sphinx) -> None: diff --git a/tests/test_integration.py b/tests/test_integration.py index cbd218e..3339916 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -1359,6 +1359,32 @@ def docstring_with_see_also() -> str: return "" +@expected( + """ + mod.has_doctest1() + + Test that we place the return type correctly when the function has + a doctest. + + Return type: + "None" + + >>> this is a fake doctest + a + >>> more doctest + b + """ +) +def has_doctest1() -> None: + r"""Test that we place the return type correctly when the function has a doctest. + + >>> this is a fake doctest + a + >>> more doctest + b + """ + + # Config settings for each test run. # Config Name: Sphinx Options as Dict. configs = {