Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Update (partial) test.support
  • Loading branch information
ShaharNaveh committed Jul 8, 2025
commit 32ee630f550bebac13d0e4609b71d337a6b14162
24 changes: 24 additions & 0 deletions Lib/test/support/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2601,6 +2601,30 @@ def adjust_int_max_str_digits(max_digits):
'skipped on s390x')
HAVE_ASAN_FORK_BUG = check_sanitizer(address=True)

# From Cpython 3.13.5
@contextlib.contextmanager
def no_color():
import _colorize
from .os_helper import EnvironmentVarGuard

with (
swap_attr(_colorize, "can_colorize", lambda file=None: False),
EnvironmentVarGuard() as env,
):
env.unset("FORCE_COLOR", "NO_COLOR", "PYTHON_COLORS")
env.set("NO_COLOR", "1")
yield

# From Cpython 3.13.5
def force_not_colorized(func):
"""Force the terminal not to be colorized."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
with no_color():
return func(*args, **kwargs)
return wrapper


# From python 3.12.8
class BrokenIter:
def __init__(self, init_raises=False, next_raises=False, iter_raises=False):
Expand Down
110 changes: 81 additions & 29 deletions Lib/test/support/os_helper.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import collections.abc
import contextlib
import errno
import logging
import os
import re
import stat
Expand All @@ -10,6 +11,8 @@
import unittest
import warnings

from test import support


# Filename used for testing
TESTFN_ASCII = '@test'
Expand All @@ -20,8 +23,8 @@

# TESTFN_UNICODE is a non-ascii filename
TESTFN_UNICODE = TESTFN_ASCII + "-\xe0\xf2\u0258\u0141\u011f"
if sys.platform == 'darwin':
# In Mac OS X's VFS API file names are, by definition, canonically
if support.is_apple:
# On Apple's VFS API file names are, by definition, canonically
# decomposed Unicode, encoded using UTF-8. See QA1173:
# http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
import unicodedata
Expand All @@ -46,8 +49,8 @@
'encoding (%s). Unicode filename tests may not be effective'
% (TESTFN_UNENCODABLE, sys.getfilesystemencoding()))
TESTFN_UNENCODABLE = None
# macOS and Emscripten deny unencodable filenames (invalid utf-8)
elif sys.platform not in {'darwin', 'emscripten', 'wasi'}:
# Apple and Emscripten deny unencodable filenames (invalid utf-8)
elif not support.is_apple and sys.platform not in {"emscripten", "wasi"}:
try:
# ascii and utf-8 cannot encode the byte 0xff
b'\xff'.decode(sys.getfilesystemencoding())
Expand Down Expand Up @@ -196,6 +199,23 @@ def skip_unless_symlink(test):
return test if ok else unittest.skip(msg)(test)


_can_hardlink = None

def can_hardlink():
global _can_hardlink
if _can_hardlink is None:
# Android blocks hard links using SELinux
# (https://stackoverflow.com/q/32365690).
_can_hardlink = hasattr(os, "link") and not support.is_android
return _can_hardlink


def skip_unless_hardlink(test):
ok = can_hardlink()
msg = "requires hardlink support"
return test if ok else unittest.skip(msg)(test)


_can_xattr = None


Expand Down Expand Up @@ -245,15 +265,15 @@ def can_chmod():
global _can_chmod
if _can_chmod is not None:
return _can_chmod
if not hasattr(os, "chown"):
if not hasattr(os, "chmod"):
_can_chmod = False
return _can_chmod
try:
with open(TESTFN, "wb") as f:
try:
os.chmod(TESTFN, 0o777)
os.chmod(TESTFN, 0o555)
mode1 = os.stat(TESTFN).st_mode
os.chmod(TESTFN, 0o666)
os.chmod(TESTFN, 0o777)
mode2 = os.stat(TESTFN).st_mode
except OSError as e:
can = False
Expand Down Expand Up @@ -300,6 +320,10 @@ def can_dac_override():
else:
_can_dac_override = True
finally:
try:
os.chmod(TESTFN, 0o700)
except OSError:
pass
unlink(TESTFN)

return _can_dac_override
Expand Down Expand Up @@ -355,8 +379,12 @@ def _waitfor(func, pathname, waitall=False):
# Increase the timeout and try again
time.sleep(timeout)
timeout *= 2
warnings.warn('tests may fail, delete still pending for ' + pathname,
RuntimeWarning, stacklevel=4)
logging.getLogger(__name__).warning(
'tests may fail, delete still pending for %s',
pathname,
stack_info=True,
stacklevel=4,
)

def _unlink(filename):
_waitfor(os.unlink, filename)
Expand Down Expand Up @@ -471,9 +499,14 @@ def temp_dir(path=None, quiet=False):
except OSError as exc:
if not quiet:
raise
warnings.warn(f'tests may fail, unable to create '
f'temporary directory {path!r}: {exc}',
RuntimeWarning, stacklevel=3)
logging.getLogger(__name__).warning(
"tests may fail, unable to create temporary directory %r: %s",
path,
exc,
exc_info=exc,
stack_info=True,
stacklevel=3,
)
if dir_created:
pid = os.getpid()
try:
Expand Down Expand Up @@ -504,9 +537,15 @@ def change_cwd(path, quiet=False):
except OSError as exc:
if not quiet:
raise
warnings.warn(f'tests may fail, unable to change the current working '
f'directory to {path!r}: {exc}',
RuntimeWarning, stacklevel=3)
logging.getLogger(__name__).warning(
'tests may fail, unable to change the current working directory '
'to %r: %s',
path,
exc,
exc_info=exc,
stack_info=True,
stacklevel=3,
)
try:
yield os.getcwd()
finally:
Expand Down Expand Up @@ -589,11 +628,18 @@ def __fspath__(self):
def fd_count():
"""Count the number of open file descriptors.
"""
if sys.platform.startswith(('linux', 'freebsd', 'emscripten')):
if sys.platform.startswith(('linux', 'android', 'freebsd', 'emscripten')):
fd_path = "/proc/self/fd"
elif support.is_apple:
fd_path = "/dev/fd"
else:
fd_path = None

if fd_path is not None:
try:
names = os.listdir("/proc/self/fd")
names = os.listdir(fd_path)
# Subtract one because listdir() internally opens a file
# descriptor to list the content of the /proc/self/fd/ directory.
# descriptor to list the content of the directory.
return len(names) - 1
except FileNotFoundError:
pass
Expand Down Expand Up @@ -663,9 +709,10 @@ def temp_umask(umask):


class EnvironmentVarGuard(collections.abc.MutableMapping):
"""Class to help protect the environment variable properly.

"""Class to help protect the environment variable properly. Can be used as
a context manager."""
Can be used as a context manager.
"""

def __init__(self):
self._environ = os.environ
Expand Down Expand Up @@ -699,8 +746,10 @@ def __len__(self):
def set(self, envvar, value):
self[envvar] = value

def unset(self, envvar):
del self[envvar]
def unset(self, envvar, /, *envvars):
"""Unset one or more environment variables."""
for ev in (envvar, *envvars):
del self[ev]

def copy(self):
# We do what os.environ.copy() does.
Expand All @@ -720,13 +769,16 @@ def __exit__(self, *ignore_exc):


try:
import ctypes
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

ERROR_FILE_NOT_FOUND = 2
DDD_REMOVE_DEFINITION = 2
DDD_EXACT_MATCH_ON_REMOVE = 4
DDD_NO_BROADCAST_SYSTEM = 8
if support.MS_WINDOWS:
import ctypes
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

ERROR_FILE_NOT_FOUND = 2
DDD_REMOVE_DEFINITION = 2
DDD_EXACT_MATCH_ON_REMOVE = 4
DDD_NO_BROADCAST_SYSTEM = 8
else:
raise AttributeError
except (ImportError, AttributeError):
def subst_drive(path):
raise unittest.SkipTest('ctypes or kernel32 is not available')
Expand Down