requests-mock

raw JSON →
1.12.1 verified Tue May 12 auth: no python install: verified

requests-mock is a Python library that provides comprehensive mocking capabilities for the popular `requests` library. It acts as a transport adapter, allowing you to predefine responses for HTTP requests in tests without making actual network calls, thus enabling faster, more reliable, and isolated unit testing. The current version is 1.12.1, released on March 28, 2024. It maintains an active development status with regular releases.

pip install requests-mock
error ModuleNotFoundError: No module named 'requests_mock'
cause The 'requests-mock' library has not been installed in the Python environment where the code is being run.
fix
pip install requests-mock
error NameError: name 'm' is not defined
cause The 'requests_mock' pytest fixture or context manager was not correctly applied or its argument was not included in the test function signature.
fix
When using 'requests_mock' as a pytest fixture, include it in the test function's arguments, e.g., 'def test_example(m):'.
error json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
cause The mock response was defined without specifying 'json=' or 'text=', resulting in an empty response body, and the client code then attempted to parse this empty body as JSON.
fix
Provide the 'json=' or 'text=' argument when defining the mock response, for example: 'm.get('http://test.com/api', json={'key': 'value'})'.
error AttributeError: 'requests.sessions.Session' object has no attribute 'add_adapter'
cause This error occurs when attempting to manually integrate 'requests_mock' with a specific 'requests.Session' instance in an unsupported way, rather than using 'requests-mock's built-in session mocking capabilities.
fix
Use 'requests_mock' as a context manager or decorator, explicitly passing the session to be mocked: 'with requests_mock.Mocker(session=my_session) as m:'.
breaking requests-mock dropped support for Python 2 in version 1.12.0. Users on Python 2 must use an older version.
fix Upgrade to Python 3.5+ or pin `requests-mock` to `<1.12.0`.
breaking The minimum required version of the 'requests' library was increased to 2.3.
fix Ensure 'requests' is updated to version 2.3 or higher. If unable to update, pin `requests-mock` to a compatible earlier version.
gotcha By default, request matching is case-insensitive for all URL components, including paths. This can lead to unexpected matches if your application relies on case-sensitive paths.
fix Set `case_sensitive=True` when creating the Mocker (e.g., `with requests_mock.Mocker(case_sensitive=True) as m:`) or globally with `requests_mock.Mocker.case_sensitive = True`. It is recommended to use the global fix as case sensitivity is planned to become the default in future releases.
gotcha If a mocked response attempts to set a cookie when used with a `requests.Session`, the cookie may not be properly registered by the session. This is due to how the `requests` library processes `httplib` responses.
fix requests-mock attempts to convert mocked cookies into `Set-Cookie` headers to mitigate this. For complex cookie scenarios with `Session` objects, manual inspection of headers or specific testing of cookie handling may be necessary.
gotcha When using nested mockers (e.g., a global mocker and a context-specific mocker), stopping them manually requires stopping innermost mockers first to avoid undefined behavior.
fix Adhere to LIFO (Last-In, First-Out) order when manually stopping nested `requests_mock.Mocker` instances. Using context managers or decorators generally handles this correctly.
python os / libc status wheel install import disk
3.10 alpine (musl) wheel - 0.60s 21.3M
3.10 alpine (musl) - - 0.59s 21.3M
3.10 slim (glibc) wheel 2.2s 0.43s 22M
3.10 slim (glibc) - - 0.43s 22M
3.11 alpine (musl) wheel - 0.73s 23.4M
3.11 alpine (musl) - - 0.80s 23.4M
3.11 slim (glibc) wheel 2.2s 0.70s 24M
3.11 slim (glibc) - - 0.60s 24M
3.12 alpine (musl) wheel - 0.67s 15.2M
3.12 alpine (musl) - - 0.69s 15.2M
3.12 slim (glibc) wheel 2.0s 0.69s 16M
3.12 slim (glibc) - - 0.66s 16M
3.13 alpine (musl) wheel - 0.68s 14.9M
3.13 alpine (musl) - - 0.68s 14.8M
3.13 slim (glibc) wheel 1.9s 0.66s 15M
3.13 slim (glibc) - - 0.67s 15M
3.9 alpine (musl) wheel - 0.56s 20.6M
3.9 alpine (musl) - - 0.54s 20.6M
3.9 slim (glibc) wheel 2.4s 0.50s 21M
3.9 slim (glibc) - - 0.45s 21M

This quickstart demonstrates how to use `requests-mock` as a context manager to intercept and mock a GET request. The commented-out section shows its usage as a decorator, which is common in testing frameworks like `pytest`.

import requests
import requests_mock
import os

# Example using a context manager
with requests_mock.Mocker() as m:
    m.get('http://test.com', json={'key': 'value'}, status_code=200)
    response = requests.get('http://test.com')
    print(f"Status Code: {response.status_code}")
    print(f"JSON: {response.json()}")

# Example using a decorator (e.g., in a test function)
# @requests_mock.Mocker()
# def test_my_function(m):
#     m.post('http://api.example.com/submit', text='OK')
#     response = requests.post('http://api.example.com/submit', data={'data': 'test'})
#     assert response.status_code == 200
#     assert response.text == 'OK'