{"id":26883964,"url":"https://github.com/colin-b/pytest_httpx","last_synced_at":"2025-05-14T06:12:27.549Z","repository":{"id":37972014,"uuid":"238477299","full_name":"Colin-b/pytest_httpx","owner":"Colin-b","description":"pytest fixture to mock HTTPX","archived":false,"fork":false,"pushed_at":"2024-11-28T19:16:49.000Z","size":420,"stargazers_count":397,"open_issues_count":8,"forks_count":32,"subscribers_count":4,"default_branch":"develop","last_synced_at":"2025-03-30T13:36:47.963Z","etag":null,"topics":["hacktoberfest","http","httpx","pytest","python","testing"],"latest_commit_sha":null,"homepage":"https://colin-b.github.io/pytest_httpx/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Colin-b.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-02-05T15:02:47.000Z","updated_at":"2025-03-29T10:13:12.000Z","dependencies_parsed_at":"2024-06-18T13:46:15.862Z","dependency_job_id":"aaaa5110-cdc1-4baf-af08-ab623090bc45","html_url":"https://github.com/Colin-b/pytest_httpx","commit_stats":{"total_commits":149,"total_committers":12,"mean_commits":"12.416666666666666","dds":"0.10067114093959728","last_synced_commit":"37a1b08ac80b4bce25ee51bbb5cee585745e74c9"},"previous_names":[],"tags_count":48,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Colin-b%2Fpytest_httpx","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Colin-b%2Fpytest_httpx/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Colin-b%2Fpytest_httpx/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Colin-b%2Fpytest_httpx/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Colin-b","download_url":"https://codeload.github.com/Colin-b/pytest_httpx/tar.gz/refs/heads/develop","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248960124,"owners_count":21189978,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["hacktoberfest","http","httpx","pytest","python","testing"],"created_at":"2025-03-31T17:37:55.980Z","updated_at":"2025-04-14T20:43:22.023Z","avatar_url":"https://github.com/Colin-b.png","language":"Python","readme":"\u003ch2 align=\"center\"\u003eSend responses to HTTPX using pytest\u003c/h2\u003e\n\n\u003cp align=\"center\"\u003e\n\u003ca href=\"https://pypi.org/project/pytest-httpx/\"\u003e\u003cimg alt=\"pypi version\" src=\"https://img.shields.io/pypi/v/pytest_httpx\"\u003e\u003c/a\u003e\n\u003ca href=\"https://github.com/Colin-b/pytest_httpx/actions\"\u003e\u003cimg alt=\"Build status\" src=\"https://github.com/Colin-b/pytest_httpx/workflows/Release/badge.svg\"\u003e\u003c/a\u003e\n\u003ca href=\"https://github.com/Colin-b/pytest_httpx/actions\"\u003e\u003cimg alt=\"Coverage\" src=\"https://img.shields.io/badge/coverage-100%25-brightgreen\"\u003e\u003c/a\u003e\n\u003ca href=\"https://github.com/psf/black\"\u003e\u003cimg alt=\"Code style: black\" src=\"https://img.shields.io/badge/code%20style-black-000000.svg\"\u003e\u003c/a\u003e\n\u003ca href=\"https://github.com/Colin-b/pytest_httpx/actions\"\u003e\u003cimg alt=\"Number of tests\" src=\"https://img.shields.io/badge/tests-272 passed-blue\"\u003e\u003c/a\u003e\n\u003ca href=\"https://pypi.org/project/pytest-httpx/\"\u003e\u003cimg alt=\"Number of downloads\" src=\"https://img.shields.io/pypi/dm/pytest_httpx\"\u003e\u003c/a\u003e\n\u003c/p\u003e\n\n\u003e [!NOTE]  \n\u003e Version 1.0.0 will be released once httpx is considered as stable (release of 1.0.0).\n\u003e\n\u003e 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 ([unless some hosts are explicitly skipped](#do-not-mock-some-requests)).\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- [Configuration](#configuring-httpx_mock)\n  - [Register more responses than requested](#allow-to-register-more-responses-than-what-will-be-requested)\n  - [Register less responses than requested](#allow-to-not-register-responses-for-every-request)\n  - [Allow to register a response for more than one request](#allow-to-register-a-response-for-more-than-one-request)\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 [(unless you turned `assert_all_responses_were_requested` option off)](#allow-to-register-more-responses-than-what-will-be-requested).\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 once, the request will [not be considered as matched](#in-case-no-response-can-be-found) [(unless you turned `can_send_already_matched_responses` option on)](#allow-to-register-a-response-for-more-than-one-request).\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\nimport re\nfrom pytest_httpx import HTTPXMock\n\n\ndef test_url(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(url=\"https://test_url?a=1\u0026b=2\")\n\n    with httpx.Client() as client:\n        response1 = client.delete(\"https://test_url?a=1\u0026b=2\")\n        response2 = client.get(\"https://test_url?b=2\u0026a=1\")\n\n\ndef test_url_as_pattern(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(url=re.compile(\".*test.*\"))\n\n    with httpx.Client() as client:\n        response = client.get(\"https://test_url\")\n\n\ndef test_url_as_httpx_url(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(url=httpx.URL(\"https://test_url\", params={\"a\": \"1\", \"b\": \"2\"}))\n\n    with httpx.Client() as client:\n        response = client.get(\"https://test_url?a=1\u0026b=2\")\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\u0026a=2\")\n\n    with httpx.Client(proxy=\"http://test_proxy_url?a=2\u0026b=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 (as a dict) 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 (as bytes) 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` or `match_files` cannot be provided if `match_json` is also provided.\n\n##### Matching on HTTP multipart body\n\nUse `match_files` and `match_data` parameters to specify the full multipart body to reply to.\n\nMatching is performed on equality.\n\n```python\nimport httpx\nfrom pytest_httpx import HTTPXMock\n\ndef test_multipart_matching(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(match_files={\"name\": (\"file_name\", b\"File content\")}, match_data={\"field\": \"value\"})\n\n    with httpx.Client() as client:\n        response = client.post(\"https://test_url\", files={\"name\": (\"file_name\", b\"File content\")}, data={\"field\": \"value\"})\n```\n        \nNote that `match_content` or `match_json` cannot be provided if `match_files` is also provided.\n\n#### Matching on extensions\n\nUse `match_extensions` parameter to specify the extensions (as a dict) to reply to.\n\nMatching is performed on equality for each provided extension.\n\n```python\nimport httpx\nfrom pytest_httpx import HTTPXMock\n\n\ndef test_extensions_matching(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(match_extensions={'test': 'value'})\n\n    with httpx.Client() as client:\n        response = client.get(\"https://test_url\", extensions={\"test\": \"value\"})\n```\n\n##### Matching on HTTP timeout(s)\n\nUse `match_extensions` parameter to specify the timeouts (as a dict) to reply to.\n\nMatching is performed on the full timeout dict equality.\n\n```python\nimport httpx\nfrom pytest_httpx import HTTPXMock\n\n\ndef test_timeout_matching(httpx_mock: HTTPXMock):\n    httpx_mock.add_response(match_extensions={'timeout': {'connect': 10, 'read': 10, 'write': 10, 'pool': 10}})\n\n    with httpx.Client() as client:\n        response = client.get(\"https://test_url\", timeout=10)\n```\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=\"\u003cbody\u003eThis is \u003cp\u003e HTML content\u003c/body\u003e\")\n\n    with httpx.Client() as client:\n        assert client.get(\"https://test_url\").text == \"\u003cbody\u003eThis is \u003cp\u003e HTML content\u003c/body\u003e\"\n\n```\n\n### Reply by streaming chunks\n\nUse `stream` parameter (as `httpx.SyncByteStream` or `httpx.AsyncByteStream`) to stream chunks that you specify.\n\nNote that `pytest_httpx.IteratorStream` can be used to provide an iterable.\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 (as an int) 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`](https://www.python-httpx.org/api/#headers) 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 (as a string) 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 [(unless you turned `assert_all_responses_were_requested` option off)](#allow-to-register-more-responses-than-what-will-be-requested).\n\nNote that callbacks are considered as responses, and thus are [selected the same way](#how-response-is-selected).\nMeaning that you can transpose `httpx_mock.add_response` calls in the related examples into `httpx_mock.add_callback`.\n\n### Dynamic responses\n\nCallback should return a [`httpx.Response`](https://www.python-httpx.org/api/#response) instance.\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\n#### In case no response can be found\n\nThe default behavior is to instantly raise a [`httpx.TimeoutException`](https://www.python-httpx.org/advanced/timeouts/) in case no matching response can be found.\n\nThe exception message will display the request and every registered responses to help you identify any possible mismatch.\n\n```python\nimport httpx\nimport pytest\nfrom pytest_httpx import HTTPXMock\n\n\n@pytest.mark.httpx_mock(assert_all_requests_were_expected=False)\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 [(unless you turned `assert_all_requests_were_expected` option off)](#allow-to-not-register-responses-for-every-request).\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\nNote that requests are [selected the same way as responses](#how-response-is-selected).\nMeaning that you can transpose `httpx_mock.add_response` calls in the related examples into `httpx_mock.get_requests` or `httpx_mock.get_request`.\n\n## Configuring httpx_mock\n\nThe `httpx_mock` marker is available and can be used to change the default behavior of the `httpx_mock` fixture.\n\nRefer to [available options](#available-options) for an exhaustive list of options that can be set [per test](#per-test), [per module](#per-module) or even [on the whole test suite](#for-the-whole-test-suite).\n\n### Per test\n\n```python\nimport pytest\n\n@pytest.mark.httpx_mock(assert_all_responses_were_requested=False)\ndef test_something(httpx_mock):\n    ...\n```\n\n### Per module\n\n```python\nimport pytest\n\npytestmark = pytest.mark.httpx_mock(assert_all_responses_were_requested=False)\n```\n\n### For the whole test suite\n\nThis should be set in the root `conftest.py` file.\n```python\nimport pytest\n\ndef pytest_collection_modifyitems(session, config, items):\n    for item in items:\n        item.add_marker(pytest.mark.httpx_mock(assert_all_responses_were_requested=False))\n```\n\n\u003e [!IMPORTANT]  \n\u003e Note that [there currently is a bug in pytest](https://github.com/pytest-dev/pytest/issues/10406) where `pytest_collection_modifyitems` will actually add the marker AFTER its `module` and `class` registration.\n\u003e \n\u003e Meaning the order is currently:\n\u003e module -\u003e class -\u003e test suite -\u003e test\n\u003e \n\u003e instead of:\n\u003e test suite -\u003e module -\u003e class -\u003e test\n\n### Available options\n\n#### Allow to register more responses than what will be requested\n\nBy default, `pytest-httpx` will ensure that every response was requested during test execution.\n\nIf you want to add an optional response, you can use the `is_optional` parameter when [registering a response](#add-responses) or [a callback](#add-callbacks).\n\n```python\ndef test_fewer_requests_than_expected(httpx_mock):\n    # Even if this response never received a corresponding request, the test will not fail at teardown\n    httpx_mock.add_response(is_optional=True)\n```\n\nIf you don't have control over the response registration process (shared fixtures), \nand you want to allow fewer requests than what you registered responses for, \nyou can use the `httpx_mock` marker `assert_all_responses_were_requested` option.\n\n\u003e [!CAUTION]\n\u003e Use this option at your own risk of not spotting regression (requests not sent) in your code base!\n\n```python\nimport pytest\n\n@pytest.mark.httpx_mock(assert_all_responses_were_requested=False)\ndef test_fewer_requests_than_expected(httpx_mock):\n    # Even if this response never received a corresponding request, the test will not fail at teardown\n    httpx_mock.add_response()\n```\n\nNote that the `is_optional` parameter will take precedence over the `assert_all_responses_were_requested` option.\nMeaning you can still register a response that will be checked for execution at teardown even if `assert_all_responses_were_requested` was set to `False`.\n\n```python\nimport pytest\n\n@pytest.mark.httpx_mock(assert_all_responses_were_requested=False)\ndef test_force_expected_request(httpx_mock):\n    # Even if the assert_all_responses_were_requested option is set, the test will fail at teardown if this is not matched\n    httpx_mock.add_response(is_optional=False)\n```\n\n#### Allow to not register responses for every request\n\nBy default, `pytest-httpx` will ensure that every request that was issued was expected.\n\nYou can use the `httpx_mock` marker `assert_all_requests_were_expected` option to allow more requests than what you registered responses for.\n\n\u003e [!CAUTION]\n\u003e Use this option at your own risk of not spotting regression (unexpected requests) in your code base!\n\n```python\nimport pytest\nimport httpx\n\n@pytest.mark.httpx_mock(assert_all_requests_were_expected=False)\ndef test_more_requests_than_expected(httpx_mock):\n    with httpx.Client() as client:\n        # Even if this request was not expected, the test will not fail at teardown\n        with pytest.raises(httpx.TimeoutException):\n            client.get(\"https://test_url\")\n```\n\n#### Allow to register a response for more than one request\n\nBy default, `pytest-httpx` will ensure that every request that was issued was expected.\n\nIf you want to add a response once, while allowing it to match more than once, you can use the `is_reusable` parameter when [registering a response](#add-responses) or [a callback](#add-callbacks).\n\n```python\nimport httpx\n\ndef test_more_requests_than_responses(httpx_mock):\n    httpx_mock.add_response(is_reusable=True)\n    with httpx.Client() as client:\n        client.get(\"https://test_url\")\n        # Even if only one response was registered, the test will not fail at teardown as this request will also be matched\n        client.get(\"https://test_url\")\n```\n\nIf you don't have control over the response registration process (shared fixtures), \nand you want to allow multiple requests to match the same registered response, \nyou can use the `httpx_mock` marker `can_send_already_matched_responses` option.\n\nWith this option, in case all matching responses have been sent at least once, the last one (according to the registration order) will be sent.\n\n\u003e [!CAUTION]\n\u003e Use this option at your own risk of not spotting regression (requests issued more than the expected number of times) in your code base!\n\n```python\nimport pytest\nimport httpx\n\n@pytest.mark.httpx_mock(can_send_already_matched_responses=True)\ndef test_more_requests_than_responses(httpx_mock):\n    httpx_mock.add_response()\n    with httpx.Client() as client:\n        client.get(\"https://test_url\")\n        # Even if only one response was registered, the test will not fail at teardown as this request will also be matched\n        client.get(\"https://test_url\")\n```\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 `httpx_mock` marker `should_mock` option and provide a callable expecting the [`httpx.Request`](https://www.python-httpx.org/api/#request) as parameter and returning a boolean.\n\nReturning `True` will ensure that the request is handled by `pytest-httpx` (mocked), `False` will let the request pass through (not mocked).\n\n```python\nimport pytest\nimport httpx\n\n@pytest.mark.httpx_mock(should_mock=lambda request: request.url.host != \"www.my_local_test_host\")\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","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcolin-b%2Fpytest_httpx","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcolin-b%2Fpytest_httpx","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcolin-b%2Fpytest_httpx/lists"}