You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

401 lines
12KB

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