Debian Codegraph @

tests/test_api.py

raw
1 """Tests for our own API exposition."""
2
3 from __future__ import annotations
4
5 from collections import defaultdict
6 from pathlib import Path
7 from typing import TYPE_CHECKING
8
9 import griffe
10 import pytest
11 from mkdocstrings import Inventory
12
13 from mkdocstrings_handlers import python
14
15 if TYPE_CHECKING:
16 from collections.abc import Iterator
17
18
19 @pytest.fixture(name="loader", scope="module")
20 def _fixture_loader() -> griffe.GriffeLoader:
21 loader = griffe.GriffeLoader()
22 loader.load("mkdocstrings")
23 loader.load("mkdocstrings_handlers.python")
24 loader.resolve_aliases()
25 return loader
26
27
28 @pytest.fixture(name="internal_api", scope="module")
29 def _fixture_internal_api(loader: griffe.GriffeLoader) -> griffe.Module:
30 return loader.modules_collection["mkdocstrings_handlers.python._internal"]
31
32
33 @pytest.fixture(name="public_api", scope="module")
34 def _fixture_public_api(loader: griffe.GriffeLoader) -> griffe.Module:
35 return loader.modules_collection["mkdocstrings_handlers.python"]
36
37
38 def _yield_public_objects(
39 obj: griffe.Module | griffe.Class | griffe.Alias,
40 *,
41 modules: bool = False,
42 modulelevel: bool = True,
43 inherited: bool = False,
44 special: bool = False,
45 ) -> Iterator[griffe.Object | griffe.Alias]:
46 for member in obj.all_members.values() if inherited else obj.members.values():
47 try:
48 if member.is_module:
49 if member.is_alias or not member.is_public:
50 continue
51 assert isinstance(member, griffe.Module)
52 if modules:
53 yield member
54 yield from _yield_public_objects(
55 member,
56 modules=modules,
57 modulelevel=modulelevel,
58 inherited=inherited,
59 special=special,
60 )
61 elif member.is_public and (special or not member.is_special):
62 yield member
63 else:
64 continue
65 if member.is_class and not modulelevel:
66 assert isinstance(member, (griffe.Class, griffe.Alias))
67 yield from _yield_public_objects(
68 member,
69 modules=modules,
70 modulelevel=False,
71 inherited=inherited,
72 special=special,
73 )
74 except (griffe.AliasResolutionError, griffe.CyclicAliasError):
75 continue
76
77
78 @pytest.fixture(name="modulelevel_internal_objects", scope="module")
79 def _fixture_modulelevel_internal_objects(internal_api: griffe.Module) -> list[griffe.Object | griffe.Alias]:
80 return list(_yield_public_objects(internal_api, modulelevel=True))
81
82
83 @pytest.fixture(name="internal_objects", scope="module")
84 def _fixture_internal_objects(internal_api: griffe.Module) -> list[griffe.Object | griffe.Alias]:
85 return list(_yield_public_objects(internal_api, modulelevel=False, special=True))
86
87
88 @pytest.fixture(name="public_objects", scope="module")
89 def _fixture_public_objects(public_api: griffe.Module) -> list[griffe.Object | griffe.Alias]:
90 return list(_yield_public_objects(public_api, modulelevel=False, inherited=True, special=True))
91
92
93 @pytest.fixture(name="inventory", scope="module")
94 def _fixture_inventory() -> Inventory:
95 inventory_file = Path(__file__).parent.parent / "site" / "objects.inv"
96 if not inventory_file.exists():
97 pytest.skip("The objects inventory is not available.") # ty: ignore[call-non-callable]
98 with inventory_file.open("rb") as file:
99 return Inventory.parse_sphinx(file)
100
101
102 def test_exposed_objects(modulelevel_internal_objects: list[griffe.Object | griffe.Alias]) -> None:
103 """All public objects in the internal API are exposed under `mkdocstrings_handlers.python`."""
104 not_exposed = [
105 obj.path
106 for obj in modulelevel_internal_objects
107 if obj.name not in python.__all__ or not hasattr(python, obj.name)
108 ]
109 assert not not_exposed, "Objects not exposed:\n" + "\n".join(sorted(not_exposed))
110
111
112 def test_unique_names(modulelevel_internal_objects: list[griffe.Object | griffe.Alias]) -> None:
113 """All internal objects have unique names."""
114 names_to_paths = defaultdict(list)
115 for obj in modulelevel_internal_objects:
116 names_to_paths[obj.name].append(obj.path)
117 non_unique = [paths for paths in names_to_paths.values() if len(paths) > 1]
118 assert not non_unique, "Non-unique names:\n" + "\n".join(str(paths) for paths in non_unique)
119
120
121 def test_single_locations(public_api: griffe.Module) -> None:
122 """All objects have a single public location."""
123
124 def _public_path(obj: griffe.Object | griffe.Alias) -> bool:
125 return obj.is_public and (obj.parent is None or _public_path(obj.parent))
126
127 multiple_locations = {}
128 for obj_name in python.__all__:
129 obj = public_api[obj_name]
130 if obj.aliases and (
131 public_aliases := [path for path, alias in obj.aliases.items() if path != obj.path and _public_path(alias)]
132 ):
133 multiple_locations[obj.path] = public_aliases
134 assert not multiple_locations, "Multiple public locations:\n" + "\n".join(
135 f"{path}: {aliases}" for path, aliases in multiple_locations.items()
136 )
137
138
139 def test_api_matches_inventory(inventory: Inventory, public_objects: list[griffe.Object | griffe.Alias]) -> None:
140 """All public objects are added to the inventory."""
141 ignore_names = {"__getattr__", "__init__", "__repr__", "__str__", "__post_init__"}
142 not_in_inventory = [
143 f"{obj.relative_filepath}:{obj.lineno}: {obj.path}"
144 for obj in public_objects
145 if obj.name not in ignore_names and obj.path not in inventory
146 ]
147 msg = "Objects not in the inventory (try running `make run mkdocs build`):\n{paths}"
148 assert not not_in_inventory, msg.format(paths="\n".join(sorted(not_in_inventory)))
149
150
151 def _module_or_child(parent: str, name: str) -> bool:
152 parents = [parent[:i] for i, char in enumerate(parent) if char == "."]
153 parents.append(parent)
154 return name in parents or name.startswith(parent + ".")
155
156
157 def test_inventory_matches_api(
158 inventory: Inventory,
159 public_objects: list[griffe.Object | griffe.Alias],
160 loader: griffe.GriffeLoader,
161 ) -> None:
162 """The inventory doesn't contain any additional Python object."""
163 not_in_api = []
164 public_api_paths = {obj.path for obj in public_objects}
165 public_api_paths.add("mkdocstrings_handlers")
166 public_api_paths.add("mkdocstrings_handlers.python")
167
168 for item in inventory.values():
169 if item.domain == "py" and "(" not in item.name and _module_or_child("mkdocstrings_handlers.python", item.name):
170 obj = loader.modules_collection[item.name]
171 if obj.path not in public_api_paths and not any(path in public_api_paths for path in obj.aliases):
172 not_in_api.append(item.name)
173 msg = "Inventory objects not in public API (try running `make run mkdocs build`):\n{paths}"
174 assert not not_in_api, msg.format(paths="\n".join(sorted(not_in_api)))
175
176
177 def test_no_module_docstrings_in_internal_api(internal_api: griffe.Module) -> None:
178 """No module docstrings should be written in our internal API.
179
180 The reasoning is that docstrings are addressed to users of the public API,
181 but internal modules are not exposed to users, so they should not have docstrings.
182 """
183
184 def _modules(obj: griffe.Module) -> Iterator[griffe.Module]:
185 for member in obj.modules.values():
186 yield member
187 yield from _modules(member)
188
189 for obj in _modules(internal_api):
190 assert not obj.docstring