`autospec` doesn't work with lazy-imported symbols
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 35.9k
- PR merge metrics
- PR metrics pending
Description
Bug report
Bug description:
unittest.mock.patch(target, autospec=True) reads unresolved lazy-import bindings directly from target.__dict__ and autospecs the LazyImportType proxy instead of the imported symbol.
from unittest.mock import patch
lazy from json import dumps
with patch("__main__.dumps", autospec=True) as mock_dumps:
mock_dumps({})
On CPython main (9d231cbc937f as of now), this raises:
TypeError: 'NonCallableMagicMock' object is not callable
Resolving dumps before patching works. This also affects patch.object, spec=True, and spec_set=True.
A practical example is concurrent.futures.ThreadPoolExecutor, which now uses an explicit lazy import: existing tests such as this one patch it with autospec=True and encounter the same issue.
CPython versions tested on:
CPython main branch
Operating systems tested on:
Linux, macOS, Windows
Linked PRs
- gh-153977
- gh-157768
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the unittest.mock.patch and patch.object entry points and reproduce the example using a lazy import of json.dumps. Compare autospec=True with spec=True and spec_set=True, including the ThreadPoolExecutor test case linked in the report; done means these cases handle the imported symbol without the reported NonCallableMagicMock error.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- testing-qa
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100