python
type_error
ai_generated
true
TypeError: test_x() 缺少 1 个必需的位置参数: 'mock_b' 处理上述异常时又出现另一个异常: TypeError: test_x() 接受 1 个位置参数但传入了 3 个
TypeError: test_x() missing 1 required positional argument: 'mock_b' During handling of the above exception, another exception occurred: TypeError: test_x() takes 1 positional argument but 3 were given
ID: python/pytest-unittest-mock-patch-decorator-order
80%修复率
90%置信度
0证据数
2024-02-14首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.11 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
堆叠的 @patch 装饰器按自下而上的顺序注入 mock,但测试函数参数按自上而下(或相反)编写。这导致 mock 与参数对应关系错位。
English
Stacked @patch decorators inject mocks in bottom-up order, but the test function parameters were written top-down (or vice versa). This mismatches mock-to-parameter assignment.
解决方案
-
95% 成功率
Remember: decorators apply bottom-up, so the LAST decorator is the FIRST parameter: @patch('a.foo') @patch('a.bar') def test_x(mock_bar, mock_foo): ... -
93% 成功率
Use context managers instead of decorators to avoid ordering confusion: def test_x(): with patch('a.foo') as mf, patch('a.bar') as mb: ...
无效尝试
常见但无效的做法:
-
85% 失败
unittest passes mocks positionally; *args accepts them but the names inside the body no longer refer to the intended mocks.
-
60% 失败
Non-deterministic across refactors; masks the real order rule.