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

Đang mở
#100,950 2 bình luận 1 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

stdlib type-bug
Ngôn ngữ chính
Python
Star
77.2k
Fork
36k
Chỉ số merge pull request
Chỉ số pull request đang chờ

Mô tả

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.

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Tái hiện ví dụ với foobar/foo-bar.py, sau đó kiểm tra phần triển khai resolve_name của pkgutil.py và unittest.mock.patch tại nơi nó được sử dụng. Thay đổi được hoàn tất khi các tên được importlib.import_module chấp nhận được xử lý nhất quán bởi patch path, với coverage cho tên tệp mô-đun chứa dấu gạch ngang.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
python
Lĩnh vực
testing-qa
Loại issue
Lỗi
Độ khó
3/5
Thời gian dự kiến
1-2 ngày
Mức độ hoạt động
Đình trệ
Độ rõ ràng
Khá rõ ràng
Mức phù hợp với người mới
48/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.