| 1 |
# mypy: allow-untyped-defs |
| 2 |
"""Python version compatibility code and random general utilities.""" |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
from collections.abc import Callable |
| 7 |
import enum |
| 8 |
import functools |
| 9 |
import inspect |
| 10 |
from inspect import Parameter |
| 11 |
from inspect import Signature |
| 12 |
import os |
| 13 |
from pathlib import Path |
| 14 |
import sys |
| 15 |
from typing import Any |
| 16 |
from typing import Final |
| 17 |
from typing import NoReturn |
| 18 |
from typing import TYPE_CHECKING |
| 19 |
|
| 20 |
import py |
| 21 |
|
| 22 |
|
| 23 |
if sys.version_info >= (3, 14): |
| 24 |
from annotationlib import Format |
| 25 |
|
| 26 |
|
| 27 |
#: constant to prepare valuing pylib path replacements/lazy proxies later on |
| 28 |
# intended for removal in pytest 8.0 or 9.0 |
| 29 |
|
| 30 |
# fmt: off |
| 31 |
# intentional space to create a fake difference for the verification |
| 32 |
LEGACY_PATH = py.path. local |
| 33 |
# fmt: on |
| 34 |
|
| 35 |
|
| 36 |
def legacy_path(path: str | os.PathLike[str]) -> LEGACY_PATH: |
| 37 |
"""Internal wrapper to prepare lazy proxies for legacy_path instances""" |
| 38 |
return LEGACY_PATH(path) |
| 39 |
|
| 40 |
|
| 41 |
# fmt: off |
| 42 |
# Singleton type for NOTSET, as described in: |
| 43 |
# https://www.python.org/dev/peps/pep-0484/#support-for-singleton-types-in-unions |
| 44 |
class NotSetType(enum.Enum): |
| 45 |
token = 0 |
| 46 |
NOTSET: Final = NotSetType.token |
| 47 |
# fmt: on |
| 48 |
|
| 49 |
|
| 50 |
def iscoroutinefunction(func: object) -> bool: |
| 51 |
"""Return True if func is a coroutine function (a function defined with async |
| 52 |
def syntax, and doesn't contain yield), or a function decorated with |
| 53 |
@asyncio.coroutine. |
| 54 |
|
| 55 |
Note: copied and modified from Python 3.5's builtin coroutines.py to avoid |
| 56 |
importing asyncio directly, which in turns also initializes the "logging" |
| 57 |
module as a side-effect (see issue #8). |
| 58 |
""" |
| 59 |
return inspect.iscoroutinefunction(func) or getattr(func, "_is_coroutine", False) |
| 60 |
|
| 61 |
|
| 62 |
def is_async_function(func: object) -> bool: |
| 63 |
"""Return True if the given function seems to be an async function or |
| 64 |
an async generator.""" |
| 65 |
return iscoroutinefunction(func) or inspect.isasyncgenfunction(func) |
| 66 |
|
| 67 |
|
| 68 |
def signature(obj: Callable[..., Any]) -> Signature: |
| 69 |
"""Return signature without evaluating annotations.""" |
| 70 |
if sys.version_info >= (3, 14): |
| 71 |
return inspect.signature(obj, annotation_format=Format.STRING) |
| 72 |
return inspect.signature(obj) |
| 73 |
|
| 74 |
|
| 75 |
def getlocation(function, curdir: str | os.PathLike[str] | None = None) -> str: |
| 76 |
function = get_real_func(function) |
| 77 |
fn = Path(inspect.getfile(function)) |
| 78 |
lineno = function.__code__.co_firstlineno |
| 79 |
if curdir is not None: |
| 80 |
try: |
| 81 |
relfn = fn.relative_to(curdir) |
| 82 |
except ValueError: |
| 83 |
pass |
| 84 |
else: |
| 85 |
return f"{relfn}:{lineno + 1}" |
| 86 |
return f"{fn}:{lineno + 1}" |
| 87 |
|
| 88 |
|
| 89 |
def num_mock_patch_args(function) -> int: |
| 90 |
"""Return number of arguments used up by mock arguments (if any).""" |
| 91 |
patchings = getattr(function, "patchings", None) |
| 92 |
if not patchings: |
| 93 |
return 0 |
| 94 |
|
| 95 |
mock_sentinel = getattr(sys.modules.get("mock"), "DEFAULT", object()) |
| 96 |
ut_mock_sentinel = getattr(sys.modules.get("unittest.mock"), "DEFAULT", object()) |
| 97 |
|
| 98 |
return len( |
| 99 |
[ |
| 100 |
p |
| 101 |
for p in patchings |
| 102 |
if not p.attribute_name |
| 103 |
and (p.new is mock_sentinel or p.new is ut_mock_sentinel) |
| 104 |
] |
| 105 |
) |
| 106 |
|
| 107 |
|
| 108 |
def getfuncargnames( |
| 109 |
function: Callable[..., object], |
| 110 |
*, |
| 111 |
name: str = "", |
| 112 |
cls: type | None = None, |
| 113 |
) -> tuple[str, ...]: |
| 114 |
"""Return the names of a function's mandatory arguments. |
| 115 |
|
| 116 |
Should return the names of all function arguments that: |
| 117 |
* Aren't bound to an instance or type as in instance or class methods. |
| 118 |
* Don't have default values. |
| 119 |
* Aren't bound with functools.partial. |
| 120 |
* Aren't replaced with mocks. |
| 121 |
|
| 122 |
The cls arguments indicate that the function should be treated as a bound |
| 123 |
method even though it's not unless the function is a static method. |
| 124 |
|
| 125 |
The name parameter should be the original name in which the function was collected. |
| 126 |
""" |
| 127 |
# TODO(RonnyPfannschmidt): This function should be refactored when we |
| 128 |
# revisit fixtures. The fixture mechanism should ask the node for |
| 129 |
# the fixture names, and not try to obtain directly from the |
| 130 |
# function object well after collection has occurred. |
| 131 |
|
| 132 |
# The parameters attribute of a Signature object contains an |
| 133 |
# ordered mapping of parameter names to Parameter instances. This |
| 134 |
# creates a tuple of the names of the parameters that don't have |
| 135 |
# defaults. |
| 136 |
try: |
| 137 |
parameters = signature(function).parameters.values() |
| 138 |
except (ValueError, TypeError) as e: |
| 139 |
from _pytest.outcomes import fail |
| 140 |
|
| 141 |
fail( |
| 142 |
f"Could not determine arguments of {function!r}: {e}", |
| 143 |
pytrace=False, |
| 144 |
) |
| 145 |
|
| 146 |
arg_names = tuple( |
| 147 |
p.name |
| 148 |
for p in parameters |
| 149 |
if ( |
| 150 |
p.kind is Parameter.POSITIONAL_OR_KEYWORD |
| 151 |
or p.kind is Parameter.KEYWORD_ONLY |
| 152 |
) |
| 153 |
and p.default is Parameter.empty |
| 154 |
) |
| 155 |
if not name: |
| 156 |
name = function.__name__ |
| 157 |
|
| 158 |
# If this function should be treated as a bound method even though |
| 159 |
# it's passed as an unbound method or function, and its first parameter |
| 160 |
# wasn't defined as positional only, remove the first parameter name. |
| 161 |
if not any(p.kind is Parameter.POSITIONAL_ONLY for p in parameters) and ( |
| 162 |
# Not using `getattr` because we don't want to resolve the staticmethod. |
| 163 |
# Not using `cls.__dict__` because we want to check the entire MRO. |
| 164 |
cls |
| 165 |
and not isinstance( |
| 166 |
inspect.getattr_static(cls, name, default=None), staticmethod |
| 167 |
) |
| 168 |
): |
| 169 |
arg_names = arg_names[1:] |
| 170 |
# Remove any names that will be replaced with mocks. |
| 171 |
if hasattr(function, "__wrapped__"): |
| 172 |
arg_names = arg_names[num_mock_patch_args(function) :] |
| 173 |
return arg_names |
| 174 |
|
| 175 |
|
| 176 |
def get_default_arg_names(function: Callable[..., Any]) -> tuple[str, ...]: |
| 177 |
# Note: this code intentionally mirrors the code at the beginning of |
| 178 |
# getfuncargnames, to get the arguments which were excluded from its result |
| 179 |
# because they had default values. |
| 180 |
return tuple( |
| 181 |
p.name |
| 182 |
for p in signature(function).parameters.values() |
| 183 |
if p.kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY) |
| 184 |
and p.default is not Parameter.empty |
| 185 |
) |
| 186 |
|
| 187 |
|
| 188 |
_non_printable_ascii_translate_table = { |
| 189 |
i: f"\\x{i:02x}" for i in range(128) if i not in range(32, 127) |
| 190 |
} |
| 191 |
_non_printable_ascii_translate_table.update( |
| 192 |
{ord("\t"): "\\t", ord("\r"): "\\r", ord("\n"): "\\n"} |
| 193 |
) |
| 194 |
|
| 195 |
|
| 196 |
def ascii_escaped(val: bytes | str) -> str: |
| 197 |
r"""If val is pure ASCII, return it as an str, otherwise, escape |
| 198 |
bytes objects into a sequence of escaped bytes: |
| 199 |
|
| 200 |
b'\xc3\xb4\xc5\xd6' -> r'\xc3\xb4\xc5\xd6' |
| 201 |
|
| 202 |
and escapes strings into a sequence of escaped unicode ids, e.g.: |
| 203 |
|
| 204 |
r'4\nV\U00043efa\x0eMXWB\x1e\u3028\u15fd\xcd\U0007d944' |
| 205 |
|
| 206 |
Note: |
| 207 |
The obvious "v.decode('unicode-escape')" will return |
| 208 |
valid UTF-8 unicode if it finds them in bytes, but we |
| 209 |
want to return escaped bytes for any byte, even if they match |
| 210 |
a UTF-8 string. |
| 211 |
""" |
| 212 |
if isinstance(val, bytes): |
| 213 |
ret = val.decode("ascii", "backslashreplace") |
| 214 |
else: |
| 215 |
ret = val.encode("unicode_escape").decode("ascii") |
| 216 |
return ret.translate(_non_printable_ascii_translate_table) |
| 217 |
|
| 218 |
|
| 219 |
def get_real_func(obj): |
| 220 |
"""Get the real function object of the (possibly) wrapped object by |
| 221 |
:func:`functools.wraps`, or :func:`functools.partial`.""" |
| 222 |
obj = inspect.unwrap(obj) |
| 223 |
|
| 224 |
if isinstance(obj, functools.partial): |
| 225 |
obj = obj.func |
| 226 |
return obj |
| 227 |
|
| 228 |
|
| 229 |
def getimfunc(func): |
| 230 |
try: |
| 231 |
return func.__func__ |
| 232 |
except AttributeError: |
| 233 |
return func |
| 234 |
|
| 235 |
|
| 236 |
def safe_getattr(object: Any, name: str, default: Any) -> Any: |
| 237 |
"""Like getattr but return default upon any Exception or any OutcomeException. |
| 238 |
|
| 239 |
Attribute access can potentially fail for 'evil' Python objects. |
| 240 |
See issue #214. |
| 241 |
It catches OutcomeException because of #2490 (issue #580), new outcomes |
| 242 |
are derived from BaseException instead of Exception (for more details |
| 243 |
check #2707). |
| 244 |
""" |
| 245 |
from _pytest.outcomes import TEST_OUTCOME |
| 246 |
|
| 247 |
try: |
| 248 |
return getattr(object, name, default) |
| 249 |
except TEST_OUTCOME: |
| 250 |
return default |
| 251 |
|
| 252 |
|
| 253 |
def safe_isclass(obj: object) -> bool: |
| 254 |
"""Ignore any exception via isinstance on Python 3.""" |
| 255 |
try: |
| 256 |
return inspect.isclass(obj) |
| 257 |
except Exception: |
| 258 |
return False |
| 259 |
|
| 260 |
|
| 261 |
def get_user_id() -> int | None: |
| 262 |
"""Return the current process's real user id or None if it could not be |
| 263 |
determined. |
| 264 |
|
| 265 |
:return: The user id or None if it could not be determined. |
| 266 |
""" |
| 267 |
# mypy follows the version and platform checking expectation of PEP 484: |
| 268 |
# https://mypy.readthedocs.io/en/stable/common_issues.html?highlight=platform#python-version-and-system-platform-checks |
| 269 |
# Containment checks are too complex for mypy v1.5.0 and cause failure. |
| 270 |
if sys.platform == "win32" or sys.platform == "emscripten": |
| 271 |
# win32 does not have a getuid() function. |
| 272 |
# Emscripten has a return 0 stub. |
| 273 |
return None |
| 274 |
else: |
| 275 |
# On other platforms, a return value of -1 is assumed to indicate that |
| 276 |
# the current process's real user id could not be determined. |
| 277 |
ERROR = -1 |
| 278 |
uid = os.getuid() |
| 279 |
return uid if uid != ERROR else None |
| 280 |
|
| 281 |
|
| 282 |
if sys.version_info >= (3, 11): |
| 283 |
from typing import assert_never |
| 284 |
else: |
| 285 |
|
| 286 |
def assert_never(value: NoReturn) -> NoReturn: |
| 287 |
assert False, f"Unhandled value: {value} ({type(value).__name__})" |
| 288 |
|
| 289 |
|
| 290 |
class CallableBool: |
| 291 |
""" |
| 292 |
A bool-like object that can also be called, returning its true/false value. |
| 293 |
|
| 294 |
Used for backwards compatibility in cases where something was supposed to be a method |
| 295 |
but was implemented as a simple attribute by mistake (see `TerminalReporter.isatty`). |
| 296 |
|
| 297 |
Do not use in new code. |
| 298 |
""" |
| 299 |
|
| 300 |
def __init__(self, value: bool) -> None: |
| 301 |
self._value = value |
| 302 |
|
| 303 |
def __bool__(self) -> bool: |
| 304 |
return self._value |
| 305 |
|
| 306 |
def __call__(self) -> bool: |
| 307 |
return self._value |
| 308 |
|
| 309 |
|
| 310 |
def running_on_ci() -> bool: |
| 311 |
"""Check if we're currently running on a CI system.""" |
| 312 |
# Only enable CI mode if one of these env variables is defined and non-empty. |
| 313 |
# Note: review `regendoc` tox env in case this list is changed. |
| 314 |
env_vars = ["CI", "BUILD_NUMBER"] |
| 315 |
return any(os.environ.get(var) for var in env_vars) |
| 316 |
|
| 317 |
|
| 318 |
if sys.version_info >= (3, 13): |
| 319 |
from warnings import deprecated as deprecated |
| 320 |
else: |
| 321 |
if TYPE_CHECKING: |
| 322 |
from typing_extensions import deprecated as deprecated |
| 323 |
else: |
| 324 |
|
| 325 |
def deprecated(msg, /, *, category=None, stacklevel=1): |
| 326 |
def decorator(func): |
| 327 |
return func |
| 328 |
|
| 329 |
return decorator |