unittest.mock spec and create_autospec should support type-hints
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 77.2k
- Forks
- 35.9k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
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
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne damit, die unittest.mock- und create_autospec-Einstiegspunkte nachzuverfolgen, einschließlich der Frage, wie spec_set=True derzeit mit in init initialisierten Instanzattributen umgeht. Lege das Verhalten für einfache Typannotationen, komplexe Unions und das vorgeschlagene optionale Inferenz-Flag fest; als erledigt gilt, dass die angeforderten Annotationen geeignete Spezifikationen erzeugen, ohne das Fallback-Verhalten für nicht unterstützte Fälle zu ändern.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- testing-qa
- Issue-Typ
- Feature
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100