python type_error ai_generated true

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

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2024-05-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active
3.12 active

Root Cause

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

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 70% fail

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

  2. 60% fail

    This may not be possible if multiple dependencies need mocking.