Skip to main content

Send responses to httpx.

Project description

Send responses to HTTPX using pytest

pypi version Build status Coverage Code style: black Number of tests Number of downloads

Version 1.0.0 will be released once httpx is considered as stable (release of 1.0.0).

However current state can be considered as stable.

Once installed, httpx_mock pytest fixture will make sure every httpx request will be replied to with user provided responses.

Add responses

You can register responses for both sync and async HTTPX requests.

httpx_mock fixture is available within pytest_httpx.

import pytest
import httpx
from pytest_httpx import httpx_mock


def test_something(httpx_mock):
    httpx_mock.add_response()

    with httpx.Client() as client:
        response = client.get("http://test_url")


@pytest.mark.asyncio
async def test_something_async(httpx_mock):
    httpx_mock.add_response()

    async with httpx.AsyncClient() as client:
        response = await client.get("http://test_url")

If all registered responses are not sent back during test execution, the test case will fail at teardown.

Default response is a HTTP/1.1 200 (OK) without any body.

How response is selected

In case more than one response match request, the first one not yet sent (according to the registration order) will be sent.

In case all matching responses have been sent, the last one (according to the registration order) will be sent.

You can add criteria so that response will be sent only in case of a more specific matching.

Matching on URL

url parameter can either be a string, a python re.Pattern instance or a httpx.URL instance.

Matching is performed on the full URL, query parameters included.

import httpx
from pytest_httpx import httpx_mock, HTTPXMock


def test_url(httpx_mock: HTTPXMock):
    httpx_mock.add_response(url="http://test_url")

    with httpx.Client() as client:
        response1 = client.delete("http://test_url")
        response2 = client.get("http://test_url")

Matching on HTTP method

Use method parameter to specify the HTTP method (POST, PUT, DELETE, PATCH, HEAD) to reply to.

method parameter must be a string. It will be upper cased so it can be provided lower cased.

Matching is performed on equality.

import httpx
from pytest_httpx import httpx_mock, HTTPXMock


def test_post(httpx_mock: HTTPXMock):
    httpx_mock.add_response(method="POST")

    with httpx.Client() as client:
        response = client.post("http://test_url")


def test_put(httpx_mock: HTTPXMock):
    httpx_mock.add_response(method="PUT")

    with httpx.Client() as client:
        response = client.put("http://test_url")


def test_delete(httpx_mock: HTTPXMock):
    httpx_mock.add_response(method="DELETE")

    with httpx.Client() as client:
        response = client.delete("http://test_url")


def test_patch(httpx_mock: HTTPXMock):
    httpx_mock.add_response(method="PATCH")

    with httpx.Client() as client:
        response = client.patch("http://test_url")


def test_head(httpx_mock: HTTPXMock):
    httpx_mock.add_response(method="HEAD")

    with httpx.Client() as client:
        response = client.head("http://test_url")

Matching on HTTP headers

Use match_headers parameter to specify the HTTP headers to reply to.

Matching is performed on equality for each provided header.

import httpx
from pytest_httpx import httpx_mock, HTTPXMock


def test_headers_matching(httpx_mock: HTTPXMock):
    httpx_mock.add_response(match_headers={'user-agent': 'python-httpx/0.11.1'})

    with httpx.Client() as client:
        response = client.get("http://test_url")

Matching on HTTP body

Use match_content parameter to specify the full HTTP body to reply to.

Matching is performed on equality.

import httpx
from pytest_httpx import httpx_mock, HTTPXMock


def test_content_matching(httpx_mock: HTTPXMock):
    httpx_mock.add_response(match_content=b"This is the body")

    with httpx.Client() as client:
        response = client.post("http://test_url", data=b"This is the body")

Add JSON response

Use json parameter to add a JSON response using python values.

import httpx
from pytest_httpx import httpx_mock, HTTPXMock


def test_json(httpx_mock: HTTPXMock):
    httpx_mock.add_response(json=[{"key1": "value1", "key2": "value2"}])

    with httpx.Client() as client:
        assert client.get("http://test_url").json() == [{"key1": "value1", "key2": "value2"}]

Reply with custom body

Use data parameter to reply with a custom body by providing bytes or UTF-8 encoded string.

import httpx
from pytest_httpx import httpx_mock, HTTPXMock


def test_str_body(httpx_mock: HTTPXMock):
    httpx_mock.add_response(data="This is my UTF-8 content")

    with httpx.Client() as client:
        assert client.get("http://test_url").text == "This is my UTF-8 content"


def test_bytes_body(httpx_mock: HTTPXMock):
    httpx_mock.add_response(data=b"This is my bytes content")

    with httpx.Client() as client:
        assert client.get("http://test_url").content == b"This is my bytes content"

Add multipart response

Use data parameter as a dictionary or files parameter (or both) to send multipart response.

You can specify boundary parameter to specify the multipart boundary to use.

import httpx
from pytest_httpx import httpx_mock, HTTPXMock


def test_multipart_body(httpx_mock: HTTPXMock):
    httpx_mock.add_response(data={"key1": "value1"}, files={"file1": "content of file 1"}, boundary=b"2256d3a36d2a61a1eba35a22bee5c74a")

    with httpx.Client() as client:
        assert client.get("http://test_url").text == '''--2256d3a36d2a61a1eba35a22bee5c74a\r
Content-Disposition: form-data; name="key1"\r
\r
value1\r
--2256d3a36d2a61a1eba35a22bee5c74a\r
Content-Disposition: form-data; name="file1"; filename="upload"\r
Content-Type: application/octet-stream\r
\r
content of file 1\r
--2256d3a36d2a61a1eba35a22bee5c74a--\r
'''

Add non 200 response

Use status_code parameter to specify the HTTP status code of the response.

import httpx
from pytest_httpx import httpx_mock, HTTPXMock


def test_status_code(httpx_mock: HTTPXMock):
    httpx_mock.add_response(status_code=404)

    with httpx.Client() as client:
        assert client.get("http://test_url").status_code == 404

Reply with custom headers

Use headers parameter to specify the extra headers of the response.

import httpx
from pytest_httpx import httpx_mock, HTTPXMock


def test_headers(httpx_mock: HTTPXMock):
    httpx_mock.add_response(headers={"X-Header1": "Test value"})

    with httpx.Client() as client:
        assert client.get("http://test_url").headers["x-header1"] == "Test value"

Add HTTP/2.0 response

Use http_version parameter to specify the HTTP protocol version of the response.

import httpx
from pytest_httpx import httpx_mock, HTTPXMock


def test_http_version(httpx_mock: HTTPXMock):
    httpx_mock.add_response(http_version="HTTP/2.0")

    with httpx.Client() as client:
        assert client.get("http://test_url").http_version == "HTTP/2.0"

Add callbacks

You can perform custom manipulation upon request reception by registering callbacks.

Callback should expect at least two parameters:

If all callbacks are not executed during test execution, the test case will fail at teardown.

Dynamic responses

Callback should return a httpcore response (as a tuple), you can use pytest_httpx.to_response function to create such a tuple.

import httpx
from pytest_httpx import httpx_mock, HTTPXMock, to_response


def test_dynamic_response(httpx_mock: HTTPXMock):
    def custom_response(request: httpx.Request, *args, **kwargs):
        return to_response(
            json={"url": str(request.url)},
        )

    httpx_mock.add_callback(custom_response)

    with httpx.Client() as client:
        response = client.get("http://test_url")
        assert response.json() == {"url": "http://test_url"}

Raising exceptions

You can simulate HTTPX exception throwing by raising an exception in your callback.

This can be useful if you want to assert that your code handles HTTPX exceptions properly.

import httpx
import pytest
from pytest_httpx import httpx_mock, HTTPXMock


def test_exception_raising(httpx_mock: HTTPXMock):
    def raise_timeout(*args, **kwargs):
        raise httpx.ReadTimeout()

    httpx_mock.add_callback(raise_timeout)

    with httpx.Client() as client:
        with pytest.raises(httpx.ReadTimeout):
            client.get("http://test_url")

How callback is selected

In case more than one callback match request, the first one not yet executed (according to the registration order) will be executed.

In case all matching callbacks have been executed, the last one (according to the registration order) will be executed.

You can add criteria so that callback will be sent only in case of a more specific matching.

Matching on URL

url parameter can either be a string, a python re.Pattern instance or a httpx.URL instance.

Matching is performed on the full URL, query parameters included.

Matching on HTTP method

Use method parameter to specify the HTTP method (POST, PUT, DELETE, PATCH, HEAD) executing the callback.

method parameter must be a string. It will be upper cased so it can be provided lower cased.

Matching is performed on equality.

Matching on HTTP headers

Use match_headers parameter to specify the HTTP headers executing the callback.

Matching is performed on equality for each provided header.

Matching on HTTP body

Use match_content parameter to specify the full HTTP body executing the callback.

Matching is performed on equality.

Check sent requests

import httpx
from pytest_httpx import httpx_mock, HTTPXMock


def test_many_requests(httpx_mock: HTTPXMock):
    httpx_mock.add_response()

    with httpx.Client() as client:
        response1 = client.get("http://test_url")
        response2 = client.get("http://test_url")

    requests = httpx_mock.get_requests()


def test_single_request(httpx_mock: HTTPXMock):
    httpx_mock.add_response()

    with httpx.Client() as client:
        response = client.get("http://test_url")

    request = httpx_mock.get_request()

How requests are selected

You can add criteria so that requests will be returned only in case of a more specific matching.

Matching on URL

url parameter can either be a string, a python re.Pattern instance or a httpx.URL instance.

Matching is performed on the full URL, query parameters included.

Matching on HTTP method

Use method parameter to specify the HTTP method (POST, PUT, DELETE, PATCH, HEAD) of the requests to retrieve.

method parameter must be a string. It will be upper cased so it can be provided lower cased.

Matching is performed on equality.

Matching on HTTP headers

Use match_headers parameter to specify the HTTP headers executing the callback.

Matching is performed on equality for each provided header.

Matching on HTTP body

Use match_content parameter to specify the full HTTP body executing the callback.

Matching is performed on equality.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pytest_httpx-0.3.0.tar.gz (10.0 kB view details)

Uploaded Source

Built Distribution

pytest_httpx-0.3.0-py3-none-any.whl (8.7 kB view details)

Uploaded Python 3

File details

Details for the file pytest_httpx-0.3.0.tar.gz.

File metadata

  • Download URL: pytest_httpx-0.3.0.tar.gz
  • Upload date:
  • Size: 10.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/46.4.0 requests-toolbelt/0.9.1 tqdm/4.46.0 CPython/3.7.1

File hashes

Hashes for pytest_httpx-0.3.0.tar.gz
Algorithm Hash digest
SHA256 e9edf611f68b4dfad48fdb213a0fe5be5b9a8ef3d386b19a8a65ca993ecb6d7d
MD5 194197cf40fdbf5b8caf7c86eb9a4276
BLAKE2b-256 c2aa5bbbcf36b551b76256dacf5de7ffe6522ac32a5f87c1ea263e49506cb5ec

See more details on using hashes here.

File details

Details for the file pytest_httpx-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: pytest_httpx-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 8.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/46.4.0 requests-toolbelt/0.9.1 tqdm/4.46.0 CPython/3.7.1

File hashes

Hashes for pytest_httpx-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 9bfd24ff25f6166e7977276bb5c18ee66faa03c7c8a2b2d126a316b0da129c97
MD5 3a3194bc1ed03e0fc153ae16d6f5991f
BLAKE2b-256 4f2ed9ba71561919a08d8107e481eec328775bd89b7ffa1753f583763ab78457

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page