Mocked value at method level not overriding class-level mock in unittest
還沒有人認領這個 Issue。
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 36k
- PR 合併指標
- PR 指標待擷取
描述
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
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
首先,使用在類別層級和方法層級都套用 unittest.mock.patch 的方式重現該範例,然後檢查 unittest.mock.patch 裝飾器及其與 unittest.TestCase 方法的互動。確認方法層級的回傳值是否會被忽略,並新增或更新一個有針對性的回歸測試,以展示預期的方法層級覆寫。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- python
- 領域
- testing-qa
- Issue 類型
- 缺陷
- 難度
- 3/5
- 預估耗時
- 1-2 天
- 活躍度
- 停滯
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100