python config_error ai_generated true

TypeError: cannot mock attribute 'requests' of 'module' object; use patch.object() instead

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2025-02-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.9 active

Root Cause

Using @patch('module.requests') when 'requests' is a module-level import and not an attribute of the module object, often due to import order or namespace issues.

generic

中文

当 'requests' 是模块级导入而不是模块对象的属性时,使用 @patch('module.requests'),通常是由于导入顺序或命名空间问题。

Workarounds

  1. 90% success
    Use patch.object(module, 'requests') to mock the attribute directly on the module object.
  2. 85% success
    Patch the module where it is used: e.g., patch('module.requests.get') if you want to mock a specific method.

Dead Ends

Common approaches that don't work:

  1. 50% fail

    Changing the import to 'from module import requests' and patching 'module.requests' may still fail if the import is inside a function.

  2. 60% fail

    Using patch('requests') instead of 'module.requests' patches the global requests module, which may affect other tests.