Debian Codegraph @

Lib/test/support/os_helper.py

raw
1 import collections.abc
2 import contextlib
3 import errno
4 import logging
5 import os
6 import re
7 import stat
8 import string
9 import sys
10 import time
11 import unittest
12 import warnings
13
14 from test import support
15
16
17 # Filename used for testing
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 support.is_apple:
27 # On Apple'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 # Apple and Emscripten deny unencodable filenames (invalid utf-8)
53 elif not support.is_apple and sys.platform not in {"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 try:
145 name.decode(sys.getfilesystemencoding(),
146 sys.getfilesystemencodeerrors())
147 except UnicodeDecodeError:
148 continue
149 TESTFN_UNDECODABLE = os.fsencode(TESTFN_ASCII) + name
150 break
151
152 if FS_NONASCII:
153 TESTFN_NONASCII = TESTFN_ASCII + FS_NONASCII
154 else:
155 TESTFN_NONASCII = None
156 TESTFN = TESTFN_NONASCII or TESTFN_ASCII
157
158
159 def make_bad_fd():
160 """
161 Create an invalid file descriptor by opening and closing a file and return
162 its fd.
163 """
164 file = open(TESTFN, "wb")
165 try:
166 return file.fileno()
167 finally:
168 file.close()
169 unlink(TESTFN)
170
171
172 _can_symlink = None
173
174
175 def can_symlink():
176 global _can_symlink
177 if _can_symlink is not None:
178 return _can_symlink
179 # WASI / wasmtime prevents symlinks with absolute paths, see man
180 # openat2(2) RESOLVE_BENEATH. Almost all symlink tests use absolute
181 # paths. Skip symlink tests on WASI for now.
182 src = os.path.abspath(TESTFN)
183 symlink_path = src + "can_symlink"
184 try:
185 os.symlink(src, symlink_path)
186 can = True
187 except (OSError, NotImplementedError, AttributeError):
188 can = False
189 else:
190 os.remove(symlink_path)
191 _can_symlink = can
192 return can
193
194
195 def skip_unless_symlink(test):
196 """Skip decorator for tests that require functional symlink"""
197 ok = can_symlink()
198 msg = "Requires functional symlink implementation"
199 return test if ok else unittest.skip(msg)(test)
200
201
202 _can_hardlink = None
203
204 def can_hardlink():
205 global _can_hardlink
206 if _can_hardlink is None:
207 # Android blocks hard links using SELinux
208 # (https://stackoverflow.com/q/32365690).
209 _can_hardlink = hasattr(os, "link") and not support.is_android
210 return _can_hardlink
211
212
213 def skip_unless_hardlink(test):
214 ok = can_hardlink()
215 msg = "requires hardlink support"
216 return test if ok else unittest.skip(msg)(test)
217
218
219 _can_xattr = None
220
221
222 def can_xattr():
223 import tempfile
224 global _can_xattr
225 if _can_xattr is not None:
226 return _can_xattr
227 if not hasattr(os, "setxattr"):
228 can = False
229 else:
230 import platform
231 tmp_dir = tempfile.mkdtemp()
232 tmp_fp, tmp_name = tempfile.mkstemp(dir=tmp_dir)
233 try:
234 with open(TESTFN, "wb") as fp:
235 try:
236 # TESTFN & tempfile may use different file systems with
237 # different capabilities
238 os.setxattr(tmp_fp, b"user.test", b"")
239 os.setxattr(tmp_name, b"trusted.foo", b"42")
240 os.setxattr(fp.fileno(), b"user.test", b"")
241 # Kernels < 2.6.39 don't respect setxattr flags.
242 kernel_version = platform.release()
243 m = re.match(r"2.6.(\d{1,2})", kernel_version)
244 can = m is None or int(m.group(1)) >= 39
245 except OSError:
246 can = False
247 finally:
248 unlink(TESTFN)
249 unlink(tmp_name)
250 rmdir(tmp_dir)
251 _can_xattr = can
252 return can
253
254
255 def skip_unless_xattr(test):
256 """Skip decorator for tests that require functional extended attributes"""
257 ok = can_xattr()
258 msg = "no non-broken extended attribute support"
259 return test if ok else unittest.skip(msg)(test)
260
261
262 _can_chmod = None
263
264 def can_chmod():
265 global _can_chmod
266 if _can_chmod is not None:
267 return _can_chmod
268 if not hasattr(os, "chmod"):
269 _can_chmod = False
270 return _can_chmod
271 try:
272 with open(TESTFN, "wb") as f:
273 try:
274 os.chmod(TESTFN, 0o555)
275 mode1 = os.stat(TESTFN).st_mode
276 os.chmod(TESTFN, 0o777)
277 mode2 = os.stat(TESTFN).st_mode
278 except OSError as e:
279 can = False
280 else:
281 can = stat.S_IMODE(mode1) != stat.S_IMODE(mode2)
282 finally:
283 unlink(TESTFN)
284 _can_chmod = can
285 return can
286
287
288 def skip_unless_working_chmod(test):
289 """Skip tests that require working os.chmod()
290
291 WASI SDK 15.0 cannot change file mode bits.
292 """
293 ok = can_chmod()
294 msg = "requires working os.chmod()"
295 return test if ok else unittest.skip(msg)(test)
296
297
298 # Check whether the current effective user has the capability to override
299 # DAC (discretionary access control). Typically user root is able to
300 # bypass file read, write, and execute permission checks. The capability
301 # is independent of the effective user. See capabilities(7).
302 _can_dac_override = None
303
304 def can_dac_override():
305 global _can_dac_override
306
307 if not can_chmod():
308 _can_dac_override = False
309 if _can_dac_override is not None:
310 return _can_dac_override
311
312 try:
313 with open(TESTFN, "wb") as f:
314 os.chmod(TESTFN, 0o400)
315 try:
316 with open(TESTFN, "wb"):
317 pass
318 except OSError:
319 _can_dac_override = False
320 else:
321 _can_dac_override = True
322 finally:
323 try:
324 os.chmod(TESTFN, 0o700)
325 except OSError:
326 pass
327 unlink(TESTFN)
328
329 return _can_dac_override
330
331
332 def skip_if_dac_override(test):
333 ok = not can_dac_override()
334 msg = "incompatible with CAP_DAC_OVERRIDE"
335 return test if ok else unittest.skip(msg)(test)
336
337
338 def skip_unless_dac_override(test):
339 ok = can_dac_override()
340 msg = "requires CAP_DAC_OVERRIDE"
341 return test if ok else unittest.skip(msg)(test)
342
343
344 def unlink(filename):
345 try:
346 _unlink(filename)
347 except (FileNotFoundError, NotADirectoryError):
348 pass
349
350
351 if sys.platform.startswith("win"):
352 def _waitfor(func, pathname, waitall=False):
353 # Perform the operation
354 func(pathname)
355 # Now setup the wait loop
356 if waitall:
357 dirname = pathname
358 else:
359 dirname, name = os.path.split(pathname)
360 dirname = dirname or '.'
361 # Check for `pathname` to be removed from the filesystem.
362 # The exponential backoff of the timeout amounts to a total
363 # of ~1 second after which the deletion is probably an error
364 # anyway.
365 # Testing on an [email protected] shows that usually only 1 iteration is
366 # required when contention occurs.
367 timeout = 0.001
368 while timeout < 1.0:
369 # Note we are only testing for the existence of the file(s) in
370 # the contents of the directory regardless of any security or
371 # access rights. If we have made it this far, we have sufficient
372 # permissions to do that much using Python's equivalent of the
373 # Windows API FindFirstFile.
374 # Other Windows APIs can fail or give incorrect results when
375 # dealing with files that are pending deletion.
376 L = os.listdir(dirname)
377 if not (L if waitall else name in L):
378 return
379 # Increase the timeout and try again
380 time.sleep(timeout)
381 timeout *= 2
382 logging.getLogger(__name__).warning(
383 'tests may fail, delete still pending for %s',
384 pathname,
385 stack_info=True,
386 stacklevel=4,
387 )
388
389 def _unlink(filename):
390 _waitfor(os.unlink, filename)
391
392 def _rmdir(dirname):
393 _waitfor(os.rmdir, dirname)
394
395 def _rmtree(path):
396 from test.support import _force_run
397
398 def _rmtree_inner(path):
399 for name in _force_run(path, os.listdir, path):
400 fullname = os.path.join(path, name)
401 try:
402 mode = os.lstat(fullname).st_mode
403 except OSError as exc:
404 print("support.rmtree(): os.lstat(%r) failed with %s"
405 % (fullname, exc),
406 file=sys.__stderr__)
407 mode = 0
408 if stat.S_ISDIR(mode):
409 _waitfor(_rmtree_inner, fullname, waitall=True)
410 _force_run(fullname, os.rmdir, fullname)
411 else:
412 _force_run(fullname, os.unlink, fullname)
413 _waitfor(_rmtree_inner, path, waitall=True)
414 _waitfor(lambda p: _force_run(p, os.rmdir, p), path)
415
416 def _longpath(path):
417 try:
418 import ctypes
419 except ImportError:
420 # No ctypes means we can't expands paths.
421 pass
422 else:
423 buffer = ctypes.create_unicode_buffer(len(path) * 2)
424 length = ctypes.windll.kernel32.GetLongPathNameW(path, buffer,
425 len(buffer))
426 if length:
427 return buffer[:length]
428 return path
429 else:
430 _unlink = os.unlink
431 _rmdir = os.rmdir
432
433 def _rmtree(path):
434 import shutil
435 try:
436 shutil.rmtree(path)
437 return
438 except OSError:
439 pass
440
441 def _rmtree_inner(path):
442 from test.support import _force_run
443 # Clear file flags (e.g. UF_IMMUTABLE, UF_NOUNLINK on BSD).
444 if hasattr(os, 'chflags'):
445 try:
446 os.chflags(path, 0)
447 except OSError:
448 pass
449 for name in _force_run(path, os.listdir, path):
450 fullname = os.path.join(path, name)
451 try:
452 mode = os.lstat(fullname).st_mode
453 except OSError:
454 mode = 0
455 if hasattr(os, 'lchflags'):
456 try:
457 os.lchflags(fullname, 0)
458 except OSError:
459 pass
460 if stat.S_ISDIR(mode):
461 _rmtree_inner(fullname)
462 _force_run(path, os.rmdir, fullname)
463 else:
464 _force_run(path, os.unlink, fullname)
465 _rmtree_inner(path)
466 os.rmdir(path)
467
468 def _longpath(path):
469 return path
470
471
472 def rmdir(dirname):
473 try:
474 _rmdir(dirname)
475 except FileNotFoundError:
476 pass
477
478
479 def rmtree(path):
480 try:
481 _rmtree(path)
482 except FileNotFoundError:
483 pass
484
485
486 @contextlib.contextmanager
487 def temp_dir(path=None, quiet=False):
488 """Return a context manager that creates a temporary directory.
489
490 Arguments:
491
492 path: the directory to create temporarily. If omitted or None,
493 defaults to creating a temporary directory using tempfile.mkdtemp.
494
495 quiet: if False (the default), the context manager raises an exception
496 on error. Otherwise, if the path is specified and cannot be
497 created, only a warning is issued.
498
499 """
500 import tempfile
501 dir_created = False
502 if path is None:
503 path = tempfile.mkdtemp()
504 dir_created = True
505 path = os.path.realpath(path)
506 else:
507 try:
508 os.mkdir(path)
509 dir_created = True
510 except OSError as exc:
511 if not quiet:
512 raise
513 logging.getLogger(__name__).warning(
514 "tests may fail, unable to create temporary directory %r: %s",
515 path,
516 exc,
517 exc_info=exc,
518 stack_info=True,
519 stacklevel=3,
520 )
521 if dir_created:
522 pid = os.getpid()
523 try:
524 yield path
525 finally:
526 # In case the process forks, let only the parent remove the
527 # directory. The child has a different process id. (bpo-30028)
528 if dir_created and pid == os.getpid():
529 rmtree(path)
530
531
532 @contextlib.contextmanager
533 def change_cwd(path, quiet=False):
534 """Return a context manager that changes the current working directory.
535
536 Arguments:
537
538 path: the directory to use as the temporary current working directory.
539
540 quiet: if False (the default), the context manager raises an exception
541 on error. Otherwise, it issues only a warning and keeps the current
542 working directory the same.
543
544 """
545 saved_dir = os.getcwd()
546 try:
547 os.chdir(os.path.realpath(path))
548 except OSError as exc:
549 if not quiet:
550 raise
551 logging.getLogger(__name__).warning(
552 'tests may fail, unable to change the current working directory '
553 'to %r: %s',
554 path,
555 exc,
556 exc_info=exc,
557 stack_info=True,
558 stacklevel=3,
559 )
560 try:
561 yield os.getcwd()
562 finally:
563 os.chdir(saved_dir)
564
565
566 @contextlib.contextmanager
567 def temp_cwd(name='tempcwd', quiet=False):
568 """
569 Context manager that temporarily creates and changes the CWD.
570
571 The function temporarily changes the current working directory
572 after creating a temporary directory in the current directory with
573 name *name*. If *name* is None, the temporary directory is
574 created using tempfile.mkdtemp.
575
576 If *quiet* is False (default) and it is not possible to
577 create or change the CWD, an error is raised. If *quiet* is True,
578 only a warning is raised and the original CWD is used.
579
580 """
581 with temp_dir(path=name, quiet=quiet) as temp_path:
582 with change_cwd(temp_path, quiet=quiet) as cwd_dir:
583 yield cwd_dir
584
585
586 def create_empty_file(filename):
587 """Create an empty file. If the file already exists, truncate it."""
588 fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
589 os.close(fd)
590
591
592 @contextlib.contextmanager
593 def open_dir_fd(path):
594 """Open a file descriptor to a directory."""
595 assert os.path.isdir(path)
596 flags = os.O_RDONLY
597 if hasattr(os, "O_DIRECTORY"):
598 flags |= os.O_DIRECTORY
599 dir_fd = os.open(path, flags)
600 try:
601 yield dir_fd
602 finally:
603 os.close(dir_fd)
604
605
606 def fs_is_case_insensitive(directory):
607 """Detects if the file system for the specified directory
608 is case-insensitive."""
609 import tempfile
610 with tempfile.NamedTemporaryFile(dir=directory) as base:
611 base_path = base.name
612 case_path = base_path.upper()
613 if case_path == base_path:
614 case_path = base_path.lower()
615 try:
616 return os.path.samefile(base_path, case_path)
617 except FileNotFoundError:
618 return False
619
620
621 class FakePath:
622 """Simple implementation of the path protocol.
623 """
624 def __init__(self, path):
625 self.path = path
626
627 def __repr__(self):
628 return f'<FakePath {self.path!r}>'
629
630 def __fspath__(self):
631 if (isinstance(self.path, BaseException) or
632 isinstance(self.path, type) and
633 issubclass(self.path, BaseException)):
634 raise self.path
635 else:
636 return self.path
637
638
639 def fd_count():
640 """Count the number of open file descriptors.
641 """
642 if sys.platform.startswith(('linux', 'android', 'freebsd', 'emscripten')):
643 fd_path = "/proc/self/fd"
644 elif support.is_apple:
645 fd_path = "/dev/fd"
646 else:
647 fd_path = None
648
649 if fd_path is not None:
650 try:
651 names = os.listdir(fd_path)
652 # Subtract one because listdir() internally opens a file
653 # descriptor to list the content of the directory.
654 return len(names) - 1
655 except FileNotFoundError:
656 pass
657
658 MAXFD = 256
659 if hasattr(os, 'sysconf'):
660 try:
661 MAXFD = os.sysconf("SC_OPEN_MAX")
662 except OSError:
663 pass
664
665 old_modes = None
666 if sys.platform == 'win32':
667 # bpo-25306, bpo-31009: Call CrtSetReportMode() to not kill the process
668 # on invalid file descriptor if Python is compiled in debug mode
669 try:
670 import msvcrt
671 msvcrt.CrtSetReportMode
672 except (AttributeError, ImportError):
673 # no msvcrt or a release build
674 pass
675 else:
676 old_modes = {}
677 for report_type in (msvcrt.CRT_WARN,
678 msvcrt.CRT_ERROR,
679 msvcrt.CRT_ASSERT):
680 old_modes[report_type] = msvcrt.CrtSetReportMode(report_type,
681 0)
682
683 try:
684 count = 0
685 for fd in range(MAXFD):
686 try:
687 # Prefer dup() over fstat(). fstat() can require input/output
688 # whereas dup() doesn't.
689 fd2 = os.dup(fd)
690 except OSError as e:
691 if e.errno != errno.EBADF:
692 raise
693 else:
694 os.close(fd2)
695 count += 1
696 finally:
697 if old_modes is not None:
698 for report_type in (msvcrt.CRT_WARN,
699 msvcrt.CRT_ERROR,
700 msvcrt.CRT_ASSERT):
701 msvcrt.CrtSetReportMode(report_type, old_modes[report_type])
702
703 return count
704
705
706 if hasattr(os, "umask"):
707 @contextlib.contextmanager
708 def temp_umask(umask):
709 """Context manager that temporarily sets the process umask."""
710 oldmask = os.umask(umask)
711 try:
712 yield
713 finally:
714 os.umask(oldmask)
715 else:
716 @contextlib.contextmanager
717 def temp_umask(umask):
718 """no-op on platforms without umask()"""
719 yield
720
721
722 class EnvironmentVarGuard(collections.abc.MutableMapping):
723 """Class to help protect the environment variable properly.
724
725 Can be used as a context manager.
726 """
727
728 def __init__(self):
729 self._environ = os.environ
730 self._changed = {}
731
732 def __getitem__(self, envvar):
733 return self._environ[envvar]
734
735 def __setitem__(self, envvar, value):
736 # Remember the initial value on the first access
737 if envvar not in self._changed:
738 self._changed[envvar] = self._environ.get(envvar)
739 self._environ[envvar] = value
740
741 def __delitem__(self, envvar):
742 # Remember the initial value on the first access
743 if envvar not in self._changed:
744 self._changed[envvar] = self._environ.get(envvar)
745 if envvar in self._environ:
746 del self._environ[envvar]
747
748 def keys(self):
749 return self._environ.keys()
750
751 def __iter__(self):
752 return iter(self._environ)
753
754 def __len__(self):
755 return len(self._environ)
756
757 def set(self, envvar, value):
758 self[envvar] = value
759
760 def unset(self, envvar, /, *envvars):
761 """Unset one or more environment variables."""
762 for ev in (envvar, *envvars):
763 del self[ev]
764
765 def copy(self):
766 # We do what os.environ.copy() does.
767 return dict(self)
768
769 def __enter__(self):
770 return self
771
772 def __exit__(self, *ignore_exc):
773 for (k, v) in self._changed.items():
774 if v is None:
775 if k in self._environ:
776 del self._environ[k]
777 else:
778 self._environ[k] = v
779 os.environ = self._environ
780
781
782 try:
783 if support.MS_WINDOWS:
784 import ctypes
785 kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
786
787 ERROR_FILE_NOT_FOUND = 2
788 DDD_REMOVE_DEFINITION = 2
789 DDD_EXACT_MATCH_ON_REMOVE = 4
790 DDD_NO_BROADCAST_SYSTEM = 8
791 else:
792 raise AttributeError
793 except (ImportError, AttributeError):
794 def subst_drive(path):
795 raise unittest.SkipTest('ctypes or kernel32 is not available')
796 else:
797 @contextlib.contextmanager
798 def subst_drive(path):
799 """Temporarily yield a substitute drive for a given path."""
800 for c in reversed(string.ascii_uppercase):
801 drive = f'{c}:'
802 if (not kernel32.QueryDosDeviceW(drive, None, 0) and
803 ctypes.get_last_error() == ERROR_FILE_NOT_FOUND):
804 break
805 else:
806 raise unittest.SkipTest('no available logical drive')
807 if not kernel32.DefineDosDeviceW(
808 DDD_NO_BROADCAST_SYSTEM, drive, path):
809 raise ctypes.WinError(ctypes.get_last_error())
810 try:
811 yield drive
812 finally:
813 if not kernel32.DefineDosDeviceW(
814 DDD_REMOVE_DEFINITION | DDD_EXACT_MATCH_ON_REMOVE,
815 drive, path):
816 raise ctypes.WinError(ctypes.get_last_error())