Mocked value at method level not overriding class-level mock in unittest
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- 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