Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. from __future__ import absolute_import
  2.  
  3. try:
  4. from types import SimpleNamespace # type: ignore
  5. except ImportError: # on Python 2
  6. from argparse import Namespace as SimpleNamespace
  7.  
  8.  
  9. def _list_comparison(context, ns, l, r):
  10. """For recursive tuple/list comparison."""
  11. if len(l) != len(r):
  12. context.errs.append("[%s]: length does not match: %s != %s" % (ns, len(l), len(r)))
  13.  
  14. for i, item in enumerate(l):
  15. if isinstance(item, context.supported_types) and len(r) > i and type(item) == type(r[i]):
  16. context.comparators[type(item)](context, ns + [str(i)], item, r[i])
  17.  
  18.  
  19. def _dict_comparison(context, ns, l, r):
  20. """For recursive dict comparison."""
  21. for k, v in l.items():
  22. if isinstance(l[k], context.supported_types) and type(l[k]) == type(r.get(k)):
  23. context.comparators[type(l[k])](context, ns + [k], l[k], r[k])
  24. else:
  25. namespaced = "][".join(map(str, ns + [str(k)]))
  26. try:
  27. if r[k] != v:
  28. context.errs.extend(
  29. [
  30. "[{}]:".format(namespaced),
  31. "LS: {0} [{1}]".format(v, type(v)),
  32. "RS: {0} [{1}]".format(r[k], type(r[k])),
  33. ]
  34. )
  35. except KeyError:
  36. context.errs.append("[{}]: missing from the right-side dict".format(namespaced))
  37.  
  38. extra_right = set(r.keys()) - set(l.keys())
  39. if extra_right:
  40. context.errs.append("extra keys in the right-side dict: {}".format(list(extra_right)))
  41.  
  42.  
  43. def pytest_assertrepr_compare(config, op, left, right):
  44. """Hook for Pytest producing a better output for non-matching nested structures."""
  45. if config.getoption("verbose") == 2:
  46. return None
  47.  
  48. context = SimpleNamespace()
  49. context.comparators = {list: _list_comparison, tuple: _list_comparison, dict: _dict_comparison}
  50. context.supported_types = tuple(context.comparators.keys())
  51. context.errs = []
  52.  
  53. if isinstance(left, context.supported_types) and type(left) == type(right) and op == "==":
  54. context.comparators[type(left)](context, [], left, right)
  55. if context.errs:
  56. return context.errs
  57. return None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement