Debian Codegraph @

tests/test_extensions/test_ext_inheritance_diagram.py

raw
1 """Test sphinx.ext.inheritance_diagram extension."""
2
3 from __future__ import annotations
4
5 import re
6 import sys
7 import zlib
8 from pathlib import Path
9 from typing import TYPE_CHECKING
10
11 import pytest
12 from docutils import nodes
13
14 from sphinx.ext.inheritance_diagram import (
15 InheritanceDiagram,
16 InheritanceException,
17 import_classes,
18 )
19 from sphinx.ext.intersphinx._load import load_mappings, validate_intersphinx_mapping
20
21 if TYPE_CHECKING:
22 from sphinx.testing.util import SphinxTestApp
23
24
25 @pytest.mark.sphinx('html', testroot='inheritance')
26 @pytest.mark.usefixtures('if_graphviz_found')
27 def test_inheritance_diagram(app: SphinxTestApp) -> None:
28 # monkey-patch InheritaceDiagram.run() so we can get access to its
29 # results.
30 orig_run = InheritanceDiagram.run
31 graphs = {}
32
33 def new_run(self):
34 result = orig_run(self)
35 node = result[0]
36 assert isinstance(node.document, nodes.document)
37 source = Path(node.document.current_source).stem
38 graphs[source] = node['graph']
39 return result
40
41 InheritanceDiagram.run = new_run # type: ignore[method-assign]
42
43 try:
44 app.build(force_all=True)
45 finally:
46 InheritanceDiagram.run = orig_run # type: ignore[method-assign]
47
48 assert app.statuscode == 0
49
50 html_warnings = app.warning.getvalue()
51 assert html_warnings == ''
52
53 # note: it is better to split these asserts into separate test functions
54 # but I can't figure out how to build only a specific .rst file
55
56 # basic inheritance diagram showing all classes
57 for cls in graphs['basic_diagram'].class_info:
58 # use in b/c traversing order is different sometimes
59 assert cls in {
60 ('dummy.test.A', 'dummy.test.A', (), None),
61 ('dummy.test.F', 'dummy.test.F', ('dummy.test.C',), None),
62 ('dummy.test.C', 'dummy.test.C', ('dummy.test.A',), None),
63 ('dummy.test.E', 'dummy.test.E', ('dummy.test.B',), None),
64 ('dummy.test.D', 'dummy.test.D', ('dummy.test.B', 'dummy.test.C'), None),
65 ('dummy.test.B', 'dummy.test.B', ('dummy.test.A',), None),
66 }
67
68 # inheritance diagram using :parts: 1 option
69 for cls in graphs['diagram_w_parts'].class_info:
70 assert cls in {
71 ('A', 'dummy.test.A', (), None),
72 ('F', 'dummy.test.F', ('C',), None),
73 ('C', 'dummy.test.C', ('A',), None),
74 ('E', 'dummy.test.E', ('B',), None),
75 ('D', 'dummy.test.D', ('B', 'C'), None),
76 ('B', 'dummy.test.B', ('A',), None),
77 }
78
79 # inheritance diagram with 1 top class
80 # :top-classes: dummy.test.B
81 # rendering should be
82 # A
83 # \
84 # B C
85 # / \ / \
86 # E D F
87 #
88 for cls in graphs['diagram_w_1_top_class'].class_info:
89 assert cls in {
90 ('dummy.test.A', 'dummy.test.A', (), None),
91 ('dummy.test.F', 'dummy.test.F', ('dummy.test.C',), None),
92 ('dummy.test.C', 'dummy.test.C', ('dummy.test.A',), None),
93 ('dummy.test.E', 'dummy.test.E', ('dummy.test.B',), None),
94 ('dummy.test.D', 'dummy.test.D', ('dummy.test.B', 'dummy.test.C'), None),
95 ('dummy.test.B', 'dummy.test.B', (), None),
96 }
97
98 # inheritance diagram with 2 top classes
99 # :top-classes: dummy.test.B, dummy.test.C
100 # Note: we're specifying separate classes, not the entire module here
101 # rendering should be
102 #
103 # B C
104 # / \ / \
105 # E D F
106 #
107 for cls in graphs['diagram_w_2_top_classes'].class_info:
108 assert cls in {
109 ('dummy.test.F', 'dummy.test.F', ('dummy.test.C',), None),
110 ('dummy.test.C', 'dummy.test.C', (), None),
111 ('dummy.test.E', 'dummy.test.E', ('dummy.test.B',), None),
112 ('dummy.test.D', 'dummy.test.D', ('dummy.test.B', 'dummy.test.C'), None),
113 ('dummy.test.B', 'dummy.test.B', (), None),
114 }
115
116 # inheritance diagram with 2 top classes and specifying the entire module
117 # rendering should be
118 #
119 # A
120 # B C
121 # / \ / \
122 # E D F
123 #
124 # Note: dummy.test.A is included in the graph before its descendants are even processed
125 # b/c we've specified to load the entire module. The way InheritanceGraph works it is very
126 # hard to exclude parent classes once after they have been included in the graph.
127 # If you'd like to not show class A in the graph don't specify the entire module.
128 # this is a known issue.
129 for cls in graphs['diagram_module_w_2_top_classes'].class_info:
130 assert cls in {
131 ('dummy.test.F', 'dummy.test.F', ('dummy.test.C',), None),
132 ('dummy.test.C', 'dummy.test.C', (), None),
133 ('dummy.test.E', 'dummy.test.E', ('dummy.test.B',), None),
134 ('dummy.test.D', 'dummy.test.D', ('dummy.test.B', 'dummy.test.C'), None),
135 ('dummy.test.B', 'dummy.test.B', (), None),
136 ('dummy.test.A', 'dummy.test.A', (), None),
137 }
138
139 # inheritance diagram involving a base class nested within another class
140 for cls in graphs['diagram_w_nested_classes'].class_info:
141 assert cls in {
142 ('dummy.test_nested.A', 'dummy.test_nested.A', (), None),
143 (
144 'dummy.test_nested.C',
145 'dummy.test_nested.C',
146 ('dummy.test_nested.A.B',),
147 None,
148 ),
149 ('dummy.test_nested.A.B', 'dummy.test_nested.A.B', (), None),
150 }
151
152
153 # An external inventory to test intersphinx links in inheritance diagrams
154 external_inventory = b"""\
155 # Sphinx inventory version 2
156 # Project: external
157 # Version: 1.0
158 # The remainder of this file is compressed using zlib.
159 """ + zlib.compress(b"""\
160 external.other.Bob py:class 1 foo.html#external.other.Bob -
161 """)
162
163
164 @pytest.mark.sphinx('html', testroot='ext-inheritance_diagram')
165 @pytest.mark.usefixtures('if_graphviz_found')
166 def test_inheritance_diagram_png_html(tmp_path, app):
167 inv_file = tmp_path / 'inventory'
168 inv_file.write_bytes(external_inventory)
169 app.config.intersphinx_mapping = {
170 'example': ('https://example.org', str(inv_file)),
171 }
172 app.config.intersphinx_cache_limit = 0
173 validate_intersphinx_mapping(app, app.config)
174 load_mappings(app)
175
176 app.build(force_all=True)
177
178 content = (app.outdir / 'index.html').read_text(encoding='utf8')
179 base_maps = re.findall('<map .+\n.+\n</map>', content)
180
181 pattern = (
182 '<figure class="align-default" id="id1">\n'
183 '<div class="graphviz">'
184 '<img src="_images/inheritance-\\w+.png" alt="Inheritance diagram of test.Foo" '
185 'class="inheritance graphviz" /></div>\n<figcaption>\n<p>'
186 '<span class="caption-text">Test Foo!</span><a class="headerlink" href="#id1" '
187 'title="Link to this image">\xb6</a></p>\n</figcaption>\n</figure>\n'
188 )
189 assert re.search(pattern, content, re.MULTILINE)
190
191 subdir_content = (app.outdir / 'subdir/page1.html').read_text(encoding='utf8')
192 subdir_maps = re.findall('<map .+\n.+\n</map>', subdir_content)
193 subdir_maps = [
194 re.sub('href="(\\S+)"', 'href="subdir/\\g<1>"', s) for s in subdir_maps
195 ]
196
197 # Go through the clickmap for every PNG inheritance diagram
198 for diagram_content in base_maps + subdir_maps:
199 # Verify that an intersphinx link was created via the external inventory
200 if 'subdir.' in diagram_content:
201 assert 'https://example.org' in diagram_content
202
203 # Extract every link in the inheritance diagram
204 for href in re.findall('href="(\\S+?)"', diagram_content):
205 if '://' in href:
206 # Verify that absolute URLs are not prefixed with ../
207 assert href.startswith('https://example.org/')
208 else:
209 # Verify that relative URLs point to existing documents
210 reluri = href.rsplit('#', 1)[0] # strip the anchor at the end
211 assert (app.outdir / reluri).exists()
212
213
214 @pytest.mark.sphinx(
215 'html',
216 testroot='ext-inheritance_diagram',
217 confoverrides={'graphviz_output_format': 'svg'},
218 )
219 @pytest.mark.usefixtures('if_graphviz_found')
220 def test_inheritance_diagram_svg_html(tmp_path, app):
221 inv_file = tmp_path / 'inventory'
222 inv_file.write_bytes(external_inventory)
223 app.config.intersphinx_mapping = {
224 'subdir': ('https://example.org', str(inv_file)),
225 }
226 app.config.intersphinx_cache_limit = 0
227 validate_intersphinx_mapping(app, app.config)
228 load_mappings(app)
229
230 app.build(force_all=True)
231
232 content = (app.outdir / 'index.html').read_text(encoding='utf8')
233 base_svgs = re.findall('<object data="(_images/inheritance-\\w+.svg?)"', content)
234
235 pattern = (
236 '<figure class="align-default" id="id1">\n'
237 '<div class="graphviz">'
238 '<object data="_images/inheritance-\\w+.svg" '
239 'type="image/svg\\+xml" class="inheritance graphviz">\n'
240 '<p class="warning">Inheritance diagram of test.Foo</p>'
241 '</object></div>\n<figcaption>\n<p><span class="caption-text">'
242 'Test Foo!</span><a class="headerlink" href="#id1" '
243 'title="Link to this image">\xb6</a></p>\n</figcaption>\n</figure>\n'
244 )
245
246 assert re.search(pattern, content, re.MULTILINE)
247
248 subdir_content = (app.outdir / 'subdir/page1.html').read_text(encoding='utf8')
249 subdir_svgs = re.findall(
250 '<object data="../(_images/inheritance-\\w+.svg?)"', subdir_content
251 )
252
253 # Go through every SVG inheritance diagram
254 for diagram in base_svgs + subdir_svgs:
255 diagram_content = (app.outdir / diagram).read_text(encoding='utf8')
256
257 # Verify that an intersphinx link was created via the external inventory
258 if 'subdir.' in diagram_content:
259 assert 'https://example.org' in diagram_content
260
261 # Extract every link in the inheritance diagram
262 for href in re.findall('href="(\\S+?)"', diagram_content):
263 if '://' in href:
264 # Verify that absolute URLs are not prefixed with ../
265 assert href.startswith('https://example.org/')
266 else:
267 # Verify that relative URLs point to existing documents
268 reluri = href.rsplit('#', 1)[0] # strip the anchor at the end
269 abs_uri = (app.outdir / app.builder.imagedir / reluri).resolve()
270 assert abs_uri.exists()
271
272
273 @pytest.mark.sphinx('latex', testroot='ext-inheritance_diagram')
274 @pytest.mark.usefixtures('if_graphviz_found')
275 def test_inheritance_diagram_latex(app: SphinxTestApp) -> None:
276 app.build(force_all=True)
277
278 content = (app.outdir / 'projectnamenotset.tex').read_text(encoding='utf8')
279
280 pattern = (
281 '\\\\begin{figure}\\[htbp]\n\\\\centering\n\\\\capstart\n\n'
282 '\\\\sphinxincludegraphics\\[\\]{inheritance-\\w+.pdf}\n'
283 '\\\\caption{Test Foo!}\\\\label{\\\\detokenize{index:id1}}\\\\end{figure}'
284 )
285 assert re.search(pattern, content, re.MULTILINE)
286
287
288 @pytest.mark.sphinx(
289 'html',
290 testroot='ext-inheritance_diagram',
291 srcdir='ext-inheritance_diagram-alias',
292 )
293 @pytest.mark.usefixtures('if_graphviz_found')
294 def test_inheritance_diagram_latex_alias(app):
295 app.config.inheritance_alias = {'test.Foo': 'alias.Foo'}
296 app.build(force_all=True)
297
298 doc = app.env.get_and_resolve_doctree('index', app.builder, tags=app.tags)
299 aliased_graph = doc.children[0].children[3]['graph'].class_info
300 assert len(aliased_graph) == 4
301 assert (
302 'test.DocSubDir2',
303 'test.DocSubDir2',
304 ('test.DocSubDir1',),
305 None,
306 ) in aliased_graph
307 assert (
308 'test.DocSubDir1',
309 'test.DocSubDir1',
310 ('test.DocHere',),
311 None,
312 ) in aliased_graph
313 assert ('test.DocHere', 'test.DocHere', ('alias.Foo',), None) in aliased_graph
314 assert ('alias.Foo', 'alias.Foo', (), None) in aliased_graph
315
316 content = (app.outdir / 'index.html').read_text(encoding='utf8')
317
318 pattern = (
319 '<figure class="align-default" id="id1">\n'
320 '<div class="graphviz">'
321 '<img src="_images/inheritance-\\w+.png" alt="Inheritance diagram of test.Foo" '
322 'class="inheritance graphviz" /></div>\n<figcaption>\n<p>'
323 '<span class="caption-text">Test Foo!</span><a class="headerlink" href="#id1" '
324 'title="Link to this image">\xb6</a></p>\n</figcaption>\n</figure>\n'
325 )
326 assert re.search(pattern, content, re.MULTILINE)
327
328
329 def test_import_classes(rootdir):
330 from sphinx.parsers import Parser, RSTParser
331 from sphinx.util.i18n import CatalogInfo
332
333 saved_path = sys.path.copy()
334 sys.path.insert(0, str(rootdir / 'test-ext-inheritance_diagram'))
335 try:
336 from example.sphinx import DummyClass # type: ignore[import-not-found]
337
338 # got exception for unknown class or module
339 with pytest.raises(InheritanceException):
340 import_classes('unknown', None)
341 with pytest.raises(InheritanceException):
342 import_classes('unknown.Unknown', None)
343
344 # got exception InheritanceException for wrong class or module
345 # not AttributeError
346 # See: https://github.com/sphinx-doc/sphinx/issues/4019
347 with pytest.raises(InheritanceException):
348 import_classes('unknown', '.')
349 with pytest.raises(InheritanceException):
350 import_classes('unknown.Unknown', '.')
351 with pytest.raises(InheritanceException):
352 import_classes('.', None)
353
354 # a module having no classes
355 classes = import_classes('sphinx', None)
356 assert classes == []
357
358 classes = import_classes('sphinx', 'foo')
359 assert classes == []
360
361 # all of classes in the module
362 classes = import_classes('sphinx.parsers', None)
363 assert set(classes) == {Parser, RSTParser}
364
365 # specified class in the module
366 classes = import_classes('sphinx.parsers.Parser', None)
367 assert classes == [Parser]
368
369 # specified class in current module
370 classes = import_classes('Parser', 'sphinx.parsers')
371 assert classes == [Parser]
372
373 # relative module name to current module
374 classes = import_classes('i18n.CatalogInfo', 'sphinx.util')
375 assert classes == [CatalogInfo]
376
377 # got exception for functions
378 with pytest.raises(InheritanceException):
379 import_classes('encode_uri', 'sphinx.util')
380
381 # import submodule on current module
382 # See: https://github.com/sphinx-doc/sphinx/issues/3164
383 classes = import_classes('sphinx', 'example')
384 assert classes == [DummyClass]
385 finally:
386 sys.path[:] = saved_path