Registry / testing / pytest-responses

pytest-responses

JSON →
library0.5.1pypypi✓ verified 87d ago

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.

pip install pytest-responses
INSTALL
IMPORT
SIG · PYTEST-RESPONSES
P
pytest-responses
testingpythonv0.5.1
Install
3.4s avg
Import
971ms
Disk
36MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.5.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.910 runs
installs and imports cleanly · install 0.0s · import 1.029s · 36.4MB
glibc
py 3.103.910 runs
installs and imports cleanly · install 3.4s · import 0.913s · 38MB
36MB installed
● package 36MB
Code
Verified usage

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

responses.activate
import responses @responses.activate def test_something(): ...
from responses import RequestsMock # Direct import of RequestsMock is less common for pytest-responses usage
The `@responses.activate` decorator automatically enables the mocking context for a test function. The `responses` fixture is also automatically available when `pytest-responses` is installed.

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
Debug
Known issues
gotchaBy default, `pytest-responses` intercepts ALL HTTP requests when `responses` is activated, preventing actual network calls. If you need to make a real external HTTP request in a specific test, `responses` must be explicitly disabled for that test.
fix
Mark the test function with `@pytest.mark.withoutresponses` to disable `responses` for that test: `@pytest.mark.withoutresponses\ndef test_external_call():\n    # This request will go to the real network\n    requests.get('http://google.com')`.
affects: All
gotchaThe underlying `responses` library, which `pytest-responses` integrates, has specific Python and `requests` library version requirements.
fix
`responses` requires Python 3.8 or newer and `requests >= 2.30.0`. Ensure your environment meets these dependencies.
affects: All
gotchaUsing `responses.add()` calls within a custom pytest fixture can sometimes lead to unexpected 'mock not used' errors or test isolation issues, especially if `responses.assert_all_requests_are_fired` is enabled.
fix
Ensure that `responses.reset()` or `responses.stop()` is called appropriately in the fixture's teardown, or consider adjusting the scope of your fixture. If `assert_all_requests_are_fired` is causing issues, temporarily disable it for specific problematic tests or consider refactoring.
affects: All
deprecatedVersion 0.5.1 fixed an internal usage of the deprecated `LooseVersion` class.
fix
Upgrade to `pytest-responses` 0.5.1 or newer to avoid `DeprecationWarning` related to `LooseVersion` when running with newer Python versions or `setuptools`.
affects: <0.5.1
Errors
Common errors & fixes
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionRefusedError(111, 'Connection refused'))
An HTTP request was made during a test where `responses` was active, but no matching mock was registered for the requested URL and HTTP method.
fix
Either add a corresponding `responses.add()` call for the exact URL and method being requested in your test, or, if an actual external network call is intended for that specific test, use `@pytest.mark.withoutresponses`.
AssertionError: Expected 1 requests, 0 have been made.
The code under test made an HTTP request, but the URL, HTTP method, or other parameters of the request did not exactly match any of the registered mocks in `responses.add()`.
fix
Carefully inspect the actual HTTP request made by your code (e.g., by debugging or logging) and ensure that the `responses.add()` call precisely matches the URL (including query parameters if `match_querystring=True`), HTTP method (GET, POST, etc.), and any headers or body content that might be used for matching.
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: ...
Your test code expected a successful response (e.g., 200 OK), but the mock was configured to return a 4xx or 5xx status code, or no mock matched and the default behavior is to raise a connection error, but `responses` was in passthrough mode, causing a real 404.
fix
Verify that your `responses.add()` call specifies the expected `status=200` (or another success code). If you are intentionally testing an error scenario, ensure your test asserts for the `requests.exceptions.HTTPError` as shown in the quickstart example.
Upgrade
Version history
0.5.1latest on PyPI · released Oct 11, 2022
Audit
Dependencies
pytestrequiredCore testing framework that pytest-responses extends.
responsesrequiredThe underlying HTTP mocking library that pytest-responses integrates. Requires `requests >= 2.30.0` and `Python 3.8+`.
requestsrequiredThe HTTP library being mocked by `responses`.
Agent activity
7 hits · last 30 days
node
6
Resources
pytest-responses — pip install pytest-responses · libregistry