Skip to content

unittest.mock.Mock does not allow name attribute to be mocked in constructor #95078

Open
@galenhwang

Description

@galenhwang

Bug report

Would like to set name attribute of a mocked object directly when creating Mock() object.

Currently, the workaround is to do:

from unittest.mock import Mock

obj = Mock(x=1, y="val")
obj.name = "name"

instead of directly assigning the attribute in the constructor.

Has been mentioned in the Stack Overflow community before in https://stackoverflow.com/questions/62552148/how-to-mock-name-attribute-with-unittest-mock-magicmock-or-mock-classes.

Affected code:

cpython/Lib/unittest/mock.py

Lines 1236 to 1238 in 4261b6b

* `name`: If the mock has a name then it will be used in the repr of the
mock. This can be useful for debugging. The name is propagated to child
mocks.

A suggestion would be to rename the current name attribute to mock_name.

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-featureA feature request or enhancement

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions