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.

478 lines
16KB

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