Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/src/_pytest/pathlib.py

raw
1 import atexit
2 import contextlib
3 from enum import Enum
4 from errno import EBADF
5 from errno import ELOOP
6 from errno import ENOENT
7 from errno import ENOTDIR
8 import fnmatch
9 from functools import partial
10 from importlib.machinery import ModuleSpec
11 import importlib.util
12 import itertools
13 import os
14 from os.path import expanduser
15 from os.path import expandvars
16 from os.path import isabs
17 from os.path import sep
18 from pathlib import Path
19 from pathlib import PurePath
20 from posixpath import sep as posix_sep
21 import shutil
22 import sys
23 import types
24 from types import ModuleType
25 from typing import Any
26 from typing import Callable
27 from typing import Dict
28 from typing import Iterable
29 from typing import Iterator
30 from typing import List
31 from typing import Optional
32 from typing import Set
33 from typing import Tuple
34 from typing import Type
35 from typing import TypeVar
36 from typing import Union
37 import uuid
38 import warnings
39
40 from _pytest.compat import assert_never
41 from _pytest.outcomes import skip
42 from _pytest.warning_types import PytestWarning
43
44
45 LOCK_TIMEOUT = 60 * 60 * 24 * 3
46
47
48 _AnyPurePath = TypeVar("_AnyPurePath", bound=PurePath)
49
50 # The following function, variables and comments were
51 # copied from cpython 3.9 Lib/pathlib.py file.
52
53 # EBADF - guard against macOS `stat` throwing EBADF
54 _IGNORED_ERRORS = (ENOENT, ENOTDIR, EBADF, ELOOP)
55
56 _IGNORED_WINERRORS = (
57 21, # ERROR_NOT_READY - drive exists but is not accessible
58 1921, # ERROR_CANT_RESOLVE_FILENAME - fix for broken symlink pointing to itself
59 )
60
61
62 def _ignore_error(exception: Exception) -> bool:
63 return (
64 getattr(exception, "errno", None) in _IGNORED_ERRORS
65 or getattr(exception, "winerror", None) in _IGNORED_WINERRORS
66 )
67
68
69 def get_lock_path(path: _AnyPurePath) -> _AnyPurePath:
70 return path.joinpath(".lock")
71
72
73 def on_rm_rf_error(
74 func: Optional[Callable[..., Any]],
75 path: str,
76 excinfo: Union[
77 BaseException,
78 Tuple[Type[BaseException], BaseException, Optional[types.TracebackType]],
79 ],
80 *,
81 start_path: Path,
82 ) -> bool:
83 """Handle known read-only errors during rmtree.
84
85 The returned value is used only by our own tests.
86 """
87 if isinstance(excinfo, BaseException):
88 exc = excinfo
89 else:
90 exc = excinfo[1]
91
92 # Another process removed the file in the middle of the "rm_rf" (xdist for example).
93 # More context: https://github.com/pytest-dev/pytest/issues/5974#issuecomment-543799018
94 if isinstance(exc, FileNotFoundError):
95 return False
96
97 if not isinstance(exc, PermissionError):
98 warnings.warn(
99 PytestWarning(f"(rm_rf) error removing {path}\n{type(exc)}: {exc}")
100 )
101 return False
102
103 if func not in (os.rmdir, os.remove, os.unlink):
104 if func not in (os.open,):
105 warnings.warn(
106 PytestWarning(
107 f"(rm_rf) unknown function {func} when removing {path}:\n{type(exc)}: {exc}"
108 )
109 )
110 return False
111
112 # Chmod + retry.
113 import stat
114
115 def chmod_rw(p: str) -> None:
116 mode = os.stat(p).st_mode
117 os.chmod(p, mode | stat.S_IRUSR | stat.S_IWUSR)
118
119 # For files, we need to recursively go upwards in the directories to
120 # ensure they all are also writable.
121 p = Path(path)
122 if p.is_file():
123 for parent in p.parents:
124 chmod_rw(str(parent))
125 # Stop when we reach the original path passed to rm_rf.
126 if parent == start_path:
127 break
128 chmod_rw(str(path))
129
130 func(path)
131 return True
132
133
134 def ensure_extended_length_path(path: Path) -> Path:
135 """Get the extended-length version of a path (Windows).
136
137 On Windows, by default, the maximum length of a path (MAX_PATH) is 260
138 characters, and operations on paths longer than that fail. But it is possible
139 to overcome this by converting the path to "extended-length" form before
140 performing the operation:
141 https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#maximum-path-length-limitation
142
143 On Windows, this function returns the extended-length absolute version of path.
144 On other platforms it returns path unchanged.
145 """
146 if sys.platform.startswith("win32"):
147 path = path.resolve()
148 path = Path(get_extended_length_path_str(str(path)))
149 return path
150
151
152 def get_extended_length_path_str(path: str) -> str:
153 """Convert a path to a Windows extended length path."""
154 long_path_prefix = "\\\\?\\"
155 unc_long_path_prefix = "\\\\?\\UNC\\"
156 if path.startswith((long_path_prefix, unc_long_path_prefix)):
157 return path
158 # UNC
159 if path.startswith("\\\\"):
160 return unc_long_path_prefix + path[2:]
161 return long_path_prefix + path
162
163
164 def rm_rf(path: Path) -> None:
165 """Remove the path contents recursively, even if some elements
166 are read-only."""
167 path = ensure_extended_length_path(path)
168 onerror = partial(on_rm_rf_error, start_path=path)
169 if sys.version_info >= (3, 12):
170 shutil.rmtree(str(path), onexc=onerror)
171 else:
172 shutil.rmtree(str(path), onerror=onerror)
173
174
175 def find_prefixed(root: Path, prefix: str) -> Iterator["os.DirEntry[str]"]:
176 """Find all elements in root that begin with the prefix, case-insensitive."""
177 l_prefix = prefix.lower()
178 for x in os.scandir(root):
179 if x.name.lower().startswith(l_prefix):
180 yield x
181
182
183 def extract_suffixes(iter: Iterable["os.DirEntry[str]"], prefix: str) -> Iterator[str]:
184 """Return the parts of the paths following the prefix.
185
186 :param iter: Iterator over path names.
187 :param prefix: Expected prefix of the path names.
188 """
189 p_len = len(prefix)
190 for entry in iter:
191 yield entry.name[p_len:]
192
193
194 def find_suffixes(root: Path, prefix: str) -> Iterator[str]:
195 """Combine find_prefixes and extract_suffixes."""
196 return extract_suffixes(find_prefixed(root, prefix), prefix)
197
198
199 def parse_num(maybe_num: str) -> int:
200 """Parse number path suffixes, returns -1 on error."""
201 try:
202 return int(maybe_num)
203 except ValueError:
204 return -1
205
206
207 def _force_symlink(
208 root: Path, target: Union[str, PurePath], link_to: Union[str, Path]
209 ) -> None:
210 """Helper to create the current symlink.
211
212 It's full of race conditions that are reasonably OK to ignore
213 for the context of best effort linking to the latest test run.
214
215 The presumption being that in case of much parallelism
216 the inaccuracy is going to be acceptable.
217 """
218 current_symlink = root.joinpath(target)
219 try:
220 current_symlink.unlink()
221 except OSError:
222 pass
223 try:
224 current_symlink.symlink_to(link_to)
225 except Exception:
226 pass
227
228
229 def make_numbered_dir(root: Path, prefix: str, mode: int = 0o700) -> Path:
230 """Create a directory with an increased number as suffix for the given prefix."""
231 for i in range(10):
232 # try up to 10 times to create the folder
233 max_existing = max(map(parse_num, find_suffixes(root, prefix)), default=-1)
234 new_number = max_existing + 1
235 new_path = root.joinpath(f"{prefix}{new_number}")
236 try:
237 new_path.mkdir(mode=mode)
238 except Exception:
239 pass
240 else:
241 _force_symlink(root, prefix + "current", new_path)
242 return new_path
243 else:
244 raise OSError(
245 "could not create numbered dir with prefix "
246 f"{prefix} in {root} after 10 tries"
247 )
248
249
250 def create_cleanup_lock(p: Path) -> Path:
251 """Create a lock to prevent premature folder cleanup."""
252 lock_path = get_lock_path(p)
253 try:
254 fd = os.open(str(lock_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
255 except FileExistsError as e:
256 raise OSError(f"cannot create lockfile in {p}") from e
257 else:
258 pid = os.getpid()
259 spid = str(pid).encode()
260 os.write(fd, spid)
261 os.close(fd)
262 if not lock_path.is_file():
263 raise OSError("lock path got renamed after successful creation")
264 return lock_path
265
266
267 def register_cleanup_lock_removal(
268 lock_path: Path, register: Any = atexit.register
269 ) -> Any:
270 """Register a cleanup function for removing a lock, by default on atexit."""
271 pid = os.getpid()
272
273 def cleanup_on_exit(lock_path: Path = lock_path, original_pid: int = pid) -> None:
274 current_pid = os.getpid()
275 if current_pid != original_pid:
276 # fork
277 return
278 try:
279 lock_path.unlink()
280 except OSError:
281 pass
282
283 return register(cleanup_on_exit)
284
285
286 def maybe_delete_a_numbered_dir(path: Path) -> None:
287 """Remove a numbered directory if its lock can be obtained and it does
288 not seem to be in use."""
289 path = ensure_extended_length_path(path)
290 lock_path = None
291 try:
292 lock_path = create_cleanup_lock(path)
293 parent = path.parent
294
295 garbage = parent.joinpath(f"garbage-{uuid.uuid4()}")
296 path.rename(garbage)
297 rm_rf(garbage)
298 except OSError:
299 # known races:
300 # * other process did a cleanup at the same time
301 # * deletable folder was found
302 # * process cwd (Windows)
303 return
304 finally:
305 # If we created the lock, ensure we remove it even if we failed
306 # to properly remove the numbered dir.
307 if lock_path is not None:
308 try:
309 lock_path.unlink()
310 except OSError:
311 pass
312
313
314 def ensure_deletable(path: Path, consider_lock_dead_if_created_before: float) -> bool:
315 """Check if `path` is deletable based on whether the lock file is expired."""
316 if path.is_symlink():
317 return False
318 lock = get_lock_path(path)
319 try:
320 if not lock.is_file():
321 return True
322 except OSError:
323 # we might not have access to the lock file at all, in this case assume
324 # we don't have access to the entire directory (#7491).
325 return False
326 try:
327 lock_time = lock.stat().st_mtime
328 except Exception:
329 return False
330 else:
331 if lock_time < consider_lock_dead_if_created_before:
332 # We want to ignore any errors while trying to remove the lock such as:
333 # - PermissionDenied, like the file permissions have changed since the lock creation;
334 # - FileNotFoundError, in case another pytest process got here first;
335 # and any other cause of failure.
336 with contextlib.suppress(OSError):
337 lock.unlink()
338 return True
339 return False
340
341
342 def try_cleanup(path: Path, consider_lock_dead_if_created_before: float) -> None:
343 """Try to cleanup a folder if we can ensure it's deletable."""
344 if ensure_deletable(path, consider_lock_dead_if_created_before):
345 maybe_delete_a_numbered_dir(path)
346
347
348 def cleanup_candidates(root: Path, prefix: str, keep: int) -> Iterator[Path]:
349 """List candidates for numbered directories to be removed - follows py.path."""
350 max_existing = max(map(parse_num, find_suffixes(root, prefix)), default=-1)
351 max_delete = max_existing - keep
352 entries = find_prefixed(root, prefix)
353 entries, entries2 = itertools.tee(entries)
354 numbers = map(parse_num, extract_suffixes(entries2, prefix))
355 for entry, number in zip(entries, numbers):
356 if number <= max_delete:
357 yield Path(entry)
358
359
360 def cleanup_dead_symlinks(root: Path) -> None:
361 for left_dir in root.iterdir():
362 if left_dir.is_symlink():
363 if not left_dir.resolve().exists():
364 left_dir.unlink()
365
366
367 def cleanup_numbered_dir(
368 root: Path, prefix: str, keep: int, consider_lock_dead_if_created_before: float
369 ) -> None:
370 """Cleanup for lock driven numbered directories."""
371 if not root.exists():
372 return
373 for path in cleanup_candidates(root, prefix, keep):
374 try_cleanup(path, consider_lock_dead_if_created_before)
375 for path in root.glob("garbage-*"):
376 try_cleanup(path, consider_lock_dead_if_created_before)
377
378 cleanup_dead_symlinks(root)
379
380
381 def make_numbered_dir_with_cleanup(
382 root: Path,
383 prefix: str,
384 keep: int,
385 lock_timeout: float,
386 mode: int,
387 ) -> Path:
388 """Create a numbered dir with a cleanup lock and remove old ones."""
389 e = None
390 for i in range(10):
391 try:
392 p = make_numbered_dir(root, prefix, mode)
393 # Only lock the current dir when keep is not 0
394 if keep != 0:
395 lock_path = create_cleanup_lock(p)
396 register_cleanup_lock_removal(lock_path)
397 except Exception as exc:
398 e = exc
399 else:
400 consider_lock_dead_if_created_before = p.stat().st_mtime - lock_timeout
401 # Register a cleanup for program exit
402 atexit.register(
403 cleanup_numbered_dir,
404 root,
405 prefix,
406 keep,
407 consider_lock_dead_if_created_before,
408 )
409 return p
410 assert e is not None
411 raise e
412
413
414 def resolve_from_str(input: str, rootpath: Path) -> Path:
415 input = expanduser(input)
416 input = expandvars(input)
417 if isabs(input):
418 return Path(input)
419 else:
420 return rootpath.joinpath(input)
421
422
423 def fnmatch_ex(pattern: str, path: Union[str, "os.PathLike[str]"]) -> bool:
424 """A port of FNMatcher from py.path.common which works with PurePath() instances.
425
426 The difference between this algorithm and PurePath.match() is that the
427 latter matches "**" glob expressions for each part of the path, while
428 this algorithm uses the whole path instead.
429
430 For example:
431 "tests/foo/bar/doc/test_foo.py" matches pattern "tests/**/doc/test*.py"
432 with this algorithm, but not with PurePath.match().
433
434 This algorithm was ported to keep backward-compatibility with existing
435 settings which assume paths match according this logic.
436
437 References:
438 * https://bugs.python.org/issue29249
439 * https://bugs.python.org/issue34731
440 """
441 path = PurePath(path)
442 iswin32 = sys.platform.startswith("win")
443
444 if iswin32 and sep not in pattern and posix_sep in pattern:
445 # Running on Windows, the pattern has no Windows path separators,
446 # and the pattern has one or more Posix path separators. Replace
447 # the Posix path separators with the Windows path separator.
448 pattern = pattern.replace(posix_sep, sep)
449
450 if sep not in pattern:
451 name = path.name
452 else:
453 name = str(path)
454 if path.is_absolute() and not os.path.isabs(pattern):
455 pattern = f"*{os.sep}{pattern}"
456 return fnmatch.fnmatch(name, pattern)
457
458
459 def parts(s: str) -> Set[str]:
460 parts = s.split(sep)
461 return {sep.join(parts[: i + 1]) or sep for i in range(len(parts))}
462
463
464 def symlink_or_skip(
465 src: Union["os.PathLike[str]", str],
466 dst: Union["os.PathLike[str]", str],
467 **kwargs: Any,
468 ) -> None:
469 """Make a symlink, or skip the test in case symlinks are not supported."""
470 try:
471 os.symlink(src, dst, **kwargs)
472 except OSError as e:
473 skip(f"symlinks not supported: {e}")
474
475
476 class ImportMode(Enum):
477 """Possible values for `mode` parameter of `import_path`."""
478
479 prepend = "prepend"
480 append = "append"
481 importlib = "importlib"
482
483
484 class ImportPathMismatchError(ImportError):
485 """Raised on import_path() if there is a mismatch of __file__'s.
486
487 This can happen when `import_path` is called multiple times with different filenames that has
488 the same basename but reside in packages
489 (for example "/tests1/test_foo.py" and "/tests2/test_foo.py").
490 """
491
492
493 def import_path(
494 path: Union[str, "os.PathLike[str]"],
495 *,
496 mode: Union[str, ImportMode] = ImportMode.prepend,
497 root: Path,
498 consider_namespace_packages: bool,
499 ) -> ModuleType:
500 """
501 Import and return a module from the given path, which can be a file (a module) or
502 a directory (a package).
503
504 :param path:
505 Path to the file to import.
506
507 :param mode:
508 Controls the underlying import mechanism that will be used:
509
510 * ImportMode.prepend: the directory containing the module (or package, taking
511 `__init__.py` files into account) will be put at the *start* of `sys.path` before
512 being imported with `importlib.import_module`.
513
514 * ImportMode.append: same as `prepend`, but the directory will be appended
515 to the end of `sys.path`, if not already in `sys.path`.
516
517 * ImportMode.importlib: uses more fine control mechanisms provided by `importlib`
518 to import the module, which avoids having to muck with `sys.path` at all. It effectively
519 allows having same-named test modules in different places.
520
521 :param root:
522 Used as an anchor when mode == ImportMode.importlib to obtain
523 a unique name for the module being imported so it can safely be stored
524 into ``sys.modules``.
525
526 :param consider_namespace_packages:
527 If True, consider namespace packages when resolving module names.
528
529 :raises ImportPathMismatchError:
530 If after importing the given `path` and the module `__file__`
531 are different. Only raised in `prepend` and `append` modes.
532 """
533 path = Path(path)
534 mode = ImportMode(mode)
535
536 if not path.exists():
537 raise ImportError(path)
538
539 if mode is ImportMode.importlib:
540 # Try to import this module using the standard import mechanisms, but
541 # without touching sys.path.
542 try:
543 pkg_root, module_name = resolve_pkg_root_and_module_name(
544 path, consider_namespace_packages=consider_namespace_packages
545 )
546 except CouldNotResolvePathError:
547 pass
548 else:
549 # If the given module name is already in sys.modules, do not import it again.
550 with contextlib.suppress(KeyError):
551 return sys.modules[module_name]
552
553 mod = _import_module_using_spec(
554 module_name, path, pkg_root, insert_modules=False
555 )
556 if mod is not None:
557 return mod
558
559 # Could not import the module with the current sys.path, so we fall back
560 # to importing the file as a single module, not being a part of a package.
561 module_name = module_name_from_path(path, root)
562 with contextlib.suppress(KeyError):
563 return sys.modules[module_name]
564
565 mod = _import_module_using_spec(
566 module_name, path, path.parent, insert_modules=True
567 )
568 if mod is None:
569 raise ImportError(f"Can't find module {module_name} at location {path}")
570 return mod
571
572 try:
573 pkg_root, module_name = resolve_pkg_root_and_module_name(
574 path, consider_namespace_packages=consider_namespace_packages
575 )
576 except CouldNotResolvePathError:
577 pkg_root, module_name = path.parent, path.stem
578
579 # Change sys.path permanently: restoring it at the end of this function would cause surprising
580 # problems because of delayed imports: for example, a conftest.py file imported by this function
581 # might have local imports, which would fail at runtime if we restored sys.path.
582 if mode is ImportMode.append:
583 if str(pkg_root) not in sys.path:
584 sys.path.append(str(pkg_root))
585 elif mode is ImportMode.prepend:
586 if str(pkg_root) != sys.path[0]:
587 sys.path.insert(0, str(pkg_root))
588 else:
589 assert_never(mode)
590
591 importlib.import_module(module_name)
592
593 mod = sys.modules[module_name]
594 if path.name == "__init__.py":
595 return mod
596
597 ignore = os.environ.get("PY_IGNORE_IMPORTMISMATCH", "")
598 if ignore != "1":
599 module_file = mod.__file__
600 if module_file is None:
601 raise ImportPathMismatchError(module_name, module_file, path)
602
603 if module_file.endswith((".pyc", ".pyo")):
604 module_file = module_file[:-1]
605 if module_file.endswith(os.sep + "__init__.py"):
606 module_file = module_file[: -(len(os.sep + "__init__.py"))]
607
608 try:
609 is_same = _is_same(str(path), module_file)
610 except FileNotFoundError:
611 is_same = False
612
613 if not is_same:
614 raise ImportPathMismatchError(module_name, module_file, path)
615
616 return mod
617
618
619 def _import_module_using_spec(
620 module_name: str, module_path: Path, module_location: Path, *, insert_modules: bool
621 ) -> Optional[ModuleType]:
622 """
623 Tries to import a module by its canonical name, path to the .py file, and its
624 parent location.
625
626 :param insert_modules:
627 If True, will call insert_missing_modules to create empty intermediate modules
628 for made-up module names (when importing test files not reachable from sys.path).
629 """
630 # Checking with sys.meta_path first in case one of its hooks can import this module,
631 # such as our own assertion-rewrite hook.
632 for meta_importer in sys.meta_path:
633 spec = meta_importer.find_spec(module_name, [str(module_location)])
634 if spec_matches_module_path(spec, module_path):
635 break
636 else:
637 spec = importlib.util.spec_from_file_location(module_name, str(module_path))
638
639 if spec_matches_module_path(spec, module_path):
640 assert spec is not None
641 # Attempt to import the parent module, seems is our responsibility:
642 # https://github.com/python/cpython/blob/73906d5c908c1e0b73c5436faeff7d93698fc074/Lib/importlib/_bootstrap.py#L1308-L1311
643 parent_module_name, _, name = module_name.rpartition(".")
644 parent_module: Optional[ModuleType] = None
645 if parent_module_name:
646 parent_module = sys.modules.get(parent_module_name)
647 if parent_module is None:
648 # Find the directory of this module's parent.
649 parent_dir = (
650 module_path.parent.parent
651 if module_path.name == "__init__.py"
652 else module_path.parent
653 )
654 # Consider the parent module path as its __init__.py file, if it has one.
655 parent_module_path = (
656 parent_dir / "__init__.py"
657 if (parent_dir / "__init__.py").is_file()
658 else parent_dir
659 )
660 parent_module = _import_module_using_spec(
661 parent_module_name,
662 parent_module_path,
663 parent_dir,
664 insert_modules=insert_modules,
665 )
666
667 # Find spec and import this module.
668 mod = importlib.util.module_from_spec(spec)
669 sys.modules[module_name] = mod
670 spec.loader.exec_module(mod) # type: ignore[union-attr]
671
672 # Set this module as an attribute of the parent module (#12194).
673 if parent_module is not None:
674 setattr(parent_module, name, mod)
675
676 if insert_modules:
677 insert_missing_modules(sys.modules, module_name)
678 return mod
679
680 return None
681
682
683 def spec_matches_module_path(
684 module_spec: Optional[ModuleSpec], module_path: Path
685 ) -> bool:
686 """Return true if the given ModuleSpec can be used to import the given module path."""
687 if module_spec is None or module_spec.origin is None:
688 return False
689
690 return Path(module_spec.origin) == module_path
691
692
693 # Implement a special _is_same function on Windows which returns True if the two filenames
694 # compare equal, to circumvent os.path.samefile returning False for mounts in UNC (#7678).
695 if sys.platform.startswith("win"):
696
697 def _is_same(f1: str, f2: str) -> bool:
698 return Path(f1) == Path(f2) or os.path.samefile(f1, f2)
699
700 else:
701
702 def _is_same(f1: str, f2: str) -> bool:
703 return os.path.samefile(f1, f2)
704
705
706 def module_name_from_path(path: Path, root: Path) -> str:
707 """
708 Return a dotted module name based on the given path, anchored on root.
709
710 For example: path="projects/src/tests/test_foo.py" and root="/projects", the
711 resulting module name will be "src.tests.test_foo".
712 """
713 path = path.with_suffix("")
714 try:
715 relative_path = path.relative_to(root)
716 except ValueError:
717 # If we can't get a relative path to root, use the full path, except
718 # for the first part ("d:\\" or "/" depending on the platform, for example).
719 path_parts = path.parts[1:]
720 else:
721 # Use the parts for the relative path to the root path.
722 path_parts = relative_path.parts
723
724 # Module name for packages do not contain the __init__ file, unless
725 # the `__init__.py` file is at the root.
726 if len(path_parts) >= 2 and path_parts[-1] == "__init__":
727 path_parts = path_parts[:-1]
728
729 # Module names cannot contain ".", normalize them to "_". This prevents
730 # a directory having a "." in the name (".env.310" for example) causing extra intermediate modules.
731 # Also, important to replace "." at the start of paths, as those are considered relative imports.
732 path_parts = tuple(x.replace(".", "_") for x in path_parts)
733
734 return ".".join(path_parts)
735
736
737 def insert_missing_modules(modules: Dict[str, ModuleType], module_name: str) -> None:
738 """
739 Used by ``import_path`` to create intermediate modules when using mode=importlib.
740
741 When we want to import a module as "src.tests.test_foo" for example, we need
742 to create empty modules "src" and "src.tests" after inserting "src.tests.test_foo",
743 otherwise "src.tests.test_foo" is not importable by ``__import__``.
744 """
745 module_parts = module_name.split(".")
746 while module_name:
747 parent_module_name, _, child_name = module_name.rpartition(".")
748 if parent_module_name:
749 parent_module = modules.get(parent_module_name)
750 if parent_module is None:
751 try:
752 # If sys.meta_path is empty, calling import_module will issue
753 # a warning and raise ModuleNotFoundError. To avoid the
754 # warning, we check sys.meta_path explicitly and raise the error
755 # ourselves to fall back to creating a dummy module.
756 if not sys.meta_path:
757 raise ModuleNotFoundError
758 parent_module = importlib.import_module(parent_module_name)
759 except ModuleNotFoundError:
760 parent_module = ModuleType(
761 module_name,
762 doc="Empty module created by pytest's importmode=importlib.",
763 )
764 modules[parent_module_name] = parent_module
765
766 # Add child attribute to the parent that can reference the child
767 # modules.
768 if not hasattr(parent_module, child_name):
769 setattr(parent_module, child_name, modules[module_name])
770
771 module_parts.pop(-1)
772 module_name = ".".join(module_parts)
773
774
775 def resolve_package_path(path: Path) -> Optional[Path]:
776 """Return the Python package path by looking for the last
777 directory upwards which still contains an __init__.py.
778
779 Returns None if it cannot be determined.
780 """
781 result = None
782 for parent in itertools.chain((path,), path.parents):
783 if parent.is_dir():
784 if not (parent / "__init__.py").is_file():
785 break
786 if not parent.name.isidentifier():
787 break
788 result = parent
789 return result
790
791
792 def resolve_pkg_root_and_module_name(
793 path: Path, *, consider_namespace_packages: bool = False
794 ) -> Tuple[Path, str]:
795 """
796 Return the path to the directory of the root package that contains the
797 given Python file, and its module name:
798
799 src/
800 app/
801 __init__.py
802 core/
803 __init__.py
804 models.py
805
806 Passing the full path to `models.py` will yield Path("src") and "app.core.models".
807
808 If consider_namespace_packages is True, then we additionally check upwards in the hierarchy
809 for namespace packages:
810
811 https://packaging.python.org/en/latest/guides/packaging-namespace-packages
812
813 Raises CouldNotResolvePathError if the given path does not belong to a package (missing any __init__.py files).
814 """
815 pkg_root: Optional[Path] = None
816 pkg_path = resolve_package_path(path)
817 if pkg_path is not None:
818 pkg_root = pkg_path.parent
819 if consider_namespace_packages:
820 start = pkg_root if pkg_root is not None else path.parent
821 for candidate in (start, *start.parents):
822 module_name = compute_module_name(candidate, path)
823 if module_name and is_importable(module_name, path):
824 # Point the pkg_root to the root of the namespace package.
825 pkg_root = candidate
826 break
827
828 if pkg_root is not None:
829 module_name = compute_module_name(pkg_root, path)
830 if module_name:
831 return pkg_root, module_name
832
833 raise CouldNotResolvePathError(f"Could not resolve for {path}")
834
835
836 def is_importable(module_name: str, module_path: Path) -> bool:
837 """
838 Return if the given module path could be imported normally by Python, akin to the user
839 entering the REPL and importing the corresponding module name directly, and corresponds
840 to the module_path specified.
841
842 :param module_name:
843 Full module name that we want to check if is importable.
844 For example, "app.models".
845
846 :param module_path:
847 Full path to the python module/package we want to check if is importable.
848 For example, "/projects/src/app/models.py".
849 """
850 try:
851 # Note this is different from what we do in ``_import_module_using_spec``, where we explicitly search through
852 # sys.meta_path to be able to pass the path of the module that we want to import (``meta_importer.find_spec``).
853 # Using importlib.util.find_spec() is different, it gives the same results as trying to import
854 # the module normally in the REPL.
855 spec = importlib.util.find_spec(module_name)
856 except (ImportError, ValueError, ImportWarning):
857 return False
858 else:
859 return spec_matches_module_path(spec, module_path)
860
861
862 def compute_module_name(root: Path, module_path: Path) -> Optional[str]:
863 """Compute a module name based on a path and a root anchor."""
864 try:
865 path_without_suffix = module_path.with_suffix("")
866 except ValueError:
867 # Empty paths (such as Path.cwd()) might break meta_path hooks (like our own assertion rewriter).
868 return None
869
870 try:
871 relative = path_without_suffix.relative_to(root)
872 except ValueError: # pragma: no cover
873 return None
874 names = list(relative.parts)
875 if not names:
876 return None
877 if names[-1] == "__init__":
878 names.pop()
879 return ".".join(names)
880
881
882 class CouldNotResolvePathError(Exception):
883 """Custom exception raised by resolve_pkg_root_and_module_name."""
884
885
886 def scandir(
887 path: Union[str, "os.PathLike[str]"],
888 sort_key: Callable[["os.DirEntry[str]"], object] = lambda entry: entry.name,
889 ) -> List["os.DirEntry[str]"]:
890 """Scan a directory recursively, in breadth-first order.
891
892 The returned entries are sorted according to the given key.
893 The default is to sort by name.
894 """
895 entries = []
896 with os.scandir(path) as s:
897 # Skip entries with symlink loops and other brokenness, so the caller
898 # doesn't have to deal with it.
899 for entry in s:
900 try:
901 entry.is_file()
902 except OSError as err:
903 if _ignore_error(err):
904 continue
905 raise
906 entries.append(entry)
907 entries.sort(key=sort_key) # type: ignore[arg-type]
908 return entries
909
910
911 def visit(
912 path: Union[str, "os.PathLike[str]"], recurse: Callable[["os.DirEntry[str]"], bool]
913 ) -> Iterator["os.DirEntry[str]"]:
914 """Walk a directory recursively, in breadth-first order.
915
916 The `recurse` predicate determines whether a directory is recursed.
917
918 Entries at each directory level are sorted.
919 """
920 entries = scandir(path)
921 yield from entries
922 for entry in entries:
923 if entry.is_dir() and recurse(entry):
924 yield from visit(entry.path, recurse)
925
926
927 def absolutepath(path: "Union[str, os.PathLike[str]]") -> Path:
928 """Convert a path to an absolute path using os.path.abspath.
929
930 Prefer this over Path.resolve() (see #6523).
931 Prefer this over Path.absolute() (not public, doesn't normalize).
932 """
933 return Path(os.path.abspath(path))
934
935
936 def commonpath(path1: Path, path2: Path) -> Optional[Path]:
937 """Return the common part shared with the other path, or None if there is
938 no common part.
939
940 If one path is relative and one is absolute, returns None.
941 """
942 try:
943 return Path(os.path.commonpath((str(path1), str(path2))))
944 except ValueError:
945 return None
946
947
948 def bestrelpath(directory: Path, dest: Path) -> str:
949 """Return a string which is a relative path from directory to dest such
950 that directory/bestrelpath == dest.
951
952 The paths must be either both absolute or both relative.
953
954 If no such path can be determined, returns dest.
955 """
956 assert isinstance(directory, Path)
957 assert isinstance(dest, Path)
958 if dest == directory:
959 return os.curdir
960 # Find the longest common directory.
961 base = commonpath(directory, dest)
962 # Can be the case on Windows for two absolute paths on different drives.
963 # Can be the case for two relative paths without common prefix.
964 # Can be the case for a relative path and an absolute path.
965 if not base:
966 return str(dest)
967 reldirectory = directory.relative_to(base)
968 reldest = dest.relative_to(base)
969 return os.path.join(
970 # Back from directory to base.
971 *([os.pardir] * len(reldirectory.parts)),
972 # Forward from base to dest.
973 *reldest.parts,
974 )
975
976
977 def safe_exists(p: Path) -> bool:
978 """Like Path.exists(), but account for input arguments that might be too long (#11394)."""
979 try:
980 return p.exists()
981 except (ValueError, OSError):
982 # ValueError: stat: path too long for Windows
983 # OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect
984 return False