pytest-responses

0.5.1 · active · verified Thu Apr 16

pytest-responses is a Pytest plugin that seamlessly integrates the `responses` library into your test suite. It automatically activates `responses`, a utility for mocking the Python `requests` library, across your tests, preventing actual HTTP requests. This helps create fast, reliable, and isolated unit and integration tests. The current version is 0.5.1, and its release cadence is irregular, with updates driven by bug fixes and compatibility needs.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the `responses` fixture provided by `pytest-responses` to mock HTTP GET requests. It includes tests for both successful responses and error scenarios, showing how to define expected JSON data and status codes, and how to assert that the mocked endpoint was called.

import pytest
import requests
import responses

def fetch_user_data(user_id):
    response = requests.get(f"https://api.example.com/users/{user_id}")
    response.raise_for_status()
    return response.json()

def test_fetch_user_data_success(responses):
    # Add a mock response for the specific URL and method
    responses.add(
        responses.GET,
        'https://api.example.com/users/123',
        json={'id': 123, 'name': 'Test User'},
        status=200
    )

    # Call the function that makes the HTTP request
    data = fetch_user_data(123)

    # Assert the returned data and that the mock was called
    assert data == {'id': 123, 'name': 'Test User'}
    assert len(responses.calls) == 1
    assert responses.calls[0].request.url == 'https://api.example.com/users/123'

def test_fetch_user_data_not_found(responses):
    responses.add(
        responses.GET,
        'https://api.example.com/users/404',
        status=404
    )

    with pytest.raises(requests.exceptions.HTTPError) as exc_info:
        fetch_user_data(404)
    assert exc_info.value.response.status_code == 404
    assert len(responses.calls) == 1

view raw JSON →