From 13781201f2ec1e744f81f9643566e3de076fbb5f Mon Sep 17 00:00:00 2001 From: Xtreak Date: Sat, 15 Jun 2019 21:49:15 +0530 Subject: [PATCH 1/2] MagicMock with function as spec supplied to mock.patch should return MagicMock --- Lib/unittest/mock.py | 3 ++- Lib/unittest/test/testmock/testasync.py | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py index c2802726d75d9c..091fd9890429d7 100644 --- a/Lib/unittest/mock.py +++ b/Lib/unittest/mock.py @@ -46,7 +46,8 @@ _safe_super = super def _is_async_obj(obj): - if getattr(obj, '__code__', None): + code = getattr(obj, '__code__', None) + if isinstance(code, CodeType): return asyncio.iscoroutinefunction(obj) or inspect.isawaitable(obj) else: return False diff --git a/Lib/unittest/test/testmock/testasync.py b/Lib/unittest/test/testmock/testasync.py index fa906e4f7152f8..5fb084e6603f17 100644 --- a/Lib/unittest/test/testmock/testasync.py +++ b/Lib/unittest/test/testmock/testasync.py @@ -321,6 +321,13 @@ def test_is_child_AsyncMock(self): self.assertIsInstance(mock.normal_method, MagicMock) self.assertIsInstance(mock, MagicMock) + def test_magicmock_lambda_spec(self): + mock_obj = MagicMock() + mock_obj.mock_func = MagicMock(spec=lambda x: x) + + with patch.object(mock_obj, "mock_func") as cm: + self.assertIsInstance(cm, MagicMock) + class AsyncArguments(unittest.TestCase): def test_add_return_value(self): From 54537f47f920688df204b4b76c02976ba6bf9b0e Mon Sep 17 00:00:00 2001 From: Xtreak Date: Sat, 15 Jun 2019 21:52:36 +0530 Subject: [PATCH 2/2] Add NEWS entry --- .../next/Library/2019-06-15-21-52-23.bpo-37251.dYzQt6.rst | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2019-06-15-21-52-23.bpo-37251.dYzQt6.rst diff --git a/Misc/NEWS.d/next/Library/2019-06-15-21-52-23.bpo-37251.dYzQt6.rst b/Misc/NEWS.d/next/Library/2019-06-15-21-52-23.bpo-37251.dYzQt6.rst new file mode 100644 index 00000000000000..545591564b8c81 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2019-06-15-21-52-23.bpo-37251.dYzQt6.rst @@ -0,0 +1,3 @@ +:class:`unittest.mock.MagicMock` with function as spec used as a spec to +:func:`unittest.mock.patch` should return a +:class:`unittest.mock.MagicMock`. Patch by Karthikeyan Singaravelan.