]> granicus.if.org Git - python/commitdiff
Make unittest.mock.create_autospec resilient against AttributeError on original object
authorMichael Foord <michael@voidspace.org.uk>
Fri, 13 Apr 2012 16:39:16 +0000 (17:39 +0100)
committerMichael Foord <michael@voidspace.org.uk>
Fri, 13 Apr 2012 16:39:16 +0000 (17:39 +0100)
Lib/unittest/mock.py
Lib/unittest/test/testmock/testhelpers.py

index ec175426694836a0e36de12d2c90a47c8470afe0..04eba918cc4f9463013633097d3f063849cf7369 100644 (file)
@@ -2044,10 +2044,14 @@ def create_autospec(spec, spec_set=False, instance=False, _parent=None,
         # object to mock it so we would rather trigger a property than mock
         # the property descriptor. Likewise we want to mock out dynamically
         # provided attributes.
-        # XXXX what about attributes that raise exceptions on being fetched
+        # XXXX what about attributes that raise exceptions other than
+        # AttributeError on being fetched?
         # we could be resilient against it, or catch and propagate the
         # exception when the attribute is fetched from the mock
-        original = getattr(spec, entry)
+        try:
+            original = getattr(spec, entry)
+        except AttributeError:
+            continue
 
         kwargs = {'spec': original}
         if spec_set:
index a2ed1003071fe7b5bf828a6dc3b23b9950416e3a..4c43f87dbcda3e5c30dac5d85b999489226947c5 100644 (file)
@@ -651,6 +651,29 @@ class SpecSignatureTest(unittest.TestCase):
         mock.f.assert_called_with(3, 4)
 
 
+    def test_skip_attributeerrors(self):
+        class Raiser(object):
+            def __get__(self, obj, type=None):
+                if obj is None:
+                    raise AttributeError('Can only be accessed via an instance')
+
+        class RaiserClass(object):
+            raiser = Raiser()
+
+            @staticmethod
+            def existing(a, b):
+                return a + b
+
+        s = create_autospec(RaiserClass)
+        self.assertRaises(TypeError, lambda x: s.existing(1, 2, 3))
+        s.existing(1, 2)
+        self.assertRaises(AttributeError, lambda: s.nonexisting)
+
+        # check we can fetch the raiser attribute and it has no spec
+        obj = s.raiser
+        obj.foo, obj.bar
+
+
     def test_signature_class(self):
         class Foo(object):
             def __init__(self, a, b=3):