python module_error ai_generated true

AttributeError: module 'unittest' has no attribute 'mock'

ID: python/unittest-module-has-no-attribute-mock

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active — — —
3.11 active — — —
3.12 active — — —

Root Cause

unittest.mock is a submodule that must be imported explicitly; `import unittest` alone does not expose `unittest.mock`, and in some environments a local file named unittest.py shadows the stdlib.

generic

中文

unittest.mock 是一个子模块,必须显式导入;仅 `import unittest` 不会暴露 `unittest.mock`,且在某些环境中名为 unittest.py 的本地文件会遮蔽标准库。

Workarounds

  1. 98% success
    from unittest import mock
    # or
    from unittest.mock import patch, MagicMock
    
    with patch('module.func') as m:
        m.return_value = 42
  2. 90% success
    python -c "import unittest; print(unittest.__file__)"
    # If it prints a path inside your project, rename that file (e.g. unittest_local.py).

Dead Ends

Common approaches that don't work:

  1. 50% fail

    If a local unittest.py shadows the stdlib, this imports the local file and still lacks .mock.

  2. 80% fail

    Star import does not import submodules and is discouraged; mock is still not bound.