util.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 assertrepr_compare(config, op: str, left: Any, right: Any) -> Optional[List[str]]:
  107. """Return specialised explanations for some operators/operands."""
  108. verbose = config.getoption("verbose")
  109. if verbose > 1:
  110. left_repr = safeformat(left)
  111. right_repr = safeformat(right)
  112. else:
  113. # XXX: "15 chars indentation" is wrong
  114. # ("E AssertionError: assert "); should use term width.
  115. maxsize = (
  116. 80 - 15 - len(op) - 2
  117. ) // 2 # 15 chars indentation, 1 space around op
  118. left_repr = saferepr(left, maxsize=maxsize)
  119. right_repr = saferepr(right, maxsize=maxsize)
  120. summary = f"{left_repr} {op} {right_repr}"
  121. explanation = None
  122. try:
  123. if op == "==":
  124. explanation = _compare_eq_any(left, right, verbose)
  125. elif op == "not in":
  126. if istext(left) and istext(right):
  127. explanation = _notin_text(left, right, verbose)
  128. except outcomes.Exit:
  129. raise
  130. except Exception:
  131. explanation = [
  132. "(pytest_assertion plugin: representation of details failed: {}.".format(
  133. _pytest._code.ExceptionInfo.from_current()._getreprcrash()
  134. ),
  135. " Probably an object has a faulty __repr__.)",
  136. ]
  137. if not explanation:
  138. return None
  139. return [summary] + explanation
  140. def _compare_eq_any(left: Any, right: Any, verbose: int = 0) -> List[str]:
  141. explanation = []
  142. if istext(left) and istext(right):
  143. explanation = _diff_text(left, right, verbose)
  144. else:
  145. from _pytest.python_api import ApproxBase
  146. if isinstance(left, ApproxBase) or isinstance(right, ApproxBase):
  147. # Although the common order should be obtained == expected, this ensures both ways
  148. approx_side = left if isinstance(left, ApproxBase) else right
  149. other_side = right if isinstance(left, ApproxBase) else left
  150. explanation = approx_side._repr_compare(other_side)
  151. elif type(left) == type(right) and (
  152. isdatacls(left) or isattrs(left) or isnamedtuple(left)
  153. ):
  154. # Note: unlike dataclasses/attrs, namedtuples compare only the
  155. # field values, not the type or field names. But this branch
  156. # intentionally only handles the same-type case, which was often
  157. # used in older code bases before dataclasses/attrs were available.
  158. explanation = _compare_eq_cls(left, right, verbose)
  159. elif issequence(left) and issequence(right):
  160. explanation = _compare_eq_sequence(left, right, verbose)
  161. elif isset(left) and isset(right):
  162. explanation = _compare_eq_set(left, right, verbose)
  163. elif isdict(left) and isdict(right):
  164. explanation = _compare_eq_dict(left, right, verbose)
  165. elif verbose > 0:
  166. explanation = _compare_eq_verbose(left, right)
  167. if isiterable(left) and isiterable(right):
  168. expl = _compare_eq_iterable(left, right, verbose)
  169. explanation.extend(expl)
  170. return explanation
  171. def _diff_text(left: str, right: str, verbose: int = 0) -> List[str]:
  172. """Return the explanation for the diff between text.
  173. Unless --verbose is used this will skip leading and trailing
  174. characters which are identical to keep the diff minimal.
  175. """
  176. from difflib import ndiff
  177. explanation: List[str] = []
  178. if verbose < 1:
  179. i = 0 # just in case left or right has zero length
  180. for i in range(min(len(left), len(right))):
  181. if left[i] != right[i]:
  182. break
  183. if i > 42:
  184. i -= 10 # Provide some context
  185. explanation = [
  186. "Skipping %s identical leading characters in diff, use -v to show" % i
  187. ]
  188. left = left[i:]
  189. right = right[i:]
  190. if len(left) == len(right):
  191. for i in range(len(left)):
  192. if left[-i] != right[-i]:
  193. break
  194. if i > 42:
  195. i -= 10 # Provide some context
  196. explanation += [
  197. "Skipping {} identical trailing "
  198. "characters in diff, use -v to show".format(i)
  199. ]
  200. left = left[:-i]
  201. right = right[:-i]
  202. keepends = True
  203. if left.isspace() or right.isspace():
  204. left = repr(str(left))
  205. right = repr(str(right))
  206. explanation += ["Strings contain only whitespace, escaping them using repr()"]
  207. # "right" is the expected base against which we compare "left",
  208. # see https://github.com/pytest-dev/pytest/issues/3333
  209. explanation += [
  210. line.strip("\n")
  211. for line in ndiff(right.splitlines(keepends), left.splitlines(keepends))
  212. ]
  213. return explanation
  214. def _compare_eq_verbose(left: Any, right: Any) -> List[str]:
  215. keepends = True
  216. left_lines = repr(left).splitlines(keepends)
  217. right_lines = repr(right).splitlines(keepends)
  218. explanation: List[str] = []
  219. explanation += ["+" + line for line in left_lines]
  220. explanation += ["-" + line for line in right_lines]
  221. return explanation
  222. def _surrounding_parens_on_own_lines(lines: List[str]) -> None:
  223. """Move opening/closing parenthesis/bracket to own lines."""
  224. opening = lines[0][:1]
  225. if opening in ["(", "[", "{"]:
  226. lines[0] = " " + lines[0][1:]
  227. lines[:] = [opening] + lines
  228. closing = lines[-1][-1:]
  229. if closing in [")", "]", "}"]:
  230. lines[-1] = lines[-1][:-1] + ","
  231. lines[:] = lines + [closing]
  232. def _compare_eq_iterable(
  233. left: Iterable[Any], right: Iterable[Any], verbose: int = 0
  234. ) -> List[str]:
  235. if not verbose and not running_on_ci():
  236. return ["Use -v to get the full diff"]
  237. # dynamic import to speedup pytest
  238. import difflib
  239. left_formatting = pprint.pformat(left).splitlines()
  240. right_formatting = pprint.pformat(right).splitlines()
  241. # Re-format for different output lengths.
  242. lines_left = len(left_formatting)
  243. lines_right = len(right_formatting)
  244. if lines_left != lines_right:
  245. left_formatting = _pformat_dispatch(left).splitlines()
  246. right_formatting = _pformat_dispatch(right).splitlines()
  247. if lines_left > 1 or lines_right > 1:
  248. _surrounding_parens_on_own_lines(left_formatting)
  249. _surrounding_parens_on_own_lines(right_formatting)
  250. explanation = ["Full diff:"]
  251. # "right" is the expected base against which we compare "left",
  252. # see https://github.com/pytest-dev/pytest/issues/3333
  253. explanation.extend(
  254. line.rstrip() for line in difflib.ndiff(right_formatting, left_formatting)
  255. )
  256. return explanation
  257. def _compare_eq_sequence(
  258. left: Sequence[Any], right: Sequence[Any], verbose: int = 0
  259. ) -> List[str]:
  260. comparing_bytes = isinstance(left, bytes) and isinstance(right, bytes)
  261. explanation: List[str] = []
  262. len_left = len(left)
  263. len_right = len(right)
  264. for i in range(min(len_left, len_right)):
  265. if left[i] != right[i]:
  266. if comparing_bytes:
  267. # when comparing bytes, we want to see their ascii representation
  268. # instead of their numeric values (#5260)
  269. # using a slice gives us the ascii representation:
  270. # >>> s = b'foo'
  271. # >>> s[0]
  272. # 102
  273. # >>> s[0:1]
  274. # b'f'
  275. left_value = left[i : i + 1]
  276. right_value = right[i : i + 1]
  277. else:
  278. left_value = left[i]
  279. right_value = right[i]
  280. explanation += [f"At index {i} diff: {left_value!r} != {right_value!r}"]
  281. break
  282. if comparing_bytes:
  283. # when comparing bytes, it doesn't help to show the "sides contain one or more
  284. # items" longer explanation, so skip it
  285. return explanation
  286. len_diff = len_left - len_right
  287. if len_diff:
  288. if len_diff > 0:
  289. dir_with_more = "Left"
  290. extra = saferepr(left[len_right])
  291. else:
  292. len_diff = 0 - len_diff
  293. dir_with_more = "Right"
  294. extra = saferepr(right[len_left])
  295. if len_diff == 1:
  296. explanation += [f"{dir_with_more} contains one more item: {extra}"]
  297. else:
  298. explanation += [
  299. "%s contains %d more items, first extra item: %s"
  300. % (dir_with_more, len_diff, extra)
  301. ]
  302. return explanation
  303. def _compare_eq_set(
  304. left: AbstractSet[Any], right: AbstractSet[Any], verbose: int = 0
  305. ) -> List[str]:
  306. explanation = []
  307. diff_left = left - right
  308. diff_right = right - left
  309. if diff_left:
  310. explanation.append("Extra items in the left set:")
  311. for item in diff_left:
  312. explanation.append(saferepr(item))
  313. if diff_right:
  314. explanation.append("Extra items in the right set:")
  315. for item in diff_right:
  316. explanation.append(saferepr(item))
  317. return explanation
  318. def _compare_eq_dict(
  319. left: Mapping[Any, Any], right: Mapping[Any, Any], verbose: int = 0
  320. ) -> List[str]:
  321. explanation: List[str] = []
  322. set_left = set(left)
  323. set_right = set(right)
  324. common = set_left.intersection(set_right)
  325. same = {k: left[k] for k in common if left[k] == right[k]}
  326. if same and verbose < 2:
  327. explanation += ["Omitting %s identical items, use -vv to show" % len(same)]
  328. elif same:
  329. explanation += ["Common items:"]
  330. explanation += pprint.pformat(same).splitlines()
  331. diff = {k for k in common if left[k] != right[k]}
  332. if diff:
  333. explanation += ["Differing items:"]
  334. for k in diff:
  335. explanation += [saferepr({k: left[k]}) + " != " + saferepr({k: right[k]})]
  336. extra_left = set_left - set_right
  337. len_extra_left = len(extra_left)
  338. if len_extra_left:
  339. explanation.append(
  340. "Left contains %d more item%s:"
  341. % (len_extra_left, "" if len_extra_left == 1 else "s")
  342. )
  343. explanation.extend(
  344. pprint.pformat({k: left[k] for k in extra_left}).splitlines()
  345. )
  346. extra_right = set_right - set_left
  347. len_extra_right = len(extra_right)
  348. if len_extra_right:
  349. explanation.append(
  350. "Right contains %d more item%s:"
  351. % (len_extra_right, "" if len_extra_right == 1 else "s")
  352. )
  353. explanation.extend(
  354. pprint.pformat({k: right[k] for k in extra_right}).splitlines()
  355. )
  356. return explanation
  357. def _compare_eq_cls(left: Any, right: Any, verbose: int) -> List[str]:
  358. if isdatacls(left):
  359. all_fields = left.__dataclass_fields__
  360. fields_to_check = [field for field, info in all_fields.items() if info.compare]
  361. elif isattrs(left):
  362. all_fields = left.__attrs_attrs__
  363. fields_to_check = [field.name for field in all_fields if getattr(field, "eq")]
  364. elif isnamedtuple(left):
  365. fields_to_check = left._fields
  366. else:
  367. assert False
  368. indent = " "
  369. same = []
  370. diff = []
  371. for field in fields_to_check:
  372. if getattr(left, field) == getattr(right, field):
  373. same.append(field)
  374. else:
  375. diff.append(field)
  376. explanation = []
  377. if same or diff:
  378. explanation += [""]
  379. if same and verbose < 2:
  380. explanation.append("Omitting %s identical items, use -vv to show" % len(same))
  381. elif same:
  382. explanation += ["Matching attributes:"]
  383. explanation += pprint.pformat(same).splitlines()
  384. if diff:
  385. explanation += ["Differing attributes:"]
  386. explanation += pprint.pformat(diff).splitlines()
  387. for field in diff:
  388. field_left = getattr(left, field)
  389. field_right = getattr(right, field)
  390. explanation += [
  391. "",
  392. "Drill down into differing attribute %s:" % field,
  393. ("%s%s: %r != %r") % (indent, field, field_left, field_right),
  394. ]
  395. explanation += [
  396. indent + line
  397. for line in _compare_eq_any(field_left, field_right, verbose)
  398. ]
  399. return explanation
  400. def _notin_text(term: str, text: str, verbose: int = 0) -> List[str]:
  401. index = text.find(term)
  402. head = text[:index]
  403. tail = text[index + len(term) :]
  404. correct_text = head + tail
  405. diff = _diff_text(text, correct_text, verbose)
  406. newdiff = ["%s is contained here:" % saferepr(term, maxsize=42)]
  407. for line in diff:
  408. if line.startswith("Skipping"):
  409. continue
  410. if line.startswith("- "):
  411. continue
  412. if line.startswith("+ "):
  413. newdiff.append(" " + line[2:])
  414. else:
  415. newdiff.append(line)
  416. return newdiff
  417. def running_on_ci() -> bool:
  418. """Check if we're currently running on a CI system."""
  419. env_vars = ["CI", "BUILD_NUMBER"]
  420. return any(var in os.environ for var in env_vars)