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
Provenance
- Commit
9c7c2ac- Tree
f55dab8- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
3bf1863
13 files changed+198 added−158 removed
modified:docs/advanced.md+29 added-1 removed
1060 unmodified lines1061 >>> response.json()1062 {"text": "Hello, world!"}1063 ```1064 1065+### Mock transports1066+1067+During testing it can often be useful to be able to mock out a transport,1068+and return pre-determined responses, rather than making actual network requests.1069+1070+The `httpx.MockTransport` class accepts a handler function, which can be used1071+to map requests onto pre-determined responses:1072+1073+```python1074+def handler(request):1075+ return httpx.Response(200, json={"text": "Hello, world!"})1076+1077+1078+# Switch to a mock transport, if the TESTING environment variable is set.1079+if os.environ['TESTING'].upper() == "TRUE":1080+ transport = httpx.MockTransport(handler)1081+else:1082+ transport = httpx.HTTPTransport()1083+1084+client = httpx.Client(transport=transport)1085+```1086+1087+For more advanced use-cases you might want to take a look at either [the third-party1088+mocking library, RESPX](https://lundberg.github.io/respx/), or the [pytest-httpx library](https://github.com/Colin-b/pytest_httpx).1089+1090 ### Mounting transports1091 1092 You can also mount transports against given schemes or domains, to control1093 which transport an outgoing request should be routed via, with [the same style31 unmodified lines1125 1126 ```python1127 # All requests to "example.org" should be mocked out.1128 # Other requests occur as usual.1129+def handler(request):1130+ return httpx.Response(200, json={"text": "Hello, World!"})1131+1104-mounts = {"all://example.org": MockTransport()}1132+mounts = {"all://example.org": httpx.MockTransport(handler)}1133 client = httpx.Client(mounts=mounts)1134 ```1135 1136 Adding support for custom schemes:6 unmodified linesadded:httpx/_transports/mock.py+56 added
1+from typing import Callable, List, Optional, Tuple2+3+import httpcore4+5+from .._models import Request6+7+8+class MockTransport(httpcore.SyncHTTPTransport, httpcore.AsyncHTTPTransport):9+ def __init__(self, handler: Callable) -> None:10+ self.handler = handler11+12+ 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+ )34+35+ 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 lines35 )36 from ._models import URL, Cookies, Headers, QueryParams, Request, Response37 from ._status_codes import StatusCode, codes38 from ._transports.asgi import ASGITransport39+from ._transports.mock import MockTransport40 from ._transports.wsgi import WSGITransport41 42 __all__ = [43 "__description__",21 unmodified lines65 "HTTPStatusError",66 "InvalidURL",67 "Limits",68 "LocalProtocolError",69+ "MockTransport",70 "NetworkError",71 "options",72 "patch",73 "PoolTimeout",36 unmodified linesmodified:tests/client/test_async_client.py+5 added-6 removed
3 unmodified lines4 import httpcore5 import pytest6 7 import httpx8-from tests.utils import MockTransport8 9 10 @pytest.mark.usefixtures("async_environment")11 async def test_get(server):233 unmodified lines245 246 247 @pytest.mark.usefixtures("async_environment")248 async 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))250 251 assert not client.is_closed252 await client.get("http://example.com")253 6 unmodified lines260 261 262 @pytest.mark.usefixtures("async_environment")263 async 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")267 268 assert client.is_closed2 unmodified lines271 272 273 @pytest.mark.usefixtures("async_environment")274 async 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 lines289 290 291 @pytest.mark.usefixtures("async_environment")292 async def test_mounted_transport():294- transport = MockTransport(unmounted)295- mounts = {"custom://": MockTransport(mounted)}293+ transport = httpx.MockTransport(unmounted)294+ mounts = {"custom://": httpx.MockTransport(mounted)}295 296 async with httpx.AsyncClient(transport=transport, mounts=mounts) as client:297 response = await client.get("https://www.example.com")298 assert response.status_code == 2005 unmodified linesmodified:tests/client/test_auth.py+39 added-34 removed
11 unmodified lines12 import pytest13 14 import httpx15 from httpx import URL, Auth, BasicAuth, DigestAuth, ProtocolError, Request, Response16-from tests.utils import MockTransport16 17 from ..common import FIXTURES_DIR18 19 133 unmodified lines153 url = "https://example.org/"154 auth = ("tomchristie", "password123")155 app = App()156 158- 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)159 160 assert response.status_code == 200161 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}7 unmodified lines169 url = "https://example.org/"170 auth = ("tomchristie", "password123")171 app = App()172 174- 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()178 179 assert response.status_code == 2004 unmodified lines184 async def test_basic_auth_in_url() -> None:185 url = "https://tomchristie:password123@example.org/"186 app = App()187 187- 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)190 191 assert response.status_code == 200192 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}4 unmodified lines197 url = "https://example.org/"198 auth = ("tomchristie", "password123")199 app = App()200 200- 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)205 206 assert response.status_code == 200207 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}7 unmodified lines215 def auth(request: Request) -> Request:216 request.headers["Authorization"] = "Token 123"217 return request218 216- 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)221 222 assert response.status_code == 200223 assert response.json() == {"auth": "Token 123"}4 unmodified lines228 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")229 url = "http://netrcexample.org"230 app = App()231 229- 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)234 235 assert response.status_code == 200236 assert response.json() == {6 unmodified lines243 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")244 url = "http://netrcexample.org"245 app = App()246 244- 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"})249 250 assert response.status_code == 200251 assert response.json() == {"auth": "Override"}5 unmodified lines257 url = "http://netrcexample.org"258 app = App()259 260 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)264 265 assert response.status_code == 200266 assert response.json() == {"auth": None}267 268 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)272 273 assert response.status_code == 2007 unmodified lines281 url = "https://example.org/"282 auth = ("tomchristie", "password123")283 app = App()284 282- 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)289 290 assert response.status_code == 200291 assert response.json() == {"auth": None}11 unmodified lines303 url = "https://example.org/"304 auth = ("example-username", "example-password")305 app = App()306 302- 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)309 310 assert "'authorization': '[secure]'" in str(response.request.headers)311 1 unmodified line313 @pytest.mark.asyncio314 async def test_auth_property() -> None:315 app = App()316 312- 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 None319 320 client.auth = ("tomchristie", "password123") # type: ignore321 assert isinstance(client.auth, BasicAuth)9 unmodified lines331 app = App()332 333 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 )338 334- 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: ignore342 343 with pytest.raises(TypeError):5 unmodified lines349 url = "https://example.org/"350 auth = DigestAuth(username="tomchristie", password="password123")351 app = App()352 348- 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)355 356 assert response.status_code == 200357 assert response.json() == {"auth": None}5 unmodified lines363 auth = DigestAuth(username="tomchristie", password="password123")364 auth_header = "Token ..."365 app = App(auth_header=auth_header, status_code=401)366 362- client = httpx.Client(transport=MockTransport(app))367+ client = httpx.Client(transport=httpx.MockTransport(app))368 response = client.get(url, auth=auth)369 370 assert response.status_code == 401371 assert response.json() == {"auth": None}6 unmodified lines378 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)381 377- 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)384 385 assert response.status_code == 200386 assert response.json() == {"auth": None}5 unmodified lines392 url = "https://example.org/"393 auth = DigestAuth(username="tomchristie", password="password123")394 app = App(auth_header="", status_code=401)395 391- 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)398 399 assert response.status_code == 401400 assert response.json() == {"auth": None}20 unmodified lines421 url = "https://example.org/"422 auth = DigestAuth(username="tomchristie", password="password123")423 app = DigestApp(algorithm=algorithm)424 420- 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)427 428 assert response.status_code == 200429 assert len(response.history) == 122 unmodified lines452 url = "https://example.org/"453 auth = DigestAuth(username="tomchristie", password="password123")454 app = DigestApp(qop="")455 451- 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)458 459 assert response.status_code == 200460 assert len(response.history) == 123 unmodified lines484 url = "https://example.org/"485 auth = DigestAuth(username="tomchristie", password="password123")486 app = DigestApp(qop=qop)487 483- 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)490 491 assert response.status_code == 200492 assert len(response.history) == 14 unmodified lines497 url = "https://example.org/"498 auth = DigestAuth(username="tomchristie", password="password123")499 app = DigestApp(qop="auth-int")500 496- 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)504 505 2 unmodified lines508 url = "https://example.org/"509 auth = DigestAuth(username="tomchristie", password="password123")510 app = DigestApp(qop="not-auth")511 507- 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)515 516 2 unmodified lines519 url = "https://example.org/"520 auth = DigestAuth(username="tomchristie", password="password123")521 app = DigestApp(send_response_after_attempt=2)522 518- 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)525 526 assert response.status_code == 401527 assert len(response.history) == 113 unmodified lines541 url = "https://example.org/"542 auth = DigestAuth(username="tomchristie", password="password123")543 app = App(auth_header=auth_header, status_code=401)544 540- 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)548 549 10 unmodified lines560 url = "https://example.org/"561 auth = DigestAuth(username="tomchristie", password="password123")562 app = App(auth_header=auth_header, status_code=401)563 559- 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)567 568 6 unmodified lines575 url = "https://example.org/"576 auth = RepeatAuth(repeat=2)577 app = App(auth_header="abc")578 574- 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)581 582 assert response.status_code == 200583 assert response.json() == {"auth": "Repeat abc.abc"}17 unmodified lines601 url = "https://example.org/"602 auth = RepeatAuth(repeat=2)603 app = App(auth_header="abc")604 600- 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)607 608 assert response.status_code == 200609 assert response.json() == {"auth": "Repeat abc.abc"}17 unmodified lines627 628 async def streaming_body():629 yield b"Example request body" # pragma: nocover630 626- 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)634 635 6 unmodified lines642 url = "https://example.org/"643 auth = ResponseBodyAuth("xyz")644 app = App()645 641- 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)648 649 assert response.status_code == 200650 assert response.json() == {"auth": '{"auth": "xyz"}'}7 unmodified lines658 url = "https://example.org/"659 auth = ResponseBodyAuth("xyz")660 app = App()661 657- 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)664 665 assert response.status_code == 200666 assert response.json() == {"auth": '{"auth": "xyz"}'}9 unmodified lines676 url = "https://example.org/"677 auth = SyncOrAsyncAuth()678 app = App()679 675- 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)682 683 assert response.status_code == 200684 assert response.json() == {"auth": "async-auth"}6 unmodified lines691 url = "https://example.org/"692 auth = SyncOrAsyncAuth()693 app = App()694 690- 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)697 698 assert response.status_code == 200699 assert response.json() == {"auth": "sync-auth"}modified:tests/client/test_client.py+8 added-7 removed
3 unmodified lines4 import httpcore5 import pytest6 7 import httpx8-from tests.utils import MockTransport8 9 10 def test_get(server):11 url = server.url278 unmodified lines290 return httpx.Response(200, text="Hello, world!")291 292 293 def test_client_closed_state_using_implicit_open():295- client = httpx.Client(transport=MockTransport(hello_world))294+ client = httpx.Client(transport=httpx.MockTransport(hello_world))295 296 assert not client.is_closed297 client.get("http://example.com")298 5 unmodified lines304 client.get("http://example.com")305 306 307 def 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")311 312 assert client.is_closed15 unmodified lines328 """329 url = "http://example.org/echo_headers"330 headers = {"Example-Header": "example-value"}331 333- 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)336 337 assert response.status_code == 200338 assert response.json() == [16 unmodified lines355 return httpx.Response(200, json=data)356 357 358 def test_mounted_transport():358- transport = MockTransport(unmounted)359- mounts = {"custom://": MockTransport(mounted)}359+ transport = httpx.MockTransport(unmounted)360+ mounts = {"custom://": httpx.MockTransport(mounted)}361 362 client = httpx.Client(transport=transport, mounts=mounts)363 364 response = client.get("https://www.example.com")5 unmodified lines370 assert response.json() == {"app": "mounted"}371 372 373 def test_all_mounted_transport():373- mounts = {"all://": MockTransport(mounted)}374+ mounts = {"all://": httpx.MockTransport(mounted)}375 376 client = httpx.Client(mounts=mounts)377 378 response = client.get("https://www.example.com")2 unmodified linesmodified:tests/client/test_cookies.py+6 added-7 removed
1 from http.cookiejar import Cookie, CookieJar2 3 import httpx4-from tests.utils import MockTransport4 5 6 def get_and_set_cookies(request: httpx.Request) -> httpx.Response:7 if request.url.path == "/echo_cookies":11 unmodified lines19 """20 url = "http://example.org/echo_cookies"21 cookies = {"example-name": "example-value"}22 24- 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)25 26 assert response.status_code == 20027 assert response.json() == {"cookies": "example-name=example-value"}26 unmodified lines54 rfc2109=False,55 )56 cookies.set_cookie(cookie)57 59- 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)60 61 assert response.status_code == 20062 assert response.json() == {"cookies": "example-name=example-value"}26 unmodified lines89 rfc2109=False,90 )91 cookies.set_cookie(cookie)92 94- 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)96 97 assert response.status_code == 2008 unmodified lines106 url = "http://example.org/echo_cookies"107 cookies = httpx.Cookies()108 cookies["example-name"] = "example-value"109 111- 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)112 113 assert response.status_code == 200114 assert response.json() == {"cookies": "example-name=example-value"}1 unmodified line116 117 def test_get_cookie() -> None:118 url = "http://example.org/set_cookie"119 121- 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)122 123 assert response.status_code == 200124 assert response.cookies["example-name"] == "example-value"3 unmodified lines128 def 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))133 134 response = client.get("http://example.org/echo_cookies")135 assert response.status_code == 200136 assert response.json() == {"cookies": None}9 unmodified linesmodified:tests/client/test_event_hooks.py+12 added-7 removed
1 import pytest2 3 import httpx4-from tests.utils import MockTransport4 5 6 def app(request: httpx.Request) -> httpx.Response:7 if request.url.path == "/redirect":15 unmodified lines23 events.append({"event": "response", "headers": dict(response.headers)})24 25 event_hooks = {"request": [on_request], "response": [on_response]}26 28- 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"))31 32 assert events == [33 {19 unmodified lines53 response.raise_for_status()54 55 event_hooks = {"response": [raise_on_4xx_5xx]}56 56- 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_closed11 unmodified lines75 76 event_hooks = {"request": [on_request], "response": [on_response]}77 78 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"))82 83 assert events == [22 unmodified lines106 107 event_hooks = {"response": [raise_on_4xx_5xx]}108 109 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 lines129 events.append({"event": "response", "headers": dict(response.headers)})130 131 event_hooks = {"request": [on_request], "response": [on_response]}132 130- 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"))137 138 assert events == [139 {30 unmodified lines170 171 event_hooks = {"request": [on_request], "response": [on_response]}172 173 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"))177 178 assert events == [16 unmodified linesmodified:tests/client/test_headers.py+11 added-8 removed
1 unmodified line2 3 import pytest4 5 import httpx6-from tests.utils import MockTransport6 7 8 def echo_headers(request: httpx.Request) -> httpx.Response:9 data = {"headers": dict(request.headers)}6 unmodified lines16 """17 url = "http://example.org/echo_headers"18 headers = {"Example-Header": "example-value"}19 21- 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)22 23 assert response.status_code == 20024 assert response.json() == {11 unmodified lines36 def 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)44 45 assert response.status_code == 20046 assert response.json() == {11 unmodified lines58 def 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)66 67 assert response.status_code == 20068 assert response.json() == {9 unmodified lines78 79 80 def 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 lines115 Remove a default header from the Client.116 """117 url = "http://example.org/echo_headers"118 116- client = httpx.Client(transport=MockTransport(echo_headers))119+ client = httpx.Client(transport=httpx.MockTransport(echo_headers))120 del client.headers["User-Agent"]121 122 response = client.get(url)123 21 unmodified lines145 be present.146 """147 url = "http://username:password@example.org:80/echo_headers"148 146- client = httpx.Client(transport=MockTransport(echo_headers))149+ client = httpx.Client(transport=httpx.MockTransport(echo_headers))150 response = client.get(url)151 152 assert response.status_code == 200153 assert response.json() == {14 unmodified lines168 the Host header.169 """170 url = "http://username:password@example.org:123/echo_headers"171 169- client = httpx.Client(transport=MockTransport(echo_headers))172+ client = httpx.Client(transport=httpx.MockTransport(echo_headers))173 response = client.get(url)174 175 assert response.status_code == 200176 assert response.json() == {14 unmodified linesmodified:tests/client/test_queryparams.py+1 added-2 removed
1 import httpx2-from tests.utils import MockTransport2 3 4 def hello_world(request: httpx.Request) -> httpx.Response:5 return httpx.Response(200, text="Hello, world")20 unmodified lines26 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)33 34 assert response.status_code == 2001 unmodified linemodified:tests/client/test_redirects.py+25 added-26 removed
1 import httpcore2 import pytest3 4 import httpx5-from tests.utils import MockTransport5 6 7 def redirects(request: httpx.Request) -> httpx.Response:8 if request.url.scheme not in ("http", "https"):105 unmodified lines114 return httpx.Response(200, html="<html><body>Hello, world!</body></html>")115 116 117 def 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) == 1123 124 125 def 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) == 1131 132 133 def 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) == 1139 140 141 def 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 lines153 154 155 @pytest.mark.usefixtures("async_environment")156 async 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 lines170 def 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 line180 assert response.text == ""181 182 183 def 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) == 1189 190 191 def 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) == 1198 199 200 def 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")204 205 206 def 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) == 1212 213 214 def 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) == 1220 221 222 def 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) == 204 unmodified lines232 233 234 @pytest.mark.usefixtures("async_environment")235 async 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")239 240 241 def 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")245 246 247 def 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")251 252 253 def 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"]260 261 262 def 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"]268 269 270 def 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 lines279 def 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 lines292 def 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 line302 assert "content-length" not in response.json()["headers"]303 304 305 def 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/"312 313 314 def 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"317 318 def streaming_body():319 yield b"Example request body" # pragma: nocover2 unmodified lines322 client.post(url, content=streaming_body())323 324 325 def 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 lines362 return httpx.Response(status_code, headers=headers)363 364 365 def test_redirect_cookie_behavior():367- client = httpx.Client(transport=MockTransport(cookie_sessions))366+ client = httpx.Client(transport=httpx.MockTransport(cookie_sessions))367 368 # The client is not logged in.369 response = client.get("https://example.com/")370 assert response.url == "https://example.com/"20 unmodified lines391 assert response.text == "Not logged in"392 393 394 def 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 lines8 9 import httpx10 from httpx._content import encode_request11 from httpx._utils import format_form_param12-from tests.utils import MockTransport12 13 14 def echo_request_content(request: httpx.Request) -> httpx.Response:15 return httpx.Response(200, content=request.content)16 17 18 @pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))19 def test_multipart(value, output):21- client = httpx.Client(transport=MockTransport(echo_request_content))20+ client = httpx.Client(transport=httpx.MockTransport(echo_request_content))21 22 # 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 lines42 43 44 @pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))45 def test_multipart_invalid_key(key):47- client = httpx.Client(transport=MockTransport(echo_request_content))46+ client = httpx.Client(transport=httpx.MockTransport(echo_request_content))47 48 data = {key: "abc"}49 files = {"file": io.BytesIO(b"<file content>")}50 with pytest.raises(TypeError) as e:7 unmodified lines58 59 60 @pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))61 def test_multipart_invalid_value(value):63- client = httpx.Client(transport=MockTransport(echo_request_content))62+ client = httpx.Client(transport=httpx.MockTransport(echo_request_content))63 64 data = {"text": value}65 files = {"file": io.BytesIO(b"<file content>")}66 with pytest.raises(TypeError) as e:1 unmodified line68 assert "Invalid type for value" in str(e.value)69 70 71 def test_multipart_file_tuple():73- client = httpx.Client(transport=MockTransport(echo_request_content))72+ client = httpx.Client(transport=httpx.MockTransport(echo_request_content))73 74 # Test with a list of values 'data' argument,75 # and a tuple style 'files' argument.76 data = {"text": ["abc"]}191 unmodified linesmodified:tests/utils.py-55 removed
1 import contextlib2 import logging3 import os4-from typing import Callable, List, Optional, Tuple4 6-import httpcore7-8-import httpx5 from httpx import _utils6 7 8 @contextlib.contextmanager8 unmodified lines17 yield18 finally:19 # Reset the logger so we don't have verbose output in all unit tests20 logging.getLogger("httpx").handlers = []25-26-27-class MockTransport(httpcore.SyncHTTPTransport, httpcore.AsyncHTTPTransport):28- def __init__(self, handler: Callable) -> None:29- self.handler = handler30-31- 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- )53-54- 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- )