util.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. # -*- coding: utf-8 -*-
  2. """Utilities for assertion debugging"""
  3. from __future__ import absolute_import
  4. from __future__ import division
  5. from __future__ import print_function
  6. import pprint
  7. import six
  8. import _pytest._code
  9. from ..compat import Sequence
  10. from _pytest import outcomes
  11. from _pytest._io.saferepr import saferepr
  12. from _pytest.compat import ATTRS_EQ_FIELD
  13. # The _reprcompare attribute on the util module is used by the new assertion
  14. # interpretation code and assertion rewriter to detect this plugin was
  15. # loaded and in turn call the hooks defined here as part of the
  16. # DebugInterpreter.
  17. _reprcompare = None
  18. # the re-encoding is needed for python2 repr
  19. # with non-ascii characters (see issue 877 and 1379)
  20. def ecu(s):
  21. if isinstance(s, bytes):
  22. return s.decode("UTF-8", "replace")
  23. else:
  24. return s
  25. def format_explanation(explanation):
  26. """This formats 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. explanation = ecu(explanation)
  35. lines = _split_explanation(explanation)
  36. result = _format_lines(lines)
  37. return u"\n".join(result)
  38. def _split_explanation(explanation):
  39. """Return a list of individual lines in the explanation
  40. This will return a list of lines split on '\n{', '\n}' and '\n~'.
  41. Any other newlines will be escaped and appear in the line as the
  42. literal '\n' characters.
  43. """
  44. raw_lines = (explanation or u"").split("\n")
  45. lines = [raw_lines[0]]
  46. for values in raw_lines[1:]:
  47. if values and values[0] in ["{", "}", "~", ">"]:
  48. lines.append(values)
  49. else:
  50. lines[-1] += "\\n" + values
  51. return lines
  52. def _format_lines(lines):
  53. """Format the individual lines
  54. This will replace the '{', '}' and '~' characters of our mini
  55. formatting language with the proper 'where ...', 'and ...' and ' +
  56. ...' text, taking care of indentation along the way.
  57. Return a list of formatted lines.
  58. """
  59. result = lines[:1]
  60. stack = [0]
  61. stackcnt = [0]
  62. for line in lines[1:]:
  63. if line.startswith("{"):
  64. if stackcnt[-1]:
  65. s = u"and "
  66. else:
  67. s = u"where "
  68. stack.append(len(result))
  69. stackcnt[-1] += 1
  70. stackcnt.append(0)
  71. result.append(u" +" + u" " * (len(stack) - 1) + s + line[1:])
  72. elif line.startswith("}"):
  73. stack.pop()
  74. stackcnt.pop()
  75. result[stack[-1]] += line[1:]
  76. else:
  77. assert line[0] in ["~", ">"]
  78. stack[-1] += 1
  79. indent = len(stack) if line.startswith("~") else len(stack) - 1
  80. result.append(u" " * indent + line[1:])
  81. assert len(stack) == 1
  82. return result
  83. # Provide basestring in python3
  84. try:
  85. basestring = basestring
  86. except NameError:
  87. basestring = str
  88. def issequence(x):
  89. return isinstance(x, Sequence) and not isinstance(x, basestring)
  90. def istext(x):
  91. return isinstance(x, basestring)
  92. def isdict(x):
  93. return isinstance(x, dict)
  94. def isset(x):
  95. return isinstance(x, (set, frozenset))
  96. def isdatacls(obj):
  97. return getattr(obj, "__dataclass_fields__", None) is not None
  98. def isattrs(obj):
  99. return getattr(obj, "__attrs_attrs__", None) is not None
  100. def isiterable(obj):
  101. try:
  102. iter(obj)
  103. return not istext(obj)
  104. except TypeError:
  105. return False
  106. def assertrepr_compare(config, op, left, right):
  107. """Return specialised explanations for some operators/operands"""
  108. width = 80 - 15 - len(op) - 2 # 15 chars indentation, 1 space around op
  109. left_repr = saferepr(left, maxsize=int(width // 2))
  110. right_repr = saferepr(right, maxsize=width - len(left_repr))
  111. summary = u"%s %s %s" % (ecu(left_repr), op, ecu(right_repr))
  112. verbose = config.getoption("verbose")
  113. explanation = None
  114. try:
  115. if op == "==":
  116. if istext(left) and istext(right):
  117. explanation = _diff_text(left, right, verbose)
  118. else:
  119. if issequence(left) and issequence(right):
  120. explanation = _compare_eq_sequence(left, right, verbose)
  121. elif isset(left) and isset(right):
  122. explanation = _compare_eq_set(left, right, verbose)
  123. elif isdict(left) and isdict(right):
  124. explanation = _compare_eq_dict(left, right, verbose)
  125. elif type(left) == type(right) and (isdatacls(left) or isattrs(left)):
  126. type_fn = (isdatacls, isattrs)
  127. explanation = _compare_eq_cls(left, right, verbose, type_fn)
  128. elif verbose > 0:
  129. explanation = _compare_eq_verbose(left, right)
  130. if isiterable(left) and isiterable(right):
  131. expl = _compare_eq_iterable(left, right, verbose)
  132. if explanation is not None:
  133. explanation.extend(expl)
  134. else:
  135. explanation = expl
  136. elif op == "not in":
  137. if istext(left) and istext(right):
  138. explanation = _notin_text(left, right, verbose)
  139. except outcomes.Exit:
  140. raise
  141. except Exception:
  142. explanation = [
  143. u"(pytest_assertion plugin: representation of details failed. "
  144. u"Probably an object has a faulty __repr__.)",
  145. six.text_type(_pytest._code.ExceptionInfo.from_current()),
  146. ]
  147. if not explanation:
  148. return None
  149. return [summary] + explanation
  150. def _diff_text(left, right, verbose=0):
  151. """Return the explanation for the diff between text or bytes.
  152. Unless --verbose is used this will skip leading and trailing
  153. characters which are identical to keep the diff minimal.
  154. If the input are bytes they will be safely converted to text.
  155. """
  156. from difflib import ndiff
  157. explanation = []
  158. def escape_for_readable_diff(binary_text):
  159. """
  160. Ensures that the internal string is always valid unicode, converting any bytes safely to valid unicode.
  161. This is done using repr() which then needs post-processing to fix the encompassing quotes and un-escape
  162. newlines and carriage returns (#429).
  163. """
  164. r = six.text_type(repr(binary_text)[1:-1])
  165. r = r.replace(r"\n", "\n")
  166. r = r.replace(r"\r", "\r")
  167. return r
  168. if isinstance(left, bytes):
  169. left = escape_for_readable_diff(left)
  170. if isinstance(right, bytes):
  171. right = escape_for_readable_diff(right)
  172. if verbose < 1:
  173. i = 0 # just in case left or right has zero length
  174. for i in range(min(len(left), len(right))):
  175. if left[i] != right[i]:
  176. break
  177. if i > 42:
  178. i -= 10 # Provide some context
  179. explanation = [
  180. u"Skipping %s identical leading characters in diff, use -v to show" % i
  181. ]
  182. left = left[i:]
  183. right = right[i:]
  184. if len(left) == len(right):
  185. for i in range(len(left)):
  186. if left[-i] != right[-i]:
  187. break
  188. if i > 42:
  189. i -= 10 # Provide some context
  190. explanation += [
  191. u"Skipping {} identical trailing "
  192. u"characters in diff, use -v to show".format(i)
  193. ]
  194. left = left[:-i]
  195. right = right[:-i]
  196. keepends = True
  197. if left.isspace() or right.isspace():
  198. left = repr(str(left))
  199. right = repr(str(right))
  200. explanation += [u"Strings contain only whitespace, escaping them using repr()"]
  201. explanation += [
  202. line.strip("\n")
  203. for line in ndiff(left.splitlines(keepends), right.splitlines(keepends))
  204. ]
  205. return explanation
  206. def _compare_eq_verbose(left, right):
  207. keepends = True
  208. left_lines = repr(left).splitlines(keepends)
  209. right_lines = repr(right).splitlines(keepends)
  210. explanation = []
  211. explanation += [u"-" + line for line in left_lines]
  212. explanation += [u"+" + line for line in right_lines]
  213. return explanation
  214. def _compare_eq_iterable(left, right, verbose=0):
  215. if not verbose:
  216. return [u"Use -v to get the full diff"]
  217. # dynamic import to speedup pytest
  218. import difflib
  219. try:
  220. left_formatting = pprint.pformat(left).splitlines()
  221. right_formatting = pprint.pformat(right).splitlines()
  222. explanation = [u"Full diff:"]
  223. except Exception:
  224. # hack: PrettyPrinter.pformat() in python 2 fails when formatting items that can't be sorted(), ie, calling
  225. # sorted() on a list would raise. See issue #718.
  226. # As a workaround, the full diff is generated by using the repr() string of each item of each container.
  227. left_formatting = sorted(repr(x) for x in left)
  228. right_formatting = sorted(repr(x) for x in right)
  229. explanation = [u"Full diff (fallback to calling repr on each item):"]
  230. explanation.extend(
  231. line.strip() for line in difflib.ndiff(left_formatting, right_formatting)
  232. )
  233. return explanation
  234. def _compare_eq_sequence(left, right, verbose=0):
  235. explanation = []
  236. len_left = len(left)
  237. len_right = len(right)
  238. for i in range(min(len_left, len_right)):
  239. if left[i] != right[i]:
  240. explanation += [u"At index %s diff: %r != %r" % (i, left[i], right[i])]
  241. break
  242. len_diff = len_left - len_right
  243. if len_diff:
  244. if len_diff > 0:
  245. dir_with_more = "Left"
  246. extra = saferepr(left[len_right])
  247. else:
  248. len_diff = 0 - len_diff
  249. dir_with_more = "Right"
  250. extra = saferepr(right[len_left])
  251. if len_diff == 1:
  252. explanation += [u"%s contains one more item: %s" % (dir_with_more, extra)]
  253. else:
  254. explanation += [
  255. u"%s contains %d more items, first extra item: %s"
  256. % (dir_with_more, len_diff, extra)
  257. ]
  258. return explanation
  259. def _compare_eq_set(left, right, verbose=0):
  260. explanation = []
  261. diff_left = left - right
  262. diff_right = right - left
  263. if diff_left:
  264. explanation.append(u"Extra items in the left set:")
  265. for item in diff_left:
  266. explanation.append(saferepr(item))
  267. if diff_right:
  268. explanation.append(u"Extra items in the right set:")
  269. for item in diff_right:
  270. explanation.append(saferepr(item))
  271. return explanation
  272. def _compare_eq_dict(left, right, verbose=0):
  273. explanation = []
  274. set_left = set(left)
  275. set_right = set(right)
  276. common = set_left.intersection(set_right)
  277. same = {k: left[k] for k in common if left[k] == right[k]}
  278. if same and verbose < 2:
  279. explanation += [u"Omitting %s identical items, use -vv to show" % len(same)]
  280. elif same:
  281. explanation += [u"Common items:"]
  282. explanation += pprint.pformat(same).splitlines()
  283. diff = {k for k in common if left[k] != right[k]}
  284. if diff:
  285. explanation += [u"Differing items:"]
  286. for k in diff:
  287. explanation += [saferepr({k: left[k]}) + " != " + saferepr({k: right[k]})]
  288. extra_left = set_left - set_right
  289. len_extra_left = len(extra_left)
  290. if len_extra_left:
  291. explanation.append(
  292. u"Left contains %d more item%s:"
  293. % (len_extra_left, "" if len_extra_left == 1 else "s")
  294. )
  295. explanation.extend(
  296. pprint.pformat({k: left[k] for k in extra_left}).splitlines()
  297. )
  298. extra_right = set_right - set_left
  299. len_extra_right = len(extra_right)
  300. if len_extra_right:
  301. explanation.append(
  302. u"Right contains %d more item%s:"
  303. % (len_extra_right, "" if len_extra_right == 1 else "s")
  304. )
  305. explanation.extend(
  306. pprint.pformat({k: right[k] for k in extra_right}).splitlines()
  307. )
  308. return explanation
  309. def _compare_eq_cls(left, right, verbose, type_fns):
  310. isdatacls, isattrs = type_fns
  311. if isdatacls(left):
  312. all_fields = left.__dataclass_fields__
  313. fields_to_check = [field for field, info in all_fields.items() if info.compare]
  314. elif isattrs(left):
  315. all_fields = left.__attrs_attrs__
  316. fields_to_check = [
  317. field.name for field in all_fields if getattr(field, ATTRS_EQ_FIELD)
  318. ]
  319. same = []
  320. diff = []
  321. for field in fields_to_check:
  322. if getattr(left, field) == getattr(right, field):
  323. same.append(field)
  324. else:
  325. diff.append(field)
  326. explanation = []
  327. if same and verbose < 2:
  328. explanation.append(u"Omitting %s identical items, use -vv to show" % len(same))
  329. elif same:
  330. explanation += [u"Matching attributes:"]
  331. explanation += pprint.pformat(same).splitlines()
  332. if diff:
  333. explanation += [u"Differing attributes:"]
  334. for field in diff:
  335. explanation += [
  336. (u"%s: %r != %r") % (field, getattr(left, field), getattr(right, field))
  337. ]
  338. return explanation
  339. def _notin_text(term, text, verbose=0):
  340. index = text.find(term)
  341. head = text[:index]
  342. tail = text[index + len(term) :]
  343. correct_text = head + tail
  344. diff = _diff_text(correct_text, text, verbose)
  345. newdiff = [u"%s is contained here:" % saferepr(term, maxsize=42)]
  346. for line in diff:
  347. if line.startswith(u"Skipping"):
  348. continue
  349. if line.startswith(u"- "):
  350. continue
  351. if line.startswith(u"+ "):
  352. newdiff.append(u" " + line[2:])
  353. else:
  354. newdiff.append(line)
  355. return newdiff