{
  "id": "python/pytest-mock-patch-wrong-target",
  "signature": "AttributeError: <module 'app.services.user'> does not have the attribute 'send_email'",
  "signature_zh": "AttributeError: <module 'app.services.user'> 没有属性 'send_email'",
  "regex": "AttributeError:\\ <module\\ 'app\\.services\\.user'>\\ does\\ not\\ have\\ the\\ attribute\\ 'send_email'",
  "domain": "python",
  "category": "runtime_error",
  "subcategory": null,
  "root_cause": "`patch('app.services.user.send_email')` fails when the name is imported into the module under test from elsewhere. Patch must target the name *where it is looked up* (the consumer module), not where it is defined.",
  "root_cause_type": "generic",
  "root_cause_zh": "当被测模块通过 `from x import send_email` 导入名称时，`patch('app.services.user.send_email')` 会失败。patch 必须指向名称被查找的位置（使用方模块），而不是定义它的位置。",
  "versions": [
    {
      "version": "3.10",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    },
    {
      "version": "3.12",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    }
  ],
  "os_specific": {},
  "dead_ends": [
    {
      "action": "",
      "why_fails": "The module under test already bound the name at import time; patching the definition site does not affect the bound reference.",
      "fail_rate": 0.8,
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "why_fails": "Creates a fake attribute on the module, but the code under test still calls the original binding, so the mock is never invoked.",
      "fail_rate": 0.75,
      "condition": "",
      "sources": []
    }
  ],
  "workarounds": [
    {
      "action": "",
      "success_rate": 0.95,
      "how": "Patch where the name is used:\n\nfrom unittest.mock import patch\n\n@patch('app.services.user.send_email')\ndef test_signup(mock_send):\n    ...",
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "success_rate": 0.85,
      "how": "Change the import in the production module to a module-level reference and patch the module:\n\n# app/services/user.py\nfrom app import notifications\nnotifications.send_email(...)\n\n# test\npatch('app.services.user.notifications.send_email')",
      "condition": "",
      "sources": []
    }
  ],
  "workarounds_zh": [],
  "transition_graph": {
    "leads_to": [],
    "preceded_by": [],
    "frequently_confused_with": []
  },
  "official_doc_url": null,
  "official_doc_section": null,
  "error_code": null,
  "verification_tier": "ai_generated",
  "confidence": 0.9,
  "fix_success_rate": 0.8,
  "resolvable": "true",
  "first_seen": "2024-04-03",
  "last_confirmed": "2025-01-01",
  "last_updated": "2025-01-01",
  "evidence_count": 0,
  "tags": [],
  "locale": "en",
  "aliases": []
}