python / python/cpython

mock.patch cannot import an invalid-name module in >=3.11 due to importlib.import_module vs pkgutil.resolve_name differences when module has a dash in its filename

Offen
#100,950 2 Kommentare 1 Reaktion 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

stdlib type-bug
Vorherrschende Sprache
Python
Sterne
77.2k
Forks
36k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug report

importlib.import_module() and pkgutil.resolve_name() are inconsistent with regards to which formats they accept. For example, if I have a module that contains a dash (-) in its filename (for example in a Django management command), importlib.import_module() is able to import the module just fine, while pkgutil.resolve_name() will raise an exception about an invalid format.

Minimal reproducer (all files are empty):

$ find . -name \*.py
./foobar/__init__.py
./foobar/foo-bar.py
$ python3 -c 'import importlib; importlib.import_module("foobar.foo-bar")'
$ python3 -c 'import pkgutil; pkgutil.resolve_name("foobar.foo-bar")'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.10/pkgutil.py", line 687, in resolve_name
    raise ValueError(f'invalid format: {name!r}')
ValueError: invalid format: 'foobar.foo-bar'

I would expect those to be consistent in the format they accept, i.e. accept and reject the same inputs.
My current actual problem is that unittest.mock.patch uses pkgutil.resolve_name() in Python 3.11 (but not in Python 3.10), what means that one cannot easily patch a function inside a Django management command module that contains a dash.

Your environment

Tested on Debian testing amd64 (x86_64) as of today, with both python 3.11.1 and 3.9.10.

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Reproduziere das Beispiel mit foobar/foo-bar.py und untersuche anschließend die Implementierung von resolve_name in pkgutil.py sowie unittest.mock.patch, wo es verwendet wird. Die Änderung ist abgeschlossen, wenn Namen, die von importlib.import_module akzeptiert werden, vom patch path konsistent verarbeitet werden, mit Testabdeckung für einen Moduldateinamen, der einen Bindestrich enthält.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
testing-qa
Issue-Typ
Bug
Schwierigkeit
3/5
Geschätzter Aufwand
1-2 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
48/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.