python / python/cpython

`autospec` doesn't work with lazy-imported symbols

Aperta
#153,888 1 commento 1 reazione 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

3.15 3.16 stdlib topic-lazy-imports type-bug
Lingua principale
Python
Stelle
77.2k
Fork
35.9k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

Bug report

Bug description:

unittest.mock.patch(target, autospec=True) reads unresolved lazy-import bindings directly from target.__dict__ and autospecs the LazyImportType proxy instead of the imported symbol.

from unittest.mock import patch

lazy from json import dumps

with patch("__main__.dumps", autospec=True) as mock_dumps:
    mock_dumps({})

On CPython main (9d231cbc937f as of now), this raises:

TypeError: 'NonCallableMagicMock' object is not callable

Resolving dumps before patching works. This also affects patch.object, spec=True, and spec_set=True.

A practical example is concurrent.futures.ThreadPoolExecutor, which now uses an explicit lazy import: existing tests such as this one patch it with autospec=True and encounter the same issue.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux, macOS, Windows

Linked PRs
  • gh-153977
  • gh-157768

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 dai punti di ingresso unittest.mock.patch e patch.object e riproduci l’esempio usando un import lazy di json.dumps. Confronta autospec=True con spec=True e spec_set=True, incluso il caso di test ThreadPoolExecutor collegato nel report; il lavoro è completato quando questi casi gestiscono il simbolo importato senza l’errore NonCallableMagicMock segnalato.

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

Valutazione

Stack tecnologico
python
Ambito
testing-qa
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
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.