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-mockVerified import paths — ran on the pinned version, not inferred.
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`.
Upgrade to Python 3.5+ or pin `requests-mock` to `<1.12.0`.
Ensure 'requests' is updated to version 2.3 or higher. If unable to update, pin `requests-mock` to a compatible earlier version.
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.
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.
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.
pip install requests-mock
When using 'requests_mock' as a pytest fixture, include it in the test function's arguments, e.g., 'def test_example(m):'.
Provide the 'json=' or 'text=' argument when defining the mock response, for example: 'm.get('http://test.com/api', json={'key': 'value'})'.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:'.