pytest-httpserver

1.1.5 · active · verified Fri Apr 10

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

Install

Imports

Quickstart

This quickstart demonstrates how to use the `httpserver` pytest fixture to set up an expected request for `/foobar` that responds with a JSON object. It then uses the `requests` library to make a call to the server's URL and asserts the response. The `url_for()` method constructs the full URL including the dynamically assigned port.

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.

view raw JSON →