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-responsesVerified import paths — ran on the pinned version, not inferred.
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.
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')`.`responses` requires Python 3.8 or newer and `requests >= 2.30.0`. Ensure your environment meets these dependencies.
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.
Upgrade to `pytest-responses` 0.5.1 or newer to avoid `DeprecationWarning` related to `LooseVersion` when running with newer Python versions or `setuptools`.
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`.
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.
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.