You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

655 lines
21KB

  1. import atexit
  2. import contextlib
  3. import fnmatch
  4. import importlib.util
  5. import itertools
  6. import os
  7. import shutil
  8. import sys
  9. import uuid
  10. import warnings
  11. from enum import Enum
  12. from errno import EBADF
  13. from errno import ELOOP
  14. from errno import ENOENT
  15. from errno import ENOTDIR
  16. from functools import partial
  17. from os.path import expanduser
  18. from os.path import expandvars
  19. from os.path import isabs
  20. from os.path import sep
  21. from pathlib import Path
  22. from pathlib import PurePath
  23. from posixpath import sep as posix_sep
  24. from types import ModuleType
  25. from typing import Callable
  26. from typing import Iterable
  27. from typing import Iterator
  28. from typing import Optional
  29. from typing import Set
  30. from typing import TypeVar
  31. from typing import Union
  32. import py
  33. from _pytest.compat import assert_never
  34. from _pytest.outcomes import skip
  35. from _pytest.warning_types import PytestWarning
  36. LOCK_TIMEOUT = 60 * 60 * 24 * 3
  37. _AnyPurePath = TypeVar("_AnyPurePath", bound=PurePath)
  38. # The following function, variables and comments were
  39. # copied from cpython 3.9 Lib/pathlib.py file.
  40. # EBADF - guard against macOS `stat` throwing EBADF
  41. _IGNORED_ERRORS = (ENOENT, ENOTDIR, EBADF, ELOOP)
  42. _IGNORED_WINERRORS = (
  43. 21, # ERROR_NOT_READY - drive exists but is not accessible
  44. 1921, # ERROR_CANT_RESOLVE_FILENAME - fix for broken symlink pointing to itself
  45. )
  46. def _ignore_error(exception):
  47. return (
  48. getattr(exception, "errno", None) in _IGNORED_ERRORS
  49. or getattr(exception, "winerror", None) in _IGNORED_WINERRORS
  50. )
  51. def get_lock_path(path: _AnyPurePath) -> _AnyPurePath:
  52. return path.joinpath(".lock")
  53. def on_rm_rf_error(func, path: str, exc, *, start_path: Path) -> bool:
  54. """Handle known read-only errors during rmtree.
  55. The returned value is used only by our own tests.
  56. """
  57. exctype, excvalue = exc[:2]
  58. # Another process removed the file in the middle of the "rm_rf" (xdist for example).
  59. # More context: https://github.com/pytest-dev/pytest/issues/5974#issuecomment-543799018
  60. if isinstance(excvalue, FileNotFoundError):
  61. return False
  62. if not isinstance(excvalue, PermissionError):
  63. warnings.warn(
  64. PytestWarning(f"(rm_rf) error removing {path}\n{exctype}: {excvalue}")
  65. )
  66. return False
  67. if func not in (os.rmdir, os.remove, os.unlink):
  68. if func not in (os.open,):
  69. warnings.warn(
  70. PytestWarning(
  71. "(rm_rf) unknown function {} when removing {}:\n{}: {}".format(
  72. func, path, exctype, excvalue
  73. )
  74. )
  75. )
  76. return False
  77. # Chmod + retry.
  78. import stat
  79. def chmod_rw(p: str) -> None:
  80. mode = os.stat(p).st_mode
  81. os.chmod(p, mode | stat.S_IRUSR | stat.S_IWUSR)
  82. # For files, we need to recursively go upwards in the directories to
  83. # ensure they all are also writable.
  84. p = Path(path)
  85. if p.is_file():
  86. for parent in p.parents:
  87. chmod_rw(str(parent))
  88. # Stop when we reach the original path passed to rm_rf.
  89. if parent == start_path:
  90. break
  91. chmod_rw(str(path))
  92. func(path)
  93. return True
  94. def ensure_extended_length_path(path: Path) -> Path:
  95. """Get the extended-length version of a path (Windows).
  96. On Windows, by default, the maximum length of a path (MAX_PATH) is 260
  97. characters, and operations on paths longer than that fail. But it is possible
  98. to overcome this by converting the path to "extended-length" form before
  99. performing the operation:
  100. https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#maximum-path-length-limitation
  101. On Windows, this function returns the extended-length absolute version of path.
  102. On other platforms it returns path unchanged.
  103. """
  104. if sys.platform.startswith("win32"):
  105. path = path.resolve()
  106. path = Path(get_extended_length_path_str(str(path)))
  107. return path
  108. def get_extended_length_path_str(path: str) -> str:
  109. """Convert a path to a Windows extended length path."""
  110. long_path_prefix = "\\\\?\\"
  111. unc_long_path_prefix = "\\\\?\\UNC\\"
  112. if path.startswith((long_path_prefix, unc_long_path_prefix)):
  113. return path
  114. # UNC
  115. if path.startswith("\\\\"):
  116. return unc_long_path_prefix + path[2:]
  117. return long_path_prefix + path
  118. def rm_rf(path: Path) -> None:
  119. """Remove the path contents recursively, even if some elements
  120. are read-only."""
  121. path = ensure_extended_length_path(path)
  122. onerror = partial(on_rm_rf_error, start_path=path)
  123. shutil.rmtree(str(path), onerror=onerror)
  124. def find_prefixed(root: Path, prefix: str) -> Iterator[Path]:
  125. """Find all elements in root that begin with the prefix, case insensitive."""
  126. l_prefix = prefix.lower()
  127. for x in root.iterdir():
  128. if x.name.lower().startswith(l_prefix):
  129. yield x
  130. def extract_suffixes(iter: Iterable[PurePath], prefix: str) -> Iterator[str]:
  131. """Return the parts of the paths following the prefix.
  132. :param iter: Iterator over path names.
  133. :param prefix: Expected prefix of the path names.
  134. """
  135. p_len = len(prefix)
  136. for p in iter:
  137. yield p.name[p_len:]
  138. def find_suffixes(root: Path, prefix: str) -> Iterator[str]:
  139. """Combine find_prefixes and extract_suffixes."""
  140. return extract_suffixes(find_prefixed(root, prefix), prefix)
  141. def parse_num(maybe_num) -> int:
  142. """Parse number path suffixes, returns -1 on error."""
  143. try:
  144. return int(maybe_num)
  145. except ValueError:
  146. return -1
  147. def _force_symlink(
  148. root: Path, target: Union[str, PurePath], link_to: Union[str, Path]
  149. ) -> None:
  150. """Helper to create the current symlink.
  151. It's full of race conditions that are reasonably OK to ignore
  152. for the context of best effort linking to the latest test run.
  153. The presumption being that in case of much parallelism
  154. the inaccuracy is going to be acceptable.
  155. """
  156. current_symlink = root.joinpath(target)
  157. try:
  158. current_symlink.unlink()
  159. except OSError:
  160. pass
  161. try:
  162. current_symlink.symlink_to(link_to)
  163. except Exception:
  164. pass
  165. def make_numbered_dir(root: Path, prefix: str, mode: int = 0o700) -> Path:
  166. """Create a directory with an increased number as suffix for the given prefix."""
  167. for i in range(10):
  168. # try up to 10 times to create the folder
  169. max_existing = max(map(parse_num, find_suffixes(root, prefix)), default=-1)
  170. new_number = max_existing + 1
  171. new_path = root.joinpath(f"{prefix}{new_number}")
  172. try:
  173. new_path.mkdir(mode=mode)
  174. except Exception:
  175. pass
  176. else:
  177. _force_symlink(root, prefix + "current", new_path)
  178. return new_path
  179. else:
  180. raise OSError(
  181. "could not create numbered dir with prefix "
  182. "{prefix} in {root} after 10 tries".format(prefix=prefix, root=root)
  183. )
  184. def create_cleanup_lock(p: Path) -> Path:
  185. """Create a lock to prevent premature folder cleanup."""
  186. lock_path = get_lock_path(p)
  187. try:
  188. fd = os.open(str(lock_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
  189. except FileExistsError as e:
  190. raise OSError(f"cannot create lockfile in {p}") from e
  191. else:
  192. pid = os.getpid()
  193. spid = str(pid).encode()
  194. os.write(fd, spid)
  195. os.close(fd)
  196. if not lock_path.is_file():
  197. raise OSError("lock path got renamed after successful creation")
  198. return lock_path
  199. def register_cleanup_lock_removal(lock_path: Path, register=atexit.register):
  200. """Register a cleanup function for removing a lock, by default on atexit."""
  201. pid = os.getpid()
  202. def cleanup_on_exit(lock_path: Path = lock_path, original_pid: int = pid) -> None:
  203. current_pid = os.getpid()
  204. if current_pid != original_pid:
  205. # fork
  206. return
  207. try:
  208. lock_path.unlink()
  209. except OSError:
  210. pass
  211. return register(cleanup_on_exit)
  212. def maybe_delete_a_numbered_dir(path: Path) -> None:
  213. """Remove a numbered directory if its lock can be obtained and it does
  214. not seem to be in use."""
  215. path = ensure_extended_length_path(path)
  216. lock_path = None
  217. try:
  218. lock_path = create_cleanup_lock(path)
  219. parent = path.parent
  220. garbage = parent.joinpath(f"garbage-{uuid.uuid4()}")
  221. path.rename(garbage)
  222. rm_rf(garbage)
  223. except OSError:
  224. # known races:
  225. # * other process did a cleanup at the same time
  226. # * deletable folder was found
  227. # * process cwd (Windows)
  228. return
  229. finally:
  230. # If we created the lock, ensure we remove it even if we failed
  231. # to properly remove the numbered dir.
  232. if lock_path is not None:
  233. try:
  234. lock_path.unlink()
  235. except OSError:
  236. pass
  237. def ensure_deletable(path: Path, consider_lock_dead_if_created_before: float) -> bool:
  238. """Check if `path` is deletable based on whether the lock file is expired."""
  239. if path.is_symlink():
  240. return False
  241. lock = get_lock_path(path)
  242. try:
  243. if not lock.is_file():
  244. return True
  245. except OSError:
  246. # we might not have access to the lock file at all, in this case assume
  247. # we don't have access to the entire directory (#7491).
  248. return False
  249. try:
  250. lock_time = lock.stat().st_mtime
  251. except Exception:
  252. return False
  253. else:
  254. if lock_time < consider_lock_dead_if_created_before:
  255. # We want to ignore any errors while trying to remove the lock such as:
  256. # - PermissionDenied, like the file permissions have changed since the lock creation;
  257. # - FileNotFoundError, in case another pytest process got here first;
  258. # and any other cause of failure.
  259. with contextlib.suppress(OSError):
  260. lock.unlink()
  261. return True
  262. return False
  263. def try_cleanup(path: Path, consider_lock_dead_if_created_before: float) -> None:
  264. """Try to cleanup a folder if we can ensure it's deletable."""
  265. if ensure_deletable(path, consider_lock_dead_if_created_before):
  266. maybe_delete_a_numbered_dir(path)
  267. def cleanup_candidates(root: Path, prefix: str, keep: int) -> Iterator[Path]:
  268. """List candidates for numbered directories to be removed - follows py.path."""
  269. max_existing = max(map(parse_num, find_suffixes(root, prefix)), default=-1)
  270. max_delete = max_existing - keep
  271. paths = find_prefixed(root, prefix)
  272. paths, paths2 = itertools.tee(paths)
  273. numbers = map(parse_num, extract_suffixes(paths2, prefix))
  274. for path, number in zip(paths, numbers):
  275. if number <= max_delete:
  276. yield path
  277. def cleanup_numbered_dir(
  278. root: Path, prefix: str, keep: int, consider_lock_dead_if_created_before: float
  279. ) -> None:
  280. """Cleanup for lock driven numbered directories."""
  281. for path in cleanup_candidates(root, prefix, keep):
  282. try_cleanup(path, consider_lock_dead_if_created_before)
  283. for path in root.glob("garbage-*"):
  284. try_cleanup(path, consider_lock_dead_if_created_before)
  285. def make_numbered_dir_with_cleanup(
  286. root: Path, prefix: str, keep: int, lock_timeout: float, mode: int,
  287. ) -> Path:
  288. """Create a numbered dir with a cleanup lock and remove old ones."""
  289. e = None
  290. for i in range(10):
  291. try:
  292. p = make_numbered_dir(root, prefix, mode)
  293. lock_path = create_cleanup_lock(p)
  294. register_cleanup_lock_removal(lock_path)
  295. except Exception as exc:
  296. e = exc
  297. else:
  298. consider_lock_dead_if_created_before = p.stat().st_mtime - lock_timeout
  299. # Register a cleanup for program exit
  300. atexit.register(
  301. cleanup_numbered_dir,
  302. root,
  303. prefix,
  304. keep,
  305. consider_lock_dead_if_created_before,
  306. )
  307. return p
  308. assert e is not None
  309. raise e
  310. def resolve_from_str(input: str, rootpath: Path) -> Path:
  311. input = expanduser(input)
  312. input = expandvars(input)
  313. if isabs(input):
  314. return Path(input)
  315. else:
  316. return rootpath.joinpath(input)
  317. def fnmatch_ex(pattern: str, path) -> bool:
  318. """A port of FNMatcher from py.path.common which works with PurePath() instances.
  319. The difference between this algorithm and PurePath.match() is that the
  320. latter matches "**" glob expressions for each part of the path, while
  321. this algorithm uses the whole path instead.
  322. For example:
  323. "tests/foo/bar/doc/test_foo.py" matches pattern "tests/**/doc/test*.py"
  324. with this algorithm, but not with PurePath.match().
  325. This algorithm was ported to keep backward-compatibility with existing
  326. settings which assume paths match according this logic.
  327. References:
  328. * https://bugs.python.org/issue29249
  329. * https://bugs.python.org/issue34731
  330. """
  331. path = PurePath(path)
  332. iswin32 = sys.platform.startswith("win")
  333. if iswin32 and sep not in pattern and posix_sep in pattern:
  334. # Running on Windows, the pattern has no Windows path separators,
  335. # and the pattern has one or more Posix path separators. Replace
  336. # the Posix path separators with the Windows path separator.
  337. pattern = pattern.replace(posix_sep, sep)
  338. if sep not in pattern:
  339. name = path.name
  340. else:
  341. name = str(path)
  342. if path.is_absolute() and not os.path.isabs(pattern):
  343. pattern = f"*{os.sep}{pattern}"
  344. return fnmatch.fnmatch(name, pattern)
  345. def parts(s: str) -> Set[str]:
  346. parts = s.split(sep)
  347. return {sep.join(parts[: i + 1]) or sep for i in range(len(parts))}
  348. def symlink_or_skip(src, dst, **kwargs):
  349. """Make a symlink, or skip the test in case symlinks are not supported."""
  350. try:
  351. os.symlink(str(src), str(dst), **kwargs)
  352. except OSError as e:
  353. skip(f"symlinks not supported: {e}")
  354. class ImportMode(Enum):
  355. """Possible values for `mode` parameter of `import_path`."""
  356. prepend = "prepend"
  357. append = "append"
  358. importlib = "importlib"
  359. class ImportPathMismatchError(ImportError):
  360. """Raised on import_path() if there is a mismatch of __file__'s.
  361. This can happen when `import_path` is called multiple times with different filenames that has
  362. the same basename but reside in packages
  363. (for example "/tests1/test_foo.py" and "/tests2/test_foo.py").
  364. """
  365. def import_path(
  366. p: Union[str, py.path.local, Path],
  367. *,
  368. mode: Union[str, ImportMode] = ImportMode.prepend,
  369. ) -> ModuleType:
  370. """Import and return a module from the given path, which can be a file (a module) or
  371. a directory (a package).
  372. The import mechanism used is controlled by the `mode` parameter:
  373. * `mode == ImportMode.prepend`: the directory containing the module (or package, taking
  374. `__init__.py` files into account) will be put at the *start* of `sys.path` before
  375. being imported with `__import__.
  376. * `mode == ImportMode.append`: same as `prepend`, but the directory will be appended
  377. to the end of `sys.path`, if not already in `sys.path`.
  378. * `mode == ImportMode.importlib`: uses more fine control mechanisms provided by `importlib`
  379. to import the module, which avoids having to use `__import__` and muck with `sys.path`
  380. at all. It effectively allows having same-named test modules in different places.
  381. :raises ImportPathMismatchError:
  382. If after importing the given `path` and the module `__file__`
  383. are different. Only raised in `prepend` and `append` modes.
  384. """
  385. mode = ImportMode(mode)
  386. path = Path(str(p))
  387. if not path.exists():
  388. raise ImportError(path)
  389. if mode is ImportMode.importlib:
  390. module_name = path.stem
  391. for meta_importer in sys.meta_path:
  392. spec = meta_importer.find_spec(module_name, [str(path.parent)])
  393. if spec is not None:
  394. break
  395. else:
  396. spec = importlib.util.spec_from_file_location(module_name, str(path))
  397. if spec is None:
  398. raise ImportError(
  399. "Can't find module {} at location {}".format(module_name, str(path))
  400. )
  401. mod = importlib.util.module_from_spec(spec)
  402. spec.loader.exec_module(mod) # type: ignore[union-attr]
  403. return mod
  404. pkg_path = resolve_package_path(path)
  405. if pkg_path is not None:
  406. pkg_root = pkg_path.parent
  407. names = list(path.with_suffix("").relative_to(pkg_root).parts)
  408. if names[-1] == "__init__":
  409. names.pop()
  410. module_name = ".".join(names)
  411. else:
  412. pkg_root = path.parent
  413. module_name = path.stem
  414. # Change sys.path permanently: restoring it at the end of this function would cause surprising
  415. # problems because of delayed imports: for example, a conftest.py file imported by this function
  416. # might have local imports, which would fail at runtime if we restored sys.path.
  417. if mode is ImportMode.append:
  418. if str(pkg_root) not in sys.path:
  419. sys.path.append(str(pkg_root))
  420. elif mode is ImportMode.prepend:
  421. if str(pkg_root) != sys.path[0]:
  422. sys.path.insert(0, str(pkg_root))
  423. else:
  424. assert_never(mode)
  425. importlib.import_module(module_name)
  426. mod = sys.modules[module_name]
  427. if path.name == "__init__.py":
  428. return mod
  429. ignore = os.environ.get("PY_IGNORE_IMPORTMISMATCH", "")
  430. if ignore != "1":
  431. module_file = mod.__file__
  432. if module_file.endswith((".pyc", ".pyo")):
  433. module_file = module_file[:-1]
  434. if module_file.endswith(os.path.sep + "__init__.py"):
  435. module_file = module_file[: -(len(os.path.sep + "__init__.py"))]
  436. try:
  437. is_same = _is_same(str(path), module_file)
  438. except FileNotFoundError:
  439. is_same = False
  440. if not is_same:
  441. raise ImportPathMismatchError(module_name, module_file, path)
  442. return mod
  443. # Implement a special _is_same function on Windows which returns True if the two filenames
  444. # compare equal, to circumvent os.path.samefile returning False for mounts in UNC (#7678).
  445. if sys.platform.startswith("win"):
  446. def _is_same(f1: str, f2: str) -> bool:
  447. return Path(f1) == Path(f2) or os.path.samefile(f1, f2)
  448. else:
  449. def _is_same(f1: str, f2: str) -> bool:
  450. return os.path.samefile(f1, f2)
  451. def resolve_package_path(path: Path) -> Optional[Path]:
  452. """Return the Python package path by looking for the last
  453. directory upwards which still contains an __init__.py.
  454. Returns None if it can not be determined.
  455. """
  456. result = None
  457. for parent in itertools.chain((path,), path.parents):
  458. if parent.is_dir():
  459. if not parent.joinpath("__init__.py").is_file():
  460. break
  461. if not parent.name.isidentifier():
  462. break
  463. result = parent
  464. return result
  465. def visit(
  466. path: str, recurse: Callable[["os.DirEntry[str]"], bool]
  467. ) -> Iterator["os.DirEntry[str]"]:
  468. """Walk a directory recursively, in breadth-first order.
  469. Entries at each directory level are sorted.
  470. """
  471. # Skip entries with symlink loops and other brokenness, so the caller doesn't
  472. # have to deal with it.
  473. entries = []
  474. for entry in os.scandir(path):
  475. try:
  476. entry.is_file()
  477. except OSError as err:
  478. if _ignore_error(err):
  479. continue
  480. raise
  481. entries.append(entry)
  482. entries.sort(key=lambda entry: entry.name)
  483. yield from entries
  484. for entry in entries:
  485. if entry.is_dir() and recurse(entry):
  486. yield from visit(entry.path, recurse)
  487. def absolutepath(path: Union[Path, str]) -> Path:
  488. """Convert a path to an absolute path using os.path.abspath.
  489. Prefer this over Path.resolve() (see #6523).
  490. Prefer this over Path.absolute() (not public, doesn't normalize).
  491. """
  492. return Path(os.path.abspath(str(path)))
  493. def commonpath(path1: Path, path2: Path) -> Optional[Path]:
  494. """Return the common part shared with the other path, or None if there is
  495. no common part.
  496. If one path is relative and one is absolute, returns None.
  497. """
  498. try:
  499. return Path(os.path.commonpath((str(path1), str(path2))))
  500. except ValueError:
  501. return None
  502. def bestrelpath(directory: Path, dest: Path) -> str:
  503. """Return a string which is a relative path from directory to dest such
  504. that directory/bestrelpath == dest.
  505. The paths must be either both absolute or both relative.
  506. If no such path can be determined, returns dest.
  507. """
  508. if dest == directory:
  509. return os.curdir
  510. # Find the longest common directory.
  511. base = commonpath(directory, dest)
  512. # Can be the case on Windows for two absolute paths on different drives.
  513. # Can be the case for two relative paths without common prefix.
  514. # Can be the case for a relative path and an absolute path.
  515. if not base:
  516. return str(dest)
  517. reldirectory = directory.relative_to(base)
  518. reldest = dest.relative_to(base)
  519. return os.path.join(
  520. # Back from directory to base.
  521. *([os.pardir] * len(reldirectory.parts)),
  522. # Forward from base to dest.
  523. *reldest.parts,
  524. )