requests-mock

1.12.1 · active · verified Sun Mar 29

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

Install

Imports

Quickstart

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'

view raw JSON →