compat.py 12 KB

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