python type_error ai_generated true

TypeError: test_foo() 缺少 1 个必需的位置参数: 'mock_bar'

TypeError: test_foo() missing 1 required positional argument: 'mock_bar'

ID: python/unittest-mock-patch-decorator-order

其他格式: JSON · Markdown 中文 · English
80%修复率
90%置信度
0证据数
2024-05-05首次发现

版本兼容性

版本状态引入弃用备注
3.8 active
3.12 active

根因分析

使用多个 @patch 装饰器时,mock 按从下到上的顺序传递。如果测试函数签名不匹配,会发生 TypeError。

English

When using multiple @patch decorators, the mocks are passed in bottom-up order. If the test function signature does not match, a TypeError occurs.

generic

解决方案

  1. 95% 成功率
    @patch('module.ClassB')
    @patch('module.ClassA')
    def test_foo(mock_a, mock_b):  # mock_a corresponds to bottom decorator
        ...
  2. 98% 成功率
    def test_foo():
        with patch('module.ClassA') as mock_a, \
             patch('module.ClassB') as mock_b:
            ...

无效尝试

常见但无效的做法:

  1. 70% 失败

    This hides the error but makes the test less clear and may cause issues with assertions.

  2. 60% 失败

    This may not be possible if multiple dependencies need mocking.