[unittest.mock] `spec_set` should be applied after setting attributes via kwargs

Open
#101,756 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

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

Research direction

Start at unittest.mock.create_autospec() and follow how its keyword arguments reach configure_mock() and spec_set enforcement. Reproduce the example from the issue, then verify that kwargs such as banana are applied before spec_set rejects later unknown attributes.

Written by the indexing model from the issue text.

Description

stdlib type-feature
>>> a=create_autospec("foo", spec_set=True, banana=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.8/unittest/mock.py", line 2607, in create_autospec
    mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
  File "/usr/lib/python3.8/unittest/mock.py", line 2006, in __init__
    _safe_super(MagicMixin, self).__init__(*args, **kw)
  File "/usr/lib/python3.8/unittest/mock.py", line 460, in __init__
    self.configure_mock(**kwargs)
  File "/usr/lib/python3.8/unittest/mock.py", line 629, in configure_mock
    setattr(obj, final, val)
  File "/usr/lib/python3.8/unittest/mock.py", line 744, in __setattr__
    raise AttributeError("Mock object has no attribute '%s'" % name)
AttributeError: Mock object has no attribute 'banana'

One reason to pass extra kwargs to create_autospec() like this is to set missing attributes (e.g. because you know that they get set dynamically later on). So, it would be nice to have those attributes set on the mock before spec_set comes into effect.

Dominant language
Python
Stars
77.2k
Forks
36k
Avg merge
1d 9h
Merged PRs (30d)
558

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.

More from python/cpython

All issues in python/cpython

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.