pytest-httpserver
pytest-httpserver is a Python package that allows you to start a real HTTP server for your tests. The server can be programmatically configured to respond to requests, providing an easy-to-use API to set up request handlers and shut down gracefully without configuration files or daemons. As the HTTP server runs in a separate thread and listens on a TCP port, it's compatible with any HTTP client. This library facilitates testing HTTP client applications and migrating between client libraries without rewriting tests. It is currently at version 1.1.5 and maintains an active release cadence, with multiple patch releases often occurring monthly or every few months.
Warnings
- breaking Python 3.9 support was officially dropped in version 1.1.4. While code might still function, CI tests are no longer run for this version.
- breaking Python 3.8 support was deprecated in version 1.1.2 to enable more robust type hinting. Users on 3.8 should expect potential compatibility issues and no active testing support.
- deprecated The `check_assertions()` method is less preferred starting from version 1.1.4. It is recommended to use the new `check()` method.
- gotcha Prior to version 1.1.0, there was a known issue where `httpserver` state could leak between function-scoped tests due to improper fixture teardown, leading to inconsistent test results.
- gotcha When matching query parameters, do not include them directly in the URI path. The underlying Werkzeug library expects query parameters to be specified separately.
- breaking Version 1.0.0 introduced backward-incompatible changes to how request expectations are set. `httpserver.expect_request()` became a general function accepting a `handler_type` parameter, `expect_oneshot_request()` no longer accepts the `ordered` parameter, and `expect_ordered_request()` was introduced as a new method.
Install
-
pip install pytest-httpserver
Imports
- httpserver
def test_my_app(httpserver):
- HTTPServer
from pytest_httpserver import HTTPServer
Quickstart
import requests
def test_json_client(httpserver):
httpserver.expect_request("/foobar").respond_with_json({"foo": "bar"})
response = requests.get(httpserver.url_for("/foobar"))
assert response.status_code == 200
assert response.json() == {"foo": "bar"}
# To run this, save as `test_example.py` and run `pytest` in the terminal.