Debian Codegraph @

lib-python/3/test/support/os_helper.py

raw symbols SCIP
1 import collections.abc
2 import contextlib
3 import errno
4 import os
5 import re
6 import stat
7 import sys
8 import time
9 import unittest
10 import warnings
11
12
13 # Filename used for testing
14 if os.name == 'java':
15 # Jython disallows @ in module names
16 TESTFN_ASCII = '$test'
17 else:
18 TESTFN_ASCII = '@test'
19
20 # Disambiguate TESTFN for parallel testing, while letting it remain a valid
21 # module name.
22 TESTFN_ASCII = "{}_{}_tmp".format(TESTFN_ASCII, os.getpid())
23
24 # TESTFN_UNICODE is a non-ascii filename
25 TESTFN_UNICODE = TESTFN_ASCII + "-\xe0\xf2\u0258\u0141\u011f"
26 if sys.platform == 'darwin':
27 # In Mac OS X's VFS API file names are, by definition, canonically
28 # decomposed Unicode, encoded using UTF-8. See QA1173:
29 # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
30 import unicodedata
31 TESTFN_UNICODE = unicodedata.normalize('NFD', TESTFN_UNICODE)
32
33 # TESTFN_UNENCODABLE is a filename (str type) that should *not* be able to be
34 # encoded by the filesystem encoding (in strict mode). It can be None if we
35 # cannot generate such filename.
36 TESTFN_UNENCODABLE = None
37 if os.name == 'nt':
38 # skip win32s (0) or Windows 9x/ME (1)
39 if sys.getwindowsversion().platform >= 2:
40 # Different kinds of characters from various languages to minimize the
41 # probability that the whole name is encodable to MBCS (issue #9819)
42 TESTFN_UNENCODABLE = TESTFN_ASCII + "-\u5171\u0141\u2661\u0363\uDC80"
43 try:
44 TESTFN_UNENCODABLE.encode(sys.getfilesystemencoding())
45 except UnicodeEncodeError:
46 pass
47 else:
48 print('WARNING: The filename %r CAN be encoded by the filesystem '
49 'encoding (%s). Unicode filename tests may not be effective'
50 % (TESTFN_UNENCODABLE, sys.getfilesystemencoding()))
51 TESTFN_UNENCODABLE = None
52 # macOS and Emscripten deny unencodable filenames (invalid utf-8)
53 elif sys.platform not in {'darwin', 'emscripten', 'wasi'}:
54 try:
55 # ascii and utf-8 cannot encode the byte 0xff
56 b'\xff'.decode(sys.getfilesystemencoding())
57 except UnicodeDecodeError:
58 # 0xff will be encoded using the surrogate character u+DCFF
59 TESTFN_UNENCODABLE = TESTFN_ASCII \
60 + b'-\xff'.decode(sys.getfilesystemencoding(), 'surrogateescape')
61 else:
62 # File system encoding (eg. ISO-8859-* encodings) can encode
63 # the byte 0xff. Skip some unicode filename tests.
64 pass
65
66 # FS_NONASCII: non-ASCII character encodable by os.fsencode(),
67 # or an empty string if there is no such character.
68 FS_NONASCII = ''
69 for character in (
70 # First try printable and common characters to have a readable filename.
71 # For each character, the encoding list are just example of encodings able
72 # to encode the character (the list is not exhaustive).
73
74 # U+00E6 (Latin Small Letter Ae): cp1252, iso-8859-1
75 '\u00E6',
76 # U+0130 (Latin Capital Letter I With Dot Above): cp1254, iso8859_3
77 '\u0130',
78 # U+0141 (Latin Capital Letter L With Stroke): cp1250, cp1257
79 '\u0141',
80 # U+03C6 (Greek Small Letter Phi): cp1253
81 '\u03C6',
82 # U+041A (Cyrillic Capital Letter Ka): cp1251
83 '\u041A',
84 # U+05D0 (Hebrew Letter Alef): Encodable to cp424
85 '\u05D0',
86 # U+060C (Arabic Comma): cp864, cp1006, iso8859_6, mac_arabic
87 '\u060C',
88 # U+062A (Arabic Letter Teh): cp720
89 '\u062A',
90 # U+0E01 (Thai Character Ko Kai): cp874
91 '\u0E01',
92
93 # Then try more "special" characters. "special" because they may be
94 # interpreted or displayed differently depending on the exact locale
95 # encoding and the font.
96
97 # U+00A0 (No-Break Space)
98 '\u00A0',
99 # U+20AC (Euro Sign)
100 '\u20AC',
101 ):
102 try:
103 # If Python is set up to use the legacy 'mbcs' in Windows,
104 # 'replace' error mode is used, and encode() returns b'?'
105 # for characters missing in the ANSI codepage
106 if os.fsdecode(os.fsencode(character)) != character:
107 raise UnicodeError
108 except UnicodeError:
109 pass
110 else:
111 FS_NONASCII = character
112 break
113
114 # Save the initial cwd
115 SAVEDCWD = os.getcwd()
116
117 # TESTFN_UNDECODABLE is a filename (bytes type) that should *not* be able to be
118 # decoded from the filesystem encoding (in strict mode). It can be None if we
119 # cannot generate such filename (ex: the latin1 encoding can decode any byte
120 # sequence). On UNIX, TESTFN_UNDECODABLE can be decoded by os.fsdecode() thanks
121 # to the surrogateescape error handler (PEP 383), but not from the filesystem
122 # encoding in strict mode.
123 TESTFN_UNDECODABLE = None
124 for name in (
125 # b'\xff' is not decodable by os.fsdecode() with code page 932. Windows
126 # accepts it to create a file or a directory, or don't accept to enter to
127 # such directory (when the bytes name is used). So test b'\xe7' first:
128 # it is not decodable from cp932.
129 b'\xe7w\xf0',
130 # undecodable from ASCII, UTF-8
131 b'\xff',
132 # undecodable from iso8859-3, iso8859-6, iso8859-7, cp424, iso8859-8, cp856
133 # and cp857
134 b'\xae\xd5'
135 # undecodable from UTF-8 (UNIX and Mac OS X)
136 b'\xed\xb2\x80', b'\xed\xb4\x80',
137 # undecodable from shift_jis, cp869, cp874, cp932, cp1250, cp1251, cp1252,
138 # cp1253, cp1254, cp1255, cp1257, cp1258
139 b'\x81\x98',
140 ):
141 try:
142 name.decode(sys.getfilesystemencoding())
143 except UnicodeDecodeError:
144 TESTFN_UNDECODABLE = os.fsencode(TESTFN_ASCII) + name
145 break
146
147 if FS_NONASCII:
148 TESTFN_NONASCII = TESTFN_ASCII + FS_NONASCII
149 else:
150 TESTFN_NONASCII = None
151 TESTFN = TESTFN_NONASCII or TESTFN_ASCII
152
153
154 def make_bad_fd():
155 """
156 Create an invalid file descriptor by opening and closing a file and return
157 its fd.
158 """
159 file = open(TESTFN, "wb")
160 try:
161 return file.fileno()
162 finally:
163 file.close()
164 unlink(TESTFN)
165
166
167 _can_symlink = None
168
169
170 def can_symlink():
171 global _can_symlink
172 if _can_symlink is not None:
173 return _can_symlink
174 # WASI / wasmtime prevents symlinks with absolute paths, see man
175 # openat2(2) RESOLVE_BENEATH. Almost all symlink tests use absolute
176 # paths. Skip symlink tests on WASI for now.
177 src = os.path.abspath(TESTFN)
178 symlink_path = src + "can_symlink"
179 try:
180 os.symlink(src, symlink_path)
181 can = True
182 except (OSError, NotImplementedError, AttributeError):
183 can = False
184 else:
185 os.remove(symlink_path)
186 _can_symlink = can
187 return can
188
189
190 def skip_unless_symlink(test):
191 """Skip decorator for tests that require functional symlink"""
192 ok = can_symlink()
193 msg = "Requires functional symlink implementation"
194 return test if ok else unittest.skip(msg)(test)
195
196
197 _can_xattr = None
198
199
200 def can_xattr():
201 import tempfile
202 global _can_xattr
203 if _can_xattr is not None:
204 return _can_xattr
205 if not hasattr(os, "setxattr"):
206 can = False
207 else:
208 import platform
209 tmp_dir = tempfile.mkdtemp()
210 tmp_fp, tmp_name = tempfile.mkstemp(dir=tmp_dir)
211 try:
212 with open(TESTFN, "wb") as fp:
213 try:
214 # TESTFN & tempfile may use different file systems with
215 # different capabilities
216 os.setxattr(tmp_fp, b"user.test", b"")
217 os.setxattr(tmp_name, b"trusted.foo", b"42")
218 os.setxattr(fp.fileno(), b"user.test", b"")
219 # Kernels < 2.6.39 don't respect setxattr flags.
220 kernel_version = platform.release()
221 m = re.match(r"2.6.(\d{1,2})", kernel_version)
222 can = m is None or int(m.group(1)) >= 39
223 except OSError:
224 can = False
225 finally:
226 unlink(TESTFN)
227 unlink(tmp_name)
228 rmdir(tmp_dir)
229 _can_xattr = can
230 return can
231
232
233 def skip_unless_xattr(test):
234 """Skip decorator for tests that require functional extended attributes"""
235 ok = can_xattr()
236 msg = "no non-broken extended attribute support"
237 return test if ok else unittest.skip(msg)(test)
238
239
240 _can_chmod = None
241
242 def can_chmod():
243 global _can_chmod
244 if _can_chmod is not None:
245 return _can_chmod
246 if not hasattr(os, "chmod"):
247 _can_chmod = False
248 return _can_chmod
249 try:
250 with open(TESTFN, "wb") as f:
251 try:
252 os.chmod(TESTFN, 0o555)
253 mode1 = os.stat(TESTFN).st_mode
254 os.chmod(TESTFN, 0o777)
255 mode2 = os.stat(TESTFN).st_mode
256 except OSError as e:
257 can = False
258 else:
259 can = stat.S_IMODE(mode1) != stat.S_IMODE(mode2)
260 finally:
261 unlink(TESTFN)
262 _can_chmod = can
263 return can
264
265
266 def skip_unless_working_chmod(test):
267 """Skip tests that require working os.chmod()
268
269 WASI SDK 15.0 cannot change file mode bits.
270 """
271 ok = can_chmod()
272 msg = "requires working os.chmod()"
273 return test if ok else unittest.skip(msg)(test)
274
275
276 # Check whether the current effective user has the capability to override
277 # DAC (discretionary access control). Typically user root is able to
278 # bypass file read, write, and execute permission checks. The capability
279 # is independent of the effective user. See capabilities(7).
280 _can_dac_override = None
281
282 def can_dac_override():
283 global _can_dac_override
284
285 if not can_chmod():
286 _can_dac_override = False
287 if _can_dac_override is not None:
288 return _can_dac_override
289
290 try:
291 with open(TESTFN, "wb") as f:
292 os.chmod(TESTFN, 0o400)
293 try:
294 with open(TESTFN, "wb"):
295 pass
296 except OSError:
297 _can_dac_override = False
298 else:
299 _can_dac_override = True
300 finally:
301 try:
302 os.chmod(TESTFN, 0o700)
303 except OSError:
304 pass
305 unlink(TESTFN)
306
307 return _can_dac_override
308
309
310 def skip_if_dac_override(test):
311 ok = not can_dac_override()
312 msg = "incompatible with CAP_DAC_OVERRIDE"
313 return test if ok else unittest.skip(msg)(test)
314
315
316 def skip_unless_dac_override(test):
317 ok = can_dac_override()
318 msg = "requires CAP_DAC_OVERRIDE"
319 return test if ok else unittest.skip(msg)(test)
320
321
322 def unlink(filename):
323 try:
324 _unlink(filename)
325 except (FileNotFoundError, NotADirectoryError):
326 pass
327
328
329 if sys.platform.startswith("win"):
330 def _waitfor(func, pathname, waitall=False):
331 # Perform the operation
332 func(pathname)
333 # Now setup the wait loop
334 if waitall:
335 dirname = pathname
336 else:
337 dirname, name = os.path.split(pathname)
338 dirname = dirname or '.'
339 # Check for `pathname` to be removed from the filesystem.
340 # The exponential backoff of the timeout amounts to a total
341 # of ~1 second after which the deletion is probably an error
342 # anyway.
343 # Testing on an [email protected] shows that usually only 1 iteration is
344 # required when contention occurs.
345 timeout = 0.001
346 while timeout < 1.0:
347 # Note we are only testing for the existence of the file(s) in
348 # the contents of the directory regardless of any security or
349 # access rights. If we have made it this far, we have sufficient
350 # permissions to do that much using Python's equivalent of the
351 # Windows API FindFirstFile.
352 # Other Windows APIs can fail or give incorrect results when
353 # dealing with files that are pending deletion.
354 L = os.listdir(dirname)
355 if not (L if waitall else name in L):
356 return
357 # Increase the timeout and try again
358 time.sleep(timeout)
359 timeout *= 2
360 warnings.warn('tests may fail, delete still pending for ' + pathname,
361 RuntimeWarning, stacklevel=4)
362
363 def _unlink(filename):
364 _waitfor(os.unlink, filename)
365
366 def _rmdir(dirname):
367 _waitfor(os.rmdir, dirname)
368
369 def _rmtree(path):
370 from test.support import _force_run
371
372 def _rmtree_inner(path):
373 for name in _force_run(path, os.listdir, path):
374 fullname = os.path.join(path, name)
375 try:
376 mode = os.lstat(fullname).st_mode
377 except OSError as exc:
378 print("support.rmtree(): os.lstat(%r) failed with %s"
379 % (fullname, exc),
380 file=sys.__stderr__)
381 mode = 0
382 if stat.S_ISDIR(mode):
383 _waitfor(_rmtree_inner, fullname, waitall=True)
384 _force_run(fullname, os.rmdir, fullname)
385 else:
386 _force_run(fullname, os.unlink, fullname)
387 _waitfor(_rmtree_inner, path, waitall=True)
388 _waitfor(lambda p: _force_run(p, os.rmdir, p), path)
389
390 def _longpath(path):
391 try:
392 import ctypes
393 except ImportError:
394 # No ctypes means we can't expands paths.
395 pass
396 else:
397 buffer = ctypes.create_unicode_buffer(len(path) * 2)
398 length = ctypes.windll.kernel32.GetLongPathNameW(path, buffer,
399 len(buffer))
400 if length:
401 return buffer[:length]
402 return path
403 else:
404 _unlink = os.unlink
405 _rmdir = os.rmdir
406
407 def _rmtree(path):
408 import shutil
409 try:
410 shutil.rmtree(path)
411 return
412 except OSError:
413 pass
414
415 def _rmtree_inner(path):
416 from test.support import _force_run
417 for name in _force_run(path, os.listdir, path):
418 fullname = os.path.join(path, name)
419 try:
420 mode = os.lstat(fullname).st_mode
421 except OSError:
422 mode = 0
423 if stat.S_ISDIR(mode):
424 _rmtree_inner(fullname)
425 _force_run(path, os.rmdir, fullname)
426 else:
427 _force_run(path, os.unlink, fullname)
428 _rmtree_inner(path)
429 os.rmdir(path)
430
431 def _longpath(path):
432 return path
433
434
435 def rmdir(dirname):
436 try:
437 _rmdir(dirname)
438 except FileNotFoundError:
439 pass
440
441
442 def rmtree(path):
443 try:
444 _rmtree(path)
445 except FileNotFoundError:
446 pass
447
448
449 @contextlib.contextmanager
450 def temp_dir(path=None, quiet=False):
451 """Return a context manager that creates a temporary directory.
452
453 Arguments:
454
455 path: the directory to create temporarily. If omitted or None,
456 defaults to creating a temporary directory using tempfile.mkdtemp.
457
458 quiet: if False (the default), the context manager raises an exception
459 on error. Otherwise, if the path is specified and cannot be
460 created, only a warning is issued.
461
462 """
463 import tempfile
464 dir_created = False
465 if path is None:
466 path = tempfile.mkdtemp()
467 dir_created = True
468 path = os.path.realpath(path)
469 else:
470 try:
471 os.mkdir(path)
472 dir_created = True
473 except OSError as exc:
474 if not quiet:
475 raise
476 warnings.warn(f'tests may fail, unable to create '
477 f'temporary directory {path!r}: {exc}',
478 RuntimeWarning, stacklevel=3)
479 if dir_created:
480 pid = os.getpid()
481 try:
482 yield path
483 finally:
484 # In case the process forks, let only the parent remove the
485 # directory. The child has a different process id. (bpo-30028)
486 if dir_created and pid == os.getpid():
487 rmtree(path)
488
489
490 @contextlib.contextmanager
491 def change_cwd(path, quiet=False):
492 """Return a context manager that changes the current working directory.
493
494 Arguments:
495
496 path: the directory to use as the temporary current working directory.
497
498 quiet: if False (the default), the context manager raises an exception
499 on error. Otherwise, it issues only a warning and keeps the current
500 working directory the same.
501
502 """
503 saved_dir = os.getcwd()
504 try:
505 os.chdir(os.path.realpath(path))
506 except OSError as exc:
507 if not quiet:
508 raise
509 warnings.warn(f'tests may fail, unable to change the current working '
510 f'directory to {path!r}: {exc}',
511 RuntimeWarning, stacklevel=3)
512 try:
513 yield os.getcwd()
514 finally:
515 os.chdir(saved_dir)
516
517
518 @contextlib.contextmanager
519 def temp_cwd(name='tempcwd', quiet=False):
520 """
521 Context manager that temporarily creates and changes the CWD.
522
523 The function temporarily changes the current working directory
524 after creating a temporary directory in the current directory with
525 name *name*. If *name* is None, the temporary directory is
526 created using tempfile.mkdtemp.
527
528 If *quiet* is False (default) and it is not possible to
529 create or change the CWD, an error is raised. If *quiet* is True,
530 only a warning is raised and the original CWD is used.
531
532 """
533 with temp_dir(path=name, quiet=quiet) as temp_path:
534 with change_cwd(temp_path, quiet=quiet) as cwd_dir:
535 yield cwd_dir
536
537
538 def create_empty_file(filename):
539 """Create an empty file. If the file already exists, truncate it."""
540 fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
541 os.close(fd)
542
543
544 @contextlib.contextmanager
545 def open_dir_fd(path):
546 """Open a file descriptor to a directory."""
547 assert os.path.isdir(path)
548 flags = os.O_RDONLY
549 if hasattr(os, "O_DIRECTORY"):
550 flags |= os.O_DIRECTORY
551 dir_fd = os.open(path, flags)
552 try:
553 yield dir_fd
554 finally:
555 os.close(dir_fd)
556
557
558 def fs_is_case_insensitive(directory):
559 """Detects if the file system for the specified directory
560 is case-insensitive."""
561 import tempfile
562 with tempfile.NamedTemporaryFile(dir=directory) as base:
563 base_path = base.name
564 case_path = base_path.upper()
565 if case_path == base_path:
566 case_path = base_path.lower()
567 try:
568 return os.path.samefile(base_path, case_path)
569 except FileNotFoundError:
570 return False
571
572
573 class FakePath:
574 """Simple implementation of the path protocol.
575 """
576 def __init__(self, path):
577 self.path = path
578
579 def __repr__(self):
580 return f'<FakePath {self.path!r}>'
581
582 def __fspath__(self):
583 if (isinstance(self.path, BaseException) or
584 isinstance(self.path, type) and
585 issubclass(self.path, BaseException)):
586 raise self.path
587 else:
588 return self.path
589
590
591 def fd_count():
592 """Count the number of open file descriptors.
593 """
594 if sys.platform.startswith(('linux', 'freebsd', 'emscripten')):
595 fd_path = "/proc/self/fd"
596 elif sys.platform == "darwin":
597 fd_path = "/dev/fd"
598 else:
599 fd_path = None
600
601 if fd_path is not None:
602 try:
603 names = os.listdir(fd_path)
604 # Subtract one because listdir() internally opens a file
605 # descriptor to list the content of the directory.
606 return len(names) - 1
607 except FileNotFoundError:
608 pass
609
610 MAXFD = 256
611 if hasattr(os, 'sysconf'):
612 try:
613 MAXFD = os.sysconf("SC_OPEN_MAX")
614 except OSError:
615 pass
616
617 old_modes = None
618 if sys.platform == 'win32':
619 # bpo-25306, bpo-31009: Call CrtSetReportMode() to not kill the process
620 # on invalid file descriptor if Python is compiled in debug mode
621 try:
622 import msvcrt
623 msvcrt.CrtSetReportMode
624 except (AttributeError, ImportError):
625 # no msvcrt or a release build
626 pass
627 else:
628 old_modes = {}
629 for report_type in (msvcrt.CRT_WARN,
630 msvcrt.CRT_ERROR,
631 msvcrt.CRT_ASSERT):
632 old_modes[report_type] = msvcrt.CrtSetReportMode(report_type,
633 0)
634
635 try:
636 count = 0
637 for fd in range(MAXFD):
638 try:
639 # Prefer dup() over fstat(). fstat() can require input/output
640 # whereas dup() doesn't.
641 fd2 = os.dup(fd)
642 except OSError as e:
643 if e.errno != errno.EBADF:
644 raise
645 else:
646 os.close(fd2)
647 count += 1
648 finally:
649 if old_modes is not None:
650 for report_type in (msvcrt.CRT_WARN,
651 msvcrt.CRT_ERROR,
652 msvcrt.CRT_ASSERT):
653 msvcrt.CrtSetReportMode(report_type, old_modes[report_type])
654
655 return count
656
657
658 if hasattr(os, "umask"):
659 @contextlib.contextmanager
660 def temp_umask(umask):
661 """Context manager that temporarily sets the process umask."""
662 oldmask = os.umask(umask)
663 try:
664 yield
665 finally:
666 os.umask(oldmask)
667 else:
668 @contextlib.contextmanager
669 def temp_umask(umask):
670 """no-op on platforms without umask()"""
671 yield
672
673
674 class EnvironmentVarGuard(collections.abc.MutableMapping):
675
676 """Class to help protect the environment variable properly. Can be used as
677 a context manager."""
678
679 def __init__(self):
680 self._environ = os.environ
681 self._changed = {}
682
683 def __getitem__(self, envvar):
684 return self._environ[envvar]
685
686 def __setitem__(self, envvar, value):
687 # Remember the initial value on the first access
688 if envvar not in self._changed:
689 self._changed[envvar] = self._environ.get(envvar)
690 self._environ[envvar] = value
691
692 def __delitem__(self, envvar):
693 # Remember the initial value on the first access
694 if envvar not in self._changed:
695 self._changed[envvar] = self._environ.get(envvar)
696 if envvar in self._environ:
697 del self._environ[envvar]
698
699 def keys(self):
700 return self._environ.keys()
701
702 def __iter__(self):
703 return iter(self._environ)
704
705 def __len__(self):
706 return len(self._environ)
707
708 def set(self, envvar, value):
709 self[envvar] = value
710
711 def unset(self, envvar):
712 del self[envvar]
713
714 def copy(self):
715 # We do what os.environ.copy() does.
716 return dict(self)
717
718 def __enter__(self):
719 return self
720
721 def __exit__(self, *ignore_exc):
722 for (k, v) in self._changed.items():
723 if v is None:
724 if k in self._environ:
725 del self._environ[k]
726 else:
727 self._environ[k] = v
728 os.environ = self._environ