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 for name in _force_run(path, os.listdir, path):
444 fullname = os.path.join(path, name)
445 try:
446 mode = os.lstat(fullname).st_mode
447 except OSError:
448 mode = 0
449 if stat.S_ISDIR(mode):
450 _rmtree_inner(fullname)
451 _force_run(path, os.rmdir, fullname)
452 else:
453 _force_run(path, os.unlink, fullname)
454 _rmtree_inner(path)
455 os.rmdir(path)
456
457 def _longpath(path):
458 return path
459
460
461 def rmdir(dirname):
462 try:
463 _rmdir(dirname)
464 except FileNotFoundError:
465 pass
466
467
468 def rmtree(path):
469 try:
470 _rmtree(path)
471 except FileNotFoundError:
472 pass
473
474
475 @contextlib.contextmanager
476 def temp_dir(path=None, quiet=False):
477 """Return a context manager that creates a temporary directory.
478
479 Arguments:
480
481 path: the directory to create temporarily. If omitted or None,
482 defaults to creating a temporary directory using tempfile.mkdtemp.
483
484 quiet: if False (the default), the context manager raises an exception
485 on error. Otherwise, if the path is specified and cannot be
486 created, only a warning is issued.
487
488 """
489 import tempfile
490 dir_created = False
491 if path is None:
492 path = tempfile.mkdtemp()
493 dir_created = True
494 path = os.path.realpath(path)
495 else:
496 try:
497 os.mkdir(path)
498 dir_created = True
499 except OSError as exc:
500 if not quiet:
501 raise
502 logging.getLogger(__name__).warning(
503 "tests may fail, unable to create temporary directory %r: %s",
504 path,
505 exc,
506 exc_info=exc,
507 stack_info=True,
508 stacklevel=3,
509 )
510 if dir_created:
511 pid = os.getpid()
512 try:
513 yield path
514 finally:
515 # In case the process forks, let only the parent remove the
516 # directory. The child has a different process id. (bpo-30028)
517 if dir_created and pid == os.getpid():
518 rmtree(path)
519
520
521 @contextlib.contextmanager
522 def change_cwd(path, quiet=False):
523 """Return a context manager that changes the current working directory.
524
525 Arguments:
526
527 path: the directory to use as the temporary current working directory.
528
529 quiet: if False (the default), the context manager raises an exception
530 on error. Otherwise, it issues only a warning and keeps the current
531 working directory the same.
532
533 """
534 saved_dir = os.getcwd()
535 try:
536 os.chdir(os.path.realpath(path))
537 except OSError as exc:
538 if not quiet:
539 raise
540 logging.getLogger(__name__).warning(
541 'tests may fail, unable to change the current working directory '
542 'to %r: %s',
543 path,
544 exc,
545 exc_info=exc,
546 stack_info=True,
547 stacklevel=3,
548 )
549 try:
550 yield os.getcwd()
551 finally:
552 os.chdir(saved_dir)
553
554
555 @contextlib.contextmanager
556 def temp_cwd(name='tempcwd', quiet=False):
557 """
558 Context manager that temporarily creates and changes the CWD.
559
560 The function temporarily changes the current working directory
561 after creating a temporary directory in the current directory with
562 name *name*. If *name* is None, the temporary directory is
563 created using tempfile.mkdtemp.
564
565 If *quiet* is False (default) and it is not possible to
566 create or change the CWD, an error is raised. If *quiet* is True,
567 only a warning is raised and the original CWD is used.
568
569 """
570 with temp_dir(path=name, quiet=quiet) as temp_path:
571 with change_cwd(temp_path, quiet=quiet) as cwd_dir:
572 yield cwd_dir
573
574
575 def create_empty_file(filename):
576 """Create an empty file. If the file already exists, truncate it."""
577 fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
578 os.close(fd)
579
580
581 @contextlib.contextmanager
582 def open_dir_fd(path):
583 """Open a file descriptor to a directory."""
584 assert os.path.isdir(path)
585 flags = os.O_RDONLY
586 if hasattr(os, "O_DIRECTORY"):
587 flags |= os.O_DIRECTORY
588 dir_fd = os.open(path, flags)
589 try:
590 yield dir_fd
591 finally:
592 os.close(dir_fd)
593
594
595 def fs_is_case_insensitive(directory):
596 """Detects if the file system for the specified directory
597 is case-insensitive."""
598 import tempfile
599 with tempfile.NamedTemporaryFile(dir=directory) as base:
600 base_path = base.name
601 case_path = base_path.upper()
602 if case_path == base_path:
603 case_path = base_path.lower()
604 try:
605 return os.path.samefile(base_path, case_path)
606 except FileNotFoundError:
607 return False
608
609
610 class FakePath:
611 """Simple implementation of the path protocol.
612 """
613 def __init__(self, path):
614 self.path = path
615
616 def __repr__(self):
617 return f'<FakePath {self.path!r}>'
618
619 def __fspath__(self):
620 if (isinstance(self.path, BaseException) or
621 isinstance(self.path, type) and
622 issubclass(self.path, BaseException)):
623 raise self.path
624 else:
625 return self.path
626
627
628 def fd_count():
629 """Count the number of open file descriptors.
630 """
631 if sys.platform.startswith(('linux', 'android', 'freebsd', 'emscripten')):
632 fd_path = "/proc/self/fd"
633 elif support.is_apple:
634 fd_path = "/dev/fd"
635 else:
636 fd_path = None
637
638 if fd_path is not None:
639 try:
640 names = os.listdir(fd_path)
641 # Subtract one because listdir() internally opens a file
642 # descriptor to list the content of the directory.
643 return len(names) - 1
644 except FileNotFoundError:
645 pass
646
647 MAXFD = 256
648 if hasattr(os, 'sysconf'):
649 try:
650 MAXFD = os.sysconf("SC_OPEN_MAX")
651 except OSError:
652 pass
653
654 old_modes = None
655 if sys.platform == 'win32':
656 # bpo-25306, bpo-31009: Call CrtSetReportMode() to not kill the process
657 # on invalid file descriptor if Python is compiled in debug mode
658 try:
659 import msvcrt
660 msvcrt.CrtSetReportMode
661 except (AttributeError, ImportError):
662 # no msvcrt or a release build
663 pass
664 else:
665 old_modes = {}
666 for report_type in (msvcrt.CRT_WARN,
667 msvcrt.CRT_ERROR,
668 msvcrt.CRT_ASSERT):
669 old_modes[report_type] = msvcrt.CrtSetReportMode(report_type,
670 0)
671
672 try:
673 count = 0
674 for fd in range(MAXFD):
675 try:
676 # Prefer dup() over fstat(). fstat() can require input/output
677 # whereas dup() doesn't.
678 fd2 = os.dup(fd)
679 except OSError as e:
680 if e.errno != errno.EBADF:
681 raise
682 else:
683 os.close(fd2)
684 count += 1
685 finally:
686 if old_modes is not None:
687 for report_type in (msvcrt.CRT_WARN,
688 msvcrt.CRT_ERROR,
689 msvcrt.CRT_ASSERT):
690 msvcrt.CrtSetReportMode(report_type, old_modes[report_type])
691
692 return count
693
694
695 if hasattr(os, "umask"):
696 @contextlib.contextmanager
697 def temp_umask(umask):
698 """Context manager that temporarily sets the process umask."""
699 oldmask = os.umask(umask)
700 try:
701 yield
702 finally:
703 os.umask(oldmask)
704 else:
705 @contextlib.contextmanager
706 def temp_umask(umask):
707 """no-op on platforms without umask()"""
708 yield
709
710
711 class EnvironmentVarGuard(collections.abc.MutableMapping):
712 """Class to help protect the environment variable properly.
713
714 Can be used as a context manager.
715 """
716
717 def __init__(self):
718 self._environ = os.environ
719 self._changed = {}
720
721 def __getitem__(self, envvar):
722 return self._environ[envvar]
723
724 def __setitem__(self, envvar, value):
725 # Remember the initial value on the first access
726 if envvar not in self._changed:
727 self._changed[envvar] = self._environ.get(envvar)
728 self._environ[envvar] = value
729
730 def __delitem__(self, envvar):
731 # Remember the initial value on the first access
732 if envvar not in self._changed:
733 self._changed[envvar] = self._environ.get(envvar)
734 if envvar in self._environ:
735 del self._environ[envvar]
736
737 def keys(self):
738 return self._environ.keys()
739
740 def __iter__(self):
741 return iter(self._environ)
742
743 def __len__(self):
744 return len(self._environ)
745
746 def set(self, envvar, value):
747 self[envvar] = value
748
749 def unset(self, envvar, /, *envvars):
750 """Unset one or more environment variables."""
751 for ev in (envvar, *envvars):
752 del self[ev]
753
754 def copy(self):
755 # We do what os.environ.copy() does.
756 return dict(self)
757
758 def __enter__(self):
759 return self
760
761 def __exit__(self, *ignore_exc):
762 for (k, v) in self._changed.items():
763 if v is None:
764 if k in self._environ:
765 del self._environ[k]
766 else:
767 self._environ[k] = v
768 os.environ = self._environ
769
770
771 try:
772 if support.MS_WINDOWS:
773 import ctypes
774 kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
775
776 ERROR_FILE_NOT_FOUND = 2
777 DDD_REMOVE_DEFINITION = 2
778 DDD_EXACT_MATCH_ON_REMOVE = 4
779 DDD_NO_BROADCAST_SYSTEM = 8
780 else:
781 raise AttributeError
782 except (ImportError, AttributeError):
783 def subst_drive(path):
784 raise unittest.SkipTest('ctypes or kernel32 is not available')
785 else:
786 @contextlib.contextmanager
787 def subst_drive(path):
788 """Temporarily yield a substitute drive for a given path."""
789 for c in reversed(string.ascii_uppercase):
790 drive = f'{c}:'
791 if (not kernel32.QueryDosDeviceW(drive, None, 0) and
792 ctypes.get_last_error() == ERROR_FILE_NOT_FOUND):
793 break
794 else:
795 raise unittest.SkipTest('no available logical drive')
796 if not kernel32.DefineDosDeviceW(
797 DDD_NO_BROADCAST_SYSTEM, drive, path):
798 raise ctypes.WinError(ctypes.get_last_error())
799 try:
800 yield drive
801 finally:
802 if not kernel32.DefineDosDeviceW(
803 DDD_REMOVE_DEFINITION | DDD_EXACT_MATCH_ON_REMOVE,
804 drive, path):
805 raise ctypes.WinError(ctypes.get_last_error())