unittest.mock spec and create_autospec should support type-hints
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- PR 合并指标
- PR 指标待抓取
描述
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
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
首先跟踪 unittest.mock 和 create_autospec 的入口点,包括 spec_set=True 当前如何处理在 init 中初始化的实例属性。定义简单类型提示、复杂联合类型和拟议的可选推断标志的行为;完成标准是所请求的注解能够生成适当的 spec,同时不改变不支持情形的回退行为。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- testing-qa
- Issue 类型
- 功能
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100