python module_error ai_generated true

ModuleNotFoundError: 没有名为 'mock' 的模块

ModuleNotFoundError: No module named 'mock'

ID: python/unittest-mock-not-found

其他格式: JSON · Markdown 中文 · English
80%修复率
89%置信度
0证据数
2024-01-17首次发现

版本兼容性

版本状态引入弃用备注
3.8 active — — —
3.12 active — — —

根因分析

代码导入了独立的 `mock` 后端包,但未安装(或项目面向 Python 3,应使用 unittest.mock)。该后端包仅在 Python 2 或很旧的 Python 3 中才需要。

English

Code imports the standalone backport `mock` package, but it is not installed (or the project targets Python 3 where unittest.mock should be used). The backport was only needed for Python 2 or very old Python 3.

generic

解决方案

  1. 97% 成功率
    Replace the import with the stdlib module:
    
    # from mock import patch  (remove)
    from unittest.mock import patch, MagicMock
    
    On Python 3.3+ this requires no installation.
  2. 90% 成功率
    If legacy code must keep `import mock`, install the backport: `pip install mock` and add it to requirements-dev.txt.

无效尝试

常见但无效的做法:

  1. 85% 失败

    The test then runs without any mocking, so the real network or DB is hit and tests fail or hang for a different reason.

  2. 80% 失败

    Old mock versions are incompatible with modern patch targets and pytest, causing AttributeError or patching failures.