Debian Codegraph @

testing/test_pathlib.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 from collections.abc import Generator
5 from collections.abc import Iterator
6 from collections.abc import Sequence
7 import errno
8 import importlib.abc
9 import importlib.machinery
10 import os.path
11 from pathlib import Path
12 import pickle
13 import shutil
14 import sys
15 from textwrap import dedent
16 from types import ModuleType
17 from typing import Any
18 import unittest.mock
19
20 from _pytest.config import ExitCode
21 from _pytest.monkeypatch import MonkeyPatch
22 from _pytest.pathlib import _import_module_using_spec
23 from _pytest.pathlib import bestrelpath
24 from _pytest.pathlib import commonpath
25 from _pytest.pathlib import compute_module_name
26 from _pytest.pathlib import CouldNotResolvePathError
27 from _pytest.pathlib import ensure_deletable
28 from _pytest.pathlib import fnmatch_ex
29 from _pytest.pathlib import get_extended_length_path_str
30 from _pytest.pathlib import get_lock_path
31 from _pytest.pathlib import import_path
32 from _pytest.pathlib import ImportMode
33 from _pytest.pathlib import ImportPathMismatchError
34 from _pytest.pathlib import insert_missing_modules
35 from _pytest.pathlib import is_importable
36 from _pytest.pathlib import maybe_delete_a_numbered_dir
37 from _pytest.pathlib import module_name_from_path
38 from _pytest.pathlib import resolve_package_path
39 from _pytest.pathlib import resolve_pkg_root_and_module_name
40 from _pytest.pathlib import safe_exists
41 from _pytest.pathlib import scandir
42 from _pytest.pathlib import spec_matches_module_path
43 from _pytest.pathlib import symlink_or_skip
44 from _pytest.pathlib import visit
45 from _pytest.pytester import Pytester
46 from _pytest.pytester import RunResult
47 from _pytest.tmpdir import TempPathFactory
48 import pytest
49
50
51 @pytest.fixture(autouse=True)
52 def autouse_pytester(pytester: Pytester) -> None:
53 """
54 Fixture to make pytester() being autouse for all tests in this module.
55
56 pytester makes sure to restore sys.path to its previous state, and many tests in this module
57 import modules and change sys.path because of that, so common module names such as "test" or "test.conftest"
58 end up leaking to tests in other modules.
59
60 Note: we might consider extracting the sys.path restoration aspect into its own fixture, and apply it
61 to the entire test suite always.
62 """
63
64
65 class TestFNMatcherPort:
66 """Test our port of py.common.FNMatcher (fnmatch_ex)."""
67
68 if sys.platform == "win32":
69 drv1 = "c:"
70 drv2 = "d:"
71 else:
72 drv1 = "/c"
73 drv2 = "/d"
74
75 @pytest.mark.parametrize(
76 "pattern, path",
77 [
78 ("*.py", "foo.py"),
79 ("*.py", "bar/foo.py"),
80 ("test_*.py", "foo/test_foo.py"),
81 ("tests/*.py", "tests/foo.py"),
82 (f"{drv1}/*.py", f"{drv1}/foo.py"),
83 (f"{drv1}/foo/*.py", f"{drv1}/foo/foo.py"),
84 ("tests/**/test*.py", "tests/foo/test_foo.py"),
85 ("tests/**/doc/test*.py", "tests/foo/bar/doc/test_foo.py"),
86 ("tests/**/doc/**/test*.py", "tests/foo/doc/bar/test_foo.py"),
87 ],
88 )
89 def test_matching(self, pattern: str, path: str) -> None:
90 assert fnmatch_ex(pattern, path)
91
92 def test_matching_abspath(self) -> None:
93 abspath = os.path.abspath(os.path.join("tests/foo.py"))
94 assert fnmatch_ex("tests/foo.py", abspath)
95
96 @pytest.mark.parametrize(
97 "pattern, path",
98 [
99 ("*.py", "foo.pyc"),
100 ("*.py", "foo/foo.pyc"),
101 ("tests/*.py", "foo/foo.py"),
102 (f"{drv1}/*.py", f"{drv2}/foo.py"),
103 (f"{drv1}/foo/*.py", f"{drv2}/foo/foo.py"),
104 ("tests/**/test*.py", "tests/foo.py"),
105 ("tests/**/test*.py", "foo/test_foo.py"),
106 ("tests/**/doc/test*.py", "tests/foo/bar/doc/foo.py"),
107 ("tests/**/doc/test*.py", "tests/foo/bar/test_foo.py"),
108 ],
109 )
110 def test_not_matching(self, pattern: str, path: str) -> None:
111 assert not fnmatch_ex(pattern, path)
112
113
114 @pytest.fixture(params=[True, False])
115 def ns_param(request: pytest.FixtureRequest) -> bool:
116 """
117 Simple parametrized fixture for tests which call import_path() with consider_namespace_packages
118 using True and False.
119 """
120 return bool(request.param)
121
122
123 class TestImportPath:
124 """
125
126 Most of the tests here were copied from py lib's tests for "py.local.path.pyimport".
127
128 Having our own pyimport-like function is inline with removing py.path dependency in the future.
129 """
130
131 @pytest.fixture(scope="session")
132 def path1(self, tmp_path_factory: TempPathFactory) -> Generator[Path]:
133 path = tmp_path_factory.mktemp("path")
134 self.setuptestfs(path)
135 yield path
136 assert path.joinpath("samplefile").exists()
137
138 @pytest.fixture(autouse=True)
139 def preserve_sys(self):
140 with unittest.mock.patch.dict(sys.modules):
141 with unittest.mock.patch.object(sys, "path", list(sys.path)):
142 yield
143
144 def setuptestfs(self, path: Path) -> None:
145 # print "setting up test fs for", repr(path)
146 samplefile = path / "samplefile"
147 samplefile.write_text("samplefile\n", encoding="utf-8")
148
149 execfile = path / "execfile"
150 execfile.write_text("x=42", encoding="utf-8")
151
152 execfilepy = path / "execfile.py"
153 execfilepy.write_text("x=42", encoding="utf-8")
154
155 d = {1: 2, "hello": "world", "answer": 42}
156 path.joinpath("samplepickle").write_bytes(pickle.dumps(d, 1))
157
158 sampledir = path / "sampledir"
159 sampledir.mkdir()
160 sampledir.joinpath("otherfile").touch()
161
162 otherdir = path / "otherdir"
163 otherdir.mkdir()
164 otherdir.joinpath("__init__.py").touch()
165
166 module_a = otherdir / "a.py"
167 module_a.write_text("from .b import stuff as result\n", encoding="utf-8")
168 module_b = otherdir / "b.py"
169 module_b.write_text('stuff="got it"\n', encoding="utf-8")
170 module_c = otherdir / "c.py"
171 module_c.write_text(
172 dedent(
173 """
174 import pluggy;
175 import otherdir.a
176 value = otherdir.a.result
177 """
178 ),
179 encoding="utf-8",
180 )
181 module_d = otherdir / "d.py"
182 module_d.write_text(
183 dedent(
184 """
185 import pluggy;
186 from otherdir import a
187 value2 = a.result
188 """
189 ),
190 encoding="utf-8",
191 )
192
193 def test_smoke_test(self, path1: Path, ns_param: bool) -> None:
194 obj = import_path(
195 path1 / "execfile.py", root=path1, consider_namespace_packages=ns_param
196 )
197 assert obj.x == 42
198 assert obj.__name__ == "execfile"
199
200 def test_import_path_missing_file(self, path1: Path, ns_param: bool) -> None:
201 with pytest.raises(ImportPathMismatchError):
202 import_path(
203 path1 / "sampledir", root=path1, consider_namespace_packages=ns_param
204 )
205
206 def test_renamed_dir_creates_mismatch(
207 self, tmp_path: Path, monkeypatch: MonkeyPatch, ns_param: bool
208 ) -> None:
209 tmp_path.joinpath("a").mkdir()
210 p = tmp_path.joinpath("a", "test_x123.py")
211 p.touch()
212 import_path(p, root=tmp_path, consider_namespace_packages=ns_param)
213 tmp_path.joinpath("a").rename(tmp_path.joinpath("b"))
214 with pytest.raises(ImportPathMismatchError):
215 import_path(
216 tmp_path.joinpath("b", "test_x123.py"),
217 root=tmp_path,
218 consider_namespace_packages=ns_param,
219 )
220
221 # Errors can be ignored.
222 monkeypatch.setenv("PY_IGNORE_IMPORTMISMATCH", "1")
223 import_path(
224 tmp_path.joinpath("b", "test_x123.py"),
225 root=tmp_path,
226 consider_namespace_packages=ns_param,
227 )
228
229 # PY_IGNORE_IMPORTMISMATCH=0 does not ignore error.
230 monkeypatch.setenv("PY_IGNORE_IMPORTMISMATCH", "0")
231 with pytest.raises(ImportPathMismatchError):
232 import_path(
233 tmp_path.joinpath("b", "test_x123.py"),
234 root=tmp_path,
235 consider_namespace_packages=ns_param,
236 )
237
238 def test_messy_name(self, tmp_path: Path, ns_param: bool) -> None:
239 # https://bitbucket.org/hpk42/py-trunk/issue/129
240 path = tmp_path / "foo__init__.py"
241 path.touch()
242 module = import_path(path, root=tmp_path, consider_namespace_packages=ns_param)
243 assert module.__name__ == "foo__init__"
244
245 def test_dir(self, tmp_path: Path, ns_param: bool) -> None:
246 p = tmp_path / "hello_123"
247 p.mkdir()
248 p_init = p / "__init__.py"
249 p_init.touch()
250 m = import_path(p, root=tmp_path, consider_namespace_packages=ns_param)
251 assert m.__name__ == "hello_123"
252 m = import_path(p_init, root=tmp_path, consider_namespace_packages=ns_param)
253 assert m.__name__ == "hello_123"
254
255 def test_a(self, path1: Path, ns_param: bool) -> None:
256 otherdir = path1 / "otherdir"
257 mod = import_path(
258 otherdir / "a.py", root=path1, consider_namespace_packages=ns_param
259 )
260 assert mod.result == "got it"
261 assert mod.__name__ == "otherdir.a"
262
263 def test_b(self, path1: Path, ns_param: bool) -> None:
264 otherdir = path1 / "otherdir"
265 mod = import_path(
266 otherdir / "b.py", root=path1, consider_namespace_packages=ns_param
267 )
268 assert mod.stuff == "got it"
269 assert mod.__name__ == "otherdir.b"
270
271 def test_c(self, path1: Path, ns_param: bool) -> None:
272 otherdir = path1 / "otherdir"
273 mod = import_path(
274 otherdir / "c.py", root=path1, consider_namespace_packages=ns_param
275 )
276 assert mod.value == "got it"
277
278 def test_d(self, path1: Path, ns_param: bool) -> None:
279 otherdir = path1 / "otherdir"
280 mod = import_path(
281 otherdir / "d.py", root=path1, consider_namespace_packages=ns_param
282 )
283 assert mod.value2 == "got it"
284
285 def test_import_after(self, tmp_path: Path, ns_param: bool) -> None:
286 tmp_path.joinpath("xxxpackage").mkdir()
287 tmp_path.joinpath("xxxpackage", "__init__.py").touch()
288 mod1path = tmp_path.joinpath("xxxpackage", "module1.py")
289 mod1path.touch()
290 mod1 = import_path(
291 mod1path, root=tmp_path, consider_namespace_packages=ns_param
292 )
293 assert mod1.__name__ == "xxxpackage.module1"
294 from xxxpackage import module1
295
296 assert module1 is mod1
297
298 def test_check_filepath_consistency(
299 self, monkeypatch: MonkeyPatch, tmp_path: Path, ns_param: bool
300 ) -> None:
301 name = "pointsback123"
302 p = tmp_path.joinpath(name + ".py")
303 p.touch()
304 with monkeypatch.context() as mp:
305 for ending in (".pyc", ".pyo"):
306 mod = ModuleType(name)
307 pseudopath = tmp_path.joinpath(name + ending)
308 pseudopath.touch()
309 mod.__file__ = str(pseudopath)
310 mp.setitem(sys.modules, name, mod)
311 newmod = import_path(
312 p, root=tmp_path, consider_namespace_packages=ns_param
313 )
314 assert mod == newmod
315 mod = ModuleType(name)
316 pseudopath = tmp_path.joinpath(name + "123.py")
317 pseudopath.touch()
318 mod.__file__ = str(pseudopath)
319 monkeypatch.setitem(sys.modules, name, mod)
320 with pytest.raises(ImportPathMismatchError) as excinfo:
321 import_path(p, root=tmp_path, consider_namespace_packages=ns_param)
322 modname, modfile, orig = excinfo.value.args
323 assert modname == name
324 assert modfile == str(pseudopath)
325 assert orig == p
326 assert issubclass(ImportPathMismatchError, ImportError)
327
328 def test_ensuresyspath_append(self, tmp_path: Path, ns_param: bool) -> None:
329 root1 = tmp_path / "root1"
330 root1.mkdir()
331 file1 = root1 / "x123.py"
332 file1.touch()
333 assert str(root1) not in sys.path
334 import_path(
335 file1, mode="append", root=tmp_path, consider_namespace_packages=ns_param
336 )
337 assert str(root1) == sys.path[-1]
338 assert str(root1) not in sys.path[:-1]
339
340 def test_invalid_path(self, tmp_path: Path, ns_param: bool) -> None:
341 with pytest.raises(ImportError):
342 import_path(
343 tmp_path / "invalid.py",
344 root=tmp_path,
345 consider_namespace_packages=ns_param,
346 )
347
348 @pytest.fixture
349 def simple_module(
350 self, tmp_path: Path, request: pytest.FixtureRequest
351 ) -> Iterator[Path]:
352 name = f"mymod_{request.node.name}"
353 fn = tmp_path / f"_src/tests/{name}.py"
354 fn.parent.mkdir(parents=True)
355 fn.write_text("def foo(x): return 40 + x", encoding="utf-8")
356 module_name = module_name_from_path(fn, root=tmp_path)
357 yield fn
358 sys.modules.pop(module_name, None)
359
360 def test_importmode_importlib(
361 self,
362 simple_module: Path,
363 tmp_path: Path,
364 request: pytest.FixtureRequest,
365 ns_param: bool,
366 ) -> None:
367 """`importlib` mode does not change sys.path."""
368 module = import_path(
369 simple_module,
370 mode="importlib",
371 root=tmp_path,
372 consider_namespace_packages=ns_param,
373 )
374 assert module.foo(2) == 42
375 assert str(simple_module.parent) not in sys.path
376 assert module.__name__ in sys.modules
377 assert module.__name__ == f"_src.tests.mymod_{request.node.name}"
378 assert "_src" in sys.modules
379 assert "_src.tests" in sys.modules
380
381 def test_remembers_previous_imports(
382 self, simple_module: Path, tmp_path: Path, ns_param: bool
383 ) -> None:
384 """`importlib` mode called remembers previous module (#10341, #10811)."""
385 module1 = import_path(
386 simple_module,
387 mode="importlib",
388 root=tmp_path,
389 consider_namespace_packages=ns_param,
390 )
391 module2 = import_path(
392 simple_module,
393 mode="importlib",
394 root=tmp_path,
395 consider_namespace_packages=ns_param,
396 )
397 assert module1 is module2
398
399 def test_no_meta_path_found(
400 self,
401 simple_module: Path,
402 monkeypatch: MonkeyPatch,
403 tmp_path: Path,
404 ns_param: bool,
405 ) -> None:
406 """Even without any meta_path should still import module."""
407 monkeypatch.setattr(sys, "meta_path", [])
408 module = import_path(
409 simple_module,
410 mode="importlib",
411 root=tmp_path,
412 consider_namespace_packages=ns_param,
413 )
414 assert module.foo(2) == 42
415
416 # mode='importlib' fails if no spec is found to load the module
417 import importlib.util
418
419 # Force module to be re-imported.
420 del sys.modules[module.__name__]
421
422 monkeypatch.setattr(
423 importlib.util, "spec_from_file_location", lambda *args, **kwargs: None
424 )
425 with pytest.raises(ImportError):
426 import_path(
427 simple_module,
428 mode="importlib",
429 root=tmp_path,
430 consider_namespace_packages=False,
431 )
432
433
434 def test_resolve_package_path(tmp_path: Path) -> None:
435 pkg = tmp_path / "pkg1"
436 pkg.mkdir()
437 (pkg / "__init__.py").touch()
438 (pkg / "subdir").mkdir()
439 (pkg / "subdir/__init__.py").touch()
440 assert resolve_package_path(pkg) == pkg
441 assert resolve_package_path(pkg / "subdir/__init__.py") == pkg
442
443
444 def test_package_unimportable(tmp_path: Path) -> None:
445 pkg = tmp_path / "pkg1-1"
446 pkg.mkdir()
447 pkg.joinpath("__init__.py").touch()
448 subdir = pkg / "subdir"
449 subdir.mkdir()
450 (pkg / "subdir/__init__.py").touch()
451 assert resolve_package_path(subdir) == subdir
452 xyz = subdir / "xyz.py"
453 xyz.touch()
454 assert resolve_package_path(xyz) == subdir
455 assert not resolve_package_path(pkg)
456
457
458 def test_access_denied_during_cleanup(tmp_path: Path, monkeypatch: MonkeyPatch) -> None:
459 """Ensure that deleting a numbered dir does not fail because of OSErrors (#4262)."""
460 path = tmp_path / "temp-1"
461 path.mkdir()
462
463 def renamed_failed(*args):
464 raise OSError("access denied")
465
466 monkeypatch.setattr(Path, "rename", renamed_failed)
467
468 lock_path = get_lock_path(path)
469 maybe_delete_a_numbered_dir(path)
470 assert not lock_path.is_file()
471
472
473 def test_long_path_during_cleanup(tmp_path: Path) -> None:
474 """Ensure that deleting long path works (particularly on Windows (#6775))."""
475 path = (tmp_path / ("a" * 250)).resolve()
476 if sys.platform == "win32":
477 # make sure that the full path is > 260 characters without any
478 # component being over 260 characters
479 assert len(str(path)) > 260
480 extended_path = "\\\\?\\" + str(path)
481 else:
482 extended_path = str(path)
483 os.mkdir(extended_path)
484 assert os.path.isdir(extended_path)
485 maybe_delete_a_numbered_dir(path)
486 assert not os.path.isdir(extended_path)
487
488
489 def test_get_extended_length_path_str() -> None:
490 assert get_extended_length_path_str(r"c:\foo") == r"\\?\c:\foo"
491 assert get_extended_length_path_str(r"\\share\foo") == r"\\?\UNC\share\foo"
492 assert get_extended_length_path_str(r"\\?\UNC\share\foo") == r"\\?\UNC\share\foo"
493 assert get_extended_length_path_str(r"\\?\c:\foo") == r"\\?\c:\foo"
494
495
496 def test_suppress_error_removing_lock(tmp_path: Path) -> None:
497 """ensure_deletable should be resilient if lock file cannot be removed (#5456, #7491)"""
498 path = tmp_path / "dir"
499 path.mkdir()
500 lock = get_lock_path(path)
501 lock.touch()
502 mtime = lock.stat().st_mtime
503
504 with unittest.mock.patch.object(Path, "unlink", side_effect=OSError) as m:
505 assert not ensure_deletable(
506 path, consider_lock_dead_if_created_before=mtime + 30
507 )
508 assert m.call_count == 1
509 assert lock.is_file()
510
511 with unittest.mock.patch.object(Path, "is_file", side_effect=OSError) as m:
512 assert not ensure_deletable(
513 path, consider_lock_dead_if_created_before=mtime + 30
514 )
515 assert m.call_count == 1
516 assert lock.is_file()
517
518 # check now that we can remove the lock file in normal circumstances
519 assert ensure_deletable(path, consider_lock_dead_if_created_before=mtime + 30)
520 assert not lock.is_file()
521
522
523 def test_bestrelpath() -> None:
524 curdir = Path("/foo/bar/baz/path")
525 assert bestrelpath(curdir, curdir) == "."
526 assert bestrelpath(curdir, curdir / "hello" / "world") == "hello" + os.sep + "world"
527 assert bestrelpath(curdir, curdir.parent / "sister") == ".." + os.sep + "sister"
528 assert bestrelpath(curdir, curdir.parent) == ".."
529 assert bestrelpath(curdir, Path("hello")) == "hello"
530
531
532 def test_commonpath() -> None:
533 path = Path("/foo/bar/baz/path")
534 subpath = path / "sampledir"
535 assert commonpath(path, subpath) == path
536 assert commonpath(subpath, path) == path
537 assert commonpath(Path(str(path) + "suffix"), path) == path.parent
538 assert commonpath(path, path.parent.parent) == path.parent.parent
539
540
541 def test_visit_ignores_errors(tmp_path: Path) -> None:
542 symlink_or_skip("recursive", tmp_path / "recursive")
543 tmp_path.joinpath("foo").write_bytes(b"")
544 tmp_path.joinpath("bar").write_bytes(b"")
545
546 assert [
547 entry.name for entry in visit(str(tmp_path), recurse=lambda entry: False)
548 ] == ["bar", "foo"]
549
550
551 @pytest.mark.skipif(not sys.platform.startswith("win"), reason="Windows only")
552 def test_samefile_false_negatives(tmp_path: Path, monkeypatch: MonkeyPatch) -> None:
553 """
554 import_file() should not raise ImportPathMismatchError if the paths are exactly
555 equal on Windows. It seems directories mounted as UNC paths make os.path.samefile
556 return False, even when they are clearly equal.
557 """
558 module_path = tmp_path.joinpath("my_module.py")
559 module_path.write_text("def foo(): return 42", encoding="utf-8")
560 monkeypatch.syspath_prepend(tmp_path)
561
562 with monkeypatch.context() as mp:
563 # Forcibly make os.path.samefile() return False here to ensure we are comparing
564 # the paths too. Using a context to narrow the patch as much as possible given
565 # this is an important system function.
566 mp.setattr(os.path, "samefile", lambda x, y: False)
567 module = import_path(
568 module_path, root=tmp_path, consider_namespace_packages=False
569 )
570 assert getattr(module, "foo")() == 42
571
572
573 def test_scandir_with_non_existent_directory() -> None:
574 # Test with a directory that does not exist
575 non_existent_dir = "path_to_non_existent_dir"
576 result = scandir(non_existent_dir)
577 # Assert that the result is an empty list
578 assert result == []
579
580
581 def test_scandir_handles_os_error() -> None:
582 # Create a mock entry that will raise an OSError when is_file is called
583 mock_entry = unittest.mock.MagicMock()
584 mock_entry.is_file.side_effect = OSError("some permission error")
585 # Mock os.scandir to return an iterator with our mock entry
586 with unittest.mock.patch("os.scandir") as mock_scandir:
587 mock_scandir.return_value.__enter__.return_value = [mock_entry]
588 # Call the scandir function with a path
589 # We expect an OSError to be raised here
590 with pytest.raises(OSError, match="some permission error"):
591 scandir("/fake/path")
592 # Verify that the is_file method was called on the mock entry
593 mock_entry.is_file.assert_called_once()
594
595
596 class TestImportLibMode:
597 def test_importmode_importlib_with_dataclass(
598 self, tmp_path: Path, ns_param: bool
599 ) -> None:
600 """Ensure that importlib mode works with a module containing dataclasses (#7856)."""
601 fn = tmp_path.joinpath("_src/tests/test_dataclass.py")
602 fn.parent.mkdir(parents=True)
603 fn.write_text(
604 dedent(
605 """
606 from dataclasses import dataclass
607
608 @dataclass
609 class Data:
610 value: str
611 """
612 ),
613 encoding="utf-8",
614 )
615
616 module = import_path(
617 fn, mode="importlib", root=tmp_path, consider_namespace_packages=ns_param
618 )
619 Data: Any = getattr(module, "Data")
620 data = Data(value="foo")
621 assert data.value == "foo"
622 assert data.__module__ == "_src.tests.test_dataclass"
623
624 # Ensure we do not import the same module again (#11475).
625 module2 = import_path(
626 fn, mode="importlib", root=tmp_path, consider_namespace_packages=ns_param
627 )
628 assert module is module2
629
630 def test_importmode_importlib_with_pickle(
631 self, tmp_path: Path, ns_param: bool
632 ) -> None:
633 """Ensure that importlib mode works with pickle (#7859)."""
634 fn = tmp_path.joinpath("_src/tests/test_pickle.py")
635 fn.parent.mkdir(parents=True)
636 fn.write_text(
637 dedent(
638 """
639 import pickle
640
641 def _action():
642 return 42
643
644 def round_trip():
645 s = pickle.dumps(_action)
646 return pickle.loads(s)
647 """
648 ),
649 encoding="utf-8",
650 )
651
652 module = import_path(
653 fn, mode="importlib", root=tmp_path, consider_namespace_packages=ns_param
654 )
655 round_trip = getattr(module, "round_trip")
656 action = round_trip()
657 assert action() == 42
658
659 # Ensure we do not import the same module again (#11475).
660 module2 = import_path(
661 fn, mode="importlib", root=tmp_path, consider_namespace_packages=ns_param
662 )
663 assert module is module2
664
665 def test_importmode_importlib_with_pickle_separate_modules(
666 self, tmp_path: Path, ns_param: bool
667 ) -> None:
668 """
669 Ensure that importlib mode works can load pickles that look similar but are
670 defined in separate modules.
671 """
672 fn1 = tmp_path.joinpath("_src/m1/tests/test.py")
673 fn1.parent.mkdir(parents=True)
674 fn1.write_text(
675 dedent(
676 """
677 import dataclasses
678 import pickle
679
680 @dataclasses.dataclass
681 class Data:
682 x: int = 42
683 """
684 ),
685 encoding="utf-8",
686 )
687
688 fn2 = tmp_path.joinpath("_src/m2/tests/test.py")
689 fn2.parent.mkdir(parents=True)
690 fn2.write_text(
691 dedent(
692 """
693 import dataclasses
694 import pickle
695
696 @dataclasses.dataclass
697 class Data:
698 x: str = ""
699 """
700 ),
701 encoding="utf-8",
702 )
703
704 import pickle
705
706 def round_trip(obj):
707 s = pickle.dumps(obj)
708 return pickle.loads(s)
709
710 module = import_path(
711 fn1, mode="importlib", root=tmp_path, consider_namespace_packages=ns_param
712 )
713 Data1 = getattr(module, "Data")
714
715 module = import_path(
716 fn2, mode="importlib", root=tmp_path, consider_namespace_packages=ns_param
717 )
718 Data2 = getattr(module, "Data")
719
720 assert round_trip(Data1(20)) == Data1(20)
721 assert round_trip(Data2("hello")) == Data2("hello")
722 assert Data1.__module__ == "_src.m1.tests.test"
723 assert Data2.__module__ == "_src.m2.tests.test"
724
725 def test_module_name_from_path(self, tmp_path: Path) -> None:
726 result = module_name_from_path(tmp_path / "src/tests/test_foo.py", tmp_path)
727 assert result == "src.tests.test_foo"
728
729 # Path is not relative to root dir: use the full path to obtain the module name.
730 result = module_name_from_path(Path("/home/foo/test_foo.py"), Path("/bar"))
731 assert result == "home.foo.test_foo"
732
733 # Importing __init__.py files should return the package as module name.
734 result = module_name_from_path(tmp_path / "src/app/__init__.py", tmp_path)
735 assert result == "src.app"
736
737 # Unless __init__.py file is at the root, in which case we cannot have an empty module name.
738 result = module_name_from_path(tmp_path / "__init__.py", tmp_path)
739 assert result == "__init__"
740
741 # Modules which start with "." are considered relative and will not be imported
742 # unless part of a package, so we replace it with a "_" when generating the fake module name.
743 result = module_name_from_path(tmp_path / ".env/tests/test_foo.py", tmp_path)
744 assert result == "_env.tests.test_foo"
745
746 # We want to avoid generating extra intermediate modules if some directory just happens
747 # to contain a "." in the name.
748 result = module_name_from_path(
749 tmp_path / ".env.310/tests/test_foo.py", tmp_path
750 )
751 assert result == "_env_310.tests.test_foo"
752
753 def test_resolve_pkg_root_and_module_name(
754 self, tmp_path: Path, monkeypatch: MonkeyPatch, pytester: Pytester
755 ) -> None:
756 # Create a directory structure first without __init__.py files.
757 (tmp_path / "src/app/core").mkdir(parents=True)
758 models_py = tmp_path / "src/app/core/models.py"
759 models_py.touch()
760
761 with pytest.raises(CouldNotResolvePathError):
762 _ = resolve_pkg_root_and_module_name(models_py)
763
764 # Create the __init__.py files, it should now resolve to a proper module name.
765 (tmp_path / "src/app/__init__.py").touch()
766 (tmp_path / "src/app/core/__init__.py").touch()
767 assert resolve_pkg_root_and_module_name(
768 models_py, consider_namespace_packages=True
769 ) == (
770 tmp_path / "src",
771 "app.core.models",
772 )
773
774 # If we add tmp_path to sys.path, src becomes a namespace package.
775 monkeypatch.syspath_prepend(tmp_path)
776 validate_namespace_package(pytester, [tmp_path], ["src.app.core.models"])
777
778 assert resolve_pkg_root_and_module_name(
779 models_py, consider_namespace_packages=True
780 ) == (
781 tmp_path,
782 "src.app.core.models",
783 )
784 assert resolve_pkg_root_and_module_name(
785 models_py, consider_namespace_packages=False
786 ) == (
787 tmp_path / "src",
788 "app.core.models",
789 )
790
791 def test_insert_missing_modules(
792 self, monkeypatch: MonkeyPatch, tmp_path: Path
793 ) -> None:
794 monkeypatch.chdir(tmp_path)
795 # Use 'xxx' and 'xxy' as parent names as they are unlikely to exist and
796 # don't end up being imported.
797 modules = {"xxx.tests.foo": ModuleType("xxx.tests.foo")}
798 insert_missing_modules(modules, "xxx.tests.foo")
799 assert sorted(modules) == ["xxx", "xxx.tests", "xxx.tests.foo"]
800
801 mod = ModuleType("mod", doc="My Module")
802 modules = {"xxy": mod}
803 insert_missing_modules(modules, "xxy")
804 assert modules == {"xxy": mod}
805
806 modules = {}
807 insert_missing_modules(modules, "")
808 assert modules == {}
809
810 @pytest.mark.parametrize("b_is_package", [True, False])
811 @pytest.mark.parametrize("insert_modules", [True, False])
812 def test_import_module_using_spec(
813 self, b_is_package, insert_modules, tmp_path: Path
814 ):
815 """
816 Verify that `_import_module_using_spec` can obtain a spec based on the path, thereby enabling the import.
817 When importing, not only the target module is imported, but also the parent modules are recursively imported.
818 """
819 file_path = tmp_path / "a/b/c/demo.py"
820 file_path.parent.mkdir(parents=True)
821 file_path.write_text("my_name='demo'", encoding="utf-8")
822
823 if b_is_package:
824 (tmp_path / "a/b/__init__.py").write_text(
825 "my_name='b.__init__'", encoding="utf-8"
826 )
827
828 mod = _import_module_using_spec(
829 "a.b.c.demo",
830 file_path,
831 insert_modules=insert_modules,
832 )
833
834 # target module is imported
835 assert mod is not None
836 assert spec_matches_module_path(mod.__spec__, file_path) is True
837
838 mod_demo = sys.modules["a.b.c.demo"]
839 assert "demo.py" in str(mod_demo)
840 assert mod_demo.my_name == "demo" # Imported and available for use
841
842 # parent modules are recursively imported.
843 mod_a = sys.modules["a"]
844 mod_b = sys.modules["a.b"]
845 mod_c = sys.modules["a.b.c"]
846
847 assert mod_a.b is mod_b
848 assert mod_a.b.c is mod_c
849 assert mod_a.b.c.demo is mod_demo
850
851 assert "namespace" in str(mod_a).lower()
852 assert "namespace" in str(mod_c).lower()
853
854 # Compatibility package and namespace package.
855 if b_is_package:
856 assert "namespace" not in str(mod_b).lower()
857 assert "__init__.py" in str(mod_b).lower() # Imported __init__.py
858 assert mod_b.my_name == "b.__init__" # Imported and available for use
859
860 else:
861 assert "namespace" in str(mod_b).lower()
862 with pytest.raises(AttributeError): # Not imported __init__.py
863 assert mod_b.my_name
864
865 def test_parent_contains_child_module_attribute(
866 self, monkeypatch: MonkeyPatch, tmp_path: Path
867 ):
868 monkeypatch.chdir(tmp_path)
869 # Use 'xxx' and 'xxy' as parent names as they are unlikely to exist and
870 # don't end up being imported.
871 modules = {"xxx.tests.foo": ModuleType("xxx.tests.foo")}
872 insert_missing_modules(modules, "xxx.tests.foo")
873 assert sorted(modules) == ["xxx", "xxx.tests", "xxx.tests.foo"]
874 assert modules["xxx"].tests is modules["xxx.tests"]
875 assert modules["xxx.tests"].foo is modules["xxx.tests.foo"]
876
877 def test_importlib_package(
878 self, monkeypatch: MonkeyPatch, tmp_path: Path, ns_param: bool
879 ):
880 """
881 Importing a package using --importmode=importlib should not import the
882 package's __init__.py file more than once (#11306).
883 """
884 monkeypatch.chdir(tmp_path)
885 monkeypatch.syspath_prepend(tmp_path)
886
887 package_name = "importlib_import_package"
888 tmp_path.joinpath(package_name).mkdir()
889 init = tmp_path.joinpath(f"{package_name}/__init__.py")
890 init.write_text(
891 dedent(
892 """
893 from .singleton import Singleton
894
895 instance = Singleton()
896 """
897 ),
898 encoding="ascii",
899 )
900 singleton = tmp_path.joinpath(f"{package_name}/singleton.py")
901 singleton.write_text(
902 dedent(
903 """
904 class Singleton:
905 INSTANCES = []
906
907 def __init__(self) -> None:
908 self.INSTANCES.append(self)
909 if len(self.INSTANCES) > 1:
910 raise RuntimeError("Already initialized")
911 """
912 ),
913 encoding="ascii",
914 )
915
916 mod = import_path(
917 init,
918 root=tmp_path,
919 mode=ImportMode.importlib,
920 consider_namespace_packages=ns_param,
921 )
922 assert len(mod.instance.INSTANCES) == 1
923 # Ensure we do not import the same module again (#11475).
924 mod2 = import_path(
925 init,
926 root=tmp_path,
927 mode=ImportMode.importlib,
928 consider_namespace_packages=ns_param,
929 )
930 assert mod is mod2
931
932 def test_importlib_root_is_package(self, pytester: Pytester) -> None:
933 """
934 Regression for importing a `__init__`.py file that is at the root
935 (#11417).
936 """
937 pytester.makepyfile(__init__="")
938 pytester.makepyfile(
939 """
940 def test_my_test():
941 assert True
942 """
943 )
944
945 result = pytester.runpytest("--import-mode=importlib")
946 result.stdout.fnmatch_lines("* 1 passed *")
947
948 @pytest.mark.parametrize("name", ["code", "time", "math"])
949 def test_importlib_same_name_as_stl(
950 self, pytester, ns_param: bool, tmp_path: Path, name: str
951 ):
952 """Import a namespace package with the same name as the standard library (#13026)."""
953 file_path = pytester.path / f"{name}/foo/test_demo.py"
954 file_path.parent.mkdir(parents=True)
955 file_path.write_text(
956 dedent(
957 """
958 def test_demo():
959 pass
960 """
961 ),
962 encoding="utf-8",
963 )
964
965 # unit test
966 importlib.import_module(name) # import standard library
967
968 import_path( # import user files
969 file_path,
970 mode=ImportMode.importlib,
971 root=pytester.path,
972 consider_namespace_packages=ns_param,
973 )
974
975 # E2E test
976 result = pytester.runpytest("--import-mode=importlib")
977 result.stdout.fnmatch_lines("* 1 passed *")
978
979 def create_installed_doctests_and_tests_dir(
980 self, path: Path, monkeypatch: MonkeyPatch
981 ) -> tuple[Path, Path, Path]:
982 """
983 Create a directory structure where the application code is installed in a virtual environment,
984 and the tests are in an outside ".tests" directory.
985
986 Return the paths to the core module (installed in the virtualenv), and the test modules.
987 """
988 app = path / "src/app"
989 app.mkdir(parents=True)
990 (app / "__init__.py").touch()
991 core_py = app / "core.py"
992 core_py.write_text(
993 dedent(
994 """
995 def foo():
996 '''
997 >>> 1 + 1
998 2
999 '''
1000 """
1001 ),
1002 encoding="ascii",
1003 )
1004
1005 # Install it into a site-packages directory, and add it to sys.path, mimicking what
1006 # happens when installing into a virtualenv.
1007 site_packages = path / ".env/lib/site-packages"
1008 site_packages.mkdir(parents=True)
1009 shutil.copytree(app, site_packages / "app")
1010 assert (site_packages / "app/core.py").is_file()
1011
1012 monkeypatch.syspath_prepend(site_packages)
1013
1014 # Create the tests files, outside 'src' and the virtualenv.
1015 # We use the same test name on purpose, but in different directories, to ensure
1016 # this works as advertised.
1017 conftest_path1 = path / ".tests/a/conftest.py"
1018 conftest_path1.parent.mkdir(parents=True)
1019 conftest_path1.write_text(
1020 dedent(
1021 """
1022 import pytest
1023 @pytest.fixture
1024 def a_fix(): return "a"
1025 """
1026 ),
1027 encoding="ascii",
1028 )
1029 test_path1 = path / ".tests/a/test_core.py"
1030 test_path1.write_text(
1031 dedent(
1032 """
1033 import app.core
1034 def test(a_fix):
1035 assert a_fix == "a"
1036 """,
1037 ),
1038 encoding="ascii",
1039 )
1040
1041 conftest_path2 = path / ".tests/b/conftest.py"
1042 conftest_path2.parent.mkdir(parents=True)
1043 conftest_path2.write_text(
1044 dedent(
1045 """
1046 import pytest
1047 @pytest.fixture
1048 def b_fix(): return "b"
1049 """
1050 ),
1051 encoding="ascii",
1052 )
1053
1054 test_path2 = path / ".tests/b/test_core.py"
1055 test_path2.write_text(
1056 dedent(
1057 """
1058 import app.core
1059 def test(b_fix):
1060 assert b_fix == "b"
1061 """,
1062 ),
1063 encoding="ascii",
1064 )
1065 return (site_packages / "app/core.py"), test_path1, test_path2
1066
1067 def test_import_using_normal_mechanism_first(
1068 self, monkeypatch: MonkeyPatch, pytester: Pytester, ns_param: bool
1069 ) -> None:
1070 """
1071 Test import_path imports from the canonical location when possible first, only
1072 falling back to its normal flow when the module being imported is not reachable via sys.path (#11475).
1073 """
1074 core_py, test_path1, test_path2 = self.create_installed_doctests_and_tests_dir(
1075 pytester.path, monkeypatch
1076 )
1077
1078 # core_py is reached from sys.path, so should be imported normally.
1079 mod = import_path(
1080 core_py,
1081 mode="importlib",
1082 root=pytester.path,
1083 consider_namespace_packages=ns_param,
1084 )
1085 assert mod.__name__ == "app.core"
1086 assert mod.__file__ and Path(mod.__file__) == core_py
1087
1088 # Ensure we do not import the same module again (#11475).
1089 mod2 = import_path(
1090 core_py,
1091 mode="importlib",
1092 root=pytester.path,
1093 consider_namespace_packages=ns_param,
1094 )
1095 assert mod is mod2
1096
1097 # tests are not reachable from sys.path, so they are imported as a standalone modules.
1098 # Instead of '.tests.a.test_core', we import as "_tests.a.test_core" because
1099 # importlib considers module names starting with '.' to be local imports.
1100 mod = import_path(
1101 test_path1,
1102 mode="importlib",
1103 root=pytester.path,
1104 consider_namespace_packages=ns_param,
1105 )
1106 assert mod.__name__ == "_tests.a.test_core"
1107
1108 # Ensure we do not import the same module again (#11475).
1109 mod2 = import_path(
1110 test_path1,
1111 mode="importlib",
1112 root=pytester.path,
1113 consider_namespace_packages=ns_param,
1114 )
1115 assert mod is mod2
1116
1117 mod = import_path(
1118 test_path2,
1119 mode="importlib",
1120 root=pytester.path,
1121 consider_namespace_packages=ns_param,
1122 )
1123 assert mod.__name__ == "_tests.b.test_core"
1124
1125 # Ensure we do not import the same module again (#11475).
1126 mod2 = import_path(
1127 test_path2,
1128 mode="importlib",
1129 root=pytester.path,
1130 consider_namespace_packages=ns_param,
1131 )
1132 assert mod is mod2
1133
1134 def test_import_using_normal_mechanism_first_integration(
1135 self, monkeypatch: MonkeyPatch, pytester: Pytester, ns_param: bool
1136 ) -> None:
1137 """
1138 Same test as above, but verify the behavior calling pytest.
1139
1140 We should not make this call in the same test as above, as the modules have already
1141 been imported by separate import_path() calls.
1142 """
1143 core_py, test_path1, test_path2 = self.create_installed_doctests_and_tests_dir(
1144 pytester.path, monkeypatch
1145 )
1146 result = pytester.runpytest(
1147 "--import-mode=importlib",
1148 "-o",
1149 f"consider_namespace_packages={ns_param}",
1150 "--doctest-modules",
1151 "--pyargs",
1152 "app",
1153 "./.tests",
1154 )
1155 result.stdout.fnmatch_lines(
1156 [
1157 f"{core_py.relative_to(pytester.path)} . *",
1158 f"{test_path1.relative_to(pytester.path)} . *",
1159 f"{test_path2.relative_to(pytester.path)} . *",
1160 "* 3 passed*",
1161 ]
1162 )
1163
1164 def test_import_path_imports_correct_file(
1165 self, pytester: Pytester, ns_param: bool
1166 ) -> None:
1167 """
1168 Import the module by the given path, even if other module with the same name
1169 is reachable from sys.path.
1170 """
1171 pytester.syspathinsert()
1172 # Create a 'x.py' module reachable from sys.path that raises AssertionError
1173 # if imported.
1174 x_at_root = pytester.path / "x.py"
1175 x_at_root.write_text("raise AssertionError('x at root')", encoding="ascii")
1176
1177 # Create another x.py module, but in some subdirectories to ensure it is not
1178 # accessible from sys.path.
1179 x_in_sub_dir = pytester.path / "a/b/x.py"
1180 x_in_sub_dir.parent.mkdir(parents=True)
1181 x_in_sub_dir.write_text("X = 'a/b/x'", encoding="ascii")
1182
1183 # Import our x.py module from the subdirectories.
1184 # The 'x.py' module from sys.path was not imported for sure because
1185 # otherwise we would get an AssertionError.
1186 mod = import_path(
1187 x_in_sub_dir,
1188 mode=ImportMode.importlib,
1189 root=pytester.path,
1190 consider_namespace_packages=ns_param,
1191 )
1192 assert mod.__file__ and Path(mod.__file__) == x_in_sub_dir
1193 assert mod.X == "a/b/x"
1194
1195 mod2 = import_path(
1196 x_in_sub_dir,
1197 mode=ImportMode.importlib,
1198 root=pytester.path,
1199 consider_namespace_packages=ns_param,
1200 )
1201 assert mod is mod2
1202
1203 # Attempt to import root 'x.py'.
1204 with pytest.raises(AssertionError, match="x at root"):
1205 _ = import_path(
1206 x_at_root,
1207 mode=ImportMode.importlib,
1208 root=pytester.path,
1209 consider_namespace_packages=ns_param,
1210 )
1211
1212
1213 def test_safe_exists(tmp_path: Path) -> None:
1214 d = tmp_path.joinpath("some_dir")
1215 d.mkdir()
1216 assert safe_exists(d) is True
1217
1218 f = tmp_path.joinpath("some_file")
1219 f.touch()
1220 assert safe_exists(f) is True
1221
1222 # Use unittest.mock() as a context manager to have a very narrow
1223 # patch lifetime.
1224 p = tmp_path.joinpath("some long filename" * 100)
1225 with unittest.mock.patch.object(
1226 Path,
1227 "exists",
1228 autospec=True,
1229 side_effect=OSError(errno.ENAMETOOLONG, "name too long"),
1230 ):
1231 assert safe_exists(p) is False
1232
1233 with unittest.mock.patch.object(
1234 Path,
1235 "exists",
1236 autospec=True,
1237 side_effect=ValueError("name too long"),
1238 ):
1239 assert safe_exists(p) is False
1240
1241
1242 def test_import_sets_module_as_attribute(pytester: Pytester) -> None:
1243 """Unittest test for #12194."""
1244 pytester.path.joinpath("foo/bar/baz").mkdir(parents=True)
1245 pytester.path.joinpath("foo/__init__.py").touch()
1246 pytester.path.joinpath("foo/bar/__init__.py").touch()
1247 pytester.path.joinpath("foo/bar/baz/__init__.py").touch()
1248 pytester.syspathinsert()
1249
1250 # Import foo.bar.baz and ensure parent modules also ended up imported.
1251 baz = import_path(
1252 pytester.path.joinpath("foo/bar/baz/__init__.py"),
1253 mode=ImportMode.importlib,
1254 root=pytester.path,
1255 consider_namespace_packages=False,
1256 )
1257 assert baz.__name__ == "foo.bar.baz"
1258 foo = sys.modules["foo"]
1259 assert foo.__name__ == "foo"
1260 bar = sys.modules["foo.bar"]
1261 assert bar.__name__ == "foo.bar"
1262
1263 # Check parent modules have an attribute pointing to their children.
1264 assert bar.baz is baz
1265 assert foo.bar is bar
1266
1267 # Ensure we returned the "foo.bar" module cached in sys.modules.
1268 bar_2 = import_path(
1269 pytester.path.joinpath("foo/bar/__init__.py"),
1270 mode=ImportMode.importlib,
1271 root=pytester.path,
1272 consider_namespace_packages=False,
1273 )
1274 assert bar_2 is bar
1275
1276
1277 def test_import_sets_module_as_attribute_without_init_files(pytester: Pytester) -> None:
1278 """Similar to test_import_sets_module_as_attribute, but without __init__.py files."""
1279 pytester.path.joinpath("foo/bar").mkdir(parents=True)
1280 pytester.path.joinpath("foo/bar/baz.py").touch()
1281 pytester.syspathinsert()
1282
1283 # Import foo.bar.baz and ensure parent modules also ended up imported.
1284 baz = import_path(
1285 pytester.path.joinpath("foo/bar/baz.py"),
1286 mode=ImportMode.importlib,
1287 root=pytester.path,
1288 consider_namespace_packages=False,
1289 )
1290 assert baz.__name__ == "foo.bar.baz"
1291 foo = sys.modules["foo"]
1292 assert foo.__name__ == "foo"
1293 bar = sys.modules["foo.bar"]
1294 assert bar.__name__ == "foo.bar"
1295
1296 # Check parent modules have an attribute pointing to their children.
1297 assert bar.baz is baz
1298 assert foo.bar is bar
1299
1300 # Ensure we returned the "foo.bar.baz" module cached in sys.modules.
1301 baz_2 = import_path(
1302 pytester.path.joinpath("foo/bar/baz.py"),
1303 mode=ImportMode.importlib,
1304 root=pytester.path,
1305 consider_namespace_packages=False,
1306 )
1307 assert baz_2 is baz
1308
1309
1310 def test_import_sets_module_as_attribute_regression(pytester: Pytester) -> None:
1311 """Regression test for #12194."""
1312 pytester.path.joinpath("foo/bar/baz").mkdir(parents=True)
1313 pytester.path.joinpath("foo/__init__.py").touch()
1314 pytester.path.joinpath("foo/bar/__init__.py").touch()
1315 pytester.path.joinpath("foo/bar/baz/__init__.py").touch()
1316 f = pytester.makepyfile(
1317 """
1318 import foo
1319 from foo.bar import baz
1320 foo.bar.baz
1321
1322 def test_foo() -> None:
1323 pass
1324 """
1325 )
1326
1327 pytester.syspathinsert()
1328 result = pytester.runpython(f)
1329 assert result.ret == 0
1330
1331 result = pytester.runpytest("--import-mode=importlib", "--doctest-modules")
1332 assert result.ret == 0
1333
1334
1335 def test_import_submodule_not_namespace(pytester: Pytester) -> None:
1336 """
1337 Regression test for importing a submodule 'foo.bar' while there is a 'bar' directory
1338 reachable from sys.path -- ensuring the top-level module does not end up imported as a namespace
1339 package.
1340
1341 #12194
1342 https://github.com/pytest-dev/pytest/pull/12208#issuecomment-2056458432
1343 """
1344 pytester.syspathinsert()
1345 # Create package 'foo' with a submodule 'bar'.
1346 pytester.path.joinpath("foo").mkdir()
1347 foo_path = pytester.path.joinpath("foo/__init__.py")
1348 foo_path.touch()
1349 bar_path = pytester.path.joinpath("foo/bar.py")
1350 bar_path.touch()
1351 # Create top-level directory in `sys.path` with the same name as that submodule.
1352 pytester.path.joinpath("bar").mkdir()
1353
1354 # Import `foo`, then `foo.bar`, and check they were imported from the correct location.
1355 foo = import_path(
1356 foo_path,
1357 mode=ImportMode.importlib,
1358 root=pytester.path,
1359 consider_namespace_packages=False,
1360 )
1361 bar = import_path(
1362 bar_path,
1363 mode=ImportMode.importlib,
1364 root=pytester.path,
1365 consider_namespace_packages=False,
1366 )
1367 assert foo.__name__ == "foo"
1368 assert bar.__name__ == "foo.bar"
1369 assert foo.__file__ is not None
1370 assert bar.__file__ is not None
1371 assert Path(foo.__file__) == foo_path
1372 assert Path(bar.__file__) == bar_path
1373
1374
1375 class TestNamespacePackages:
1376 """Test import_path support when importing from properly namespace packages."""
1377
1378 @pytest.fixture(autouse=True)
1379 def setup_imports_tracking(self, monkeypatch: MonkeyPatch) -> None:
1380 monkeypatch.setattr(sys, "pytest_namespace_packages_test", [], raising=False)
1381
1382 def setup_directories(
1383 self, tmp_path: Path, monkeypatch: MonkeyPatch | None, pytester: Pytester
1384 ) -> tuple[Path, Path]:
1385 # Use a code to guard against modules being imported more than once.
1386 # This is a safeguard in case future changes break this invariant.
1387 code = dedent(
1388 """
1389 import sys
1390 imported = getattr(sys, "pytest_namespace_packages_test", [])
1391 assert __name__ not in imported, f"{__name__} already imported"
1392 imported.append(__name__)
1393 sys.pytest_namespace_packages_test = imported
1394 """
1395 )
1396
1397 # Set up a namespace package "com.company", containing
1398 # two subpackages, "app" and "calc".
1399 (tmp_path / "src/dist1/com/company/app/core").mkdir(parents=True)
1400 (tmp_path / "src/dist1/com/company/app/__init__.py").write_text(
1401 code, encoding="UTF-8"
1402 )
1403 (tmp_path / "src/dist1/com/company/app/core/__init__.py").write_text(
1404 code, encoding="UTF-8"
1405 )
1406 models_py = tmp_path / "src/dist1/com/company/app/core/models.py"
1407 models_py.touch()
1408
1409 (tmp_path / "src/dist2/com/company/calc/algo").mkdir(parents=True)
1410 (tmp_path / "src/dist2/com/company/calc/__init__.py").write_text(
1411 code, encoding="UTF-8"
1412 )
1413 (tmp_path / "src/dist2/com/company/calc/algo/__init__.py").write_text(
1414 code, encoding="UTF-8"
1415 )
1416 algorithms_py = tmp_path / "src/dist2/com/company/calc/algo/algorithms.py"
1417 algorithms_py.write_text(code, encoding="UTF-8")
1418
1419 r = validate_namespace_package(
1420 pytester,
1421 [tmp_path / "src/dist1", tmp_path / "src/dist2"],
1422 ["com.company.app.core.models", "com.company.calc.algo.algorithms"],
1423 )
1424 assert r.ret == 0
1425 if monkeypatch is not None:
1426 monkeypatch.syspath_prepend(tmp_path / "src/dist1")
1427 monkeypatch.syspath_prepend(tmp_path / "src/dist2")
1428 return models_py, algorithms_py
1429
1430 @pytest.mark.parametrize("import_mode", ["prepend", "append", "importlib"])
1431 def test_resolve_pkg_root_and_module_name_ns_multiple_levels(
1432 self,
1433 tmp_path: Path,
1434 monkeypatch: MonkeyPatch,
1435 pytester: Pytester,
1436 import_mode: str,
1437 ) -> None:
1438 models_py, algorithms_py = self.setup_directories(
1439 tmp_path, monkeypatch, pytester
1440 )
1441
1442 pkg_root, module_name = resolve_pkg_root_and_module_name(
1443 models_py, consider_namespace_packages=True
1444 )
1445 assert (pkg_root, module_name) == (
1446 tmp_path / "src/dist1",
1447 "com.company.app.core.models",
1448 )
1449
1450 mod = import_path(
1451 models_py, mode=import_mode, root=tmp_path, consider_namespace_packages=True
1452 )
1453 assert mod.__name__ == "com.company.app.core.models"
1454 assert mod.__file__ == str(models_py)
1455
1456 # Ensure we do not import the same module again (#11475).
1457 mod2 = import_path(
1458 models_py, mode=import_mode, root=tmp_path, consider_namespace_packages=True
1459 )
1460 assert mod is mod2
1461
1462 pkg_root, module_name = resolve_pkg_root_and_module_name(
1463 algorithms_py, consider_namespace_packages=True
1464 )
1465 assert (pkg_root, module_name) == (
1466 tmp_path / "src/dist2",
1467 "com.company.calc.algo.algorithms",
1468 )
1469
1470 mod = import_path(
1471 algorithms_py,
1472 mode=import_mode,
1473 root=tmp_path,
1474 consider_namespace_packages=True,
1475 )
1476 assert mod.__name__ == "com.company.calc.algo.algorithms"
1477 assert mod.__file__ == str(algorithms_py)
1478
1479 # Ensure we do not import the same module again (#11475).
1480 mod2 = import_path(
1481 algorithms_py,
1482 mode=import_mode,
1483 root=tmp_path,
1484 consider_namespace_packages=True,
1485 )
1486 assert mod is mod2
1487
1488 def test_ns_multiple_levels_import_rewrite_assertions(
1489 self,
1490 tmp_path: Path,
1491 monkeypatch: MonkeyPatch,
1492 pytester: Pytester,
1493 ) -> None:
1494 """Check assert rewriting with `--import-mode=importlib` (#12659)."""
1495 self.setup_directories(tmp_path, monkeypatch, pytester)
1496 code = dedent("""
1497 def test():
1498 assert "four lights" == "five lights"
1499 """)
1500
1501 # A case is in a subdirectory with an `__init__.py` file.
1502 test_py = tmp_path / "src/dist2/com/company/calc/algo/test_demo.py"
1503 test_py.write_text(code, encoding="UTF-8")
1504
1505 pkg_root, module_name = resolve_pkg_root_and_module_name(
1506 test_py, consider_namespace_packages=True
1507 )
1508 assert (pkg_root, module_name) == (
1509 tmp_path / "src/dist2",
1510 "com.company.calc.algo.test_demo",
1511 )
1512
1513 result = pytester.runpytest("--import-mode=importlib", test_py)
1514
1515 result.stdout.fnmatch_lines(
1516 [
1517 "E AssertionError: assert 'four lights' == 'five lights'",
1518 "E *",
1519 "E - five lights*",
1520 "E + four lights",
1521 ]
1522 )
1523
1524 def test_ns_multiple_levels_import_error(
1525 self,
1526 tmp_path: Path,
1527 pytester: Pytester,
1528 ) -> None:
1529 # Trigger condition 1: ns and file with the same name
1530 file = pytester.path / "cow/moo/moo.py"
1531 file.parent.mkdir(parents=True)
1532 file.write_text("data=123", encoding="utf-8")
1533
1534 # Trigger condition 2: tests are located in ns
1535 tests = pytester.path / "cow/moo/test_moo.py"
1536
1537 tests.write_text(
1538 dedent(
1539 """
1540 from cow.moo.moo import data
1541
1542 def test_moo():
1543 print(data)
1544 """
1545 ),
1546 encoding="utf-8",
1547 )
1548
1549 result = pytester.runpytest("--import-mode=importlib")
1550 assert result.ret == ExitCode.OK
1551
1552 @pytest.mark.parametrize("import_mode", ["prepend", "append", "importlib"])
1553 def test_incorrect_namespace_package(
1554 self,
1555 tmp_path: Path,
1556 monkeypatch: MonkeyPatch,
1557 pytester: Pytester,
1558 import_mode: str,
1559 ) -> None:
1560 models_py, algorithms_py = self.setup_directories(
1561 tmp_path, monkeypatch, pytester
1562 )
1563 # Namespace packages must not have an __init__.py at its top-level
1564 # directory; if it does, it is no longer a namespace package, and we fall back
1565 # to importing just the part of the package containing the __init__.py files.
1566 (tmp_path / "src/dist1/com/__init__.py").touch()
1567
1568 # Because of the __init__ file, 'com' is no longer a namespace package:
1569 # 'com.company.app' is importable as a normal module.
1570 # 'com.company.calc' is no longer importable because 'com' is not a namespace package anymore.
1571 r = validate_namespace_package(
1572 pytester,
1573 [tmp_path / "src/dist1", tmp_path / "src/dist2"],
1574 ["com.company.app.core.models", "com.company.calc.algo.algorithms"],
1575 )
1576 assert r.ret == 1
1577 r.stderr.fnmatch_lines("*No module named 'com.company.calc*")
1578
1579 pkg_root, module_name = resolve_pkg_root_and_module_name(
1580 models_py, consider_namespace_packages=True
1581 )
1582 assert (pkg_root, module_name) == (
1583 tmp_path / "src/dist1",
1584 "com.company.app.core.models",
1585 )
1586
1587 # dist2/com/company will contain a normal Python package.
1588 pkg_root, module_name = resolve_pkg_root_and_module_name(
1589 algorithms_py, consider_namespace_packages=True
1590 )
1591 assert (pkg_root, module_name) == (
1592 tmp_path / "src/dist2/com/company",
1593 "calc.algo.algorithms",
1594 )
1595
1596 def test_detect_meta_path(
1597 self,
1598 tmp_path: Path,
1599 monkeypatch: MonkeyPatch,
1600 pytester: Pytester,
1601 ) -> None:
1602 """
1603 resolve_pkg_root_and_module_name() considers sys.meta_path when importing namespace packages.
1604
1605 Regression test for #12112.
1606 """
1607
1608 class CustomImporter(importlib.abc.MetaPathFinder):
1609 """
1610 Imports the module name "com" as a namespace package.
1611
1612 This ensures our namespace detection considers sys.meta_path, which is important
1613 to support all possible ways a module can be imported (for example editable installs).
1614 """
1615
1616 def find_spec(
1617 self, name: str, path: Any = None, target: Any = None
1618 ) -> importlib.machinery.ModuleSpec | None:
1619 if name == "com":
1620 spec = importlib.machinery.ModuleSpec("com", loader=None)
1621 spec.submodule_search_locations = [str(com_root_2), str(com_root_1)]
1622 return spec
1623 return None
1624
1625 # Setup directories without configuring sys.path.
1626 models_py, _algorithms_py = self.setup_directories(
1627 tmp_path, monkeypatch=None, pytester=pytester
1628 )
1629 com_root_1 = tmp_path / "src/dist1/com"
1630 com_root_2 = tmp_path / "src/dist2/com"
1631
1632 # Because the namespace package is not setup correctly, we cannot resolve it as a namespace package.
1633 pkg_root, module_name = resolve_pkg_root_and_module_name(
1634 models_py, consider_namespace_packages=True
1635 )
1636 assert (pkg_root, module_name) == (
1637 tmp_path / "src/dist1/com/company",
1638 "app.core.models",
1639 )
1640
1641 # Insert our custom importer, which will recognize the "com" directory as a namespace package.
1642 new_meta_path = [CustomImporter(), *sys.meta_path]
1643 monkeypatch.setattr(sys, "meta_path", new_meta_path)
1644
1645 # Now we should be able to resolve the path as namespace package.
1646 pkg_root, module_name = resolve_pkg_root_and_module_name(
1647 models_py, consider_namespace_packages=True
1648 )
1649 assert (pkg_root, module_name) == (
1650 tmp_path / "src/dist1",
1651 "com.company.app.core.models",
1652 )
1653
1654 @pytest.mark.parametrize("insert", [True, False])
1655 def test_full_ns_packages_without_init_files(
1656 self, pytester: Pytester, tmp_path: Path, monkeypatch: MonkeyPatch, insert: bool
1657 ) -> None:
1658 (tmp_path / "src/dist1/ns/b/app/bar/test").mkdir(parents=True)
1659 (tmp_path / "src/dist1/ns/b/app/bar/m.py").touch()
1660
1661 if insert:
1662 # The presence of this __init__.py is not a problem, ns.b.app is still part of the namespace package.
1663 (tmp_path / "src/dist1/ns/b/app/__init__.py").touch()
1664
1665 (tmp_path / "src/dist2/ns/a/core/foo/test").mkdir(parents=True)
1666 (tmp_path / "src/dist2/ns/a/core/foo/m.py").touch()
1667
1668 # Validate the namespace package by importing it in a Python subprocess.
1669 r = validate_namespace_package(
1670 pytester,
1671 [tmp_path / "src/dist1", tmp_path / "src/dist2"],
1672 ["ns.b.app.bar.m", "ns.a.core.foo.m"],
1673 )
1674 assert r.ret == 0
1675 monkeypatch.syspath_prepend(tmp_path / "src/dist1")
1676 monkeypatch.syspath_prepend(tmp_path / "src/dist2")
1677
1678 assert resolve_pkg_root_and_module_name(
1679 tmp_path / "src/dist1/ns/b/app/bar/m.py", consider_namespace_packages=True
1680 ) == (tmp_path / "src/dist1", "ns.b.app.bar.m")
1681 assert resolve_pkg_root_and_module_name(
1682 tmp_path / "src/dist2/ns/a/core/foo/m.py", consider_namespace_packages=True
1683 ) == (tmp_path / "src/dist2", "ns.a.core.foo.m")
1684
1685
1686 def test_ns_import_same_name_directory_12592(
1687 tmp_path: Path, pytester: Pytester
1688 ) -> None:
1689 """Regression for `--import-mode=importlib` with directory parent and child with same name (#12592)."""
1690 y_dir = tmp_path / "x/y/y"
1691 y_dir.mkdir(parents=True)
1692 test_y = tmp_path / "x/y/test_y.py"
1693 test_y.write_text("def test(): pass", encoding="UTF-8")
1694
1695 result = pytester.runpytest("--import-mode=importlib", test_y)
1696 assert result.ret == ExitCode.OK
1697
1698
1699 def test_is_importable(pytester: Pytester) -> None:
1700 pytester.syspathinsert()
1701
1702 path = pytester.path / "bar/foo.py"
1703 path.parent.mkdir()
1704 path.touch()
1705 assert is_importable("bar.foo", path) is True
1706
1707 # Ensure that the module that can be imported points to the path we expect.
1708 path = pytester.path / "some/other/path/bar/foo.py"
1709 path.mkdir(parents=True, exist_ok=True)
1710 assert is_importable("bar.foo", path) is False
1711
1712 # Paths containing "." cannot be imported.
1713 path = pytester.path / "bar.x/__init__.py"
1714 path.parent.mkdir()
1715 path.touch()
1716 assert is_importable("bar.x", path) is False
1717
1718 # Pass starting with "." denote relative imports and cannot be checked using is_importable.
1719 path = pytester.path / ".bar.x/__init__.py"
1720 path.parent.mkdir()
1721 path.touch()
1722 assert is_importable(".bar.x", path) is False
1723
1724
1725 def test_compute_module_name(tmp_path: Path) -> None:
1726 assert compute_module_name(tmp_path, tmp_path) is None
1727 assert compute_module_name(Path(), Path()) is None
1728
1729 assert compute_module_name(tmp_path, tmp_path / "mod.py") == "mod"
1730 assert compute_module_name(tmp_path, tmp_path / "src/app/bar") == "src.app.bar"
1731 assert compute_module_name(tmp_path, tmp_path / "src/app/bar.py") == "src.app.bar"
1732 assert (
1733 compute_module_name(tmp_path, tmp_path / "src/app/bar/__init__.py")
1734 == "src.app.bar"
1735 )
1736
1737
1738 def validate_namespace_package(
1739 pytester: Pytester, paths: Sequence[Path], modules: Sequence[str]
1740 ) -> RunResult:
1741 """
1742 Validate that a Python namespace package is set up correctly.
1743
1744 In a sub interpreter, add 'paths' to sys.path and attempt to import the given modules.
1745
1746 In this module many tests configure a set of files as a namespace package, this function
1747 is used as sanity check that our files are configured correctly from the point of view of Python.
1748 """
1749 lines = [
1750 "import sys",
1751 # Configure sys.path.
1752 *[f"sys.path.append(r{str(x)!r})" for x in paths],
1753 # Imports.
1754 *[f"import {x}" for x in modules],
1755 ]
1756 return pytester.runpython_c("\n".join(lines))