Registry / testing / requests-mock

requests-mock

JSON →
library1.12.1pypypi✓ verified 27d ago

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
INSTALL
IMPORT
SIG · REQUESTS-MOCK
R
requests-mock
testingpythonv1.12.1
Install
2.1s avg
Import
371ms
Disk
19MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.12.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.382s · 21.2MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.1s · import 0.360s · 22MB
19MB installed
● package 19MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Mocker
import requests_mock

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'
Debug
Known issues
breakingrequests-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`.
affects: >=1.12.0
breakingThe 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.
affects: >=1.11.0 (or possibly earlier like >=1.6)
gotchaBy 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.
affects: <1.13.0 (planned change)
gotchaIf 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.
affects: All versions
gotchaWhen 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.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'requests_mock'
The 'requests-mock' library has not been installed in the Python environment where the code is being run.
fix
pip install requests-mock
NameError: name 'm' is not defined
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):'.
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
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'})'.
AttributeError: 'requests.sessions.Session' object has no attribute 'add_adapter'
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:'.
Upgrade
Version history
1.12.1latest on PyPI · released Mar 29, 2024
Audit
Dependencies
requestsrequiredCore library for which requests-mock provides mocking capabilities. A minimum version of 2.3 is required.
Agent activity
8 hits · last 30 days
node
6
Resources
requests-mock — pip install requests-mock · libregistry