util.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. """Utilities for assertion debugging."""
  2. import collections.abc
  3. import os
  4. import pprint
  5. from typing import AbstractSet
  6. from typing import Any
  7. from typing import Callable
  8. from typing import Iterable
  9. from typing import List
  10. from typing import Mapping
  11. from typing import Optional
  12. from typing import Sequence
  13. import _pytest._code
  14. from _pytest import outcomes
  15. from _pytest._io.saferepr import _pformat_dispatch
  16. from _pytest._io.saferepr import safeformat
  17. from _pytest._io.saferepr import saferepr
  18. from _pytest.config import Config
  19. # The _reprcompare attribute on the util module is used by the new assertion
  20. # interpretation code and assertion rewriter to detect this plugin was
  21. # loaded and in turn call the hooks defined here as part of the
  22. # DebugInterpreter.
  23. _reprcompare: Optional[Callable[[str, object, object], Optional[str]]] = None
  24. # Works similarly as _reprcompare attribute. Is populated with the hook call
  25. # when pytest_runtest_setup is called.
  26. _assertion_pass: Optional[Callable[[int, str, str], None]] = None
  27. # Config object which is assigned during pytest_runtest_protocol.
  28. _config: Optional[Config] = None
  29. def format_explanation(explanation: str) -> str:
  30. r"""Format an explanation.
  31. Normally all embedded newlines are escaped, however there are
  32. three exceptions: \n{, \n} and \n~. The first two are intended
  33. cover nested explanations, see function and attribute explanations
  34. for examples (.visit_Call(), visit_Attribute()). The last one is
  35. for when one explanation needs to span multiple lines, e.g. when
  36. displaying diffs.
  37. """
  38. lines = _split_explanation(explanation)
  39. result = _format_lines(lines)
  40. return "\n".join(result)
  41. def _split_explanation(explanation: str) -> List[str]:
  42. r"""Return a list of individual lines in the explanation.
  43. This will return a list of lines split on '\n{', '\n}' and '\n~'.
  44. Any other newlines will be escaped and appear in the line as the
  45. literal '\n' characters.
  46. """
  47. raw_lines = (explanation or "").split("\n")
  48. lines = [raw_lines[0]]
  49. for values in raw_lines[1:]:
  50. if values and values[0] in ["{", "}", "~", ">"]:
  51. lines.append(values)
  52. else:
  53. lines[-1] += "\\n" + values
  54. return lines
  55. def _format_lines(lines: Sequence[str]) -> List[str]:
  56. """Format the individual lines.
  57. This will replace the '{', '}' and '~' characters of our mini formatting
  58. language with the proper 'where ...', 'and ...' and ' + ...' text, taking
  59. care of indentation along the way.
  60. Return a list of formatted lines.
  61. """
  62. result = list(lines[:1])
  63. stack = [0]
  64. stackcnt = [0]
  65. for line in lines[1:]:
  66. if line.startswith("{"):
  67. if stackcnt[-1]:
  68. s = "and "
  69. else:
  70. s = "where "
  71. stack.append(len(result))
  72. stackcnt[-1] += 1
  73. stackcnt.append(0)
  74. result.append(" +" + " " * (len(stack) - 1) + s + line[1:])
  75. elif line.startswith("}"):
  76. stack.pop()
  77. stackcnt.pop()
  78. result[stack[-1]] += line[1:]
  79. else:
  80. assert line[0] in ["~", ">"]
  81. stack[-1] += 1
  82. indent = len(stack) if line.startswith("~") else len(stack) - 1
  83. result.append(" " * indent + line[1:])
  84. assert len(stack) == 1
  85. return result
  86. def issequence(x: Any) -> bool:
  87. return isinstance(x, collections.abc.Sequence) and not isinstance(x, str)
  88. def istext(x: Any) -> bool:
  89. return isinstance(x, str)
  90. def isdict(x: Any) -> bool:
  91. return isinstance(x, dict)
  92. def isset(x: Any) -> bool:
  93. return isinstance(x, (set, frozenset))
  94. def isnamedtuple(obj: Any) -> bool:
  95. return isinstance(obj, tuple) and getattr(obj, "_fields", None) is not None
  96. def isdatacls(obj: Any) -> bool:
  97. return getattr(obj, "__dataclass_fields__", None) is not None
  98. def isattrs(obj: Any) -> bool:
  99. return getattr(obj, "__attrs_attrs__", None) is not None
  100. def isiterable(obj: Any) -> bool:
  101. try:
  102. iter(obj)
  103. return not istext(obj)
  104. except TypeError:
  105. return False
  106. def has_default_eq(
  107. obj: object,
  108. ) -> bool:
  109. """Check if an instance of an object contains the default eq
  110. First, we check if the object's __eq__ attribute has __code__,
  111. if so, we check the equally of the method code filename (__code__.co_filename)
  112. to the default one generated by the dataclass and attr module
  113. for dataclasses the default co_filename is <string>, for attrs class, the __eq__ should contain "attrs eq generated"
  114. """
  115. # inspired from https://github.com/willmcgugan/rich/blob/07d51ffc1aee6f16bd2e5a25b4e82850fb9ed778/rich/pretty.py#L68
  116. if hasattr(obj.__eq__, "__code__") and hasattr(obj.__eq__.__code__, "co_filename"):
  117. code_filename = obj.__eq__.__code__.co_filename
  118. if isattrs(obj):
  119. return "attrs generated eq" in code_filename
  120. return code_filename == "<string>" # data class
  121. return True
  122. def assertrepr_compare(config, op: str, left: Any, right: Any) -> Optional[List[str]]:
  123. """Return specialised explanations for some operators/operands."""
  124. verbose = config.getoption("verbose")
  125. if verbose > 1:
  126. left_repr = safeformat(left)
  127. right_repr = safeformat(right)
  128. else:
  129. # XXX: "15 chars indentation" is wrong
  130. # ("E AssertionError: assert "); should use term width.
  131. maxsize = (
  132. 80 - 15 - len(op) - 2
  133. ) // 2 # 15 chars indentation, 1 space around op
  134. left_repr = saferepr(left, maxsize=maxsize)
  135. right_repr = saferepr(right, maxsize=maxsize)
  136. summary = f"{left_repr} {op} {right_repr}"
  137. explanation = None
  138. try:
  139. if op == "==":
  140. explanation = _compare_eq_any(left, right, verbose)
  141. elif op == "not in":
  142. if istext(left) and istext(right):
  143. explanation = _notin_text(left, right, verbose)
  144. except outcomes.Exit:
  145. raise
  146. except Exception:
  147. explanation = [
  148. "(pytest_assertion plugin: representation of details failed: {}.".format(
  149. _pytest._code.ExceptionInfo.from_current()._getreprcrash()
  150. ),
  151. " Probably an object has a faulty __repr__.)",
  152. ]
  153. if not explanation:
  154. return None
  155. return [summary] + explanation
  156. def _compare_eq_any(left: Any, right: Any, verbose: int = 0) -> List[str]:
  157. explanation = []
  158. if istext(left) and istext(right):
  159. explanation = _diff_text(left, right, verbose)
  160. else:
  161. from _pytest.python_api import ApproxBase
  162. if isinstance(left, ApproxBase) or isinstance(right, ApproxBase):
  163. # Although the common order should be obtained == expected, this ensures both ways
  164. approx_side = left if isinstance(left, ApproxBase) else right
  165. other_side = right if isinstance(left, ApproxBase) else left
  166. explanation = approx_side._repr_compare(other_side)
  167. elif type(left) == type(right) and (
  168. isdatacls(left) or isattrs(left) or isnamedtuple(left)
  169. ):
  170. # Note: unlike dataclasses/attrs, namedtuples compare only the
  171. # field values, not the type or field names. But this branch
  172. # intentionally only handles the same-type case, which was often
  173. # used in older code bases before dataclasses/attrs were available.
  174. explanation = _compare_eq_cls(left, right, verbose)
  175. elif issequence(left) and issequence(right):
  176. explanation = _compare_eq_sequence(left, right, verbose)
  177. elif isset(left) and isset(right):
  178. explanation = _compare_eq_set(left, right, verbose)
  179. elif isdict(left) and isdict(right):
  180. explanation = _compare_eq_dict(left, right, verbose)
  181. if isiterable(left) and isiterable(right):
  182. expl = _compare_eq_iterable(left, right, verbose)
  183. explanation.extend(expl)
  184. return explanation
  185. def _diff_text(left: str, right: str, verbose: int = 0) -> List[str]:
  186. """Return the explanation for the diff between text.
  187. Unless --verbose is used this will skip leading and trailing
  188. characters which are identical to keep the diff minimal.
  189. """
  190. from difflib import ndiff
  191. explanation: List[str] = []
  192. if verbose < 1:
  193. i = 0 # just in case left or right has zero length
  194. for i in range(min(len(left), len(right))):
  195. if left[i] != right[i]:
  196. break
  197. if i > 42:
  198. i -= 10 # Provide some context
  199. explanation = [
  200. "Skipping %s identical leading characters in diff, use -v to show" % i
  201. ]
  202. left = left[i:]
  203. right = right[i:]
  204. if len(left) == len(right):
  205. for i in range(len(left)):
  206. if left[-i] != right[-i]:
  207. break
  208. if i > 42:
  209. i -= 10 # Provide some context
  210. explanation += [
  211. "Skipping {} identical trailing "
  212. "characters in diff, use -v to show".format(i)
  213. ]
  214. left = left[:-i]
  215. right = right[:-i]
  216. keepends = True
  217. if left.isspace() or right.isspace():
  218. left = repr(str(left))
  219. right = repr(str(right))
  220. explanation += ["Strings contain only whitespace, escaping them using repr()"]
  221. # "right" is the expected base against which we compare "left",
  222. # see https://github.com/pytest-dev/pytest/issues/3333
  223. explanation += [
  224. line.strip("\n")
  225. for line in ndiff(right.splitlines(keepends), left.splitlines(keepends))
  226. ]
  227. return explanation
  228. def _surrounding_parens_on_own_lines(lines: List[str]) -> None:
  229. """Move opening/closing parenthesis/bracket to own lines."""
  230. opening = lines[0][:1]
  231. if opening in ["(", "[", "{"]:
  232. lines[0] = " " + lines[0][1:]
  233. lines[:] = [opening] + lines
  234. closing = lines[-1][-1:]
  235. if closing in [")", "]", "}"]:
  236. lines[-1] = lines[-1][:-1] + ","
  237. lines[:] = lines + [closing]
  238. def _compare_eq_iterable(
  239. left: Iterable[Any], right: Iterable[Any], verbose: int = 0
  240. ) -> List[str]:
  241. if verbose <= 0 and not running_on_ci():
  242. return ["Use -v to get more diff"]
  243. # dynamic import to speedup pytest
  244. import difflib
  245. left_formatting = pprint.pformat(left).splitlines()
  246. right_formatting = pprint.pformat(right).splitlines()
  247. # Re-format for different output lengths.
  248. lines_left = len(left_formatting)
  249. lines_right = len(right_formatting)
  250. if lines_left != lines_right:
  251. left_formatting = _pformat_dispatch(left).splitlines()
  252. right_formatting = _pformat_dispatch(right).splitlines()
  253. if lines_left > 1 or lines_right > 1:
  254. _surrounding_parens_on_own_lines(left_formatting)
  255. _surrounding_parens_on_own_lines(right_formatting)
  256. explanation = ["Full diff:"]
  257. # "right" is the expected base against which we compare "left",
  258. # see https://github.com/pytest-dev/pytest/issues/3333
  259. explanation.extend(
  260. line.rstrip() for line in difflib.ndiff(right_formatting, left_formatting)
  261. )
  262. return explanation
  263. def _compare_eq_sequence(
  264. left: Sequence[Any], right: Sequence[Any], verbose: int = 0
  265. ) -> List[str]:
  266. comparing_bytes = isinstance(left, bytes) and isinstance(right, bytes)
  267. explanation: List[str] = []
  268. len_left = len(left)
  269. len_right = len(right)
  270. for i in range(min(len_left, len_right)):
  271. if left[i] != right[i]:
  272. if comparing_bytes:
  273. # when comparing bytes, we want to see their ascii representation
  274. # instead of their numeric values (#5260)
  275. # using a slice gives us the ascii representation:
  276. # >>> s = b'foo'
  277. # >>> s[0]
  278. # 102
  279. # >>> s[0:1]
  280. # b'f'
  281. left_value = left[i : i + 1]
  282. right_value = right[i : i + 1]
  283. else:
  284. left_value = left[i]
  285. right_value = right[i]
  286. explanation += [f"At index {i} diff: {left_value!r} != {right_value!r}"]
  287. break
  288. if comparing_bytes:
  289. # when comparing bytes, it doesn't help to show the "sides contain one or more
  290. # items" longer explanation, so skip it
  291. return explanation
  292. len_diff = len_left - len_right
  293. if len_diff:
  294. if len_diff > 0:
  295. dir_with_more = "Left"
  296. extra = saferepr(left[len_right])
  297. else:
  298. len_diff = 0 - len_diff
  299. dir_with_more = "Right"
  300. extra = saferepr(right[len_left])
  301. if len_diff == 1:
  302. explanation += [f"{dir_with_more} contains one more item: {extra}"]
  303. else:
  304. explanation += [
  305. "%s contains %d more items, first extra item: %s"
  306. % (dir_with_more, len_diff, extra)
  307. ]
  308. return explanation
  309. def _compare_eq_set(
  310. left: AbstractSet[Any], right: AbstractSet[Any], verbose: int = 0
  311. ) -> List[str]:
  312. explanation = []
  313. diff_left = left - right
  314. diff_right = right - left
  315. if diff_left:
  316. explanation.append("Extra items in the left set:")
  317. for item in diff_left:
  318. explanation.append(saferepr(item))
  319. if diff_right:
  320. explanation.append("Extra items in the right set:")
  321. for item in diff_right:
  322. explanation.append(saferepr(item))
  323. return explanation
  324. def _compare_eq_dict(
  325. left: Mapping[Any, Any], right: Mapping[Any, Any], verbose: int = 0
  326. ) -> List[str]:
  327. explanation: List[str] = []
  328. set_left = set(left)
  329. set_right = set(right)
  330. common = set_left.intersection(set_right)
  331. same = {k: left[k] for k in common if left[k] == right[k]}
  332. if same and verbose < 2:
  333. explanation += ["Omitting %s identical items, use -vv to show" % len(same)]
  334. elif same:
  335. explanation += ["Common items:"]
  336. explanation += pprint.pformat(same).splitlines()
  337. diff = {k for k in common if left[k] != right[k]}
  338. if diff:
  339. explanation += ["Differing items:"]
  340. for k in diff:
  341. explanation += [saferepr({k: left[k]}) + " != " + saferepr({k: right[k]})]
  342. extra_left = set_left - set_right
  343. len_extra_left = len(extra_left)
  344. if len_extra_left:
  345. explanation.append(
  346. "Left contains %d more item%s:"
  347. % (len_extra_left, "" if len_extra_left == 1 else "s")
  348. )
  349. explanation.extend(
  350. pprint.pformat({k: left[k] for k in extra_left}).splitlines()
  351. )
  352. extra_right = set_right - set_left
  353. len_extra_right = len(extra_right)
  354. if len_extra_right:
  355. explanation.append(
  356. "Right contains %d more item%s:"
  357. % (len_extra_right, "" if len_extra_right == 1 else "s")
  358. )
  359. explanation.extend(
  360. pprint.pformat({k: right[k] for k in extra_right}).splitlines()
  361. )
  362. return explanation
  363. def _compare_eq_cls(left: Any, right: Any, verbose: int) -> List[str]:
  364. if not has_default_eq(left):
  365. return []
  366. if isdatacls(left):
  367. import dataclasses
  368. all_fields = dataclasses.fields(left)
  369. fields_to_check = [info.name for info in all_fields if info.compare]
  370. elif isattrs(left):
  371. all_fields = left.__attrs_attrs__
  372. fields_to_check = [field.name for field in all_fields if getattr(field, "eq")]
  373. elif isnamedtuple(left):
  374. fields_to_check = left._fields
  375. else:
  376. assert False
  377. indent = " "
  378. same = []
  379. diff = []
  380. for field in fields_to_check:
  381. if getattr(left, field) == getattr(right, field):
  382. same.append(field)
  383. else:
  384. diff.append(field)
  385. explanation = []
  386. if same or diff:
  387. explanation += [""]
  388. if same and verbose < 2:
  389. explanation.append("Omitting %s identical items, use -vv to show" % len(same))
  390. elif same:
  391. explanation += ["Matching attributes:"]
  392. explanation += pprint.pformat(same).splitlines()
  393. if diff:
  394. explanation += ["Differing attributes:"]
  395. explanation += pprint.pformat(diff).splitlines()
  396. for field in diff:
  397. field_left = getattr(left, field)
  398. field_right = getattr(right, field)
  399. explanation += [
  400. "",
  401. "Drill down into differing attribute %s:" % field,
  402. ("%s%s: %r != %r") % (indent, field, field_left, field_right),
  403. ]
  404. explanation += [
  405. indent + line
  406. for line in _compare_eq_any(field_left, field_right, verbose)
  407. ]
  408. return explanation
  409. def _notin_text(term: str, text: str, verbose: int = 0) -> List[str]:
  410. index = text.find(term)
  411. head = text[:index]
  412. tail = text[index + len(term) :]
  413. correct_text = head + tail
  414. diff = _diff_text(text, correct_text, verbose)
  415. newdiff = ["%s is contained here:" % saferepr(term, maxsize=42)]
  416. for line in diff:
  417. if line.startswith("Skipping"):
  418. continue
  419. if line.startswith("- "):
  420. continue
  421. if line.startswith("+ "):
  422. newdiff.append(" " + line[2:])
  423. else:
  424. newdiff.append(line)
  425. return newdiff
  426. def running_on_ci() -> bool:
  427. """Check if we're currently running on a CI system."""
  428. env_vars = ["CI", "BUILD_NUMBER"]
  429. return any(var in os.environ for var in env_vars)