| 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 |
|
| 18 |
TESTFN_ASCII = '@test' |
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
TESTFN_ASCII = "{}_{}_tmp".format(TESTFN_ASCII, os.getpid()) |
| 23 |
|
| 24 |
|
| 25 |
TESTFN_UNICODE = TESTFN_ASCII + "-\xe0\xf2\u0258\u0141\u011f" |
| 26 |
if support.is_apple: |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
import unicodedata |
| 31 |
TESTFN_UNICODE = unicodedata.normalize('NFD', TESTFN_UNICODE) |
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
TESTFN_UNENCODABLE = None |
| 37 |
if os.name == 'nt': |
| 38 |
|
| 39 |
if sys.getwindowsversion().platform >= 2: |
| 40 |
|
| 41 |
|
| 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 |
|
| 53 |
elif not support.is_apple and sys.platform not in {"emscripten", "wasi"}: |
| 54 |
try: |
| 55 |
|
| 56 |
b'\xff'.decode(sys.getfilesystemencoding()) |
| 57 |
except UnicodeDecodeError: |
| 58 |
|
| 59 |
TESTFN_UNENCODABLE = TESTFN_ASCII \ |
| 60 |
+ b'-\xff'.decode(sys.getfilesystemencoding(), 'surrogateescape') |
| 61 |
else: |
| 62 |
|
| 63 |
|
| 64 |
pass |
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
FS_NONASCII = '' |
| 69 |
for character in ( |
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
'\u00E6', |
| 76 |
|
| 77 |
'\u0130', |
| 78 |
|
| 79 |
'\u0141', |
| 80 |
|
| 81 |
'\u03C6', |
| 82 |
|
| 83 |
'\u041A', |
| 84 |
|
| 85 |
'\u05D0', |
| 86 |
|
| 87 |
'\u060C', |
| 88 |
|
| 89 |
'\u062A', |
| 90 |
|
| 91 |
'\u0E01', |
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
'\u00A0', |
| 99 |
|
| 100 |
'\u20AC', |
| 101 |
): |
| 102 |
try: |
| 103 |
|
| 104 |
|
| 105 |
|
| 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 |
|
| 115 |
SAVEDCWD = os.getcwd() |
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
TESTFN_UNDECODABLE = None |
| 124 |
for name in ( |
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
b'\xe7w\xf0', |
| 130 |
|
| 131 |
b'\xff', |
| 132 |
|
| 133 |
|
| 134 |
b'\xae\xd5' |
| 135 |
|
| 136 |
b'\xed\xb2\x80', b'\xed\xb4\x80', |
| 137 |
|
| 138 |
|
| 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 |
|
| 180 |
|
| 181 |
|
| 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 |
|
| 208 |
|
| 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 |
|
| 237 |
|
| 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 |
|
| 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 |
@contextlib.contextmanager |
| 299 |
def save_mode(path, *, quiet=False): |
| 300 |
"""Context manager that restores the mode (permissions) of *path* on exit. |
| 301 |
|
| 302 |
Arguments: |
| 303 |
|
| 304 |
path: Path of the file to restore the mode of. |
| 305 |
|
| 306 |
quiet: if False (the default), the context manager raises an exception |
| 307 |
on error. Otherwise, it issues only a warning and keeps the current |
| 308 |
working directory the same. |
| 309 |
|
| 310 |
""" |
| 311 |
saved_mode = os.stat(path) |
| 312 |
try: |
| 313 |
yield |
| 314 |
finally: |
| 315 |
try: |
| 316 |
os.chmod(path, saved_mode.st_mode) |
| 317 |
except OSError as exc: |
| 318 |
if not quiet: |
| 319 |
raise |
| 320 |
warnings.warn(f'tests may fail, unable to restore the mode of ' |
| 321 |
f'{path!r} to {saved_mode.st_mode}: {exc}', |
| 322 |
RuntimeWarning, stacklevel=3) |
| 323 |
|
| 324 |
|
| 325 |
|
| 326 |
|
| 327 |
|
| 328 |
|
| 329 |
_can_dac_override = None |
| 330 |
|
| 331 |
def can_dac_override(): |
| 332 |
global _can_dac_override |
| 333 |
|
| 334 |
if not can_chmod(): |
| 335 |
_can_dac_override = False |
| 336 |
if _can_dac_override is not None: |
| 337 |
return _can_dac_override |
| 338 |
|
| 339 |
try: |
| 340 |
with open(TESTFN, "wb") as f: |
| 341 |
os.chmod(TESTFN, 0o400) |
| 342 |
try: |
| 343 |
with open(TESTFN, "wb"): |
| 344 |
pass |
| 345 |
except OSError: |
| 346 |
_can_dac_override = False |
| 347 |
else: |
| 348 |
_can_dac_override = True |
| 349 |
finally: |
| 350 |
try: |
| 351 |
os.chmod(TESTFN, 0o700) |
| 352 |
except OSError: |
| 353 |
pass |
| 354 |
unlink(TESTFN) |
| 355 |
|
| 356 |
return _can_dac_override |
| 357 |
|
| 358 |
|
| 359 |
def skip_if_dac_override(test): |
| 360 |
ok = not can_dac_override() |
| 361 |
msg = "incompatible with CAP_DAC_OVERRIDE" |
| 362 |
return test if ok else unittest.skip(msg)(test) |
| 363 |
|
| 364 |
|
| 365 |
def skip_unless_dac_override(test): |
| 366 |
ok = can_dac_override() |
| 367 |
msg = "requires CAP_DAC_OVERRIDE" |
| 368 |
return test if ok else unittest.skip(msg)(test) |
| 369 |
|
| 370 |
|
| 371 |
def unlink(filename): |
| 372 |
try: |
| 373 |
_unlink(filename) |
| 374 |
except (FileNotFoundError, NotADirectoryError): |
| 375 |
pass |
| 376 |
|
| 377 |
|
| 378 |
if sys.platform.startswith("win"): |
| 379 |
def _waitfor(func, pathname, waitall=False): |
| 380 |
|
| 381 |
func(pathname) |
| 382 |
|
| 383 |
if waitall: |
| 384 |
dirname = pathname |
| 385 |
else: |
| 386 |
dirname, name = os.path.split(pathname) |
| 387 |
dirname = dirname or '.' |
| 388 |
|
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
|
| 393 |
|
| 394 |
timeout = 0.001 |
| 395 |
while timeout < 1.0: |
| 396 |
|
| 397 |
|
| 398 |
|
| 399 |
|
| 400 |
|
| 401 |
|
| 402 |
|
| 403 |
L = os.listdir(dirname) |
| 404 |
if not (L if waitall else name in L): |
| 405 |
return |
| 406 |
|
| 407 |
time.sleep(timeout) |
| 408 |
timeout *= 2 |
| 409 |
logging.getLogger(__name__).warning( |
| 410 |
'tests may fail, delete still pending for %s', |
| 411 |
pathname, |
| 412 |
stack_info=True, |
| 413 |
stacklevel=4, |
| 414 |
) |
| 415 |
|
| 416 |
def _unlink(filename): |
| 417 |
_waitfor(os.unlink, filename) |
| 418 |
|
| 419 |
def _rmdir(dirname): |
| 420 |
_waitfor(os.rmdir, dirname) |
| 421 |
|
| 422 |
def _rmtree(path): |
| 423 |
from test.support import _force_run |
| 424 |
|
| 425 |
def _rmtree_inner(path): |
| 426 |
for name in _force_run(path, os.listdir, path): |
| 427 |
fullname = os.path.join(path, name) |
| 428 |
try: |
| 429 |
mode = os.lstat(fullname).st_mode |
| 430 |
except OSError as exc: |
| 431 |
print("support.rmtree(): os.lstat(%r) failed with %s" |
| 432 |
% (fullname, exc), |
| 433 |
file=sys.__stderr__) |
| 434 |
mode = 0 |
| 435 |
if stat.S_ISDIR(mode): |
| 436 |
_waitfor(_rmtree_inner, fullname, waitall=True) |
| 437 |
_force_run(fullname, os.rmdir, fullname) |
| 438 |
else: |
| 439 |
_force_run(fullname, os.unlink, fullname) |
| 440 |
_waitfor(_rmtree_inner, path, waitall=True) |
| 441 |
_waitfor(lambda p: _force_run(p, os.rmdir, p), path) |
| 442 |
|
| 443 |
def _longpath(path): |
| 444 |
try: |
| 445 |
import ctypes |
| 446 |
except ImportError: |
| 447 |
|
| 448 |
pass |
| 449 |
else: |
| 450 |
buffer = ctypes.create_unicode_buffer(len(path) * 2) |
| 451 |
length = ctypes.windll.kernel32.GetLongPathNameW(path, buffer, |
| 452 |
len(buffer)) |
| 453 |
if length: |
| 454 |
return buffer[:length] |
| 455 |
return path |
| 456 |
else: |
| 457 |
_unlink = os.unlink |
| 458 |
_rmdir = os.rmdir |
| 459 |
|
| 460 |
def _rmtree(path): |
| 461 |
import shutil |
| 462 |
try: |
| 463 |
shutil.rmtree(path) |
| 464 |
return |
| 465 |
except OSError: |
| 466 |
pass |
| 467 |
|
| 468 |
def _rmtree_inner(path): |
| 469 |
from test.support import _force_run |
| 470 |
|
| 471 |
if hasattr(os, 'chflags'): |
| 472 |
try: |
| 473 |
os.chflags(path, 0) |
| 474 |
except OSError: |
| 475 |
pass |
| 476 |
for name in _force_run(path, os.listdir, path): |
| 477 |
fullname = os.path.join(path, name) |
| 478 |
try: |
| 479 |
mode = os.lstat(fullname).st_mode |
| 480 |
except OSError: |
| 481 |
mode = 0 |
| 482 |
if hasattr(os, 'lchflags'): |
| 483 |
try: |
| 484 |
os.lchflags(fullname, 0) |
| 485 |
except OSError: |
| 486 |
pass |
| 487 |
if stat.S_ISDIR(mode): |
| 488 |
_rmtree_inner(fullname) |
| 489 |
_force_run(path, os.rmdir, fullname) |
| 490 |
else: |
| 491 |
_force_run(path, os.unlink, fullname) |
| 492 |
_rmtree_inner(path) |
| 493 |
os.rmdir(path) |
| 494 |
|
| 495 |
def _longpath(path): |
| 496 |
return path |
| 497 |
|
| 498 |
|
| 499 |
def rmdir(dirname): |
| 500 |
try: |
| 501 |
_rmdir(dirname) |
| 502 |
except FileNotFoundError: |
| 503 |
pass |
| 504 |
|
| 505 |
|
| 506 |
def rmtree(path): |
| 507 |
try: |
| 508 |
_rmtree(path) |
| 509 |
except FileNotFoundError: |
| 510 |
pass |
| 511 |
|
| 512 |
|
| 513 |
@contextlib.contextmanager |
| 514 |
def temp_dir(path=None, quiet=False): |
| 515 |
"""Return a context manager that creates a temporary directory. |
| 516 |
|
| 517 |
Arguments: |
| 518 |
|
| 519 |
path: the directory to create temporarily. If omitted or None, |
| 520 |
defaults to creating a temporary directory using tempfile.mkdtemp. |
| 521 |
|
| 522 |
quiet: if False (the default), the context manager raises an exception |
| 523 |
on error. Otherwise, if the path is specified and cannot be |
| 524 |
created, only a warning is issued. |
| 525 |
|
| 526 |
""" |
| 527 |
import tempfile |
| 528 |
dir_created = False |
| 529 |
if path is None: |
| 530 |
path = tempfile.mkdtemp() |
| 531 |
dir_created = True |
| 532 |
path = os.path.realpath(path) |
| 533 |
else: |
| 534 |
try: |
| 535 |
os.mkdir(path) |
| 536 |
dir_created = True |
| 537 |
except OSError as exc: |
| 538 |
if not quiet: |
| 539 |
raise |
| 540 |
logging.getLogger(__name__).warning( |
| 541 |
"tests may fail, unable to create temporary directory %r: %s", |
| 542 |
path, |
| 543 |
exc, |
| 544 |
exc_info=exc, |
| 545 |
stack_info=True, |
| 546 |
stacklevel=3, |
| 547 |
) |
| 548 |
if dir_created: |
| 549 |
pid = os.getpid() |
| 550 |
try: |
| 551 |
yield path |
| 552 |
finally: |
| 553 |
|
| 554 |
|
| 555 |
if dir_created and pid == os.getpid(): |
| 556 |
rmtree(path) |
| 557 |
|
| 558 |
|
| 559 |
@contextlib.contextmanager |
| 560 |
def change_cwd(path, quiet=False): |
| 561 |
"""Return a context manager that changes the current working directory. |
| 562 |
|
| 563 |
Arguments: |
| 564 |
|
| 565 |
path: the directory to use as the temporary current working directory. |
| 566 |
|
| 567 |
quiet: if False (the default), the context manager raises an exception |
| 568 |
on error. Otherwise, it issues only a warning and keeps the current |
| 569 |
working directory the same. |
| 570 |
|
| 571 |
""" |
| 572 |
saved_dir = os.getcwd() |
| 573 |
try: |
| 574 |
os.chdir(os.path.realpath(path)) |
| 575 |
except OSError as exc: |
| 576 |
if not quiet: |
| 577 |
raise |
| 578 |
logging.getLogger(__name__).warning( |
| 579 |
'tests may fail, unable to change the current working directory ' |
| 580 |
'to %r: %s', |
| 581 |
path, |
| 582 |
exc, |
| 583 |
exc_info=exc, |
| 584 |
stack_info=True, |
| 585 |
stacklevel=3, |
| 586 |
) |
| 587 |
try: |
| 588 |
yield os.getcwd() |
| 589 |
finally: |
| 590 |
os.chdir(saved_dir) |
| 591 |
|
| 592 |
|
| 593 |
@contextlib.contextmanager |
| 594 |
def temp_cwd(name='tempcwd', quiet=False): |
| 595 |
""" |
| 596 |
Context manager that temporarily creates and changes the CWD. |
| 597 |
|
| 598 |
The function temporarily changes the current working directory |
| 599 |
after creating a temporary directory in the current directory with |
| 600 |
name *name*. If *name* is None, the temporary directory is |
| 601 |
created using tempfile.mkdtemp. |
| 602 |
|
| 603 |
If *quiet* is False (default) and it is not possible to |
| 604 |
create or change the CWD, an error is raised. If *quiet* is True, |
| 605 |
only a warning is raised and the original CWD is used. |
| 606 |
|
| 607 |
""" |
| 608 |
with temp_dir(path=name, quiet=quiet) as temp_path: |
| 609 |
with change_cwd(temp_path, quiet=quiet) as cwd_dir: |
| 610 |
yield cwd_dir |
| 611 |
|
| 612 |
|
| 613 |
def create_empty_file(filename): |
| 614 |
"""Create an empty file. If the file already exists, truncate it.""" |
| 615 |
fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC) |
| 616 |
os.close(fd) |
| 617 |
|
| 618 |
|
| 619 |
@contextlib.contextmanager |
| 620 |
def open_dir_fd(path): |
| 621 |
"""Open a file descriptor to a directory.""" |
| 622 |
assert os.path.isdir(path) |
| 623 |
flags = os.O_RDONLY |
| 624 |
if hasattr(os, "O_DIRECTORY"): |
| 625 |
flags |= os.O_DIRECTORY |
| 626 |
dir_fd = os.open(path, flags) |
| 627 |
try: |
| 628 |
yield dir_fd |
| 629 |
finally: |
| 630 |
os.close(dir_fd) |
| 631 |
|
| 632 |
|
| 633 |
def fs_is_case_insensitive(directory): |
| 634 |
"""Detects if the file system for the specified directory |
| 635 |
is case-insensitive.""" |
| 636 |
import tempfile |
| 637 |
with tempfile.NamedTemporaryFile(dir=directory) as base: |
| 638 |
base_path = base.name |
| 639 |
case_path = base_path.upper() |
| 640 |
if case_path == base_path: |
| 641 |
case_path = base_path.lower() |
| 642 |
try: |
| 643 |
return os.path.samefile(base_path, case_path) |
| 644 |
except FileNotFoundError: |
| 645 |
return False |
| 646 |
|
| 647 |
|
| 648 |
class FakePath: |
| 649 |
"""Simple implementation of the path protocol. |
| 650 |
""" |
| 651 |
def __init__(self, path): |
| 652 |
self.path = path |
| 653 |
|
| 654 |
def __repr__(self): |
| 655 |
return f'<FakePath {self.path!r}>' |
| 656 |
|
| 657 |
def __fspath__(self): |
| 658 |
if (isinstance(self.path, BaseException) or |
| 659 |
isinstance(self.path, type) and |
| 660 |
issubclass(self.path, BaseException)): |
| 661 |
raise self.path |
| 662 |
else: |
| 663 |
return self.path |
| 664 |
|
| 665 |
|
| 666 |
def fd_count(): |
| 667 |
"""Count the number of open file descriptors. |
| 668 |
""" |
| 669 |
if sys.platform.startswith(('linux', 'android', 'freebsd', 'emscripten')): |
| 670 |
fd_path = "/proc/self/fd" |
| 671 |
elif support.is_apple: |
| 672 |
fd_path = "/dev/fd" |
| 673 |
else: |
| 674 |
fd_path = None |
| 675 |
|
| 676 |
if fd_path is not None: |
| 677 |
try: |
| 678 |
names = os.listdir(fd_path) |
| 679 |
|
| 680 |
|
| 681 |
return len(names) - 1 |
| 682 |
except FileNotFoundError: |
| 683 |
pass |
| 684 |
|
| 685 |
MAXFD = 256 |
| 686 |
if hasattr(os, 'sysconf'): |
| 687 |
try: |
| 688 |
MAXFD = os.sysconf("SC_OPEN_MAX") |
| 689 |
except OSError: |
| 690 |
pass |
| 691 |
|
| 692 |
old_modes = None |
| 693 |
if sys.platform == 'win32': |
| 694 |
|
| 695 |
|
| 696 |
try: |
| 697 |
import msvcrt |
| 698 |
msvcrt.CrtSetReportMode |
| 699 |
except (AttributeError, ImportError): |
| 700 |
|
| 701 |
pass |
| 702 |
else: |
| 703 |
old_modes = {} |
| 704 |
for report_type in (msvcrt.CRT_WARN, |
| 705 |
msvcrt.CRT_ERROR, |
| 706 |
msvcrt.CRT_ASSERT): |
| 707 |
old_modes[report_type] = msvcrt.CrtSetReportMode(report_type, |
| 708 |
0) |
| 709 |
|
| 710 |
try: |
| 711 |
count = 0 |
| 712 |
for fd in range(MAXFD): |
| 713 |
try: |
| 714 |
|
| 715 |
|
| 716 |
fd2 = os.dup(fd) |
| 717 |
except OSError as e: |
| 718 |
if e.errno != errno.EBADF: |
| 719 |
raise |
| 720 |
else: |
| 721 |
os.close(fd2) |
| 722 |
count += 1 |
| 723 |
finally: |
| 724 |
if old_modes is not None: |
| 725 |
for report_type in (msvcrt.CRT_WARN, |
| 726 |
msvcrt.CRT_ERROR, |
| 727 |
msvcrt.CRT_ASSERT): |
| 728 |
msvcrt.CrtSetReportMode(report_type, old_modes[report_type]) |
| 729 |
|
| 730 |
return count |
| 731 |
|
| 732 |
|
| 733 |
if hasattr(os, "umask"): |
| 734 |
@contextlib.contextmanager |
| 735 |
def temp_umask(umask): |
| 736 |
"""Context manager that temporarily sets the process umask.""" |
| 737 |
oldmask = os.umask(umask) |
| 738 |
try: |
| 739 |
yield |
| 740 |
finally: |
| 741 |
os.umask(oldmask) |
| 742 |
else: |
| 743 |
@contextlib.contextmanager |
| 744 |
def temp_umask(umask): |
| 745 |
"""no-op on platforms without umask()""" |
| 746 |
yield |
| 747 |
|
| 748 |
|
| 749 |
class EnvironmentVarGuard(collections.abc.MutableMapping): |
| 750 |
"""Class to help protect the environment variable properly. |
| 751 |
|
| 752 |
Can be used as a context manager. |
| 753 |
""" |
| 754 |
|
| 755 |
def __init__(self): |
| 756 |
self._environ = os.environ |
| 757 |
self._changed = {} |
| 758 |
|
| 759 |
def __getitem__(self, envvar): |
| 760 |
return self._environ[envvar] |
| 761 |
|
| 762 |
def __setitem__(self, envvar, value): |
| 763 |
|
| 764 |
if envvar not in self._changed: |
| 765 |
self._changed[envvar] = self._environ.get(envvar) |
| 766 |
self._environ[envvar] = value |
| 767 |
|
| 768 |
def __delitem__(self, envvar): |
| 769 |
|
| 770 |
if envvar not in self._changed: |
| 771 |
self._changed[envvar] = self._environ.get(envvar) |
| 772 |
if envvar in self._environ: |
| 773 |
del self._environ[envvar] |
| 774 |
|
| 775 |
def keys(self): |
| 776 |
return self._environ.keys() |
| 777 |
|
| 778 |
def __iter__(self): |
| 779 |
return iter(self._environ) |
| 780 |
|
| 781 |
def __len__(self): |
| 782 |
return len(self._environ) |
| 783 |
|
| 784 |
def set(self, envvar, value): |
| 785 |
self[envvar] = value |
| 786 |
|
| 787 |
def unset(self, envvar, /, *envvars): |
| 788 |
"""Unset one or more environment variables.""" |
| 789 |
for ev in (envvar, *envvars): |
| 790 |
del self[ev] |
| 791 |
|
| 792 |
def copy(self): |
| 793 |
|
| 794 |
return dict(self) |
| 795 |
|
| 796 |
def __enter__(self): |
| 797 |
return self |
| 798 |
|
| 799 |
def __exit__(self, *ignore_exc): |
| 800 |
for (k, v) in self._changed.items(): |
| 801 |
if v is None: |
| 802 |
if k in self._environ: |
| 803 |
del self._environ[k] |
| 804 |
else: |
| 805 |
self._environ[k] = v |
| 806 |
os.environ = self._environ |
| 807 |
|
| 808 |
|
| 809 |
try: |
| 810 |
if support.MS_WINDOWS: |
| 811 |
import ctypes |
| 812 |
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) |
| 813 |
|
| 814 |
ERROR_FILE_NOT_FOUND = 2 |
| 815 |
DDD_REMOVE_DEFINITION = 2 |
| 816 |
DDD_EXACT_MATCH_ON_REMOVE = 4 |
| 817 |
DDD_NO_BROADCAST_SYSTEM = 8 |
| 818 |
else: |
| 819 |
raise AttributeError |
| 820 |
except (ImportError, AttributeError): |
| 821 |
def subst_drive(path): |
| 822 |
raise unittest.SkipTest('ctypes or kernel32 is not available') |
| 823 |
else: |
| 824 |
@contextlib.contextmanager |
| 825 |
def subst_drive(path): |
| 826 |
"""Temporarily yield a substitute drive for a given path.""" |
| 827 |
for c in reversed(string.ascii_uppercase): |
| 828 |
drive = f'{c}:' |
| 829 |
if (not kernel32.QueryDosDeviceW(drive, None, 0) and |
| 830 |
ctypes.get_last_error() == ERROR_FILE_NOT_FOUND): |
| 831 |
break |
| 832 |
else: |
| 833 |
raise unittest.SkipTest('no available logical drive') |
| 834 |
if not kernel32.DefineDosDeviceW( |
| 835 |
DDD_NO_BROADCAST_SYSTEM, drive, path): |
| 836 |
raise ctypes.WinError(ctypes.get_last_error()) |
| 837 |
try: |
| 838 |
yield drive |
| 839 |
finally: |
| 840 |
if not kernel32.DefineDosDeviceW( |
| 841 |
DDD_REMOVE_DEFINITION | DDD_EXACT_MATCH_ON_REMOVE, |
| 842 |
drive, path): |
| 843 |
raise ctypes.WinError(ctypes.get_last_error()) |