Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/src/_pytest/compat.py

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