unittest.mock spec and create_autospec should support type-hints
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 35.9k
- PR merge metrics
- PR metrics pending
Description
Feature or enhancement
Proposal:
Current recommendation for spec=... and create_autospec is to set a default class value in case of attributes created within an instance's __init__():
Probably the best way of solving the problem is to add class attributes as default values for instance members initialised in
__init__()
The problem is that like written, Nones are never useful and together with spec_set=True it just results in a regular mock that accepts everything.
That recommendation and method are unfortunately very old and they existed long before the type hinting system was so developed. I believe type hints can now be reliably used to infer the spec, at least in simple terms, and in the other cases the same behavior as None can be implemented.
from unittest.mock import create_autospec
class A:
a: dict[str, int]
b: Iterator[str]
c: int | str | complex
mock = create_autospec(A)
mock().a # should be supported, with a dict spec.
mock().b # Iterator spec
mock().c # Too complex... Any spec (just like current behavior for None)
It will lead into more accurate unit tests, and we can optionally hide the behavior behind a boolean such as infer_types=True.
Has this already been discussed elsewhere?
This is a minor feature, which does not need previous discussion elsewhere
Links to previous discussion of this feature:
No response
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 by tracing the unittest.mock spec and create_autospec entry points, including how spec_set=True currently handles instance attributes initialized in init. Define the behavior for simple type hints, complex unions, and the proposed optional inference flag; done means the requested annotations produce appropriate specs without changing the fallback behavior for unsupported cases.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- testing-qa
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100