Debian Codegraph @

packages/griffelib/tests/test_finder.py

raw symbols SCIP
1 """Tests for the `finder` module."""
2
3 from __future__ import annotations
4
5 import os
6 from pathlib import Path
7 from textwrap import dedent
8
9 import pytest
10
11 from griffe import Module, ModuleFinder, NamespacePackage, Package, temporary_pypackage
12 from griffe._internal.finder import _handle_editable_module, _handle_pth_file
13
14
15 @pytest.mark.parametrize(
16 (
17 "pypackage",
18 "module",
19 "add_to_search_path",
20 "expected_top_name",
21 "expected_top_path",
22 ),
23 [
24 (("a", ["b.py"]), "a/b.py", True, "a", "a/__init__.py"),
25 (("a", ["b.py"]), "a/b.py", False, "a", "a/__init__.py"),
26 (("a/b", ["c.py"]), "a/b/c.py", True, "a", "a"),
27 (("a/b", ["c.py"]), "a/b/c.py", False, "b", "a/b/__init__.py"),
28 ],
29 )
30 def test_find_module_with_path(
31 pypackage: tuple[str, list[str]],
32 module: str,
33 add_to_search_path: bool,
34 expected_top_name: str,
35 expected_top_path: str,
36 ) -> None:
37 """Check that the finder can find modules using strings and Paths.
38
39 Parameters:
40 pypackage: A temporary package (metadata) on the file system (parametrized).
41 module: The module path to load (parametrized).
42 add_to_search_path: Whether to add the temporary package parent path to the finder search paths (parametrized).
43 expected_top_name: Expected top module name (parametrized).
44 expected_top_path: Expected top module path (parametrized).
45 """
46 with temporary_pypackage(*pypackage) as tmp_package:
47 finder = ModuleFinder(
48 search_paths=[tmp_package.tmpdir] if add_to_search_path else None,
49 )
50 _, package = finder.find_spec(tmp_package.tmpdir / module)
51 assert package.name == expected_top_name
52 if isinstance(package, NamespacePackage):
53 assert package.path == [tmp_package.tmpdir / expected_top_path]
54 else:
55 assert package.path == tmp_package.tmpdir / expected_top_path
56
57
58 @pytest.mark.parametrize(
59 "statement",
60 [
61 "__import__('pkg_resources').declare_namespace(__name__)",
62 "__path__ = __import__('pkgutil').extend_path(__path__, __name__)",
63 ],
64 )
65 def test_find_pkg_style_namespace_packages(statement: str) -> None:
66 """Check that the finder can find pkg-style namespace packages.
67
68 Parameters:
69 statement: The statement in the `__init__` module allowing to mark the package as namespace.
70 """
71 with (
72 temporary_pypackage("namespace/package1") as tmp_package1,
73 temporary_pypackage("namespace/package2") as tmp_package2,
74 ):
75 tmp_package1.path.parent.joinpath("__init__.py").write_text(
76 statement,
77 encoding="utf8",
78 )
79 tmp_package2.path.parent.joinpath("__init__.py").write_text(
80 statement,
81 encoding="utf8",
82 )
83 finder = ModuleFinder(search_paths=[tmp_package1.tmpdir, tmp_package2.tmpdir])
84 _, package = finder.find_spec("namespace")
85 assert package.name == "namespace"
86 assert isinstance(package, NamespacePackage)
87 assert package.path == [tmp_package1.path.parent, tmp_package2.path.parent]
88
89
90 def test_pth_file_handling(tmp_path: Path) -> None:
91 """Assert .pth files are correctly handled.
92
93 Parameters:
94 tmp_path: Pytest fixture.
95 """
96 pth_file = tmp_path / "hello.pth"
97 pth_file.write_text(
98 dedent(
99 """
100 # comment
101
102 import thing
103 import\tthing
104 /doesnotexist
105 tests
106 """,
107 ),
108 encoding="utf8",
109 )
110 paths = [sp.path for sp in _handle_pth_file(pth_file)]
111 assert paths == [Path("tests")]
112
113
114 def test_pth_file_handling_with_semi_colon(tmp_path: Path) -> None:
115 """Assert .pth files are correctly handled.
116
117 Parameters:
118 tmp_path: Pytest fixture.
119 """
120 pth_file = tmp_path / "hello.pth"
121 pth_file.write_text(
122 dedent(
123 """
124 # comment
125 import thing; import\tthing; /doesnotexist; tests
126 """,
127 ),
128 encoding="utf8",
129 )
130 paths = [sp.path for sp in _handle_pth_file(pth_file)]
131 assert paths == [Path("tests")]
132
133
134 @pytest.mark.parametrize(
135 "editable_file_name",
136 ["__editables_whatever.py", "_editable_impl_whatever.py"],
137 )
138 def test_editables_file_handling(tmp_path: Path, editable_file_name: str) -> None:
139 """Assert editable modules by `editables` are handled.
140
141 Parameters:
142 tmp_path: Pytest fixture.
143 """
144 pth_file = tmp_path / editable_file_name
145 pth_file.write_text(
146 "hello\nF.map_module('griffe', 'packages/griffelib/src/griffe/__init__.py')",
147 encoding="utf8",
148 )
149 paths = [sp.path for sp in _handle_editable_module(pth_file)]
150 assert paths == [Path("packages/griffelib/src")]
151
152
153 @pytest.mark.parametrize("annotation", ["", ": dict[str, str]"])
154 def test_setuptools_file_handling(tmp_path: Path, annotation: str) -> None:
155 """Assert editable modules by `setuptools` are handled.
156
157 Parameters:
158 tmp_path: Pytest fixture.
159 annotation: The type annotation of the MAPPING variable.
160 """
161 pth_file = tmp_path / "__editable__whatever.py"
162 pth_file.write_text(
163 f"hello\nMAPPING{annotation} = {{'griffe': 'src/griffe'}}",
164 encoding="utf8",
165 )
166 paths = [sp.path for sp in _handle_editable_module(pth_file)]
167 assert paths == [Path("src")]
168
169
170 @pytest.mark.parametrize("annotation", ["", ": dict[str, str]"])
171 def test_setuptools_file_handling_multiple_paths(
172 tmp_path: Path,
173 annotation: str,
174 ) -> None:
175 """Assert editable modules by `setuptools` are handled when multiple packages are installed in the same editable.
176
177 Parameters:
178 tmp_path: Pytest fixture.
179 annotation: The type annotation of the MAPPING variable.
180 """
181 pth_file = tmp_path / "__editable__whatever.py"
182 pth_file.write_text(
183 "hello=1\n"
184 f"MAPPING{annotation} = {{\n'griffe':\n 'src1/griffe', 'briffe':'src2/briffe'}}\n"
185 "def printer():\n print(hello)",
186 encoding="utf8",
187 )
188 paths = [sp.path for sp in _handle_editable_module(pth_file)]
189 assert paths == [Path("src1"), Path("src2")]
190
191
192 def test_scikit_build_core_file_handling(tmp_path: Path) -> None:
193 """Assert editable modules by `scikit-build-core` are handled.
194
195 Parameters:
196 tmp_path: Pytest fixture.
197 """
198 pth_file = tmp_path / "_whatever_editable.py"
199 pth_file.write_text(
200 "hello=1\ninstall({'whatever': '/path/to/whatever'}, {'whatever.else': '/else'}, None, False, True)",
201 encoding="utf8",
202 )
203 # The second dict is not handled: scikit-build-core puts these files
204 # in a location that Griffe won't be able to discover anyway
205 # (they don't respect standard package or namespace package layouts,
206 # and rely on dynamic meta path finder stuff).
207 paths = [sp.path for sp in _handle_editable_module(pth_file)]
208 assert paths == [Path("/path/to/whatever")]
209
210
211 @pytest.mark.skipif(
212 not Path("packages", "griffelib").exists(),
213 reason="not running from monorepo root",
214 )
215 def test_meson_python_file_handling(tmp_path: Path) -> None:
216 """Assert editable modules by `meson-python` are handled.
217
218 Parameters:
219 tmp_path: Pytest fixture.
220 """
221 pth_file = tmp_path / "_whatever_editable_loader.py"
222 pth_file.write_text(
223 # The path in argument 2 suffixed with src must exist, so we pass `packages/griffelib`.
224 "hello=1\ninstall({'griffe', 'hello'}, 'packages/griffelib', ['/tmp/ninja'], False)",
225 encoding="utf8",
226 )
227 search_paths = _handle_editable_module(pth_file)
228 assert all(sp.always_scan_for == "griffe" for sp in search_paths)
229 paths = [sp.path for sp in search_paths]
230 assert paths == [Path("packages/griffelib/src")]
231
232
233 @pytest.mark.parametrize(
234 ("first", "second", "find_stubs", "expect"),
235 [
236 ("package", "stubs", True, "both"),
237 ("stubs", "package", True, "both"),
238 ("package", None, True, "package"),
239 (None, "package", True, "package"),
240 ("stubs", None, True, "stubs"),
241 (None, "stubs", True, "stubs"),
242 (None, None, True, "none"),
243 ("package", "stubs", False, "package"),
244 ("stubs", "package", False, "package"),
245 ("package", None, False, "package"),
246 (None, "package", False, "package"),
247 ("stubs", None, False, "none"),
248 (None, "stubs", False, "none"),
249 (None, None, False, "none"),
250 ],
251 )
252 def test_finding_stubs_packages(
253 tmp_path: Path,
254 first: str | None,
255 second: str | None,
256 find_stubs: bool,
257 expect: str,
258 ) -> None:
259 """Find stubs-only packages.
260
261 Parameters:
262 tmp_path: Pytest fixture.
263 """
264 search_path1 = tmp_path / "sp1"
265 search_path2 = tmp_path / "sp2"
266 search_path1.mkdir()
267 search_path2.mkdir()
268
269 if first == "package":
270 package = search_path1 / "package"
271 package.mkdir()
272 package.joinpath("__init__.py").touch()
273 elif first == "stubs":
274 stubs = search_path1 / "package-stubs"
275 stubs.mkdir()
276 stubs.joinpath("__init__.pyi").touch()
277
278 if second == "package":
279 package = search_path2 / "package"
280 package.mkdir()
281 package.joinpath("__init__.py").touch()
282 elif second == "stubs":
283 stubs = search_path2 / "package-stubs"
284 stubs.mkdir()
285 stubs.joinpath("__init__.pyi").touch()
286
287 finder = ModuleFinder([search_path1, search_path2])
288
289 if expect == "none":
290 with pytest.raises(ModuleNotFoundError):
291 finder.find_spec(
292 "package",
293 try_relative_path=False,
294 find_stubs_package=find_stubs,
295 )
296 return
297
298 name, result = finder.find_spec(
299 "package",
300 try_relative_path=False,
301 find_stubs_package=find_stubs,
302 )
303 assert name == "package"
304
305 if expect == "both":
306 assert isinstance(result, Package)
307 assert result.path.suffix == ".py"
308 assert not result.path.parent.name.endswith("-stubs")
309 assert result.stubs
310 assert result.stubs.suffix == ".pyi"
311 assert result.stubs.parent.name.endswith("-stubs")
312 elif expect == "package":
313 assert isinstance(result, Package)
314 assert result.path.suffix == ".py"
315 assert not result.path.parent.name.endswith("-stubs")
316 assert result.stubs is None
317 elif expect == "stubs":
318 assert isinstance(result, Package)
319 assert result.path.suffix == ".pyi"
320 assert result.path.parent.name.endswith("-stubs")
321 assert result.stubs is None
322
323
324 @pytest.mark.parametrize("namespace_package", [False, True])
325 def test_scanning_package_and_module_with_same_names(namespace_package: bool) -> None:
326 """The finder correctly scans package and module having same the name.
327
328 Parameters:
329 namespace_package: Whether the temporary package is a namespace one.
330 """
331 init = not namespace_package
332 with temporary_pypackage(
333 "pkg",
334 ["pkg/mod.py", "mod/mod.py"],
335 init=init,
336 inits=init,
337 ) as tmp_package:
338 # Here we must make sure that all paths are relative
339 # to correctly assert the finder's behavior,
340 # so we pass `.` and actually enter the temporary directory.
341 path = Path(tmp_package.name)
342 filepath: Path | list[Path] = [path] if namespace_package else path
343 old = Path.cwd()
344 os.chdir(tmp_package.path.parent)
345 try:
346 finder = ModuleFinder(search_paths=[])
347 found = [path for _, path in finder.submodules(Module("pkg", filepath=filepath))]
348 finally:
349 os.chdir(old)
350 check = (
351 path / "pkg/mod.py",
352 path / "mod/mod.py",
353 )
354 for mod in check:
355 assert mod in found
356
357
358 def test_not_finding_namespace_package_twice() -> None:
359 """Deduplicate paths when finding namespace packages."""
360 with temporary_pypackage(
361 "pkg",
362 ["pkg/mod.py", "mod/mod.py"],
363 init=False,
364 inits=False,
365 ) as tmp_package:
366 old = Path.cwd()
367 os.chdir(tmp_package.tmpdir)
368 try:
369 finder = ModuleFinder(search_paths=[Path(), tmp_package.tmpdir])
370 found = finder.find_package("pkg")
371 finally:
372 os.chdir(old)
373 assert isinstance(found, NamespacePackage)
374 assert len(found.path) == 1