backunittest.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
  2. # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt
  3. """Implementations of unittest features from the future."""
  4. # Use unittest2 if it's available, otherwise unittest. This gives us
  5. # back-ported features for 2.6.
  6. try:
  7. import unittest2 as unittest
  8. except ImportError:
  9. import unittest
  10. def unittest_has(method):
  11. """Does `unittest.TestCase` have `method` defined?"""
  12. return hasattr(unittest.TestCase, method)
  13. class TestCase(unittest.TestCase):
  14. """Just like unittest.TestCase, but with assert methods added.
  15. Designed to be compatible with 3.1 unittest. Methods are only defined if
  16. `unittest` doesn't have them.
  17. """
  18. # pylint: disable=missing-docstring
  19. # Many Pythons have this method defined. But PyPy3 has a bug with it
  20. # somehow (https://bitbucket.org/pypy/pypy/issues/2092), so always use our
  21. # own implementation that works everywhere, at least for the ways we're
  22. # calling it.
  23. def assertCountEqual(self, s1, s2):
  24. """Assert these have the same elements, regardless of order."""
  25. self.assertEqual(sorted(s1), sorted(s2))
  26. if not unittest_has('assertRaisesRegex'):
  27. def assertRaisesRegex(self, *args, **kwargs):
  28. return self.assertRaisesRegexp(*args, **kwargs)
  29. if not unittest_has('assertRegex'):
  30. def assertRegex(self, *args, **kwargs):
  31. return self.assertRegexpMatches(*args, **kwargs)