Skip to content
Myr

Add `httpx.MockTransport()` (#1401)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Add httpx.MockTransport * Add docs on MockTransport * Add pointer to RESPX * Add note on pytest-httpx * Tweak existing docs example to use 'httpx.MockTransport'

authored by Tom Christie · committed by GitHub · parent 3bf1863 · Browse files · 13 files+198 added−158 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Florimond Manca <florimond.manca@gmail.com>

Diff stats

13 files+198 added−158 removed

  • tests:+111 added−157 removed
  • other:+87 added−1 removed

13 files+198 added−158 removed

modified:docs/advanced.md+29 added-1 removed
1060 unmodified lines
1061>>> response.json()1062{"text": "Hello, world!"}1063```10641065### Mock transports10661067During testing it can often be useful to be able to mock out a transport,1068and return pre-determined responses, rather than making actual network requests.10691070The `httpx.MockTransport` class accepts a handler function, which can be used1071to map requests onto pre-determined responses:10721073```python1074def handler(request):1075 return httpx.Response(200, json={"text": "Hello, world!"})107610771078# Switch to a mock transport, if the TESTING environment variable is set.1079if os.environ['TESTING'].upper() == "TRUE":1080 transport = httpx.MockTransport(handler)1081else:1082 transport = httpx.HTTPTransport()10831084client = httpx.Client(transport=transport)1085```10861087For more advanced use-cases you might want to take a look at either [the third-party1088mocking library, RESPX](https://lundberg.github.io/respx/), or the [pytest-httpx library](https://github.com/Colin-b/pytest_httpx).10891090### Mounting transports10911092You can also mount transports against given schemes or domains, to control1093which transport an outgoing request should be routed via, with [the same style
31 unmodified lines
11251126```python1127# All requests to "example.org" should be mocked out.1128# Other requests occur as usual.1129def handler(request):1130 return httpx.Response(200, json={"text": "Hello, World!"})11311104mounts = {"all://example.org": MockTransport()}1132mounts = {"all://example.org": httpx.MockTransport(handler)}1133client = httpx.Client(mounts=mounts)1134```11351136Adding support for custom schemes:
6 unmodified lines
added:httpx/_transports/mock.py+56 added
1from typing import Callable, List, Optional, Tuple23import httpcore45from .._models import Request678class MockTransport(httpcore.SyncHTTPTransport, httpcore.AsyncHTTPTransport):9 def __init__(self, handler: Callable) -> None:10 self.handler = handler1112 def request(13 self,14 method: bytes,15 url: Tuple[bytes, bytes, Optional[int], bytes],16 headers: List[Tuple[bytes, bytes]] = None,17 stream: httpcore.SyncByteStream = None,18 ext: dict = None,19 ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.SyncByteStream, dict]:20 request = Request(21 method=method,22 url=url,23 headers=headers,24 stream=stream,25 )26 request.read()27 response = self.handler(request)28 return (29 response.status_code,30 response.headers.raw,31 response.stream,32 response.ext,33 )3435 async def arequest(36 self,37 method: bytes,38 url: Tuple[bytes, bytes, Optional[int], bytes],39 headers: List[Tuple[bytes, bytes]] = None,40 stream: httpcore.AsyncByteStream = None,41 ext: dict = None,42 ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]:43 request = Request(44 method=method,45 url=url,46 headers=headers,47 stream=stream,48 )49 await request.aread()50 response = self.handler(request)51 return (52 response.status_code,53 response.headers.raw,54 response.stream,55 response.ext,56 )
modified:httpx/__init__.py+2 added
34 unmodified lines
35)36from ._models import URL, Cookies, Headers, QueryParams, Request, Response37from ._status_codes import StatusCode, codes38from ._transports.asgi import ASGITransport39from ._transports.mock import MockTransport40from ._transports.wsgi import WSGITransport4142__all__ = [43 "__description__",
21 unmodified lines
65 "HTTPStatusError",66 "InvalidURL",67 "Limits",68 "LocalProtocolError",69 "MockTransport",70 "NetworkError",71 "options",72 "patch",73 "PoolTimeout",
36 unmodified lines
modified:tests/client/test_async_client.py+5 added-6 removed
3 unmodified lines
4import httpcore5import pytest67import httpx8from tests.utils import MockTransport8910@pytest.mark.usefixtures("async_environment")11async def test_get(server):
233 unmodified lines
245246247@pytest.mark.usefixtures("async_environment")248async def test_client_closed_state_using_implicit_open():250 client = httpx.AsyncClient(transport=MockTransport(hello_world))249 client = httpx.AsyncClient(transport=httpx.MockTransport(hello_world))250251 assert not client.is_closed252 await client.get("http://example.com")253
6 unmodified lines
260261262@pytest.mark.usefixtures("async_environment")263async def test_client_closed_state_using_with_block():265 async with httpx.AsyncClient(transport=MockTransport(hello_world)) as client:264 async with httpx.AsyncClient(transport=httpx.MockTransport(hello_world)) as client:265 assert not client.is_closed266 await client.get("http://example.com")267268 assert client.is_closed
2 unmodified lines
271272273@pytest.mark.usefixtures("async_environment")274async def test_deleting_unclosed_async_client_causes_warning():276 client = httpx.AsyncClient(transport=MockTransport(hello_world))275 client = httpx.AsyncClient(transport=httpx.MockTransport(hello_world))276 await client.get("http://example.com")277 with pytest.warns(UserWarning):278 del client279
9 unmodified lines
289290291@pytest.mark.usefixtures("async_environment")292async def test_mounted_transport():294 transport = MockTransport(unmounted)295 mounts = {"custom://": MockTransport(mounted)}293 transport = httpx.MockTransport(unmounted)294 mounts = {"custom://": httpx.MockTransport(mounted)}295296 async with httpx.AsyncClient(transport=transport, mounts=mounts) as client:297 response = await client.get("https://www.example.com")298 assert response.status_code == 200
5 unmodified lines
modified:tests/client/test_auth.py+39 added-34 removed
11 unmodified lines
12import pytest1314import httpx15from httpx import URL, Auth, BasicAuth, DigestAuth, ProtocolError, Request, Response16from tests.utils import MockTransport1617from ..common import FIXTURES_DIR1819
133 unmodified lines
153 url = "https://example.org/"154 auth = ("tomchristie", "password123")155 app = App()156158 async with httpx.AsyncClient(transport=MockTransport(app)) as client:157 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:158 response = await client.get(url, auth=auth)159160 assert response.status_code == 200161 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}
7 unmodified lines
169 url = "https://example.org/"170 auth = ("tomchristie", "password123")171 app = App()172174 async with httpx.AsyncClient(transport=MockTransport(app), auth=auth) as client:173 async with httpx.AsyncClient(174 transport=httpx.MockTransport(app), auth=auth175 ) as client:176 async with client.stream("GET", url) as response:177 await response.aread()178179 assert response.status_code == 200
4 unmodified lines
184async def test_basic_auth_in_url() -> None:185 url = "https://tomchristie:password123@example.org/"186 app = App()187187 async with httpx.AsyncClient(transport=MockTransport(app)) as client:188 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:189 response = await client.get(url)190191 assert response.status_code == 200192 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}
4 unmodified lines
197 url = "https://example.org/"198 auth = ("tomchristie", "password123")199 app = App()200200 async with httpx.AsyncClient(transport=MockTransport(app), auth=auth) as client:201 async with httpx.AsyncClient(202 transport=httpx.MockTransport(app), auth=auth203 ) as client:204 response = await client.get(url)205206 assert response.status_code == 200207 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}
7 unmodified lines
215 def auth(request: Request) -> Request:216 request.headers["Authorization"] = "Token 123"217 return request218216 async with httpx.AsyncClient(transport=MockTransport(app)) as client:219 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:220 response = await client.get(url, auth=auth)221222 assert response.status_code == 200223 assert response.json() == {"auth": "Token 123"}
4 unmodified lines
228 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")229 url = "http://netrcexample.org"230 app = App()231229 async with httpx.AsyncClient(transport=MockTransport(app)) as client:232 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:233 response = await client.get(url)234235 assert response.status_code == 200236 assert response.json() == {
6 unmodified lines
243 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")244 url = "http://netrcexample.org"245 app = App()246244 async with httpx.AsyncClient(transport=MockTransport(app)) as client:247 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:248 response = await client.get(url, headers={"Authorization": "Override"})249250 assert response.status_code == 200251 assert response.json() == {"auth": "Override"}
5 unmodified lines
257 url = "http://netrcexample.org"258 app = App()259260 async with httpx.AsyncClient(258 transport=MockTransport(app), trust_env=False261 transport=httpx.MockTransport(app), trust_env=False262 ) as client:263 response = await client.get(url)264265 assert response.status_code == 200266 assert response.json() == {"auth": None}267268 async with httpx.AsyncClient(266 transport=MockTransport(app), trust_env=True269 transport=httpx.MockTransport(app), trust_env=True270 ) as client:271 response = await client.get(url)272273 assert response.status_code == 200
7 unmodified lines
281 url = "https://example.org/"282 auth = ("tomchristie", "password123")283 app = App()284282 async with httpx.AsyncClient(transport=MockTransport(app), auth=auth) as client:285 async with httpx.AsyncClient(286 transport=httpx.MockTransport(app), auth=auth287 ) as client:288 response = await client.get(url, auth=None)289290 assert response.status_code == 200291 assert response.json() == {"auth": None}
11 unmodified lines
303 url = "https://example.org/"304 auth = ("example-username", "example-password")305 app = App()306302 async with httpx.AsyncClient(transport=MockTransport(app)) as client:307 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:308 response = await client.get(url, auth=auth)309310 assert "'authorization': '[secure]'" in str(response.request.headers)311
1 unmodified line
313@pytest.mark.asyncio314async def test_auth_property() -> None:315 app = App()316312 async with httpx.AsyncClient(transport=MockTransport(app)) as client:317 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:318 assert client.auth is None319320 client.auth = ("tomchristie", "password123") # type: ignore321 assert isinstance(client.auth, BasicAuth)
9 unmodified lines
331 app = App()332333 with pytest.raises(TypeError):334 client = httpx.AsyncClient(330 transport=MockTransport(app),335 transport=httpx.MockTransport(app),336 auth="not a tuple, not a callable", # type: ignore337 )338334 async with httpx.AsyncClient(transport=MockTransport(app)) as client:339 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:340 with pytest.raises(TypeError):341 await client.get(auth="not a tuple, not a callable") # type: ignore342343 with pytest.raises(TypeError):
5 unmodified lines
349 url = "https://example.org/"350 auth = DigestAuth(username="tomchristie", password="password123")351 app = App()352348 async with httpx.AsyncClient(transport=MockTransport(app)) as client:353 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:354 response = await client.get(url, auth=auth)355356 assert response.status_code == 200357 assert response.json() == {"auth": None}
5 unmodified lines
363 auth = DigestAuth(username="tomchristie", password="password123")364 auth_header = "Token ..."365 app = App(auth_header=auth_header, status_code=401)366362 client = httpx.Client(transport=MockTransport(app))367 client = httpx.Client(transport=httpx.MockTransport(app))368 response = client.get(url, auth=auth)369370 assert response.status_code == 401371 assert response.json() == {"auth": None}
6 unmodified lines
378 auth = DigestAuth(username="tomchristie", password="password123")379 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'380 app = App(auth_header=auth_header, status_code=200)381377 async with httpx.AsyncClient(transport=MockTransport(app)) as client:382 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:383 response = await client.get(url, auth=auth)384385 assert response.status_code == 200386 assert response.json() == {"auth": None}
5 unmodified lines
392 url = "https://example.org/"393 auth = DigestAuth(username="tomchristie", password="password123")394 app = App(auth_header="", status_code=401)395391 async with httpx.AsyncClient(transport=MockTransport(app)) as client:396 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:397 response = await client.get(url, auth=auth)398399 assert response.status_code == 401400 assert response.json() == {"auth": None}
20 unmodified lines
421 url = "https://example.org/"422 auth = DigestAuth(username="tomchristie", password="password123")423 app = DigestApp(algorithm=algorithm)424420 async with httpx.AsyncClient(transport=MockTransport(app)) as client:425 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:426 response = await client.get(url, auth=auth)427428 assert response.status_code == 200429 assert len(response.history) == 1
22 unmodified lines
452 url = "https://example.org/"453 auth = DigestAuth(username="tomchristie", password="password123")454 app = DigestApp(qop="")455451 async with httpx.AsyncClient(transport=MockTransport(app)) as client:456 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:457 response = await client.get(url, auth=auth)458459 assert response.status_code == 200460 assert len(response.history) == 1
23 unmodified lines
484 url = "https://example.org/"485 auth = DigestAuth(username="tomchristie", password="password123")486 app = DigestApp(qop=qop)487483 async with httpx.AsyncClient(transport=MockTransport(app)) as client:488 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:489 response = await client.get(url, auth=auth)490491 assert response.status_code == 200492 assert len(response.history) == 1
4 unmodified lines
497 url = "https://example.org/"498 auth = DigestAuth(username="tomchristie", password="password123")499 app = DigestApp(qop="auth-int")500496 async with httpx.AsyncClient(transport=MockTransport(app)) as client:501 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:502 with pytest.raises(NotImplementedError):503 await client.get(url, auth=auth)504505
2 unmodified lines
508 url = "https://example.org/"509 auth = DigestAuth(username="tomchristie", password="password123")510 app = DigestApp(qop="not-auth")511507 async with httpx.AsyncClient(transport=MockTransport(app)) as client:512 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:513 with pytest.raises(ProtocolError):514 await client.get(url, auth=auth)515516
2 unmodified lines
519 url = "https://example.org/"520 auth = DigestAuth(username="tomchristie", password="password123")521 app = DigestApp(send_response_after_attempt=2)522518 async with httpx.AsyncClient(transport=MockTransport(app)) as client:523 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:524 response = await client.get(url, auth=auth)525526 assert response.status_code == 401527 assert len(response.history) == 1
13 unmodified lines
541 url = "https://example.org/"542 auth = DigestAuth(username="tomchristie", password="password123")543 app = App(auth_header=auth_header, status_code=401)544540 async with httpx.AsyncClient(transport=MockTransport(app)) as client:545 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:546 with pytest.raises(ProtocolError):547 await client.get(url, auth=auth)548549
10 unmodified lines
560 url = "https://example.org/"561 auth = DigestAuth(username="tomchristie", password="password123")562 app = App(auth_header=auth_header, status_code=401)563559 with httpx.Client(transport=MockTransport(app)) as client:564 with httpx.Client(transport=httpx.MockTransport(app)) as client:565 with pytest.raises(ProtocolError):566 client.get(url, auth=auth)567568
6 unmodified lines
575 url = "https://example.org/"576 auth = RepeatAuth(repeat=2)577 app = App(auth_header="abc")578574 async with httpx.AsyncClient(transport=MockTransport(app)) as client:579 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:580 response = await client.get(url, auth=auth)581582 assert response.status_code == 200583 assert response.json() == {"auth": "Repeat abc.abc"}
17 unmodified lines
601 url = "https://example.org/"602 auth = RepeatAuth(repeat=2)603 app = App(auth_header="abc")604600 with httpx.Client(transport=MockTransport(app)) as client:605 with httpx.Client(transport=httpx.MockTransport(app)) as client:606 response = client.get(url, auth=auth)607608 assert response.status_code == 200609 assert response.json() == {"auth": "Repeat abc.abc"}
17 unmodified lines
627628 async def streaming_body():629 yield b"Example request body" # pragma: nocover630626 async with httpx.AsyncClient(transport=MockTransport(app)) as client:631 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:632 with pytest.raises(httpx.StreamConsumed):633 await client.post(url, data=streaming_body(), auth=auth)634635
6 unmodified lines
642 url = "https://example.org/"643 auth = ResponseBodyAuth("xyz")644 app = App()645641 async with httpx.AsyncClient(transport=MockTransport(app)) as client:646 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:647 response = await client.get(url, auth=auth)648649 assert response.status_code == 200650 assert response.json() == {"auth": '{"auth": "xyz"}'}
7 unmodified lines
658 url = "https://example.org/"659 auth = ResponseBodyAuth("xyz")660 app = App()661657 with httpx.Client(transport=MockTransport(app)) as client:662 with httpx.Client(transport=httpx.MockTransport(app)) as client:663 response = client.get(url, auth=auth)664665 assert response.status_code == 200666 assert response.json() == {"auth": '{"auth": "xyz"}'}
9 unmodified lines
676 url = "https://example.org/"677 auth = SyncOrAsyncAuth()678 app = App()679675 async with httpx.AsyncClient(transport=MockTransport(app)) as client:680 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:681 response = await client.get(url, auth=auth)682683 assert response.status_code == 200684 assert response.json() == {"auth": "async-auth"}
6 unmodified lines
691 url = "https://example.org/"692 auth = SyncOrAsyncAuth()693 app = App()694690 with httpx.Client(transport=MockTransport(app)) as client:695 with httpx.Client(transport=httpx.MockTransport(app)) as client:696 response = client.get(url, auth=auth)697698 assert response.status_code == 200699 assert response.json() == {"auth": "sync-auth"}
modified:tests/client/test_client.py+8 added-7 removed
3 unmodified lines
4import httpcore5import pytest67import httpx8from tests.utils import MockTransport8910def test_get(server):11 url = server.url
278 unmodified lines
290 return httpx.Response(200, text="Hello, world!")291292293def test_client_closed_state_using_implicit_open():295 client = httpx.Client(transport=MockTransport(hello_world))294 client = httpx.Client(transport=httpx.MockTransport(hello_world))295296 assert not client.is_closed297 client.get("http://example.com")298
5 unmodified lines
304 client.get("http://example.com")305306307def test_client_closed_state_using_with_block():309 with httpx.Client(transport=MockTransport(hello_world)) as client:308 with httpx.Client(transport=httpx.MockTransport(hello_world)) as client:309 assert not client.is_closed310 client.get("http://example.com")311312 assert client.is_closed
15 unmodified lines
328 """329 url = "http://example.org/echo_headers"330 headers = {"Example-Header": "example-value"}331333 client = httpx.Client(transport=MockTransport(echo_raw_headers), headers=headers)332 client = httpx.Client(333 transport=httpx.MockTransport(echo_raw_headers), headers=headers334 )335 response = client.get(url)336337 assert response.status_code == 200338 assert response.json() == [
16 unmodified lines
355 return httpx.Response(200, json=data)356357358def test_mounted_transport():358 transport = MockTransport(unmounted)359 mounts = {"custom://": MockTransport(mounted)}359 transport = httpx.MockTransport(unmounted)360 mounts = {"custom://": httpx.MockTransport(mounted)}361362 client = httpx.Client(transport=transport, mounts=mounts)363364 response = client.get("https://www.example.com")
5 unmodified lines
370 assert response.json() == {"app": "mounted"}371372373def test_all_mounted_transport():373 mounts = {"all://": MockTransport(mounted)}374 mounts = {"all://": httpx.MockTransport(mounted)}375376 client = httpx.Client(mounts=mounts)377378 response = client.get("https://www.example.com")
2 unmodified lines
modified:tests/client/test_cookies.py+6 added-7 removed
1from http.cookiejar import Cookie, CookieJar23import httpx4from tests.utils import MockTransport456def get_and_set_cookies(request: httpx.Request) -> httpx.Response:7 if request.url.path == "/echo_cookies":
11 unmodified lines
19 """20 url = "http://example.org/echo_cookies"21 cookies = {"example-name": "example-value"}2224 client = httpx.Client(transport=MockTransport(get_and_set_cookies))23 client = httpx.Client(transport=httpx.MockTransport(get_and_set_cookies))24 response = client.get(url, cookies=cookies)2526 assert response.status_code == 20027 assert response.json() == {"cookies": "example-name=example-value"}
26 unmodified lines
54 rfc2109=False,55 )56 cookies.set_cookie(cookie)5759 client = httpx.Client(transport=MockTransport(get_and_set_cookies))58 client = httpx.Client(transport=httpx.MockTransport(get_and_set_cookies))59 response = client.get(url, cookies=cookies)6061 assert response.status_code == 20062 assert response.json() == {"cookies": "example-name=example-value"}
26 unmodified lines
89 rfc2109=False,90 )91 cookies.set_cookie(cookie)9294 client = httpx.Client(transport=MockTransport(get_and_set_cookies))93 client = httpx.Client(transport=httpx.MockTransport(get_and_set_cookies))94 client.cookies = cookies # type: ignore95 response = client.get(url)9697 assert response.status_code == 200
8 unmodified lines
106 url = "http://example.org/echo_cookies"107 cookies = httpx.Cookies()108 cookies["example-name"] = "example-value"109111 client = httpx.Client(transport=MockTransport(get_and_set_cookies))110 client = httpx.Client(transport=httpx.MockTransport(get_and_set_cookies))111 response = client.get(url, cookies=cookies)112113 assert response.status_code == 200114 assert response.json() == {"cookies": "example-name=example-value"}
1 unmodified line
116117def test_get_cookie() -> None:118 url = "http://example.org/set_cookie"119121 client = httpx.Client(transport=MockTransport(get_and_set_cookies))120 client = httpx.Client(transport=httpx.MockTransport(get_and_set_cookies))121 response = client.get(url)122123 assert response.status_code == 200124 assert response.cookies["example-name"] == "example-value"
3 unmodified lines
128def test_cookie_persistence() -> None:129 """130 Ensure that Client instances persist cookies between requests.131 """133 client = httpx.Client(transport=MockTransport(get_and_set_cookies))132 client = httpx.Client(transport=httpx.MockTransport(get_and_set_cookies))133134 response = client.get("http://example.org/echo_cookies")135 assert response.status_code == 200136 assert response.json() == {"cookies": None}
9 unmodified lines
modified:tests/client/test_event_hooks.py+12 added-7 removed
1import pytest23import httpx4from tests.utils import MockTransport456def app(request: httpx.Request) -> httpx.Response:7 if request.url.path == "/redirect":
15 unmodified lines
23 events.append({"event": "response", "headers": dict(response.headers)})2425 event_hooks = {"request": [on_request], "response": [on_response]}2628 with httpx.Client(event_hooks=event_hooks, transport=MockTransport(app)) as http:27 with httpx.Client(28 event_hooks=event_hooks, transport=httpx.MockTransport(app)29 ) as http:30 http.get("http://127.0.0.1:8000/", auth=("username", "password"))3132 assert events == [33 {
19 unmodified lines
53 response.raise_for_status()5455 event_hooks = {"response": [raise_on_4xx_5xx]}5656 with httpx.Client(event_hooks=event_hooks, transport=MockTransport(app)) as http:57 with httpx.Client(58 event_hooks=event_hooks, transport=httpx.MockTransport(app)59 ) as http:60 try:61 http.get("http://127.0.0.1:8000/status/400")62 except httpx.HTTPStatusError as exc:63 assert exc.response.is_closed
11 unmodified lines
7576 event_hooks = {"request": [on_request], "response": [on_response]}7778 async with httpx.AsyncClient(76 event_hooks=event_hooks, transport=MockTransport(app)79 event_hooks=event_hooks, transport=httpx.MockTransport(app)80 ) as http:81 await http.get("http://127.0.0.1:8000/", auth=("username", "password"))8283 assert events == [
22 unmodified lines
106107 event_hooks = {"response": [raise_on_4xx_5xx]}108109 async with httpx.AsyncClient(107 event_hooks=event_hooks, transport=MockTransport(app)110 event_hooks=event_hooks, transport=httpx.MockTransport(app)111 ) as http:112 try:113 await http.get("http://127.0.0.1:8000/status/400")114 except httpx.HTTPStatusError as exc:
14 unmodified lines
129 events.append({"event": "response", "headers": dict(response.headers)})130131 event_hooks = {"request": [on_request], "response": [on_response]}132130 with httpx.Client(event_hooks=event_hooks, transport=MockTransport(app)) as http:133 with httpx.Client(134 event_hooks=event_hooks, transport=httpx.MockTransport(app)135 ) as http:136 http.get("http://127.0.0.1:8000/redirect", auth=("username", "password"))137138 assert events == [139 {
30 unmodified lines
170171 event_hooks = {"request": [on_request], "response": [on_response]}172173 async with httpx.AsyncClient(169 event_hooks=event_hooks, transport=MockTransport(app)174 event_hooks=event_hooks, transport=httpx.MockTransport(app)175 ) as http:176 await http.get("http://127.0.0.1:8000/redirect", auth=("username", "password"))177178 assert events == [
16 unmodified lines
modified:tests/client/test_headers.py+11 added-8 removed
1 unmodified line
23import pytest45import httpx6from tests.utils import MockTransport678def echo_headers(request: httpx.Request) -> httpx.Response:9 data = {"headers": dict(request.headers)}
6 unmodified lines
16 """17 url = "http://example.org/echo_headers"18 headers = {"Example-Header": "example-value"}1921 client = httpx.Client(transport=MockTransport(echo_headers), headers=headers)20 client = httpx.Client(transport=httpx.MockTransport(echo_headers), headers=headers)21 response = client.get(url)2223 assert response.status_code == 20024 assert response.json() == {
11 unmodified lines
36def test_header_merge():37 url = "http://example.org/echo_headers"38 client_headers = {"User-Agent": "python-myclient/0.2.1"}39 request_headers = {"X-Auth-Token": "FooBarBazToken"}41 client = httpx.Client(transport=MockTransport(echo_headers), headers=client_headers)40 client = httpx.Client(41 transport=httpx.MockTransport(echo_headers), headers=client_headers42 )43 response = client.get(url, headers=request_headers)4445 assert response.status_code == 20046 assert response.json() == {
11 unmodified lines
58def test_header_merge_conflicting_headers():59 url = "http://example.org/echo_headers"60 client_headers = {"X-Auth-Token": "FooBar"}61 request_headers = {"X-Auth-Token": "BazToken"}61 client = httpx.Client(transport=MockTransport(echo_headers), headers=client_headers)62 client = httpx.Client(63 transport=httpx.MockTransport(echo_headers), headers=client_headers64 )65 response = client.get(url, headers=request_headers)6667 assert response.status_code == 20068 assert response.json() == {
9 unmodified lines
787980def test_header_update():81 url = "http://example.org/echo_headers"79 client = httpx.Client(transport=MockTransport(echo_headers))82 client = httpx.Client(transport=httpx.MockTransport(echo_headers))83 first_response = client.get(url)84 client.headers.update(85 {"User-Agent": "python-myclient/0.2.1", "Another-Header": "AThing"}86 )
28 unmodified lines
115 Remove a default header from the Client.116 """117 url = "http://example.org/echo_headers"118116 client = httpx.Client(transport=MockTransport(echo_headers))119 client = httpx.Client(transport=httpx.MockTransport(echo_headers))120 del client.headers["User-Agent"]121122 response = client.get(url)123
21 unmodified lines
145 be present.146 """147 url = "http://username:password@example.org:80/echo_headers"148146 client = httpx.Client(transport=MockTransport(echo_headers))149 client = httpx.Client(transport=httpx.MockTransport(echo_headers))150 response = client.get(url)151152 assert response.status_code == 200153 assert response.json() == {
14 unmodified lines
168 the Host header.169 """170 url = "http://username:password@example.org:123/echo_headers"171169 client = httpx.Client(transport=MockTransport(echo_headers))172 client = httpx.Client(transport=httpx.MockTransport(echo_headers))173 response = client.get(url)174175 assert response.status_code == 200176 assert response.json() == {
14 unmodified lines
modified:tests/client/test_queryparams.py+1 added-2 removed
1import httpx2from tests.utils import MockTransport234def hello_world(request: httpx.Request) -> httpx.Response:5 return httpx.Response(200, text="Hello, world")
20 unmodified lines
26 url = "http://example.org/echo_queryparams"27 client_queryparams = "first=str"28 request_queryparams = {"second": "dict"}29 client = httpx.Client(31 transport=MockTransport(hello_world), params=client_queryparams30 transport=httpx.MockTransport(hello_world), params=client_queryparams31 )32 response = client.get(url, params=request_queryparams)3334 assert response.status_code == 200
1 unmodified line
modified:tests/client/test_redirects.py+25 added-26 removed
1import httpcore2import pytest34import httpx5from tests.utils import MockTransport567def redirects(request: httpx.Request) -> httpx.Response:8 if request.url.scheme not in ("http", "https"):
105 unmodified lines
114 return httpx.Response(200, html="<html><body>Hello, world!</body></html>")115116117def test_redirect_301():119 client = httpx.Client(transport=MockTransport(redirects))118 client = httpx.Client(transport=httpx.MockTransport(redirects))119 response = client.post("https://example.org/redirect_301")120 assert response.status_code == httpx.codes.OK121 assert response.url == "https://example.org/"122 assert len(response.history) == 1123124125def test_redirect_302():127 client = httpx.Client(transport=MockTransport(redirects))126 client = httpx.Client(transport=httpx.MockTransport(redirects))127 response = client.post("https://example.org/redirect_302")128 assert response.status_code == httpx.codes.OK129 assert response.url == "https://example.org/"130 assert len(response.history) == 1131132133def test_redirect_303():135 client = httpx.Client(transport=MockTransport(redirects))134 client = httpx.Client(transport=httpx.MockTransport(redirects))135 response = client.get("https://example.org/redirect_303")136 assert response.status_code == httpx.codes.OK137 assert response.url == "https://example.org/"138 assert len(response.history) == 1139140141def test_next_request():143 client = httpx.Client(transport=MockTransport(redirects))142 client = httpx.Client(transport=httpx.MockTransport(redirects))143 request = client.build_request("POST", "https://example.org/redirect_303")144 response = client.send(request, allow_redirects=False)145 assert response.status_code == httpx.codes.SEE_OTHER146 assert response.url == "https://example.org/redirect_303"
6 unmodified lines
153154155@pytest.mark.usefixtures("async_environment")156async def test_async_next_request():158 async with httpx.AsyncClient(transport=MockTransport(redirects)) as client:157 async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client:158 request = client.build_request("POST", "https://example.org/redirect_303")159 response = await client.send(request, allow_redirects=False)160 assert response.status_code == httpx.codes.SEE_OTHER161 assert response.url == "https://example.org/redirect_303"
8 unmodified lines
170def test_head_redirect():171 """172 Contrary to Requests, redirects remain enabled by default for HEAD requests.173 """175 client = httpx.Client(transport=MockTransport(redirects))174 client = httpx.Client(transport=httpx.MockTransport(redirects))175 response = client.head("https://example.org/redirect_302")176 assert response.status_code == httpx.codes.OK177 assert response.url == "https://example.org/"178 assert response.request.method == "HEAD"
1 unmodified line
180 assert response.text == ""181182183def test_relative_redirect():185 client = httpx.Client(transport=MockTransport(redirects))184 client = httpx.Client(transport=httpx.MockTransport(redirects))185 response = client.get("https://example.org/relative_redirect")186 assert response.status_code == httpx.codes.OK187 assert response.url == "https://example.org/"188 assert len(response.history) == 1189190191def test_malformed_redirect():192 # https://github.com/encode/httpx/issues/771194 client = httpx.Client(transport=MockTransport(redirects))193 client = httpx.Client(transport=httpx.MockTransport(redirects))194 response = client.get("http://example.org/malformed_redirect")195 assert response.status_code == httpx.codes.OK196 assert response.url == "https://example.org:443/"197 assert len(response.history) == 1198199200def test_invalid_redirect():202 client = httpx.Client(transport=MockTransport(redirects))201 client = httpx.Client(transport=httpx.MockTransport(redirects))202 with pytest.raises(httpx.RemoteProtocolError):203 client.get("http://example.org/invalid_redirect")204205206def test_no_scheme_redirect():208 client = httpx.Client(transport=MockTransport(redirects))207 client = httpx.Client(transport=httpx.MockTransport(redirects))208 response = client.get("https://example.org/no_scheme_redirect")209 assert response.status_code == httpx.codes.OK210 assert response.url == "https://example.org/"211 assert len(response.history) == 1212213214def test_fragment_redirect():216 client = httpx.Client(transport=MockTransport(redirects))215 client = httpx.Client(transport=httpx.MockTransport(redirects))216 response = client.get("https://example.org/relative_redirect#fragment")217 assert response.status_code == httpx.codes.OK218 assert response.url == "https://example.org/#fragment"219 assert len(response.history) == 1220221222def test_multiple_redirects():224 client = httpx.Client(transport=MockTransport(redirects))223 client = httpx.Client(transport=httpx.MockTransport(redirects))224 response = client.get("https://example.org/multiple_redirects?count=20")225 assert response.status_code == httpx.codes.OK226 assert response.url == "https://example.org/multiple_redirects"227 assert len(response.history) == 20
4 unmodified lines
232233234@pytest.mark.usefixtures("async_environment")235async def test_async_too_many_redirects():237 async with httpx.AsyncClient(transport=MockTransport(redirects)) as client:236 async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client:237 with pytest.raises(httpx.TooManyRedirects):238 await client.get("https://example.org/multiple_redirects?count=21")239240241def test_sync_too_many_redirects():243 client = httpx.Client(transport=MockTransport(redirects))242 client = httpx.Client(transport=httpx.MockTransport(redirects))243 with pytest.raises(httpx.TooManyRedirects):244 client.get("https://example.org/multiple_redirects?count=21")245246247def test_redirect_loop():249 client = httpx.Client(transport=MockTransport(redirects))248 client = httpx.Client(transport=httpx.MockTransport(redirects))249 with pytest.raises(httpx.TooManyRedirects):250 client.get("https://example.org/redirect_loop")251252253def test_cross_domain_redirect_with_auth_header():255 client = httpx.Client(transport=MockTransport(redirects))254 client = httpx.Client(transport=httpx.MockTransport(redirects))255 url = "https://example.com/cross_domain"256 headers = {"Authorization": "abc"}257 response = client.get(url, headers=headers)258 assert response.url == "https://example.org/cross_domain_target"259 assert "authorization" not in response.json()["headers"]260261262def test_cross_domain_redirect_with_auth():264 client = httpx.Client(transport=MockTransport(redirects))263 client = httpx.Client(transport=httpx.MockTransport(redirects))264 url = "https://example.com/cross_domain"265 response = client.get(url, auth=("user", "pass"))266 assert response.url == "https://example.org/cross_domain_target"267 assert "authorization" not in response.json()["headers"]268269270def test_same_domain_redirect():272 client = httpx.Client(transport=MockTransport(redirects))271 client = httpx.Client(transport=httpx.MockTransport(redirects))272 url = "https://example.org/cross_domain"273 headers = {"Authorization": "abc"}274 response = client.get(url, headers=headers)275 assert response.url == "https://example.org/cross_domain_target"
3 unmodified lines
279def test_body_redirect():280 """281 A 308 redirect should preserve the request body.282 """284 client = httpx.Client(transport=MockTransport(redirects))283 client = httpx.Client(transport=httpx.MockTransport(redirects))284 url = "https://example.org/redirect_body"285 content = b"Example request body"286 response = client.post(url, content=content)287 assert response.url == "https://example.org/redirect_body_target"
4 unmodified lines
292def test_no_body_redirect():293 """294 A 303 redirect should remove the request body.295 """297 client = httpx.Client(transport=MockTransport(redirects))296 client = httpx.Client(transport=httpx.MockTransport(redirects))297 url = "https://example.org/redirect_no_body"298 content = b"Example request body"299 response = client.post(url, content=content)300 assert response.url == "https://example.org/redirect_body_target"
1 unmodified line
302 assert "content-length" not in response.json()["headers"]303304305def test_can_stream_if_no_redirect():307 client = httpx.Client(transport=MockTransport(redirects))306 client = httpx.Client(transport=httpx.MockTransport(redirects))307 url = "https://example.org/redirect_301"308 with client.stream("GET", url, allow_redirects=False) as response:309 assert not response.is_closed310 assert response.status_code == httpx.codes.MOVED_PERMANENTLY311 assert response.headers["location"] == "https://example.org/"312313314def test_cannot_redirect_streaming_body():316 client = httpx.Client(transport=MockTransport(redirects))315 client = httpx.Client(transport=httpx.MockTransport(redirects))316 url = "https://example.org/redirect_body"317318 def streaming_body():319 yield b"Example request body" # pragma: nocover
2 unmodified lines
322 client.post(url, content=streaming_body())323324325def test_cross_subdomain_redirect():327 client = httpx.Client(transport=MockTransport(redirects))326 client = httpx.Client(transport=httpx.MockTransport(redirects))327 url = "https://example.com/cross_subdomain"328 response = client.get(url)329 assert response.url == "https://www.example.org/cross_subdomain"330
31 unmodified lines
362 return httpx.Response(status_code, headers=headers)363364365def test_redirect_cookie_behavior():367 client = httpx.Client(transport=MockTransport(cookie_sessions))366 client = httpx.Client(transport=httpx.MockTransport(cookie_sessions))367368 # The client is not logged in.369 response = client.get("https://example.com/")370 assert response.url == "https://example.com/"
20 unmodified lines
391 assert response.text == "Not logged in"392393394def test_redirect_custom_scheme():396 client = httpx.Client(transport=MockTransport(redirects))395 client = httpx.Client(transport=httpx.MockTransport(redirects))396 with pytest.raises(httpx.UnsupportedProtocol) as e:397 client.post("https://example.org/redirect_custom_scheme")398 assert str(e.value) == "Scheme 'market' not supported."
modified:tests/test_multipart.py+4 added-5 removed
7 unmodified lines
89import httpx10from httpx._content import encode_request11from httpx._utils import format_form_param12from tests.utils import MockTransport121314def echo_request_content(request: httpx.Request) -> httpx.Response:15 return httpx.Response(200, content=request.content)161718@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))19def test_multipart(value, output):21 client = httpx.Client(transport=MockTransport(echo_request_content))20 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))2122 # Test with a single-value 'data' argument, and a plain file 'files' argument.23 data = {"text": value}24 files = {"file": io.BytesIO(b"<file content>")}
17 unmodified lines
424344@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))45def test_multipart_invalid_key(key):47 client = httpx.Client(transport=MockTransport(echo_request_content))46 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))4748 data = {key: "abc"}49 files = {"file": io.BytesIO(b"<file content>")}50 with pytest.raises(TypeError) as e:
7 unmodified lines
585960@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))61def test_multipart_invalid_value(value):63 client = httpx.Client(transport=MockTransport(echo_request_content))62 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))6364 data = {"text": value}65 files = {"file": io.BytesIO(b"<file content>")}66 with pytest.raises(TypeError) as e:
1 unmodified line
68 assert "Invalid type for value" in str(e.value)697071def test_multipart_file_tuple():73 client = httpx.Client(transport=MockTransport(echo_request_content))72 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))7374 # Test with a list of values 'data' argument,75 # and a tuple style 'files' argument.76 data = {"text": ["abc"]}
191 unmodified lines
modified:tests/utils.py-55 removed
1import contextlib2import logging3import os4from typing import Callable, List, Optional, Tuple46import httpcore78import httpx5from httpx import _utils678@contextlib.contextmanager
8 unmodified lines
17 yield18 finally:19 # Reset the logger so we don't have verbose output in all unit tests20 logging.getLogger("httpx").handlers = []252627class MockTransport(httpcore.SyncHTTPTransport, httpcore.AsyncHTTPTransport):28 def __init__(self, handler: Callable) -> None:29 self.handler = handler3031 def request(32 self,33 method: bytes,34 url: Tuple[bytes, bytes, Optional[int], bytes],35 headers: List[Tuple[bytes, bytes]] = None,36 stream: httpcore.SyncByteStream = None,37 ext: dict = None,38 ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.SyncByteStream, dict]:39 request = httpx.Request(40 method=method,41 url=url,42 headers=headers,43 stream=stream,44 )45 request.read()46 response = self.handler(request)47 return (48 response.status_code,49 response.headers.raw,50 response.stream,51 response.ext,52 )5354 async def arequest(55 self,56 method: bytes,57 url: Tuple[bytes, bytes, Optional[int], bytes],58 headers: List[Tuple[bytes, bytes]] = None,59 stream: httpcore.AsyncByteStream = None,60 ext: dict = None,61 ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]:62 request = httpx.Request(63 method=method,64 url=url,65 headers=headers,66 stream=stream,67 )68 await request.aread()69 response = self.handler(request)70 return (71 response.status_code,72 response.headers.raw,73 response.stream,74 response.ext,75 )