python
type_error
ai_generated
true
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%Fix Rate
90%Confidence
0Evidence
2024-02-14First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.11 | active | — | — | — |
| 3.12 | active | — | — | — |
Root Cause
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.
generic中文
堆叠的 @patch 装饰器按自下而上的顺序注入 mock,但测试函数参数按自上而下(或相反)编写。这导致 mock 与参数对应关系错位。
Workarounds
-
95% success
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% success
Use context managers instead of decorators to avoid ordering confusion: def test_x(): with patch('a.foo') as mf, patch('a.bar') as mb: ...
Dead Ends
Common approaches that don't work:
-
85% fail
unittest passes mocks positionally; *args accepts them but the names inside the body no longer refer to the intended mocks.
-
60% fail
Non-deterministic across refactors; masks the real order rule.