requests-mock
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.
Warnings
- breaking requests-mock dropped support for Python 2 in version 1.12.0. Users on Python 2 must use an older version.
- breaking The minimum required version of the 'requests' library was increased to 2.3.
- 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.
- 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.
- 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.
Install
-
pip install requests-mock
Imports
- Mocker
import requests_mock
Quickstart
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'