]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-120732: Fix `name` passing to `Mock`, when using kwargs to `create_autospec` ...
authorNikita Sobolev <mail@sobolevn.me>
Wed, 19 Jun 2024 20:35:11 +0000 (23:35 +0300)
committerGitHub <noreply@github.com>
Wed, 19 Jun 2024 20:35:11 +0000 (21:35 +0100)
Lib/test/test_unittest/testmock/testmock.py
Lib/unittest/mock.py
Misc/NEWS.d/next/Library/2024-06-19-15-06-58.gh-issue-120732.OvYV9b.rst [new file with mode: 0644]

index 77f6f1eb4b76b9538049b5a066e75375bb2f1475..e1b108f81e513c12245f7f2593ff9175875e7449 100644 (file)
@@ -129,6 +129,11 @@ class MockTest(unittest.TestCase):
         # pass kwargs with respect to the parent mock.
         self.assertEqual(class_mock().return_value.meth.side_effect, None)
 
+    def test_create_autospec_correctly_handles_name(self):
+        class X: ...
+        mock = create_autospec(X, spec_set=True, name="Y")
+        self.assertEqual(mock._mock_name, "Y")
+
     def test_repr(self):
         mock = Mock(name='foo')
         self.assertIn('foo', repr(mock))
index 08975e0e1bd1321dbb72729e149b03b0f52701a3..d50535dffeb5d1835000f0ef0e19eb96e81352be 100644 (file)
@@ -2755,6 +2755,12 @@ def create_autospec(spec, spec_set=False, instance=False, _parent=None,
     if not unsafe:
         _check_spec_arg_typos(kwargs)
 
+    _name = kwargs.pop('name', _name)
+    _new_name = _name
+    if _parent is None:
+        # for a top level object no _new_name should be set
+        _new_name = ''
+
     _kwargs.update(kwargs)
 
     Klass = MagicMock
@@ -2772,13 +2778,6 @@ def create_autospec(spec, spec_set=False, instance=False, _parent=None,
     elif is_type and instance and not _instance_callable(spec):
         Klass = NonCallableMagicMock
 
-    _name = _kwargs.pop('name', _name)
-
-    _new_name = _name
-    if _parent is None:
-        # for a top level object no _new_name should be set
-        _new_name = ''
-
     mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
                  name=_name, **_kwargs)
 
diff --git a/Misc/NEWS.d/next/Library/2024-06-19-15-06-58.gh-issue-120732.OvYV9b.rst b/Misc/NEWS.d/next/Library/2024-06-19-15-06-58.gh-issue-120732.OvYV9b.rst
new file mode 100644 (file)
index 0000000..e31c4dd
--- /dev/null
@@ -0,0 +1,2 @@
+Fix ``name`` passing to :class:`unittest.mock.Mock` object when using
+:func:`unittest.mock.create_autospec`.