python / python/cpython

Mocked value at method level not overriding class-level mock in unittest

Đang mở
#122,726 2 bình luận 0 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
35.9k
Chỉ số merge pull request
Chỉ số pull request đang chờ

Mô tả

Bug report

Bug description:
Description

I encountered an issue where mocking a value at the method level does not override the class-level mock in unit tests. Even though the method-level mock should take precedence, the value from the class-level mock is still being used.

Steps to Reproduce

Create a test class with a class-level mock using @mock.patch.
Add a method-level mock to one of the test methods to override the class-level mock.
Run the tests and observe that the class-level mock value is still used instead of the method-level mock.

Expected Behavior

The method-level mock should override the class-level mock, and the value set in the method-level mock should be used in the test.

Actual Behavior

The class-level mock value is used, and the method-level mock is ignored.

Sample code
import unittest
from unittest import mock

# Function to be mocked
def get_value():
    return "original"

# Class-level mock
@mock.patch('module.get_value', return_value='class-level')
class TestMock(unittest.TestCase):

    def test_class_level_mock(self, mock_get_value):
        # This should return 'class-level'
        result = get_value()
        self.assertEqual(result, 'class-level')

    @mock.patch('module.get_value', return_value='method-level')
    def test_method_level_mock(self, mock_get_value):
        # This should return 'method-level', but it returns 'class-level'
        result = get_value()
        self.assertEqual(result, 'method-level')

if __name__ == '__main__':
    unittest.main()

CPython versions tested on:

3.10

Operating systems tested on:

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 tái hiện ví dụ với unittest.mock.patch được áp dụng ở cả cấp lớp và cấp phương thức, sau đó kiểm tra các decorator của unittest.mock.patch và cách chúng tương tác với các phương thức của unittest.TestCase. Xác nhận liệu giá trị trả về ở cấp phương thức có bị bỏ qua hay không, đồng thời thêm hoặc cập nhật một bài kiểm thử hồi quy tập trung, thể hiện việc ghi đè ở cấp phương thức như mong đợi.

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
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.