compat.py 12 KB

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