Debian Codegraph @

tests/test_handler.py

raw
1 """Tests for the `handler` module."""
2
3 from __future__ import annotations
4
5 import os
6 import sys
7 from dataclasses import replace
8 from glob import glob
9 from io import BytesIO
10 from pathlib import Path
11 from textwrap import dedent
12 from typing import TYPE_CHECKING
13
14 import bs4
15 import mkdocstrings
16 import pytest
17 from griffe import (
18 Docstring,
19 DocstringSectionExamples,
20 DocstringSectionKind,
21 Module,
22 temporary_inspected_module,
23 temporary_visited_module,
24 )
25 from mkdocstrings import CollectionError
26
27 from mkdocstrings_handlers.python import Inventory, PythonConfig, PythonHandler, PythonOptions
28
29 if TYPE_CHECKING:
30 from mkdocstrings import MkdocstringsPlugin
31
32
33 def test_collect_missing_module(handler: PythonHandler) -> None:
34 """Assert error is raised for missing modules."""
35 with pytest.raises(CollectionError):
36 handler.collect("aaaaaaaa", PythonOptions())
37
38
39 def test_collect_missing_module_item(handler: PythonHandler) -> None:
40 """Assert error is raised for missing items within existing modules."""
41 with pytest.raises(CollectionError):
42 handler.collect("mkdocstrings.aaaaaaaa", PythonOptions())
43
44
45 def test_collect_module(handler: PythonHandler) -> None:
46 """Assert existing module can be collected."""
47 assert handler.collect("mkdocstrings", PythonOptions())
48
49
50 def test_collect_with_null_parser(handler: PythonHandler) -> None:
51 """Assert we can pass `None` as parser when collecting."""
52 assert handler.collect("mkdocstrings", PythonOptions(docstring_style=None))
53
54
55 @pytest.mark.parametrize(
56 "handler",
57 [
58 {"theme": "mkdocs"},
59 {"theme": "readthedocs"},
60 {"theme": {"name": "material"}},
61 ],
62 indirect=["handler"],
63 )
64 def test_render_docstring_examples_section(handler: PythonHandler) -> None:
65 """Assert docstrings' examples section can be rendered.
66
67 Parameters:
68 handler: A handler instance (parametrized).
69 """
70 section = DocstringSectionExamples(
71 value=[
72 (DocstringSectionKind.text, "This is an example."),
73 (DocstringSectionKind.examples, ">>> print('Hello')\nHello"),
74 ],
75 )
76 template = handler.env.get_template("docstring/examples.html.jinja")
77 rendered = template.render(section=section, locale="en")
78 template.render(section=section, locale="not_existing")
79 assert "<p>This is an example.</p>" in rendered
80 assert "print" in rendered
81 assert "Hello" in rendered
82
83
84 def test_expand_globs(tmp_path: Path, plugin: MkdocstringsPlugin) -> None:
85 """Assert globs are correctly expanded.
86
87 Parameters:
88 tmp_path: Pytext fixture that creates a temporary directory.
89 """
90 globbed_names = (
91 "expanded_a",
92 "expanded_b",
93 "other_expanded_c",
94 "other_expanded_d",
95 )
96 globbed_paths = [tmp_path.joinpath(globbed_name) for globbed_name in globbed_names]
97 for path in globbed_paths:
98 path.touch()
99 plugin.handlers._tool_config.config_file_path = str(tmp_path.joinpath("mkdocs.yml"))
100 handler: PythonHandler = plugin.handlers.get_handler("python", {"paths": ["*exp*"]}) # type: ignore[assignment]
101 for path in globbed_paths:
102 assert str(path) in handler._paths
103
104
105 def test_expand_globs_without_changing_directory(plugin: MkdocstringsPlugin) -> None:
106 """Assert globs are correctly expanded when we are already in the right directory."""
107 plugin.handlers._tool_config.config_file_path = "mkdocs.yml"
108 handler: PythonHandler = plugin.handlers.get_handler("python", {"paths": ["*.md"]}) # type: ignore[assignment]
109 for path in list(glob(os.path.abspath(".") + "/*.md")):
110 assert path in handler._paths
111
112
113 @pytest.mark.parametrize(
114 ("expect_change", "extension"),
115 [
116 (True, "extension.py"),
117 (True, "extension.py:SomeExtension"),
118 (True, "path/to/extension.py"),
119 (True, "path/to/extension.py:SomeExtension"),
120 (True, {"extension.py": {"option": "value"}}),
121 (True, {"extension.py:SomeExtension": {"option": "value"}}),
122 (True, {"path/to/extension.py": {"option": "value"}}),
123 (True, {"path/to/extension.py:SomeExtension": {"option": "value"}}),
124 # True because OS path normalization.
125 (True, "/absolute/path/to/extension.py"),
126 (True, "/absolute/path/to/extension.py:SomeExtension"),
127 (True, {"/absolute/path/to/extension.py": {"option": "value"}}),
128 (True, {"/absolute/path/to/extension.py:SomeExtension": {"option": "value"}}),
129 (False, "dot.notation.path.to.extension"),
130 (False, "dot.notation.path.to.pyextension"),
131 (False, {"dot.notation.path.to.extension": {"option": "value"}}),
132 (False, {"dot.notation.path.to.pyextension": {"option": "value"}}),
133 ],
134 )
135 def test_extension_paths(
136 tmp_path: Path,
137 expect_change: bool,
138 extension: str | dict,
139 plugin: MkdocstringsPlugin,
140 ) -> None:
141 """Assert extension paths are resolved relative to config file."""
142 plugin.handlers._tool_config.config_file_path = str(tmp_path.joinpath("mkdocs.yml"))
143 handler: PythonHandler = plugin.handlers.get_handler("python") # type: ignore[assignment]
144 normalized = handler.normalize_extension_paths([extension])[0]
145 if expect_change:
146 if isinstance(normalized, str) and isinstance(extension, str):
147 assert normalized == str(tmp_path.joinpath(extension))
148 elif isinstance(normalized, dict) and isinstance(extension, dict):
149 pth, options = next(iter(extension.items()))
150 assert normalized == {str(tmp_path.joinpath(pth)): options}
151 else:
152 raise ValueError("Normalization must not change extension items type")
153 else:
154 assert normalized == extension
155
156
157 def test_rendering_object_source_without_lineno(handler: PythonHandler) -> None:
158 """Test rendering objects without a line number."""
159 code = dedent(
160 """
161 '''Module docstring.'''
162
163 class Class:
164 '''Class docstring.'''
165
166 def function(self):
167 '''Function docstring.'''
168
169 attribute = 0
170 '''Attribute docstring.'''
171 """,
172 )
173 with temporary_visited_module(code) as module:
174 module["Class"].lineno = None
175 module["Class.function"].lineno = None
176 module["attribute"].lineno = None
177 assert handler.render(module, PythonOptions(show_source=True))
178
179
180 def test_give_precedence_to_user_paths() -> None:
181 """Assert user paths take precedence over default paths."""
182 last_sys_path = sys.path[-1]
183 handler = PythonHandler(
184 theme="material",
185 custom_templates=None,
186 base_dir=Path("."),
187 config=PythonConfig.from_data(paths=[last_sys_path]),
188 mdx=[],
189 mdx_config={},
190 )
191 assert handler._paths[0] == last_sys_path
192
193
194 @pytest.mark.parametrize(
195 ("section", "code"),
196 [
197 (
198 "Attributes",
199 """
200 class A:
201 '''Summary.
202
203 Attributes:
204 x: X.
205 y: Y.
206 '''
207 x: int = 0
208 '''X.'''
209 y: int = 0
210 '''Y.'''
211 """,
212 ),
213 (
214 "Methods",
215 """
216 class A:
217 '''Summary.
218
219 Methods:
220 x: X.
221 y: Y.
222 '''
223 def x(self): ...
224 '''X.'''
225 def y(self): ...
226 '''Y.'''
227 """,
228 ),
229 (
230 "Functions",
231 """
232 '''Summary.
233
234 Functions:
235 x: X.
236 y: Y.
237 '''
238 def x(): ...
239 '''X.'''
240 def y(): ...
241 '''Y.'''
242 """,
243 ),
244 (
245 "Classes",
246 """
247 '''Summary.
248
249 Classes:
250 A: A.
251 B: B.
252 '''
253 class A: ...
254 '''A.'''
255 class B: ...
256 '''B.'''
257 """,
258 ),
259 (
260 "Modules",
261 """
262 '''Summary.
263
264 Modules:
265 a: A.
266 b: B.
267 '''
268 """,
269 ),
270 ],
271 )
272 def test_deduplicate_summary_sections(handler: PythonHandler, section: str, code: str) -> None:
273 """Assert summary sections are deduplicated."""
274 summary_section = section.lower()
275 summary_section = "functions" if summary_section == "methods" else summary_section
276 with temporary_visited_module(code, docstring_parser="google") as module:
277 if summary_section == "modules":
278 module.set_member("a", Module("A", docstring=Docstring("A.")))
279 module.set_member("b", Module("B", docstring=Docstring("B.")))
280 html = handler.render(
281 module,
282 handler.get_options(
283 {
284 "summary": {summary_section: True},
285 "show_source": False,
286 "show_submodules": True,
287 },
288 ),
289 )
290 assert html.count(f"{section}:") == 1
291
292
293 def test_inheriting_self_from_parent_class(handler: PythonHandler) -> None:
294 """Inspect self only once when inheriting it from parent class."""
295 with temporary_inspected_module(
296 """
297 class A: ...
298 class B(A): ...
299 A.B = B
300 """,
301 ) as module:
302 # Assert no recusrion error.
303 handler.render(
304 module,
305 handler.get_options({"inherited_members": True}),
306 )
307
308
309 def test_specifying_inventory_base_url(handler: PythonHandler) -> None:
310 """Assert that the handler renders inventory URLs using the specified base_url."""
311 # Update handler config to include an inventory with a base URL
312 base_url = "https://docs.com/my_library"
313 inventory = Inventory(url="https://example.com/objects.inv", base_url=base_url)
314 handler.config = replace(handler.config, inventories=[inventory])
315
316 # Mock inventory bytes
317 item_name = "my_library.my_module.MyClass"
318 mocked_inventory = mkdocstrings.Inventory()
319 mocked_inventory.register(
320 name=item_name,
321 domain="py",
322 role="class",
323 uri=f"api-reference/#{item_name}",
324 dispname=item_name,
325 )
326 mocked_bytes = BytesIO(mocked_inventory.format_sphinx())
327
328 # Get inventory URL and config
329 url, config = handler.get_inventory_urls()[0]
330
331 # Load the mocked inventory
332 _, item_url = next(handler.load_inventory(mocked_bytes, url, **config))
333
334 # Assert the URL is based on the provided base URL
335 msg = "Expected inventory URL to start with base_url"
336 assert item_url.startswith(base_url), msg
337
338
339 def _source_labels(html: str) -> list[Path]:
340 soup = bs4.BeautifulSoup(html, features="html.parser")
341 labels = []
342 for summary in soup.find_all("summary"):
343 if "Source code in" in summary.get_text():
344 code_tag = summary.find("code")
345 assert code_tag is not None
346 labels.append(Path(code_tag.get_text(strip=True)))
347 return labels
348
349
350 def _write_site_packages_package(tmp_path: Path, *, single_module: bool) -> None:
351 """Lay out the issue-333 scenario: a package installed in a virtual environment inside the project.
352
353 The environment's `site-packages` directory is relative to the current
354 working directory, so the package's `relative_filepath` is relative too,
355 slipping past `is_absolute()` checks.
356 """
357 code = """
358 class Model:
359 '''Model docstring.'''
360
361 def __init__(self) -> None:
362 '''Init docstring.'''
363 self.model_attribute = 0
364
365 def method(self) -> None:
366 '''Method docstring.'''
367 """
368 site = tmp_path / "site-packages"
369 module_path = site / "pkg.py" if single_module else site / "pkg" / "__init__.py"
370 module_path.parent.mkdir(parents=True)
371 module_path.write_text(dedent(code), encoding="utf-8")
372
373
374 @pytest.mark.parametrize(
375 "handler",
376 [
377 {"theme": "readthedocs"},
378 {"theme": {"name": "material"}},
379 ],
380 indirect=["handler"],
381 )
382 @pytest.mark.parametrize(
383 ("single_module", "extra_options", "expected_label"),
384 [
385 pytest.param(False, {"merge_init_into_class": True}, Path("pkg", "__init__.py"), id="merged-init"),
386 pytest.param(False, {}, Path("pkg", "__init__.py"), id="class-and-methods"),
387 pytest.param(True, {"merge_init_into_class": True}, Path("pkg.py"), id="single-module"),
388 ],
389 )
390 def test_no_environment_path_in_source_labels(
391 *,
392 tmp_path: Path,
393 monkeypatch: pytest.MonkeyPatch,
394 handler: PythonHandler,
395 single_module: bool,
396 extra_options: dict,
397 expected_label: Path,
398 ) -> None:
399 """Assert source labels never show an environment path."""
400 _write_site_packages_package(tmp_path, single_module=single_module)
401 monkeypatch.chdir(tmp_path)
402 # `collect()` reads the search paths lazily from this attribute.
403 handler._paths = [str(tmp_path / "site-packages")]
404 options = handler.get_options({"show_source": True, **extra_options})
405 html = handler.render(handler.collect("pkg.Model", options), options)
406 labels = _source_labels(html)
407 assert labels
408 assert set(labels) == {expected_label}
409 # The source bodies themselves are still rendered.
410 assert "model_attribute" in html