python / python/cpython

unittest.mock spec and create_autospec should support type-hints

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

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

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

Mô tả

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

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

Bắt đầu bằng cách truy vết các điểm vào của unittest.mock và create_autospec, bao gồm cách spec_set=True hiện xử lý các thuộc tính instance được khởi tạo trong init. Xác định hành vi cho các gợi ý kiểu đơn giản, các union phức tạp và cờ suy luận tùy chọn được đề xuất; được coi là hoàn thành khi các annotation được yêu cầu tạo ra các spec phù hợp mà không thay đổi hành vi fallback đối với các trường hợp không được hỗ trợ.

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
Tính năng
Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
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
35/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.