python / python/cpython

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

Open
#95,078 4 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib type-feature
Dominant language
Python
Stars
77.2k
Forks
36k
PR merge metrics
PR metrics pending

Description

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:
https://github.com/python/cpython/blob/4261b6bffc0b8bb5c6d4d80578a81b7520f4aefc/Lib/unittest/mock.py#L1236-L1238

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at Lib/unittest/mock.py around lines 1236-1238, where Mock’s name handling is implemented. Determine how constructor keyword attributes are separated from the internal name value, then make completion mean that Mock(name="name") exposes name as the mocked attribute without losing existing behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
testing-qa
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.