{"id":782,"library":"mock","title":"Mock (unittest.mock backport)","description":"The `mock` library is the official backport of the `unittest.mock` module, providing powerful tools for testing in Python. It enables developers to replace parts of their system under test with mock objects, allowing for isolated and predictable testing without relying on actual implementations or external dependencies. While `unittest.mock` has been part of Python's standard library since version 3.3, the `mock` package on PyPI historically provided these functionalities for older Python versions and sometimes offered newer features or bug fixes that were later integrated into the standard library. The current version is 5.2.0, with ongoing maintenance.","status":"active","version":"5.2.0","language":"python","source_language":"en","source_url":"https://github.com/testing-cabal/mock","tags":["testing","mocking","unittest","backport","unit-testing"],"install":[{"cmd":"pip install mock","lang":"bash","label":"Install the mock library"}],"dependencies":[],"imports":[{"note":"Use 'from mock import ...' when using the PyPI backport. For Python 3.3+, it's generally preferred to use the built-in 'unittest.mock' instead.","wrong":"from unittest.mock import Mock","symbol":"Mock","correct":"from mock import Mock"},{"note":"Use 'from mock import ...' when using the PyPI backport. For Python 3.3+, it's generally preferred to use the built-in 'unittest.mock' instead.","wrong":"from unittest.mock import patch","symbol":"patch","correct":"from mock import patch"},{"note":"Use 'from mock import ...' when using the PyPI backport. For Python 3.3+, it's generally preferred to use the built-in 'unittest.mock' instead.","wrong":"from unittest.mock import MagicMock","symbol":"MagicMock","correct":"from mock import MagicMock"}],"quickstart":{"code":"from mock import patch, Mock\nimport requests\n\ndef fetch_data(url):\n    response = requests.get(url)\n    response.raise_for_status()\n    return response.json()\n\n# Mocking requests.get using patch as a decorator\n@patch('requests.get')\ndef test_fetch_data_success(mock_get):\n    # Configure the mock response\n    mock_response = Mock()\n    mock_response.status_code = 200\n    mock_response.json.return_value = {'key': 'mocked_value'}\n    mock_get.return_value = mock_response\n\n    data = fetch_data('http://example.com/api/data')\n\n    mock_get.assert_called_once_with('http://example.com/api/data')\n    assert data == {'key': 'mocked_value'}\n\n# To run the test (e.g., with pytest, or manually calling):\n# print('Running test_fetch_data_success...')\n# test_fetch_data_success() # Call the decorated function\n# print('Test passed.')\n","lang":"python","description":"This quickstart demonstrates how to mock an external dependency (HTTP request via `requests.get`) using `mock.patch` as a decorator. It shows how to configure the mock's return value and assert that it was called correctly."},"warnings":[{"fix":"For Python >= 3.3, use `from unittest.mock import Mock, patch, MagicMock`. If targeting older Python versions or requiring specific features/fixes from the PyPI backport, ensure consistent imports (`from mock import ...`).","message":"The `mock` library was merged into the Python standard library as `unittest.mock` starting with Python 3.3. For Python 3.3 and newer, it is generally recommended to use `from unittest.mock import ...` instead of installing and importing the standalone `mock` package.","severity":"breaking","affected_versions":"<3.3 (requires PyPI 'mock'), >=3.3 (has built-in 'unittest.mock')"},{"fix":"Always trace the import chain to determine the correct module path. For example, if `my_module.py` imports `requests` as `req`, and `your_app.py` imports `my_module`, you might need to patch `your_app.my_module.req`.","message":"When using `patch`, it is crucial to patch the object where it is *looked up* (i.e., where it is imported by the code under test), not where it is defined. Incorrect patching paths are a very common source of silent test failures.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Use `Mock(spec=OriginalClass)` or `Mock(spec_set=OriginalClass)` (or `patch.object(..., spec=...)`/`patch.object(..., spec_set=...)`) to make the mock conform to the interface of a real object. This ensures `AttributeError` is raised for non-existent attributes. `MagicMock` is also 'loose' by default in terms of user-defined attributes.","message":"Mocks are 'loose' by default. If you misspell an attribute or method name on a `Mock` object, it will silently create a new mock attribute instead of raising an `AttributeError`. This can lead to tests that pass but don't actually test the intended behavior.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Use `MagicMock` when you expect a mock object to behave like a container, context manager, or support other magic methods. Use `Mock` when you need a simpler, more controlled object that doesn't have magic methods pre-configured.","message":"`Mock` and `MagicMock` have key differences. `MagicMock` automatically provides implementations for most Python magic methods (e.g., `__len__`, `__str__`, `__enter__`, `__exit__`), whereas `Mock` does not.","severity":"gotcha","affected_versions":"All versions"},{"fix":"To reset `return_value` and `side_effect` on the mock itself, explicitly set them to their default values (e.g., `mock_obj.return_value = Mock()`, `mock_obj.side_effect = None`) or use `mock.reset_mock(return_value=True, side_effect=True)` (Python 3.6+). Alternatively, recreate mocks between tests.","message":"Calling `mock.reset_mock()` only resets call information (e.g., `called`, `call_args`) and child mocks. It *does not* clear `return_value` or `side_effect` on the mock itself by default.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Ensure all necessary packages are installed using a package manager like `pip` (e.g., `pip install requests`). Verify the correct virtual environment is activated if applicable, or that the package is available on the `PYTHONPATH`.","message":"A `ModuleNotFoundError` indicates that a required Python package is not installed in the environment. This often happens for third-party libraries (e.g., `requests`, `numpy`, `pandas`) or custom modules that are not discoverable on the Python path.","severity":"breaking","affected_versions":"All versions"},{"fix":"Ensure that all necessary third-party packages are listed in your `requirements.txt` file and are installed in the environment using `pip install -r requirements.txt` or `pip install <package-name>`.","message":"A `ModuleNotFoundError` indicates that a required Python package is not installed in the execution environment. This often happens if the package was not included in the `requirements.txt` file or if `pip install -r requirements.txt` was not run.","severity":"breaking","affected_versions":"All versions"}],"env_vars":null,"search_vec":"'3.3':62 '5.2.0':96 'actual':45 'allow':36 'backport':3,10,103 'bug':82 'current':93 'depend':49 'develop':24 'enabl':23 'extern':48 'featur':80 'fix':83 'function':71 'histor':68 'implement':46 'integr':87 'isol':38 'later':86 'librari':6,59,91 'mainten':99 'mock':1,5,34,64,101 'modul':14 'newer':79 'object':35 'offer':78 'offici':9 'older':73 'ongo':98 'packag':65 'part':27,54 'power':16 'predict':40 'provid':15,69 'pypi':67 'python':21,56,74 'reli':43 'replac':26 'sinc':60 'sometim':77 'standard':58,90 'system':30 'test':19,32,41,100,106 'tool':17 'unit':105 'unit-test':104 'unittest':102 'unittest.mock':2,13,51 'version':61,75,94 'without':42","created_at":"2026-03-29T04:21:27.776661+00:00","updated_at":"2026-04-16T16:37:50.976095+00:00","problems":[{"fix":"For Python 3.3 and newer, use `from unittest.mock import Mock` (or `patch`, `MagicMock`, etc.). For Python versions older than 3.3 (e.g., 2.7, 3.2), install the backport (`pip install mock`) and then use `from mock import Mock`.","cause":"This error occurs when trying to import the `mock` library directly on Python versions 3.3 and newer, where mocking functionality is integrated into the standard library as `unittest.mock`. Conversely, it can also happen if `from unittest.mock import X` is used on Python versions older than 3.3 without the `mock` backport installed.","error":"ModuleNotFoundError: No module named 'mock'"},{"fix":"Ensure the mocked method or attribute name exactly matches the real object's API or the correct `mock` assertion. If using `spec` or `autospec`, either correct the name or, if the attribute is dynamically added or an instance attribute, set it on `mock_obj.return_value.attribute = value` or disable `spec`/`autospec` if strict adherence is not required.","cause":"This `AttributeError` typically arises when a mock object is created with `spec=True` or `autospec=True`, and the test attempts to access a method or attribute (including typos in assertion methods) that does not exist on the *real* object being mocked. It also occurs when patching a class and trying to access instance-specific attributes set in `__init__` without explicitly configuring the mock's `return_value`.","error":"AttributeError: Mock object has no attribute 'some_method'"},{"fix":"If the original object is callable, ensure the mock is not `NonCallableMock`. When mocking an `async def` function, use `unittest.mock.AsyncMock`. If patching a class, remember that `patch` replaces the class itself; to simulate calling an instance, interact with `mock_class.return_value` (e.g., `mock_class.return_value.method()`).","cause":"This `TypeError` occurs when you attempt to call a mock object that was created as a `NonCallableMock`, or when a `MagicMock` is used to mock an asynchronous function (`async def`) without being made awaitable, or when you incorrectly call the mocked *class* directly instead of its `return_value` to interact with a mocked instance.","error":"TypeError: 'MagicMock' object is not callable"},{"fix":"Identify the precise path where the object or function is accessed by the code being tested. Construct the `patch` target string using that exact lookup path. For example, if `my_app.views` imports `send_email` from `my_app.utils`, then to mock it within `views`, the target should be `'my_app.views.send_email'`.","cause":"The most common reason for this behavior (which doesn't raise an explicit error but leads to unexpected test failures) is providing an incorrect target string to `mock.patch`. Mocking must occur where the object is *looked up* by the code under test, not necessarily where it is defined. For example, if a module imports `from another_module import some_function`, you must patch `my_module.some_function`, not `another_module.some_function`.","error":"Mock does not appear to be called / original function is executed"}],"ecosystem":"pypi","meta_description":null,"install_score":100,"quickstart_score":0,"quickstart_tag":"stale","pypi_latest":"5.2.0","cli_name":"","cli_version":null,"type":"library","homepage":"http://mock.readthedocs.org/en/latest/","github":"https://github.com/testing-cabal/mock","docs":null,"changelog":null,"pypi":"https://pypi.org/project/mock/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["testing"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-06-28","next_check":"2026-07-28","install_tag":"verified"}}