]> granicus.if.org Git - python/commitdiff
#7031: Add TestCase.assertIsInstance and negated method.
authorGeorg Brandl <georg@python.org>
Thu, 1 Oct 2009 20:59:31 +0000 (20:59 +0000)
committerGeorg Brandl <georg@python.org>
Thu, 1 Oct 2009 20:59:31 +0000 (20:59 +0000)
Doc/library/unittest.rst
Lib/test/test_unittest.py
Lib/unittest/case.py

index 078c339b33e3f18259821bd22afbbfe0872b1987..4de6829e8394c0da4c720bb7ded0da4b539fe6fd 100644 (file)
@@ -955,6 +955,22 @@ Test cases
       .. versionadded:: 2.7
 
 
+   .. method:: assertIsInstance(obj, cls[, msg])
+
+      This signals a test failure if *obj* is not an instance of *cls* (which
+      can be a class or a tuple of classes, as supported by :func:`isinstance`).
+
+      .. versionadded:: 2.7
+
+
+   .. method:: assertNotIsInstance(obj, cls[, msg])
+
+      The inverse of the :meth:`assertIsInstance` method.  This signals a test
+      failure if *obj* is an instance of *cls*.
+
+      .. versionadded:: 2.7
+
+
    .. method:: assertFalse(expr[, msg])
                failIf(expr[, msg])
 
index 459334b9580d1e3d4ead6ce1f4bbd1f4c0669b15..de687e2776aec633f4e99837fa6b4747ee629fe8 100644 (file)
@@ -2500,6 +2500,18 @@ class Test_TestCase(TestCase, TestEquality, TestHashing):
         self.assertIsNot(thing, object())
         self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
 
+    def testAssertIsInstance(self):
+        thing = []
+        self.assertIsInstance(thing, list)
+        self.assertRaises(self.failureException, self.assertIsInstance,
+                          thing, dict)
+
+    def testAssertNotIsInstance(self):
+        thing = []
+        self.assertNotIsInstance(thing, dict)
+        self.assertRaises(self.failureException, self.assertNotIsInstance,
+                          thing, list)
+
     def testAssertIn(self):
         animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
 
index fb96a8891bddde10c2adfca369f2a0f0371ea7bf..113422caa35324e1e21c7dc5ba244d3fbf5d3201 100644 (file)
@@ -817,6 +817,19 @@ class TestCase(object):
             standardMsg = 'unexpectedly None'
             self.fail(self._formatMessage(msg, standardMsg))
 
+    def assertIsInstance(self, obj, cls, msg=None):
+        """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
+        default message."""
+        if not isinstance(obj, cls):
+            standardMsg = '%r is not an instance of %r' % (obj, cls)
+            self.fail(self._formatMessage(msg, standardMsg))
+
+    def assertNotIsInstance(self, obj, cls, msg=None):
+        """Included for symmetry with assertIsInstance."""
+        if isinstance(obj, cls):
+            standardMsg = '%r is an instance of %r' % (obj, cls)
+            self.fail(self._formatMessage(msg, standardMsg))
+
     def assertRaisesRegexp(self, expected_exception, expected_regexp,
                            callable_obj=None, *args, **kwargs):
         """Asserts that the message in a raised exception matches a regexp.