Development of an internal social media platform with personalised dashboards for students
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.

utils.py 5.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. from __future__ import absolute_import
  2. import re
  3. import sys
  4. import warnings
  5. try:
  6. import unittest # noqa
  7. unittest.skip
  8. from unittest.util import safe_repr, unorderable_list_difference
  9. except AttributeError:
  10. import unittest2 as unittest # noqa
  11. from unittest2.util import safe_repr, unorderable_list_difference # noqa
  12. from billiard.five import string_t, items, values
  13. from .compat import catch_warnings
  14. # -- adds assertWarns from recent unittest2, not in Python 2.7.
  15. class _AssertRaisesBaseContext(object):
  16. def __init__(self, expected, test_case, callable_obj=None,
  17. expected_regex=None):
  18. self.expected = expected
  19. self.failureException = test_case.failureException
  20. self.obj_name = None
  21. if isinstance(expected_regex, string_t):
  22. expected_regex = re.compile(expected_regex)
  23. self.expected_regex = expected_regex
  24. class _AssertWarnsContext(_AssertRaisesBaseContext):
  25. """A context manager used to implement TestCase.assertWarns* methods."""
  26. def __enter__(self):
  27. # The __warningregistry__'s need to be in a pristine state for tests
  28. # to work properly.
  29. warnings.resetwarnings()
  30. for v in values(sys.modules):
  31. if getattr(v, '__warningregistry__', None):
  32. v.__warningregistry__ = {}
  33. self.warnings_manager = catch_warnings(record=True)
  34. self.warnings = self.warnings_manager.__enter__()
  35. warnings.simplefilter('always', self.expected)
  36. return self
  37. def __exit__(self, exc_type, exc_value, tb):
  38. self.warnings_manager.__exit__(exc_type, exc_value, tb)
  39. if exc_type is not None:
  40. # let unexpected exceptions pass through
  41. return
  42. try:
  43. exc_name = self.expected.__name__
  44. except AttributeError:
  45. exc_name = str(self.expected)
  46. first_matching = None
  47. for m in self.warnings:
  48. w = m.message
  49. if not isinstance(w, self.expected):
  50. continue
  51. if first_matching is None:
  52. first_matching = w
  53. if (self.expected_regex is not None and
  54. not self.expected_regex.search(str(w))):
  55. continue
  56. # store warning for later retrieval
  57. self.warning = w
  58. self.filename = m.filename
  59. self.lineno = m.lineno
  60. return
  61. # Now we simply try to choose a helpful failure message
  62. if first_matching is not None:
  63. raise self.failureException(
  64. '%r does not match %r' % (
  65. self.expected_regex.pattern, str(first_matching)))
  66. if self.obj_name:
  67. raise self.failureException(
  68. '%s not triggered by %s' % (exc_name, self.obj_name))
  69. else:
  70. raise self.failureException('%s not triggered' % exc_name)
  71. class Case(unittest.TestCase):
  72. def assertWarns(self, expected_warning):
  73. return _AssertWarnsContext(expected_warning, self, None)
  74. def assertWarnsRegex(self, expected_warning, expected_regex):
  75. return _AssertWarnsContext(expected_warning, self,
  76. None, expected_regex)
  77. def assertDictContainsSubset(self, expected, actual, msg=None):
  78. missing, mismatched = [], []
  79. for key, value in items(expected):
  80. if key not in actual:
  81. missing.append(key)
  82. elif value != actual[key]:
  83. mismatched.append('%s, expected: %s, actual: %s' % (
  84. safe_repr(key), safe_repr(value),
  85. safe_repr(actual[key])))
  86. if not (missing or mismatched):
  87. return
  88. standard_msg = ''
  89. if missing:
  90. standard_msg = 'Missing: %s' % ','.join(map(safe_repr, missing))
  91. if mismatched:
  92. if standard_msg:
  93. standard_msg += '; '
  94. standard_msg += 'Mismatched values: %s' % (
  95. ','.join(mismatched))
  96. self.fail(self._formatMessage(msg, standard_msg))
  97. def assertItemsEqual(self, expected_seq, actual_seq, msg=None):
  98. missing = unexpected = None
  99. try:
  100. expected = sorted(expected_seq)
  101. actual = sorted(actual_seq)
  102. except TypeError:
  103. # Unsortable items (example: set(), complex(), ...)
  104. expected = list(expected_seq)
  105. actual = list(actual_seq)
  106. missing, unexpected = unorderable_list_difference(
  107. expected, actual)
  108. else:
  109. return self.assertSequenceEqual(expected, actual, msg=msg)
  110. errors = []
  111. if missing:
  112. errors.append(
  113. 'Expected, but missing:\n %s' % (safe_repr(missing), ),
  114. )
  115. if unexpected:
  116. errors.append(
  117. 'Unexpected, but present:\n %s' % (safe_repr(unexpected), ),
  118. )
  119. if errors:
  120. standardMsg = '\n'.join(errors)
  121. self.fail(self._formatMessage(msg, standardMsg))