Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-120732: Fix name passing to Mock, when using kwargs to create_autospec #120737

Merged
merged 1 commit into from
Jun 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Lib/test/test_unittest/testmock/testmock.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,11 @@ def test_create_autospec_should_be_configurable_by_kwargs(self):
# 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))
Expand Down
13 changes: 6 additions & 7 deletions Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix ``name`` passing to :class:`unittest.mock.Mock` object when using
:func:`unittest.mock.create_autospec`.
Loading