Commits

Ned Batchelder  committed f2dc01f

Use unittest2 to get rid of a bunch of our own test assertion implementations.

  • Participants
  • Parent commits f6129e1

Comments (0)

Files changed (3)

File tests/backunittest.py

 """Implementations of unittest features from the future."""
 
-import difflib, re, unittest
+# Use unittest2 if it's available, otherwise unittest.  This gives us
+# backported features for 2.6.
+try:
+    import unittest2 as unittest            # pylint: disable=F0401
+except ImportError:
+    import unittest
 
 
 def _need(method):
     """Just like unittest.TestCase, but with assert methods added.
 
     Designed to be compatible with 3.1 unittest.  Methods are only defined if
-    the builtin `unittest` doesn't have them.
+    `unittest` doesn't have them.
 
     """
-    if _need('assertIn'):
-        def assertIn(self, member, container, msg=None):
-            """Assert that `member` is in `container`."""
-            if member not in container:
-                msg = msg or ('%r not found in %r' % (member, container))
-                self.fail(msg)
-
-    if _need('assertNotIn'):
-        def assertNotIn(self, member, container, msg=None):
-            """Assert that `member` is not in `container`."""
-            if member in container:
-                msg = msg or ('%r found in %r' % (member, container))
-                self.fail(msg)
-
-    if _need('assertGreater'):
-        def assertGreater(self, a, b, msg=None):
-            """Assert that `a` is greater than `b`."""
-            if not a > b:
-                msg = msg or ('%r not greater than %r' % (a, b))
-                self.fail(msg)
-
-    if _need('assertRaisesRegexp'):
-        def assertRaisesRegexp(self, excClass, regexp, callobj, *args, **kw):
-            """ Just like unittest.TestCase.assertRaises,
-                but checks that the message is right too.
-            """
-            try:
-                callobj(*args, **kw)
-            except excClass as exc:
-                excMsg = str(exc)
-                if re.search(regexp, excMsg):
-                    # Message provided, and we got the right one: it passes.
-                    return
-                else:
-                    # Message provided, and it didn't match: fail!
-                    raise self.failureException(
-                        "Right exception, wrong message: "
-                            "%r doesn't match %r" % (excMsg, regexp)
-                        )
-            # No need to catch other exceptions: They'll fail the test all by
-            # themselves!
-            else:
-                if hasattr(excClass, '__name__'):
-                    excName = excClass.__name__
-                else:
-                    excName = str(excClass)
-                raise self.failureException(
-                    "Expected to raise %s, didn't get an exception at all" %
-                    excName
-                    )
-
     if _need('assertSameElements'):
         def assertSameElements(self, s1, s2):
             """Assert that the two arguments are equal as sets."""
             self.assertEqual(set(s1), set(s2))
-
-    if _need('assertRegexpMatches'):
-        def assertRegexpMatches(self, text, regex, msg=None):
-            """Assert that `text` matches `regex`."""
-            m = re.search(regex, text)
-            if not m:
-                msg = msg or ("%r doesn't match %r" % (text, regex))
-                raise self.failureException(msg)
-
-    if _need('assertMultiLineEqual'):
-        def assertMultiLineEqual(self, first, second, msg=None):
-            """Assert that two multi-line strings are equal.
-
-            If they aren't, show a nice diff.
-
-            """
-            # Adapted from Py3.1 unittest.
-            self.assertTrue(isinstance(first, str),
-                    'First argument is not a string')
-            self.assertTrue(isinstance(second, str),
-                    'Second argument is not a string')
-
-            if first != second:
-                message = ''.join(difflib.ndiff(first.splitlines(True),
-                                                    second.splitlines(True)))
-                if msg:
-                    message += " : " + msg
-                self.fail("Multi-line strings are unequal:\n" + message)

File tests/test_testing.py

 
     run_in_temp_dir = False
 
-    def please_raise(self, exc, msg):
-        """Raise an exception for testing assertRaisesRegexp."""
-        raise exc(msg)
-
-    def please_succeed(self):
-        """A simple successful method for testing assertRaisesRegexp."""
-        return "All is well"
-
     def test_assert_same_elements(self):
         self.assertSameElements(set(), set())
         self.assertSameElements(set([1,2,3]), set([3,1,2]))
             set([1,2,3]), set([4,5,6])
             )
 
-    def test_assert_regexp_matches(self):
-        self.assertRegexpMatches("hello", "hel*o")
-        self.assertRegexpMatches("Oh, hello there!", "hel*o")
-        self.assertRaises(AssertionError, self.assertRegexpMatches,
-            "hello there", "^hello$"
-            )
-
-    def test_assert_multiline_equal(self):
-        self.assertMultiLineEqual("hello", "hello")
-        self.assertRaises(AssertionError, self.assertMultiLineEqual,
-            "hello there", "Hello there"
-            )
-        self.assertRaises(AssertionError, self.assertMultiLineEqual,
-            "hello\nthere", "hello\nThere"
-            )
-        # With messages also.
-        self.assertMultiLineEqual("hi", "hi", "it's ok")
-        self.assertRaisesRegexp(
-            AssertionError, "my message",
-            self.assertMultiLineEqual, "xyz", "abc", "my message"
-        )
-
-    def test_assert_raises_regexp(self):
-        # Raising the right error with the right message passes.
-        self.assertRaisesRegexp(
-            ZeroDivisionError, "Wow! Zero!",
-            self.please_raise, ZeroDivisionError, "Wow! Zero!"
-            )
-        # Raising the right error with a match passes.
-        self.assertRaisesRegexp(
-            ZeroDivisionError, "Zero",
-            self.please_raise, ZeroDivisionError, "Wow! Zero!"
-            )
-        # Raising the right error with a mismatch fails.
-        self.assertRaises(AssertionError,
-            self.assertRaisesRegexp, ZeroDivisionError, "XYZ",
-            self.please_raise, ZeroDivisionError, "Wow! Zero!"
-            )
-        # Raising the right error with a mismatch fails.
-        self.assertRaises(AssertionError,
-            self.assertRaisesRegexp, ZeroDivisionError, "XYZ",
-            self.please_raise, ZeroDivisionError, "Wow! Zero!"
-            )
-        # Raising the wrong error raises the error itself.
-        self.assertRaises(ZeroDivisionError,
-            self.assertRaisesRegexp, IOError, "Wow! Zero!",
-            self.please_raise, ZeroDivisionError, "Wow! Zero!"
-            )
-        # Raising no error fails.
-        self.assertRaises(AssertionError,
-            self.assertRaisesRegexp, ZeroDivisionError, "XYZ",
-            self.please_succeed
-            )
-
-    def test_assert_true(self):
-        self.assertTrue(True)
-        self.assertRaises(AssertionError, self.assertTrue, False)
-
-    def test_assert_false(self):
-        self.assertFalse(False)
-        self.assertRaises(AssertionError, self.assertFalse, True)
-
-    def test_assert_in(self):
-        self.assertIn("abc", "hello abc")
-        self.assertIn("abc", ["xyz", "abc", "foo"])
-        self.assertIn("abc", {'abc': 1, 'xyz': 2})
-        self.assertRaises(AssertionError, self.assertIn, "abc", "xyz")
-        self.assertRaises(AssertionError, self.assertIn, "abc", ["x", "xabc"])
-        self.assertRaises(AssertionError, self.assertIn, "abc", {'x':'abc'})
-
-    def test_assert_not_in(self):
-        self.assertRaises(AssertionError, self.assertNotIn, "abc", "hello abc")
-        self.assertRaises(AssertionError,
-            self.assertNotIn, "abc", ["xyz", "abc", "foo"]
-            )
-        self.assertRaises(AssertionError,
-            self.assertNotIn, "abc", {'abc': 1, 'xyz': 2}
-            )
-        self.assertNotIn("abc", "xyz")
-        self.assertNotIn("abc", ["x", "xabc"])
-        self.assertNotIn("abc", {'x':'abc'})
-
-    def test_assert_greater(self):
-        self.assertGreater(10, 9)
-        self.assertGreater("xyz", "abc")
-        self.assertRaises(AssertionError, self.assertGreater, 9, 10)
-        self.assertRaises(AssertionError, self.assertGreater, 10, 10)
-        self.assertRaises(AssertionError, self.assertGreater, "abc", "xyz")
-        self.assertRaises(AssertionError, self.assertGreater, "xyz", "xyz")
-
 
 class CoverageTestTest(CoverageTest):
     """Test the methods in `CoverageTest`."""
     nose
     mock
 
+[testenv:py26]
+deps =
+    nose
+    mock
+    unittest2
+
+[testenv:py27]
+deps =
+    nose
+    mock
+    unittest2
+
 [testenv:pypy]
 # PyPy has no C extensions
 setenv =