diff --git a/Lib/test/test_unittest_mock.py b/Lib/test/test_unittest_mock.py new file mode 100644 index 0000000..88ffa46 --- /dev/null +++ b/Lib/test/test_unittest_mock.py @@ -0,0 +1,23 @@ +import unittest +from unittest import mock + + +class InstanceMethodDoubleMockTest(unittest.TestCase): + def test_double_mock(self): + class C: + def f(self): + pass + + c = C() + + with mock.patch.object(c, 'f', autospec=True) as patch1: + with mock.patch.object(c, 'f', autospec=True) as patch2: + c.f() + self.assertEqual(patch2.call_count, 1) + self.assertEqual(patch1.call_count, 0) + c.f() + self.assertEqual(patch1.call_count, 1) + +if __name__ == "__main__": + unittest.main() + diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py index 7400fb7..b16f04c 100644 --- a/Lib/unittest/mock.py +++ b/Lib/unittest/mock.py @@ -2199,6 +2199,11 @@ def create_autospec(spec, spec_set=False, instance=False, _parent=None, except AttributeError: continue + # If our autospeccing already created this attribute through + # _setup_func above, skip it! + if hasattr(mock, entry): + continue + kwargs = {'spec': original} if spec_set: kwargs = {'spec_set': original}