pytest-httpx


Namepytest-httpx JSON
Version 0.30.0 PyPI version JSON
download
home_page
SummarySend responses to httpx.
upload_time2024-02-21 17:59:56
maintainer
docs_urlNone
author
requires_python>=3.9
licenseMIT License Copyright (c) 2024 Colin Bounouar Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords httpx mock pytest testing
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <h2 align="center">Send responses to HTTPX using pytest</h2>

<p align="center">
<a href="https://pypi.org/project/pytest-httpx/"><img alt="pypi version" src="https://img.shields.io/pypi/v/pytest_httpx"></a>
<a href="https://github.com/Colin-b/pytest_httpx/actions"><img alt="Build status" src="https://github.com/Colin-b/pytest_httpx/workflows/Release/badge.svg"></a>
<a href="https://github.com/Colin-b/pytest_httpx/actions"><img alt="Coverage" src="https://img.shields.io/badge/coverage-100%25-brightgreen"></a>
<a href="https://github.com/psf/black"><img alt="Code style: black" src="https://img.shields.io/badge/code%20style-black-000000.svg"></a>
<a href="https://github.com/Colin-b/pytest_httpx/actions"><img alt="Number of tests" src="https://img.shields.io/badge/tests-208 passed-blue"></a>
<a href="https://pypi.org/project/pytest-httpx/"><img alt="Number of downloads" src="https://img.shields.io/pypi/dm/pytest_httpx"></a>
</p>

> 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`](https://docs.pytest.org/en/latest/) fixture will make sure every [`httpx`](https://www.python-httpx.org) request will be replied to with user provided responses.

- [Add responses](#add-responses)
  - [JSON body](#add-json-response)
  - [Custom body](#reply-with-custom-body)
  - [Multipart body (files, ...)](#add-multipart-response)
  - [HTTP status code](#add-non-200-response)
  - [HTTP headers](#reply-with-custom-headers)
  - [HTTP/2.0](#add-http/2.0-response)
- [Add dynamic responses](#dynamic-responses)
- [Raising exceptions](#raising-exceptions)
- [Check requests](#check-sent-requests)
- [Do not mock some requests](#do-not-mock-some-requests)
- [Migrating](#migrating-to-pytest-httpx)
  - [responses](#from-responses)
  - [aioresponses](#from-aioresponses)

## Add responses

You can register responses for both sync and async [`HTTPX`](https://www.python-httpx.org) requests.

```python
import pytest
import httpx


def test_something(httpx_mock):
    httpx_mock.add_response()

    with httpx.Client() as client:
        response = client.get("https://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("https://test_url")
```

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

This behavior can be disabled thanks to the `assert_all_responses_were_requested` fixture:

```python
import pytest

@pytest.fixture
def assert_all_responses_were_requested() -> bool:
    return False
```

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](https://docs.python.org/3/library/re.html) instance or a [httpx.URL](https://www.python-httpx.org/api/#url) instance.

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

Order of parameters in the query string does not matter, however order of values do matter if the same parameter is provided more than once.

```python
import httpx
from pytest_httpx import HTTPXMock


def test_url(httpx_mock: HTTPXMock):
    httpx_mock.add_response(url="https://test_url?a=1&b=2")

    with httpx.Client() as client:
        response1 = client.delete("https://test_url?a=1&b=2")
        response2 = client.get("https://test_url?b=2&a=1")
```

#### 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.

```python
import httpx
from pytest_httpx import HTTPXMock


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

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


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

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


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

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


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

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


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

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

#### Matching on proxy URL

`proxy_url` parameter can either be a string, a python [re.Pattern](https://docs.python.org/3/library/re.html) instance or a [httpx.URL](https://www.python-httpx.org/api/#url) instance.

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

Order of parameters in the query string does not matter, however order of values do matter if the same parameter is provided more than once.

```python
import httpx
from pytest_httpx import HTTPXMock


def test_proxy_url(httpx_mock: HTTPXMock):
    httpx_mock.add_response(proxy_url="http://test_proxy_url?b=1&a=2")

    with httpx.Client(proxy="http://test_proxy_url?a=2&b=1") as client:
        response = client.get("https://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.

```python
import httpx
from pytest_httpx import HTTPXMock


def test_headers_matching(httpx_mock: HTTPXMock):
    httpx_mock.add_response(match_headers={'User-Agent': 'python-httpx/0.25.0'})

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

#### Matching on HTTP body

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

Matching is performed on equality.

```python
import httpx
from pytest_httpx import 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("https://test_url", content=b"This is the body")
```

##### Matching on HTTP JSON body

Use `match_json` parameter to specify the JSON decoded HTTP body to reply to.

Matching is performed on equality. You can however use `unittest.mock.ANY` to do partial matching.

```python
import httpx
from pytest_httpx import HTTPXMock
from unittest.mock import ANY

def test_json_matching(httpx_mock: HTTPXMock):
    httpx_mock.add_response(match_json={"a": "json", "b": 2})

    with httpx.Client() as client:
        response = client.post("https://test_url", json={"a": "json", "b": 2})

        
def test_partial_json_matching(httpx_mock: HTTPXMock):
    httpx_mock.add_response(match_json={"a": "json", "b": ANY})

    with httpx.Client() as client:
        response = client.post("https://test_url", json={"a": "json", "b": 2})
```
        
Note that `match_content` cannot be provided if `match_json` is also provided.

### Add JSON response

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

```python
import httpx
from pytest_httpx import HTTPXMock


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

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

Note that the `content-type` header will be set to `application/json` by default in the response.

### Reply with custom body

Use `text` parameter to reply with a custom body by providing UTF-8 encoded string.

```python
import httpx
from pytest_httpx import HTTPXMock


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

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

```

Use `content` parameter to reply with a custom body by providing bytes.

```python
import httpx
from pytest_httpx import HTTPXMock


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

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

Use `html` parameter to reply with a custom body by providing UTF-8 encoded string.

```python
import httpx
from pytest_httpx import HTTPXMock


def test_html_body(httpx_mock: HTTPXMock):
    httpx_mock.add_response(html="<body>This is <p> HTML content</body>")

    with httpx.Client() as client:
        assert client.get("https://test_url").text == "<body>This is <p> HTML content</body>"

```

### Reply by streaming chunks

Use `stream` parameter to stream chunks that you specify.

```python
import httpx
import pytest
from pytest_httpx import HTTPXMock, IteratorStream

def test_sync_streaming(httpx_mock: HTTPXMock):
    httpx_mock.add_response(stream=IteratorStream([b"part 1", b"part 2"]))

    with httpx.Client() as client:
        with client.stream(method="GET", url="https://test_url") as response:
            assert list(response.iter_raw()) == [b"part 1", b"part 2"]


@pytest.mark.asyncio
async def test_async_streaming(httpx_mock: HTTPXMock):
    httpx_mock.add_response(stream=IteratorStream([b"part 1", b"part 2"]))

    async with httpx.AsyncClient() as client:
        async with client.stream(method="GET", url="https://test_url") as response:
            assert [part async for part in response.aiter_raw()] == [b"part 1", b"part 2"]
    
```

### Add multipart response

Use the httpx `MultipartStream` via the `stream` parameter to send a multipart response.

Reach out to `httpx` developers if you need this publicly exposed as [this is not a standard use case](https://github.com/encode/httpx/issues/872#issuecomment-633584819).

```python
import httpx
from httpx._multipart import MultipartStream
from pytest_httpx import HTTPXMock


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

    with httpx.Client() as client:
        assert client.get("https://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.

```python
import httpx
from pytest_httpx import HTTPXMock


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

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

```

### Reply with custom headers

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

Any valid httpx headers type is supported, you can submit headers as a dict (str or bytes), a list of 2-tuples (str or bytes) or a `httpx.Header` instance.

```python
import httpx
from pytest_httpx import HTTPXMock


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

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


def test_headers_as_str_tuple_list(httpx_mock: HTTPXMock):
    httpx_mock.add_response(headers=[("X-Header1", "Test value")])

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


def test_headers_as_httpx_headers(httpx_mock: HTTPXMock):
    httpx_mock.add_response(headers=httpx.Headers({b"X-Header1": b"Test value"}))

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

```

#### Reply with cookies

Cookies are sent in the `set-cookie` HTTP header.

You can then send cookies in the response by setting the `set-cookie` header with [the value following key=value format]((https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie)).

```python
import httpx
from pytest_httpx import HTTPXMock


def test_cookie(httpx_mock: HTTPXMock):
    httpx_mock.add_response(headers={"set-cookie": "key=value"})

    with httpx.Client() as client:
        response = client.get("https://test_url")
    assert dict(response.cookies) == {"key": "value"}


def test_cookies(httpx_mock: HTTPXMock):
    httpx_mock.add_response(headers=[("set-cookie", "key=value"), ("set-cookie", "key2=value2")])

    with httpx.Client() as client:
        response = client.get("https://test_url")
    assert dict(response.cookies) == {"key": "value", "key2": "value2"}

```


### Add HTTP/2.0 response

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

```python
import httpx
from pytest_httpx import 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("https://test_url").http_version == "HTTP/2.0"

```

## Add callbacks

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

Callback should expect one parameter, the received [`httpx.Request`](https://www.python-httpx.org/api/#request).

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

This behavior can be disabled thanks to the `assert_all_responses_were_requested` fixture:

```python
import pytest

@pytest.fixture
def assert_all_responses_were_requested() -> bool:
    return False
```

Note that callbacks are considered as responses, and thus are [selected the same way](#how-response-is-selected).

### Dynamic responses

Callback should return a `httpx.Response`.

```python
import httpx
from pytest_httpx import HTTPXMock


def test_dynamic_response(httpx_mock: HTTPXMock):
    def custom_response(request: httpx.Request):
        return httpx.Response(
            status_code=200, json={"url": str(request.url)},
        )

    httpx_mock.add_callback(custom_response)

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

```

Alternatively, callbacks can also be asynchronous.

As in the following sample simulating network latency on some responses only.

```python
import asyncio
import httpx
import pytest
from pytest_httpx import HTTPXMock


@pytest.mark.asyncio
async def test_dynamic_async_response(httpx_mock: HTTPXMock):
    async def simulate_network_latency(request: httpx.Request):
        await asyncio.sleep(1)
        return httpx.Response(
            status_code=200, json={"url": str(request.url)},
        )

    httpx_mock.add_callback(simulate_network_latency)
    httpx_mock.add_response()

    async with httpx.AsyncClient() as client:
        responses = await asyncio.gather(
            # Response will be received after one second
            client.get("https://test_url"),
            # Response will instantly be received (1 second before the first request)
            client.get("https://test_url")
        )

```

### Raising exceptions

You can simulate HTTPX exception throwing by raising an exception in your callback or use `httpx_mock.add_exception` with the exception instance.

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

```python
import httpx
import pytest
from pytest_httpx import HTTPXMock


def test_exception_raising(httpx_mock: HTTPXMock):
    httpx_mock.add_exception(httpx.ReadTimeout("Unable to read within timeout"))
    
    with httpx.Client() as client:
        with pytest.raises(httpx.ReadTimeout):
            client.get("https://test_url")

```

Note that default behavior is to send an `httpx.TimeoutException` in case no response can be found. You can then test this kind of exception this way:

```python
import httpx
import pytest
from pytest_httpx import HTTPXMock


def test_timeout(httpx_mock: HTTPXMock):
    with httpx.Client() as client:
        with pytest.raises(httpx.TimeoutException):
            client.get("https://test_url")

```

## Check sent requests

The best way to ensure the content of your requests is still to use the `match_headers` and / or `match_content` parameters when adding a response.
In the same spirit, ensuring that no request was issued does not necessarily require any code.

In any case, you always have the ability to retrieve the requests that were issued.

As in the following samples:

```python
import httpx
from pytest_httpx import HTTPXMock


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

    with httpx.Client() as client:
        response1 = client.get("https://test_url")
        response2 = client.get("https://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("https://test_url")

    request = httpx_mock.get_request()


def test_no_request(httpx_mock: HTTPXMock):
    assert not 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](https://docs.python.org/3/library/re.html) instance or a [httpx.URL](https://www.python-httpx.org/api/#url) instance.

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

Order of parameters in the query string does not matter, however order of values do matter if the same parameter is provided more than once.

#### 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 proxy URL

`proxy_url` parameter can either be a string, a python [re.Pattern](https://docs.python.org/3/library/re.html) instance or a [httpx.URL](https://www.python-httpx.org/api/#url) instance.

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

Order of parameters in the query string does not matter, however order of values do matter if the same parameter is provided more than once.

#### 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.

##### Matching on HTTP JSON body

Use `match_json` parameter to specify the JSON decoded HTTP body executing the callback.

Matching is performed on equality. You can however use `unittest.mock.ANY` to do partial matching.

Note that `match_content` cannot be provided if `match_json` is also provided.

## Do not mock some requests

By default, `pytest-httpx` will mock every request.

But, for instance, in case you want to write integration tests with other servers, you might want to let some requests go through.

To do so, you can use the `non_mocked_hosts` fixture:

```python
import pytest

@pytest.fixture
def non_mocked_hosts() -> list:
    return ["my_local_test_host", "my_other_test_host"]
```

Every other requested hosts will be mocked as in the following example

```python
import pytest
import httpx

@pytest.fixture
def non_mocked_hosts() -> list:
    return ["my_local_test_host"]


def test_partial_mock(httpx_mock):
    httpx_mock.add_response()

    with httpx.Client() as client:
        # This request will NOT be mocked
        response1 = client.get("https://www.my_local_test_host/sub?param=value")
        # This request will be mocked
        response2 = client.get("https://test_url")
```

## Migrating to pytest-httpx

Here is how to migrate from well-known testing libraries to `pytest-httpx`.

### From responses

| Feature           | responses                  | pytest-httpx                |
|:------------------|:---------------------------|:----------------------------|
| Add a response    | `responses.add()`          | `httpx_mock.add_response()` |
| Add a callback    | `responses.add_callback()` | `httpx_mock.add_callback()` |
| Retrieve requests | `responses.calls`          | `httpx_mock.get_requests()` |

#### Add a response or a callback

Undocumented parameters means that they are unchanged between `responses` and `pytest-httpx`.
Below is a list of parameters that will require a change in your code.

| Parameter            | responses                           | pytest-httpx                                                         |
|:---------------------|:------------------------------------|:---------------------------------------------------------------------|
| method               | `method=responses.GET`              | `method="GET"`                                                       |
| body (as bytes)      | `body=b"sample"`                    | `content=b"sample"`                                                  |
| body (as str)        | `body="sample"`                     | `text="sample"`                                                      |
| status code          | `status=201`                        | `status_code=201`                                                    |
| headers              | `adding_headers={"name": "value"}`  | `headers={"name": "value"}`                                          |
| content-type header  | `content_type="application/custom"` | `headers={"content-type": "application/custom"}`                     |
| Match the full query | `match_querystring=True`            | The full query is always matched when providing the `url` parameter. |

Sample adding a response with `responses`:
```python
from responses import RequestsMock

def test_response(responses: RequestsMock):
    responses.add(
        method=responses.GET,
        url="https://test_url",
        body=b"This is the response content",
        status=400,
    )

```

Sample adding the same response with `pytest-httpx`:
```python
from pytest_httpx import HTTPXMock

def test_response(httpx_mock: HTTPXMock):
    httpx_mock.add_response(
        method="GET",
        url="https://test_url",
        content=b"This is the response content",
        status_code=400,
    )

```

### From aioresponses

| Feature        | aioresponses            | pytest-httpx                               |
|:---------------|:------------------------|:-------------------------------------------|
| Add a response | `aioresponses.method()` | `httpx_mock.add_response(method="METHOD")` |
| Add a callback | `aioresponses.method()` | `httpx_mock.add_callback(method="METHOD")` |

#### Add a response or a callback

Undocumented parameters means that they are unchanged between `responses` and `pytest-httpx`.
Below is a list of parameters that will require a change in your code.

| Parameter       | responses            | pytest-httpx        |
|:----------------|:---------------------|:--------------------|
| body (as bytes) | `body=b"sample"`     | `content=b"sample"` |
| body (as str)   | `body="sample"`      | `text="sample"`     |
| body (as JSON)  | `payload=["sample"]` | `json=["sample"]`   |
| status code     | `status=201`         | `status_code=201`   |

Sample adding a response with `aioresponses`:
```python
import pytest
from aioresponses import aioresponses


@pytest.fixture
def mock_aioresponse():
    with aioresponses() as m:
        yield m


def test_response(mock_aioresponse):
    mock_aioresponse.get(
        url="https://test_url",
        body=b"This is the response content",
        status=400,
    )

```

Sample adding the same response with `pytest-httpx`:
```python
def test_response(httpx_mock):
    httpx_mock.add_response(
        method="GET",
        url="https://test_url",
        content=b"This is the response content",
        status_code=400,
    )

```

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "pytest-httpx",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": "Colin Bounouar <colin.bounouar.dev@gmail.com>",
    "keywords": "httpx,mock,pytest,testing",
    "author": "",
    "author_email": "Colin Bounouar <colin.bounouar.dev@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/84/82/28ae814b16ac7c756d4a53797fbec98965b7d84dad3e50c3b4d56d3c0c77/pytest-httpx-0.30.0.tar.gz",
    "platform": null,
    "description": "<h2 align=\"center\">Send responses to HTTPX using pytest</h2>\n\n<p align=\"center\">\n<a href=\"https://pypi.org/project/pytest-httpx/\"><img alt=\"pypi version\" src=\"https://img.shields.io/pypi/v/pytest_httpx\"></a>\n<a href=\"https://github.com/Colin-b/pytest_httpx/actions\"><img alt=\"Build status\" src=\"https://github.com/Colin-b/pytest_httpx/workflows/Release/badge.svg\"></a>\n<a href=\"https://github.com/Colin-b/pytest_httpx/actions\"><img alt=\"Coverage\" src=\"https://img.shields.io/badge/coverage-100%25-brightgreen\"></a>\n<a href=\"https://github.com/psf/black\"><img alt=\"Code style: black\" src=\"https://img.shields.io/badge/code%20style-black-000000.svg\"></a>\n<a href=\"https://github.com/Colin-b/pytest_httpx/actions\"><img alt=\"Number of tests\" src=\"https://img.shields.io/badge/tests-208 passed-blue\"></a>\n<a href=\"https://pypi.org/project/pytest-httpx/\"><img alt=\"Number of downloads\" src=\"https://img.shields.io/pypi/dm/pytest_httpx\"></a>\n</p>\n\n> Version 1.0.0 will be released once httpx is considered as stable (release of 1.0.0).\n>\n> However, current state can be considered as stable.\n\nOnce installed, `httpx_mock` [`pytest`](https://docs.pytest.org/en/latest/) fixture will make sure every [`httpx`](https://www.python-httpx.org) request will be replied to with user provided responses.\n\n- [Add responses](#add-responses)\n  - [JSON body](#add-json-response)\n  - [Custom body](#reply-with-custom-body)\n  - [Multipart body (files, ...)](#add-multipart-response)\n  - [HTTP status code](#add-non-200-response)\n  - [HTTP headers](#reply-with-custom-headers)\n  - [HTTP/2.0](#add-http/2.0-response)\n- [Add dynamic responses](#dynamic-responses)\n- [Raising exceptions](#raising-exceptions)\n- [Check requests](#check-sent-requests)\n- [Do not mock some requests](#do-not-mock-some-requests)\n- [Migrating](#migrating-to-pytest-httpx)\n  - [responses](#from-responses)\n  - [aioresponses](#from-aioresponses)\n\n## Add responses\n\nYou can register responses for both sync and async [`HTTPX`](https://www.python-httpx.org) requests.\n\n```python\nimport pytest\nimport httpx\n\n\ndef test_something(httpx_mock):\n    httpx_mock.add_response()\n\n    with httpx.Client() as client:\n        response = client.get(\"https://test_url\")\n\n\n@pytest.mark.asyncio\nasync def test_something_async(httpx_mock):\n    httpx_mock.add_response()\n\n    async with httpx.AsyncClient() as client:\n        response = await client.get(\"https://test_url\")\n```\n\nIf all registered responses are not sent back during test execution, the test case will fail at teardown.\n\nThis behavior can be disabled thanks to the `assert_all_responses_were_requested` fixture:\n\n```python\nimport pytest\n\n@pytest.fixture\ndef assert_all_responses_were_requested() -> bool:\n    return False\n```\n\nDefault response is a HTTP/1.1 200 (OK) without any body.\n\n### How response is selected\n\nIn case more than one response match request, the first one not yet sent (according to the registration order) will be sent.\n\nIn case all matching responses have been sent, the last one (according to the registration order) will be sent.\n\nYou can add criteria so that response will be sent only in case of a more specific matching.\n\n#### Matching on URL\n\n`url` parameter can either be a string, a python [re.Pattern](https://docs.python.org/3/library/re.html) instance or a [httpx.URL](https://www.python-httpx.org/api/#url) instance.\n\nMatching is performed on the full URL, query parameters included.\n\nOrder of parameters in the query string does not matter, however order of values do matter if the same parameter is provided more than once.\n\n```python\nimport httpx\nfrom pytest_httpx import HTTPXMock\n\n\ndef test_url(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(url=\"https://test_url?a=1&b=2\")\n\n    with httpx.Client() as client:\n        response1 = client.delete(\"https://test_url?a=1&b=2\")\n        response2 = client.get(\"https://test_url?b=2&a=1\")\n```\n\n#### Matching on HTTP method\n\nUse `method` parameter to specify the HTTP method (POST, PUT, DELETE, PATCH, HEAD) to reply to.\n\n`method` parameter must be a string. It will be upper-cased, so it can be provided lower cased.\n\nMatching is performed on equality.\n\n```python\nimport httpx\nfrom pytest_httpx import HTTPXMock\n\n\ndef test_post(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(method=\"POST\")\n\n    with httpx.Client() as client:\n        response = client.post(\"https://test_url\")\n\n\ndef test_put(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(method=\"PUT\")\n\n    with httpx.Client() as client:\n        response = client.put(\"https://test_url\")\n\n\ndef test_delete(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(method=\"DELETE\")\n\n    with httpx.Client() as client:\n        response = client.delete(\"https://test_url\")\n\n\ndef test_patch(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(method=\"PATCH\")\n\n    with httpx.Client() as client:\n        response = client.patch(\"https://test_url\")\n\n\ndef test_head(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(method=\"HEAD\")\n\n    with httpx.Client() as client:\n        response = client.head(\"https://test_url\")\n    \n```\n\n#### Matching on proxy URL\n\n`proxy_url` parameter can either be a string, a python [re.Pattern](https://docs.python.org/3/library/re.html) instance or a [httpx.URL](https://www.python-httpx.org/api/#url) instance.\n\nMatching is performed on the full proxy URL, query parameters included.\n\nOrder of parameters in the query string does not matter, however order of values do matter if the same parameter is provided more than once.\n\n```python\nimport httpx\nfrom pytest_httpx import HTTPXMock\n\n\ndef test_proxy_url(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(proxy_url=\"http://test_proxy_url?b=1&a=2\")\n\n    with httpx.Client(proxy=\"http://test_proxy_url?a=2&b=1\") as client:\n        response = client.get(\"https://test_url\")\n```\n\n#### Matching on HTTP headers\n\nUse `match_headers` parameter to specify the HTTP headers to reply to.\n\nMatching is performed on equality for each provided header.\n\n```python\nimport httpx\nfrom pytest_httpx import HTTPXMock\n\n\ndef test_headers_matching(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(match_headers={'User-Agent': 'python-httpx/0.25.0'})\n\n    with httpx.Client() as client:\n        response = client.get(\"https://test_url\")\n```\n\n#### Matching on HTTP body\n\nUse `match_content` parameter to specify the full HTTP body to reply to.\n\nMatching is performed on equality.\n\n```python\nimport httpx\nfrom pytest_httpx import HTTPXMock\n\n\ndef test_content_matching(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(match_content=b\"This is the body\")\n\n    with httpx.Client() as client:\n        response = client.post(\"https://test_url\", content=b\"This is the body\")\n```\n\n##### Matching on HTTP JSON body\n\nUse `match_json` parameter to specify the JSON decoded HTTP body to reply to.\n\nMatching is performed on equality. You can however use `unittest.mock.ANY` to do partial matching.\n\n```python\nimport httpx\nfrom pytest_httpx import HTTPXMock\nfrom unittest.mock import ANY\n\ndef test_json_matching(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(match_json={\"a\": \"json\", \"b\": 2})\n\n    with httpx.Client() as client:\n        response = client.post(\"https://test_url\", json={\"a\": \"json\", \"b\": 2})\n\n        \ndef test_partial_json_matching(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(match_json={\"a\": \"json\", \"b\": ANY})\n\n    with httpx.Client() as client:\n        response = client.post(\"https://test_url\", json={\"a\": \"json\", \"b\": 2})\n```\n        \nNote that `match_content` cannot be provided if `match_json` is also provided.\n\n### Add JSON response\n\nUse `json` parameter to add a JSON response using python values.\n\n```python\nimport httpx\nfrom pytest_httpx import HTTPXMock\n\n\ndef test_json(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(json=[{\"key1\": \"value1\", \"key2\": \"value2\"}])\n\n    with httpx.Client() as client:\n        assert client.get(\"https://test_url\").json() == [{\"key1\": \"value1\", \"key2\": \"value2\"}]\n    \n```\n\nNote that the `content-type` header will be set to `application/json` by default in the response.\n\n### Reply with custom body\n\nUse `text` parameter to reply with a custom body by providing UTF-8 encoded string.\n\n```python\nimport httpx\nfrom pytest_httpx import HTTPXMock\n\n\ndef test_str_body(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(text=\"This is my UTF-8 content\")\n\n    with httpx.Client() as client:\n        assert client.get(\"https://test_url\").text == \"This is my UTF-8 content\"\n\n```\n\nUse `content` parameter to reply with a custom body by providing bytes.\n\n```python\nimport httpx\nfrom pytest_httpx import HTTPXMock\n\n\ndef test_bytes_body(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(content=b\"This is my bytes content\")\n\n    with httpx.Client() as client:\n        assert client.get(\"https://test_url\").content == b\"This is my bytes content\"\n    \n```\n\nUse `html` parameter to reply with a custom body by providing UTF-8 encoded string.\n\n```python\nimport httpx\nfrom pytest_httpx import HTTPXMock\n\n\ndef test_html_body(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(html=\"<body>This is <p> HTML content</body>\")\n\n    with httpx.Client() as client:\n        assert client.get(\"https://test_url\").text == \"<body>This is <p> HTML content</body>\"\n\n```\n\n### Reply by streaming chunks\n\nUse `stream` parameter to stream chunks that you specify.\n\n```python\nimport httpx\nimport pytest\nfrom pytest_httpx import HTTPXMock, IteratorStream\n\ndef test_sync_streaming(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(stream=IteratorStream([b\"part 1\", b\"part 2\"]))\n\n    with httpx.Client() as client:\n        with client.stream(method=\"GET\", url=\"https://test_url\") as response:\n            assert list(response.iter_raw()) == [b\"part 1\", b\"part 2\"]\n\n\n@pytest.mark.asyncio\nasync def test_async_streaming(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(stream=IteratorStream([b\"part 1\", b\"part 2\"]))\n\n    async with httpx.AsyncClient() as client:\n        async with client.stream(method=\"GET\", url=\"https://test_url\") as response:\n            assert [part async for part in response.aiter_raw()] == [b\"part 1\", b\"part 2\"]\n    \n```\n\n### Add multipart response\n\nUse the httpx `MultipartStream` via the `stream` parameter to send a multipart response.\n\nReach out to `httpx` developers if you need this publicly exposed as [this is not a standard use case](https://github.com/encode/httpx/issues/872#issuecomment-633584819).\n\n```python\nimport httpx\nfrom httpx._multipart import MultipartStream\nfrom pytest_httpx import HTTPXMock\n\n\ndef test_multipart_body(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(stream=MultipartStream(data={\"key1\": \"value1\"}, files={\"file1\": b\"content of file 1\"}, boundary=b\"2256d3a36d2a61a1eba35a22bee5c74a\"))\n\n    with httpx.Client() as client:\n        assert client.get(\"https://test_url\").text == '''--2256d3a36d2a61a1eba35a22bee5c74a\\r\nContent-Disposition: form-data; name=\"key1\"\\r\n\\r\nvalue1\\r\n--2256d3a36d2a61a1eba35a22bee5c74a\\r\nContent-Disposition: form-data; name=\"file1\"; filename=\"upload\"\\r\nContent-Type: application/octet-stream\\r\n\\r\ncontent of file 1\\r\n--2256d3a36d2a61a1eba35a22bee5c74a--\\r\n'''\n    \n```\n\n### Add non 200 response\n\nUse `status_code` parameter to specify the HTTP status code of the response.\n\n```python\nimport httpx\nfrom pytest_httpx import HTTPXMock\n\n\ndef test_status_code(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(status_code=404)\n\n    with httpx.Client() as client:\n        assert client.get(\"https://test_url\").status_code == 404\n\n```\n\n### Reply with custom headers\n\nUse `headers` parameter to specify the extra headers of the response.\n\nAny valid httpx headers type is supported, you can submit headers as a dict (str or bytes), a list of 2-tuples (str or bytes) or a `httpx.Header` instance.\n\n```python\nimport httpx\nfrom pytest_httpx import HTTPXMock\n\n\ndef test_headers_as_str_dict(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(headers={\"X-Header1\": \"Test value\"})\n\n    with httpx.Client() as client:\n        assert client.get(\"https://test_url\").headers[\"x-header1\"] == \"Test value\"\n\n\ndef test_headers_as_str_tuple_list(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(headers=[(\"X-Header1\", \"Test value\")])\n\n    with httpx.Client() as client:\n        assert client.get(\"https://test_url\").headers[\"x-header1\"] == \"Test value\"\n\n\ndef test_headers_as_httpx_headers(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(headers=httpx.Headers({b\"X-Header1\": b\"Test value\"}))\n\n    with httpx.Client() as client:\n        assert client.get(\"https://test_url\").headers[\"x-header1\"] == \"Test value\"\n\n```\n\n#### Reply with cookies\n\nCookies are sent in the `set-cookie` HTTP header.\n\nYou can then send cookies in the response by setting the `set-cookie` header with [the value following key=value format]((https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie)).\n\n```python\nimport httpx\nfrom pytest_httpx import HTTPXMock\n\n\ndef test_cookie(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(headers={\"set-cookie\": \"key=value\"})\n\n    with httpx.Client() as client:\n        response = client.get(\"https://test_url\")\n    assert dict(response.cookies) == {\"key\": \"value\"}\n\n\ndef test_cookies(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(headers=[(\"set-cookie\", \"key=value\"), (\"set-cookie\", \"key2=value2\")])\n\n    with httpx.Client() as client:\n        response = client.get(\"https://test_url\")\n    assert dict(response.cookies) == {\"key\": \"value\", \"key2\": \"value2\"}\n\n```\n\n\n### Add HTTP/2.0 response\n\nUse `http_version` parameter to specify the HTTP protocol version of the response.\n\n```python\nimport httpx\nfrom pytest_httpx import HTTPXMock\n\n\ndef test_http_version(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(http_version=\"HTTP/2.0\")\n\n    with httpx.Client() as client:\n        assert client.get(\"https://test_url\").http_version == \"HTTP/2.0\"\n\n```\n\n## Add callbacks\n\nYou can perform custom manipulation upon request reception by registering callbacks.\n\nCallback should expect one parameter, the received [`httpx.Request`](https://www.python-httpx.org/api/#request).\n\nIf all callbacks are not executed during test execution, the test case will fail at teardown.\n\nThis behavior can be disabled thanks to the `assert_all_responses_were_requested` fixture:\n\n```python\nimport pytest\n\n@pytest.fixture\ndef assert_all_responses_were_requested() -> bool:\n    return False\n```\n\nNote that callbacks are considered as responses, and thus are [selected the same way](#how-response-is-selected).\n\n### Dynamic responses\n\nCallback should return a `httpx.Response`.\n\n```python\nimport httpx\nfrom pytest_httpx import HTTPXMock\n\n\ndef test_dynamic_response(httpx_mock: HTTPXMock):\n    def custom_response(request: httpx.Request):\n        return httpx.Response(\n            status_code=200, json={\"url\": str(request.url)},\n        )\n\n    httpx_mock.add_callback(custom_response)\n\n    with httpx.Client() as client:\n        response = client.get(\"https://test_url\")\n        assert response.json() == {\"url\": \"https://test_url\"}\n\n```\n\nAlternatively, callbacks can also be asynchronous.\n\nAs in the following sample simulating network latency on some responses only.\n\n```python\nimport asyncio\nimport httpx\nimport pytest\nfrom pytest_httpx import HTTPXMock\n\n\n@pytest.mark.asyncio\nasync def test_dynamic_async_response(httpx_mock: HTTPXMock):\n    async def simulate_network_latency(request: httpx.Request):\n        await asyncio.sleep(1)\n        return httpx.Response(\n            status_code=200, json={\"url\": str(request.url)},\n        )\n\n    httpx_mock.add_callback(simulate_network_latency)\n    httpx_mock.add_response()\n\n    async with httpx.AsyncClient() as client:\n        responses = await asyncio.gather(\n            # Response will be received after one second\n            client.get(\"https://test_url\"),\n            # Response will instantly be received (1 second before the first request)\n            client.get(\"https://test_url\")\n        )\n\n```\n\n### Raising exceptions\n\nYou can simulate HTTPX exception throwing by raising an exception in your callback or use `httpx_mock.add_exception` with the exception instance.\n\nThis can be useful if you want to assert that your code handles HTTPX exceptions properly.\n\n```python\nimport httpx\nimport pytest\nfrom pytest_httpx import HTTPXMock\n\n\ndef test_exception_raising(httpx_mock: HTTPXMock):\n    httpx_mock.add_exception(httpx.ReadTimeout(\"Unable to read within timeout\"))\n    \n    with httpx.Client() as client:\n        with pytest.raises(httpx.ReadTimeout):\n            client.get(\"https://test_url\")\n\n```\n\nNote that default behavior is to send an `httpx.TimeoutException` in case no response can be found. You can then test this kind of exception this way:\n\n```python\nimport httpx\nimport pytest\nfrom pytest_httpx import HTTPXMock\n\n\ndef test_timeout(httpx_mock: HTTPXMock):\n    with httpx.Client() as client:\n        with pytest.raises(httpx.TimeoutException):\n            client.get(\"https://test_url\")\n\n```\n\n## Check sent requests\n\nThe best way to ensure the content of your requests is still to use the `match_headers` and / or `match_content` parameters when adding a response.\nIn the same spirit, ensuring that no request was issued does not necessarily require any code.\n\nIn any case, you always have the ability to retrieve the requests that were issued.\n\nAs in the following samples:\n\n```python\nimport httpx\nfrom pytest_httpx import HTTPXMock\n\n\ndef test_many_requests(httpx_mock: HTTPXMock):\n    httpx_mock.add_response()\n\n    with httpx.Client() as client:\n        response1 = client.get(\"https://test_url\")\n        response2 = client.get(\"https://test_url\")\n\n    requests = httpx_mock.get_requests()\n\n\ndef test_single_request(httpx_mock: HTTPXMock):\n    httpx_mock.add_response()\n\n    with httpx.Client() as client:\n        response = client.get(\"https://test_url\")\n\n    request = httpx_mock.get_request()\n\n\ndef test_no_request(httpx_mock: HTTPXMock):\n    assert not httpx_mock.get_request()\n```\n\n### How requests are selected\n\nYou can add criteria so that requests will be returned only in case of a more specific matching.\n\n#### Matching on URL\n\n`url` parameter can either be a string, a python [re.Pattern](https://docs.python.org/3/library/re.html) instance or a [httpx.URL](https://www.python-httpx.org/api/#url) instance.\n\nMatching is performed on the full URL, query parameters included.\n\nOrder of parameters in the query string does not matter, however order of values do matter if the same parameter is provided more than once.\n\n#### Matching on HTTP method\n\nUse `method` parameter to specify the HTTP method (POST, PUT, DELETE, PATCH, HEAD) of the requests to retrieve.\n\n`method` parameter must be a string. It will be upper-cased, so it can be provided lower cased.\n\nMatching is performed on equality.\n\n#### Matching on proxy URL\n\n`proxy_url` parameter can either be a string, a python [re.Pattern](https://docs.python.org/3/library/re.html) instance or a [httpx.URL](https://www.python-httpx.org/api/#url) instance.\n\nMatching is performed on the full proxy URL, query parameters included.\n\nOrder of parameters in the query string does not matter, however order of values do matter if the same parameter is provided more than once.\n\n#### Matching on HTTP headers\n\nUse `match_headers` parameter to specify the HTTP headers executing the callback.\n\nMatching is performed on equality for each provided header.\n\n#### Matching on HTTP body\n\nUse `match_content` parameter to specify the full HTTP body executing the callback.\n\nMatching is performed on equality.\n\n##### Matching on HTTP JSON body\n\nUse `match_json` parameter to specify the JSON decoded HTTP body executing the callback.\n\nMatching is performed on equality. You can however use `unittest.mock.ANY` to do partial matching.\n\nNote that `match_content` cannot be provided if `match_json` is also provided.\n\n## Do not mock some requests\n\nBy default, `pytest-httpx` will mock every request.\n\nBut, for instance, in case you want to write integration tests with other servers, you might want to let some requests go through.\n\nTo do so, you can use the `non_mocked_hosts` fixture:\n\n```python\nimport pytest\n\n@pytest.fixture\ndef non_mocked_hosts() -> list:\n    return [\"my_local_test_host\", \"my_other_test_host\"]\n```\n\nEvery other requested hosts will be mocked as in the following example\n\n```python\nimport pytest\nimport httpx\n\n@pytest.fixture\ndef non_mocked_hosts() -> list:\n    return [\"my_local_test_host\"]\n\n\ndef test_partial_mock(httpx_mock):\n    httpx_mock.add_response()\n\n    with httpx.Client() as client:\n        # This request will NOT be mocked\n        response1 = client.get(\"https://www.my_local_test_host/sub?param=value\")\n        # This request will be mocked\n        response2 = client.get(\"https://test_url\")\n```\n\n## Migrating to pytest-httpx\n\nHere is how to migrate from well-known testing libraries to `pytest-httpx`.\n\n### From responses\n\n| Feature           | responses                  | pytest-httpx                |\n|:------------------|:---------------------------|:----------------------------|\n| Add a response    | `responses.add()`          | `httpx_mock.add_response()` |\n| Add a callback    | `responses.add_callback()` | `httpx_mock.add_callback()` |\n| Retrieve requests | `responses.calls`          | `httpx_mock.get_requests()` |\n\n#### Add a response or a callback\n\nUndocumented parameters means that they are unchanged between `responses` and `pytest-httpx`.\nBelow is a list of parameters that will require a change in your code.\n\n| Parameter            | responses                           | pytest-httpx                                                         |\n|:---------------------|:------------------------------------|:---------------------------------------------------------------------|\n| method               | `method=responses.GET`              | `method=\"GET\"`                                                       |\n| body (as bytes)      | `body=b\"sample\"`                    | `content=b\"sample\"`                                                  |\n| body (as str)        | `body=\"sample\"`                     | `text=\"sample\"`                                                      |\n| status code          | `status=201`                        | `status_code=201`                                                    |\n| headers              | `adding_headers={\"name\": \"value\"}`  | `headers={\"name\": \"value\"}`                                          |\n| content-type header  | `content_type=\"application/custom\"` | `headers={\"content-type\": \"application/custom\"}`                     |\n| Match the full query | `match_querystring=True`            | The full query is always matched when providing the `url` parameter. |\n\nSample adding a response with `responses`:\n```python\nfrom responses import RequestsMock\n\ndef test_response(responses: RequestsMock):\n    responses.add(\n        method=responses.GET,\n        url=\"https://test_url\",\n        body=b\"This is the response content\",\n        status=400,\n    )\n\n```\n\nSample adding the same response with `pytest-httpx`:\n```python\nfrom pytest_httpx import HTTPXMock\n\ndef test_response(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(\n        method=\"GET\",\n        url=\"https://test_url\",\n        content=b\"This is the response content\",\n        status_code=400,\n    )\n\n```\n\n### From aioresponses\n\n| Feature        | aioresponses            | pytest-httpx                               |\n|:---------------|:------------------------|:-------------------------------------------|\n| Add a response | `aioresponses.method()` | `httpx_mock.add_response(method=\"METHOD\")` |\n| Add a callback | `aioresponses.method()` | `httpx_mock.add_callback(method=\"METHOD\")` |\n\n#### Add a response or a callback\n\nUndocumented parameters means that they are unchanged between `responses` and `pytest-httpx`.\nBelow is a list of parameters that will require a change in your code.\n\n| Parameter       | responses            | pytest-httpx        |\n|:----------------|:---------------------|:--------------------|\n| body (as bytes) | `body=b\"sample\"`     | `content=b\"sample\"` |\n| body (as str)   | `body=\"sample\"`      | `text=\"sample\"`     |\n| body (as JSON)  | `payload=[\"sample\"]` | `json=[\"sample\"]`   |\n| status code     | `status=201`         | `status_code=201`   |\n\nSample adding a response with `aioresponses`:\n```python\nimport pytest\nfrom aioresponses import aioresponses\n\n\n@pytest.fixture\ndef mock_aioresponse():\n    with aioresponses() as m:\n        yield m\n\n\ndef test_response(mock_aioresponse):\n    mock_aioresponse.get(\n        url=\"https://test_url\",\n        body=b\"This is the response content\",\n        status=400,\n    )\n\n```\n\nSample adding the same response with `pytest-httpx`:\n```python\ndef test_response(httpx_mock):\n    httpx_mock.add_response(\n        method=\"GET\",\n        url=\"https://test_url\",\n        content=b\"This is the response content\",\n        status_code=400,\n    )\n\n```\n",
    "bugtrack_url": null,
    "license": "MIT License  Copyright (c) 2024 Colin Bounouar  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ",
    "summary": "Send responses to httpx.",
    "version": "0.30.0",
    "project_urls": {
        "changelog": "https://github.com/Colin-b/pytest_httpx/blob/master/CHANGELOG.md",
        "documentation": "https://colin-b.github.io/pytest_httpx/",
        "issues": "https://github.com/Colin-b/pytest_httpx/issues",
        "repository": "https://github.com/Colin-b/pytest_httpx"
    },
    "split_keywords": [
        "httpx",
        "mock",
        "pytest",
        "testing"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "1460ba9895a260e16c1115e40f8ae6f615c7e8ccdfa5d55418078391dd30b476",
                "md5": "5c88b85a7df47784ef8cb8f157818644",
                "sha256": "6d47849691faf11d2532565d0c8e0e02b9f4ee730da31687feae315581d7520c"
            },
            "downloads": -1,
            "filename": "pytest_httpx-0.30.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "5c88b85a7df47784ef8cb8f157818644",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 15373,
            "upload_time": "2024-02-21T17:59:54",
            "upload_time_iso_8601": "2024-02-21T17:59:54.488241Z",
            "url": "https://files.pythonhosted.org/packages/14/60/ba9895a260e16c1115e40f8ae6f615c7e8ccdfa5d55418078391dd30b476/pytest_httpx-0.30.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "848228ae814b16ac7c756d4a53797fbec98965b7d84dad3e50c3b4d56d3c0c77",
                "md5": "5b1babaabb8d8396a12894cf616d4ac5",
                "sha256": "755b8edca87c974dd4f3605c374fda11db84631de3d163b99c0df5807023a19a"
            },
            "downloads": -1,
            "filename": "pytest-httpx-0.30.0.tar.gz",
            "has_sig": false,
            "md5_digest": "5b1babaabb8d8396a12894cf616d4ac5",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 36959,
            "upload_time": "2024-02-21T17:59:56",
            "upload_time_iso_8601": "2024-02-21T17:59:56.587401Z",
            "url": "https://files.pythonhosted.org/packages/84/82/28ae814b16ac7c756d4a53797fbec98965b7d84dad3e50c3b4d56d3c0c77/pytest-httpx-0.30.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-02-21 17:59:56",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Colin-b",
    "github_project": "pytest_httpx",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "pytest-httpx"
}
        
Elapsed time: 0.45194s