Debian Codegraph @

tests/test_transforms/test_transforms_post_transforms.py

raw
1 """Tests the post_transforms"""
2
3 from __future__ import annotations
4
5 import logging
6 from typing import TYPE_CHECKING
7
8 import pytest
9 from docutils import nodes
10
11 from sphinx import addnodes
12 from sphinx.addnodes import SIG_ELEMENTS
13 from sphinx.testing.util import SphinxTestApp, assert_node
14 from sphinx.transforms.post_transforms import SigElementFallbackTransform
15 from sphinx.util.docutils import new_document
16
17 if TYPE_CHECKING:
18 from typing import Any, NoReturn
19
20 from _pytest.fixtures import SubRequest
21
22 from sphinx.application import Sphinx
23 from sphinx.builders import Builder
24 from sphinx.environment import BuildEnvironment
25 from sphinx.testing.util import SphinxTestApp
26
27
28 @pytest.mark.sphinx('html', testroot='transforms-post_transforms-missing-reference')
29 def test_nitpicky_warning(app: SphinxTestApp) -> None:
30 app.build()
31 assert (
32 'index.rst:4: WARNING: py:class reference target not found: io.StringIO'
33 ) in app.warning.getvalue()
34
35 content = (app.outdir / 'index.html').read_text(encoding='utf8')
36 assert (
37 '<p><code class="xref py py-class docutils literal notranslate"><span class="pre">'
38 'io.StringIO</span></code></p>'
39 ) in content
40
41
42 @pytest.mark.sphinx(
43 'html',
44 testroot='transforms-post_transforms-missing-reference',
45 freshenv=True,
46 )
47 def test_missing_reference(app: SphinxTestApp) -> None:
48 def missing_reference(
49 app_: Sphinx,
50 env_: BuildEnvironment,
51 node_: addnodes.pending_xref,
52 contnode_: nodes.Node,
53 ) -> nodes.inline:
54 assert app_ is app
55 assert env_ is app.env
56 assert node_['reftarget'] == 'io.StringIO'
57 assert contnode_.astext() == 'io.StringIO'
58
59 return nodes.inline('', 'missing-reference.StringIO')
60
61 app.warning.truncate(0)
62 app.connect('missing-reference', missing_reference)
63 app.build()
64 assert app.warning.getvalue() == ''
65
66 content = (app.outdir / 'index.html').read_text(encoding='utf8')
67 assert '<p><span>missing-reference.StringIO</span></p>' in content
68
69
70 @pytest.mark.sphinx(
71 'html',
72 testroot='domain-py-python_use_unqualified_type_names',
73 freshenv=True,
74 )
75 def test_missing_reference_conditional_pending_xref(app: SphinxTestApp) -> None:
76 def missing_reference(
77 _app: Sphinx,
78 _env: BuildEnvironment,
79 _node: addnodes.pending_xref,
80 contnode: nodes.Node,
81 ) -> nodes.Node:
82 return contnode
83
84 app.warning.truncate(0)
85 app.connect('missing-reference', missing_reference)
86 app.build()
87 assert app.warning.getvalue() == ''
88
89 content = (app.outdir / 'index.html').read_text(encoding='utf8')
90 assert '<span class="n"><span class="pre">Age</span></span>' in content
91
92
93 @pytest.mark.sphinx(
94 'html',
95 testroot='transforms-post_transforms-keyboard',
96 freshenv=True,
97 )
98 def test_keyboard_hyphen_spaces(app: SphinxTestApp) -> None:
99 # https://github.com/sphinx-doc/sphinx/issues/10495
100 app.build()
101 assert 'spanish' in (app.outdir / 'index.html').read_text(encoding='utf8')
102 assert 'inquisition' in (app.outdir / 'index.html').read_text(encoding='utf8')
103
104
105 class TestSigElementFallbackTransform:
106 """Integration test for :class:`sphinx.transforms.post_transforms.SigElementFallbackTransform`."""
107
108 # safe copy of the "built-in" desc_sig_* nodes (during the test, instances of such nodes
109 # will be created sequentially, so we fix a possible order at the beginning using a tuple)
110 _builtin_sig_elements: tuple[type[addnodes.desc_sig_element], ...] = tuple(
111 SIG_ELEMENTS
112 )
113
114 @pytest.fixture(autouse=True)
115 def builtin_sig_elements(self) -> tuple[type[addnodes.desc_sig_element], ...]:
116 """Fixture returning an ordered view on the original value of :data:`!sphinx.addnodes.SIG_ELEMENTS`."""
117 return self._builtin_sig_elements
118
119 @pytest.fixture
120 def document(
121 self,
122 app: SphinxTestApp,
123 builtin_sig_elements: tuple[type[addnodes.desc_sig_element], ...],
124 ) -> nodes.document:
125 """Fixture returning a new document with built-in ``desc_sig_*`` nodes and a final ``desc_inline`` node."""
126 doc = new_document('')
127 doc.settings.env = app.env
128 # Nodes that should be supported by a default custom translator class.
129 # It is important that builtin_sig_elements has a fixed order so that
130 # the nodes can be deterministically checked.
131 doc += [node_type('', '') for node_type in builtin_sig_elements]
132 doc += addnodes.desc_inline('py')
133 return doc
134
135 @pytest.fixture
136 def with_desc_sig_elements(self, value: Any) -> bool:
137 """Dynamic fixture acting as the identity on booleans."""
138 assert isinstance(value, bool)
139 return value
140
141 @pytest.fixture
142 def add_visitor_method_for(self, value: Any) -> list[str]:
143 """Dynamic fixture acting as the identity on a list of strings."""
144 assert isinstance(value, list)
145 assert all(isinstance(item, str) for item in value)
146 return value
147
148 @pytest.fixture(autouse=True)
149 def translator_class(self, request: SubRequest) -> type[nodes.NodeVisitor]:
150 """Minimal interface fixture similar to SphinxTranslator but orthogonal thereof."""
151 logger = logging.getLogger(__name__)
152
153 class BaseCustomTranslatorClass(nodes.NodeVisitor):
154 """Base class for a custom translator class, orthogonal to ``SphinxTranslator``."""
155
156 def __init__(
157 self, document: nodes.document, _builder: Builder | None = None
158 ) -> None:
159 super().__init__(document)
160 # ignore other arguments
161
162 def dispatch_visit(self, node: nodes.Node) -> None:
163 for node_class in node.__class__.__mro__:
164 if method := getattr(self, f'visit_{node_class.__name__}', None):
165 method(node)
166 break
167 else:
168 logger.info('generic visit: %r', node.__class__.__name__)
169 super().dispatch_visit(node)
170
171 def unknown_visit(self, node: nodes.Node) -> None:
172 logger.warning('unknown visit: %r', node.__class__.__name__)
173 raise nodes.SkipDeparture # ignore unknown departure
174
175 def visit_document(self, node: nodes.document) -> None:
176 raise nodes.SkipDeparture # ignore departure
177
178 def mark_node(self, node: nodes.Node) -> NoReturn:
179 logger.info('mark: %r', node.__class__.__name__)
180 raise nodes.SkipDeparture # ignore departure
181
182 with_desc_sig_elements = request.getfixturevalue('with_desc_sig_elements')
183 if with_desc_sig_elements:
184 desc_sig_elements_list = request.getfixturevalue('builtin_sig_elements')
185 else:
186 desc_sig_elements_list = []
187 add_visitor_method_for = request.getfixturevalue('add_visitor_method_for')
188 visitor_methods = {f'visit_{tp.__name__}' for tp in desc_sig_elements_list}
189 visitor_methods.update(f'visit_{name}' for name in add_visitor_method_for)
190 class_dict = dict.fromkeys(visitor_methods, BaseCustomTranslatorClass.mark_node)
191 return type('CustomTranslatorClass', (BaseCustomTranslatorClass,), class_dict) # ty: ignore[invalid-return-type]
192
193 @pytest.mark.parametrize(
194 'add_visitor_method_for',
195 [[], ['desc_inline']],
196 ids=[
197 'no_explicit_visitor',
198 'explicit_desc_inline_visitor',
199 ],
200 )
201 @pytest.mark.parametrize(
202 'with_desc_sig_elements',
203 [True, False],
204 ids=[
205 'with_default_visitors_for_desc_sig_elements',
206 'without_default_visitors_for_desc_sig_elements',
207 ],
208 )
209 @pytest.mark.sphinx('dummy', testroot='root')
210 def test_support_desc_inline(
211 self,
212 document: nodes.document,
213 with_desc_sig_elements: bool,
214 add_visitor_method_for: list[str],
215 request: SubRequest,
216 ) -> None:
217 document, _, _ = self._exec(request)
218 # count the number of desc_inline nodes with the extra _sig_node_type field
219 desc_inline_typename = addnodes.desc_inline.__name__
220 visit_desc_inline = desc_inline_typename in add_visitor_method_for
221 if visit_desc_inline:
222 assert_node(document[-1], addnodes.desc_inline)
223 else:
224 assert_node(document[-1], nodes.inline, _sig_node_type=desc_inline_typename)
225
226 @pytest.mark.parametrize(
227 'add_visitor_method_for',
228 [
229 [], # no support
230 ['desc_sig_space'], # enable desc_sig_space visitor
231 ['desc_sig_element'], # enable generic visitor
232 [
233 # enable desc_sig_space and generic visitors
234 'desc_sig_space',
235 'desc_sig_element',
236 ],
237 ],
238 ids=[
239 'no_explicit_visitor',
240 'explicit_desc_sig_space_visitor',
241 'explicit_desc_sig_element_visitor',
242 'explicit_desc_sig_space_and_desc_sig_element_visitors',
243 ],
244 )
245 @pytest.mark.parametrize(
246 'with_desc_sig_elements',
247 [True, False],
248 ids=[
249 'with_default_visitors_for_desc_sig_elements',
250 'without_default_visitors_for_desc_sig_elements',
251 ],
252 )
253 @pytest.mark.sphinx('dummy', testroot='root')
254 def test_custom_implementation(
255 self,
256 document: nodes.document,
257 with_desc_sig_elements: bool,
258 add_visitor_method_for: list[str],
259 request: SubRequest,
260 ) -> None:
261 document, stdout, stderr = self._exec(request)
262 assert (
263 len(self._builtin_sig_elements)
264 == len(document.children[:-1])
265 == len(stdout[:-1])
266 )
267
268 visit_desc_sig_element = (
269 addnodes.desc_sig_element.__name__ in add_visitor_method_for
270 )
271 ignore_sig_element_fallback_transform = (
272 visit_desc_sig_element or with_desc_sig_elements
273 )
274
275 if ignore_sig_element_fallback_transform:
276 # desc_sig_element is implemented or desc_sig_* nodes are properly handled (and left untouched)
277 for node_type, node, mess in zip(
278 self._builtin_sig_elements,
279 document.children[:-1],
280 stdout[:-1],
281 strict=True,
282 ):
283 assert_node(node, node_type)
284 assert not hasattr(node, '_sig_node_type')
285 assert mess == f'mark: {node_type.__name__!r}'
286 else:
287 # desc_sig_* nodes are converted into inline nodes
288 for node_type, node, mess in zip(
289 self._builtin_sig_elements,
290 document.children[:-1],
291 stdout[:-1],
292 strict=True,
293 ):
294 assert_node(node, nodes.inline, _sig_node_type=node_type.__name__)
295 assert mess == f'generic visit: {nodes.inline.__name__!r}'
296
297 # desc_inline node is never handled and always transformed
298 assert addnodes.desc_inline.__name__ not in add_visitor_method_for
299 assert_node(
300 document[-1], nodes.inline, _sig_node_type=addnodes.desc_inline.__name__
301 )
302 assert stdout[-1] == f'generic visit: {nodes.inline.__name__!r}'
303
304 # nodes.inline are never handled
305 assert (
306 len(stderr) == 1
307 if ignore_sig_element_fallback_transform
308 else len(document.children)
309 )
310 assert set(stderr) == {f'unknown visit: {nodes.inline.__name__!r}'}
311
312 @staticmethod
313 def _exec(request: SubRequest) -> tuple[nodes.document, list[str], list[str]]:
314 caplog = request.getfixturevalue('caplog')
315 caplog.set_level(logging.INFO, logger=__name__)
316
317 app = request.getfixturevalue('app')
318 translator_class = request.getfixturevalue('translator_class')
319 app.set_translator('dummy', translator_class)
320 # run the post-transform directly [building phase]
321 # document contains SIG_ELEMENTS nodes followed by a desc_inline node
322 document = request.getfixturevalue('document')
323 SigElementFallbackTransform(document).run()
324 # run the translator [writing phase]
325 translator = translator_class(document, app.builder)
326 document.walkabout(translator)
327 # extract messages
328 messages = caplog.record_tuples
329 stdout = [message for _, lvl, message in messages if lvl == logging.INFO]
330 stderr = [message for _, lvl, message in messages if lvl == logging.WARNING]
331 return document, stdout, stderr