python / python/cpython

unittest.mock spec and create_autospec should support type-hints

Aperta
#124,816 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

type-feature
Lingua principale
Python
Stelle
77.2k
Fork
35.9k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia tracciando i punti di ingresso di unittest.mock e create_autospec, incluso il modo in cui spec_set=True gestisce attualmente gli attributi di istanza inizializzati in init. Definisci il comportamento per i semplici suggerimenti di tipo, le unioni complesse e il flag opzionale di inferenza proposto; il lavoro è completo quando le annotazioni richieste producono specifiche appropriate senza modificare il comportamento di fallback per i casi non supportati.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
testing-qa
Tipo di issue
Funzionalità
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.