python / python/cpython

unittest.mock spec and create_autospec should support type-hints

オープン
#124,816 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

type-feature
主要言語
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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず unittest.mock と create_autospec のエントリポイントを追跡します。これには、spec_set=True が現在、init で初期化されるインスタンス属性をどのように扱っているかも含まれます。単純な型ヒント、複雑なユニオン、および提案されているオプションの推論フラグについて動作を定義します。完了条件は、要求されたアノテーションによって適切なスペックが生成され、サポートされていないケースのフォールバック動作を変更しないことです。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
testing-qa
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。