Skip to content
Myr

Closing AsyncClient in all tests (#871) (#1219)

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

All over the AsyncClient invocation is made using context manager or with try-finally block

authored by cdeler · committed by GitHub · parent aad8209 · Browse files · 3 files+167 added−147 removed
This commit

State

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

Diff stats

3 files+167 added−147 removed

  • tests:+167 added−147 removed

3 files+167 added−147 removed

modified:tests/client/test_auth.py+94 added-80 removed
3 unmodified lines
45import httpcore6import pytest78import httpx9from httpx import (10 URL,10 AsyncClient,11 Auth,12 BasicAuth,13 Client,13 DigestAuth,14 ProtocolError,15 Request,16 RequestBodyUnavailable,
170 unmodified lines
187async def test_basic_auth() -> None:188 url = "https://example.org/"189 auth = ("tomchristie", "password123")190192 client = AsyncClient(transport=AsyncMockTransport())193 response = await client.get(url, auth=auth)191 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:192 response = await client.get(url, auth=auth)193194 assert response.status_code == 200195 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}196
1 unmodified line
198@pytest.mark.asyncio199async def test_basic_auth_in_url() -> None:200 url = "https://tomchristie:password123@example.org/"201203 client = AsyncClient(transport=AsyncMockTransport())204 response = await client.get(url)202 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:203 response = await client.get(url)204205 assert response.status_code == 200206 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}207
2 unmodified lines
210async def test_basic_auth_on_session() -> None:211 url = "https://example.org/"212 auth = ("tomchristie", "password123")213215 client = AsyncClient(transport=AsyncMockTransport(), auth=auth)216 response = await client.get(url)214 async with httpx.AsyncClient(transport=AsyncMockTransport(), auth=auth) as client:215 response = await client.get(url)216217 assert response.status_code == 200218 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}219
5 unmodified lines
225 def auth(request: Request) -> Request:226 request.headers["Authorization"] = "Token 123"227 return request228230 client = AsyncClient(transport=AsyncMockTransport())231 response = await client.get(url, auth=auth)229 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:230 response = await client.get(url, auth=auth)231232 assert response.status_code == 200233 assert response.json() == {"auth": "Token 123"}234
2 unmodified lines
237async def test_netrc_auth() -> None:238 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")239 url = "http://netrcexample.org"240242 client = AsyncClient(transport=AsyncMockTransport())243 response = await client.get(url)241 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:242 response = await client.get(url)243244 assert response.status_code == 200245 assert response.json() == {246 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"
4 unmodified lines
251async def test_auth_header_has_priority_over_netrc() -> None:252 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")253 url = "http://netrcexample.org"254256 client = AsyncClient(transport=AsyncMockTransport())257 response = await client.get(url, headers={"Authorization": "Override"})255 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:256 response = await client.get(url, headers={"Authorization": "Override"})257258 assert response.status_code == 200259 assert response.json() == {"auth": "Override"}260
2 unmodified lines
263async def test_trust_env_auth() -> None:264 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")265 url = "http://netrcexample.org"266268 client = AsyncClient(transport=AsyncMockTransport(), trust_env=False)269 response = await client.get(url)267 async with httpx.AsyncClient(268 transport=AsyncMockTransport(), trust_env=False269 ) as client:270 response = await client.get(url)271272 assert response.status_code == 200273 assert response.json() == {"auth": None}274274 client = AsyncClient(transport=AsyncMockTransport(), trust_env=True)275 response = await client.get(url)275 async with httpx.AsyncClient(276 transport=AsyncMockTransport(), trust_env=True277 ) as client:278 response = await client.get(url)279280 assert response.status_code == 200281 assert response.json() == {282 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"
4 unmodified lines
287async def test_auth_disable_per_request() -> None:288 url = "https://example.org/"289 auth = ("tomchristie", "password123")290288 client = AsyncClient(transport=AsyncMockTransport(), auth=auth)289 response = await client.get(url, auth=None)291 async with httpx.AsyncClient(transport=AsyncMockTransport(), auth=auth) as client:292 response = await client.get(url, auth=None)293294 assert response.status_code == 200295 assert response.json() == {"auth": None}296
9 unmodified lines
306async def test_auth_hidden_header() -> None:307 url = "https://example.org/"308 auth = ("example-username", "example-password")309307 client = AsyncClient(transport=AsyncMockTransport())308 response = await client.get(url, auth=auth)310 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:311 response = await client.get(url, auth=auth)312313 assert "'authorization': '[secure]'" in str(response.request.headers)314315316@pytest.mark.asyncio317async def test_auth_property() -> None:315 client = AsyncClient(transport=AsyncMockTransport())316 assert client.auth is None318 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:319 assert client.auth is None320318 client.auth = ("tomchristie", "password123") # type: ignore319 assert isinstance(client.auth, BasicAuth)321 client.auth = ("tomchristie", "password123") # type: ignore322 assert isinstance(client.auth, BasicAuth)323321 url = "https://example.org/"322 response = await client.get(url)323 assert response.status_code == 200324 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}324 url = "https://example.org/"325 response = await client.get(url)326 assert response.status_code == 200327 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}328329330@pytest.mark.asyncio331async def test_auth_invalid_type() -> None:332 with pytest.raises(TypeError):330 client = AsyncClient(333 client = httpx.AsyncClient(334 transport=AsyncMockTransport(),335 auth="not a tuple, not a callable", # type: ignore336 )337335 client = AsyncClient(transport=AsyncMockTransport())338 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:339 with pytest.raises(TypeError):340 await client.get(auth="not a tuple, not a callable") # type: ignore341337 with pytest.raises(TypeError):338 await client.get(auth="not a tuple, not a callable") # type: ignore342 with pytest.raises(TypeError):343 client.auth = "not a tuple, not a callable" # type: ignore344340 with pytest.raises(TypeError):341 client.auth = "not a tuple, not a callable" # type: ignore345343346@pytest.mark.asyncio347async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:348 url = "https://example.org/"349 auth = DigestAuth(username="tomchristie", password="password123")350349 client = AsyncClient(transport=AsyncMockTransport())350 response = await client.get(url, auth=auth)351 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:352 response = await client.get(url, auth=auth)353354 assert response.status_code == 200355 assert response.json() == {"auth": None}356 assert len(response.history) == 0
4 unmodified lines
361 url = "https://example.org/"362 auth = DigestAuth(username="tomchristie", password="password123")363 auth_header = b'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'364363 client = AsyncClient(365 async with httpx.AsyncClient(366 transport=AsyncMockTransport(auth_header=auth_header, status_code=200)365 )366 response = await client.get(url, auth=auth)367 ) as client:368 response = await client.get(url, auth=auth)369370 assert response.status_code == 200371 assert response.json() == {"auth": None}372 assert len(response.history) == 0
3 unmodified lines
376async def test_digest_auth_401_response_without_digest_auth_header() -> None:377 url = "https://example.org/"378 auth = DigestAuth(username="tomchristie", password="password123")379378 client = AsyncClient(transport=AsyncMockTransport(auth_header=b"", status_code=401))379 response = await client.get(url, auth=auth)380 async with httpx.AsyncClient(381 transport=AsyncMockTransport(auth_header=b"", status_code=401)382 ) as client:383 response = await client.get(url, auth=auth)384385 assert response.status_code == 401386 assert response.json() == {"auth": None}387 assert len(response.history) == 0
18 unmodified lines
406) -> None:407 url = "https://example.org/"408 auth = DigestAuth(username="tomchristie", password="password123")409406 client = AsyncClient(transport=MockDigestAuthTransport(algorithm=algorithm))407 response = await client.get(url, auth=auth)410 async with httpx.AsyncClient(411 transport=MockDigestAuthTransport(algorithm=algorithm)412 ) as client:413 response = await client.get(url, auth=auth)414415 assert response.status_code == 200416 assert len(response.history) == 1417
20 unmodified lines
438async def test_digest_auth_no_specified_qop() -> None:439 url = "https://example.org/"440 auth = DigestAuth(username="tomchristie", password="password123")441436 client = AsyncClient(transport=MockDigestAuthTransport(qop=""))437 response = await client.get(url, auth=auth)442 async with httpx.AsyncClient(transport=MockDigestAuthTransport(qop="")) as client:443 response = await client.get(url, auth=auth)444445 assert response.status_code == 200446 assert len(response.history) == 1447
21 unmodified lines
469async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:470 url = "https://example.org/"471 auth = DigestAuth(username="tomchristie", password="password123")472467 client = AsyncClient(transport=MockDigestAuthTransport(qop=qop))468 response = await client.get(url, auth=auth)473 async with httpx.AsyncClient(transport=MockDigestAuthTransport(qop=qop)) as client:474 response = await client.get(url, auth=auth)475476 assert response.status_code == 200477 assert len(response.history) == 1478
1 unmodified line
480@pytest.mark.asyncio481async def test_digest_auth_qop_auth_int_not_implemented() -> None:482 url = "https://example.org/"483 auth = DigestAuth(username="tomchristie", password="password123")478 client = AsyncClient(transport=MockDigestAuthTransport(qop="auth-int"))484485 async with httpx.AsyncClient(486 transport=MockDigestAuthTransport(qop="auth-int")487 ) as client:480 with pytest.raises(NotImplementedError):481 await client.get(url, auth=auth)488 with pytest.raises(NotImplementedError):489 await client.get(url, auth=auth)490491492@pytest.mark.asyncio493async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:494 url = "https://example.org/"495 auth = DigestAuth(username="tomchristie", password="password123")488 client = AsyncClient(transport=MockDigestAuthTransport(qop="not-auth"))496497 async with httpx.AsyncClient(498 transport=MockDigestAuthTransport(qop="not-auth")499 ) as client:490 with pytest.raises(ProtocolError):491 await client.get(url, auth=auth)500 with pytest.raises(ProtocolError):501 await client.get(url, auth=auth)502503504@pytest.mark.asyncio505async def test_digest_auth_incorrect_credentials() -> None:506 url = "https://example.org/"507 auth = DigestAuth(username="tomchristie", password="password123")508499 client = AsyncClient(509 async with httpx.AsyncClient(510 transport=MockDigestAuthTransport(send_response_after_attempt=2)501 )502 response = await client.get(url, auth=auth)511 ) as client:512 response = await client.get(url, auth=auth)513514 assert response.status_code == 401515 assert len(response.history) == 1516
13 unmodified lines
530 auth_header: bytes,531) -> None:532 url = "https://example.org/"533 auth = DigestAuth(username="tomchristie", password="password123")524 client = AsyncClient(534 async with httpx.AsyncClient(535 transport=AsyncMockTransport(auth_header=auth_header, status_code=401)526 )536 ) as client:537 with pytest.raises(ProtocolError):538 await client.get(url, auth=auth)539528 with pytest.raises(ProtocolError):529 await client.get(url, auth=auth)540531541@pytest.mark.parametrize(542 "auth_header",543 [544 b'Digest realm="httpx@example.org", qop="auth"', # missing fields
7 unmodified lines
552 auth_header: bytes,553) -> None:554 url = "https://example.org/"555 auth = DigestAuth(username="tomchristie", password="password123")547 client = Client(556557 with httpx.Client(558 transport=SyncMockTransport(auth_header=auth_header, status_code=401)549 )559 ) as client:560 with pytest.raises(ProtocolError):561 client.get(url, auth=auth)562551 with pytest.raises(ProtocolError):552 client.get(url, auth=auth)563554564@pytest.mark.asyncio565async def test_async_auth_history() -> None:566 """567 Test that intermediate requests sent as part of an authentication flow568 are recorded in the response history.569 """570 url = "https://example.org/"571 auth = RepeatAuth(repeat=2)563 client = AsyncClient(transport=AsyncMockTransport(auth_header=b"abc"))572573 async with httpx.AsyncClient(574 transport=AsyncMockTransport(auth_header=b"abc")575 ) as client:565 response = await client.get(url, auth=auth)576 response = await client.get(url, auth=auth)577578 assert response.status_code == 200579 assert response.json() == {"auth": "Repeat abc.abc"}580581 assert len(response.history) == 2
13 unmodified lines
595 are recorded in the response history.596 """597 url = "https://example.org/"598 auth = RepeatAuth(repeat=2)587 client = Client(transport=SyncMockTransport(auth_header=b"abc"))599600 with httpx.Client(transport=SyncMockTransport(auth_header=b"abc")) as client:589 response = client.get(url, auth=auth)601 response = client.get(url, auth=auth)602603 assert response.status_code == 200604 assert response.json() == {"auth": "Repeat abc.abc"}605606 assert len(response.history) == 2
10 unmodified lines
617@pytest.mark.asyncio618async def test_digest_auth_unavailable_streaming_body():619 url = "https://example.org/"620 auth = DigestAuth(username="tomchristie", password="password123")608 client = AsyncClient(transport=AsyncMockTransport())621622 async def streaming_body():623 yield b"Example request body" # pragma: nocover624625 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:613 with pytest.raises(RequestBodyUnavailable):614 await client.post(url, data=streaming_body(), auth=auth)626 with pytest.raises(RequestBodyUnavailable):627 await client.post(url, data=streaming_body(), auth=auth)628629630@pytest.mark.asyncio631async def test_async_auth_reads_response_body() -> None:
2 unmodified lines
634 is set.635 """636 url = "https://example.org/"637 auth = ResponseBodyAuth("xyz")625 client = AsyncClient(transport=AsyncMockTransport())638 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:639 response = await client.get(url, auth=auth)640627 response = await client.get(url, auth=auth)641 assert response.status_code == 200642 assert response.json() == {"auth": '{"auth": "xyz"}'}643644
3 unmodified lines
648 is set.649 """650 url = "https://example.org/"651 auth = ResponseBodyAuth("xyz")639 client = Client(transport=SyncMockTransport())652653 with httpx.Client(transport=SyncMockTransport()) as client:641 response = client.get(url, auth=auth)654 response = client.get(url, auth=auth)655656 assert response.status_code == 200657 assert response.json() == {"auth": '{"auth": "xyz"}'}
modified:tests/test_asgi.py+18 added-15 removed
41 unmodified lines
424344@pytest.mark.usefixtures("async_environment")45async def test_asgi():46 client = httpx.AsyncClient(app=hello_world)47 response = await client.get("http://www.example.org/")46 async with httpx.AsyncClient(app=hello_world) as client:47 response = await client.get("http://www.example.org/")4849 assert response.status_code == 20050 assert response.text == "Hello, World!"515253@pytest.mark.usefixtures("async_environment")54async def test_asgi_upload():54 client = httpx.AsyncClient(app=echo_body)55 response = await client.post("http://www.example.org/", data=b"example")55 async with httpx.AsyncClient(app=echo_body) as client:56 response = await client.post("http://www.example.org/", data=b"example")5758 assert response.status_code == 20059 assert response.text == "example"606162@pytest.mark.usefixtures("async_environment")63async def test_asgi_exc():62 client = httpx.AsyncClient(app=raise_exc)63 with pytest.raises(ValueError):64 await client.get("http://www.example.org/")64 async with httpx.AsyncClient(app=raise_exc) as client:65 with pytest.raises(ValueError):66 await client.get("http://www.example.org/")676869@pytest.mark.usefixtures("async_environment")70async def test_asgi_http_error():69 client = httpx.AsyncClient(app=partial(raise_exc, exc=RuntimeError))70 with pytest.raises(RuntimeError):71 await client.get("http://www.example.org/")71 async with httpx.AsyncClient(app=partial(raise_exc, exc=RuntimeError)) as client:72 with pytest.raises(RuntimeError):73 await client.get("http://www.example.org/")747576@pytest.mark.usefixtures("async_environment")77async def test_asgi_exc_after_response():76 client = httpx.AsyncClient(app=raise_exc_after_response)77 with pytest.raises(ValueError):78 await client.get("http://www.example.org/")78 async with httpx.AsyncClient(app=raise_exc_after_response) as client:79 with pytest.raises(ValueError):80 await client.get("http://www.example.org/")818283@pytest.mark.usefixtures("async_environment")84async def test_asgi_disconnect_after_response_complete():
21 unmodified lines
106 # So if receive() is called again, the disconnect message should be received107 message = await receive()108 disconnect = message.get("type") == "http.disconnect"109108 client = httpx.AsyncClient(app=read_body)109 response = await client.post("http://www.example.org/", data=b"example")110 async with httpx.AsyncClient(app=read_body) as client:111 response = await client.post("http://www.example.org/", data=b"example")112113 assert response.status_code == 200114 assert disconnect
modified:tests/test_multipart.py+55 added-52 removed
33 unmodified lines
3435@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))36@pytest.mark.asyncio37async def test_multipart(value, output):38 client = httpx.AsyncClient(transport=MockTransport())38 async with httpx.AsyncClient(transport=MockTransport()) as client:39 # Test with a single-value 'data' argument, and a plain file 'files' argument.40 data = {"text": value}41 files = {"file": io.BytesIO(b"<file content>")}42 response = await client.post("http://127.0.0.1:8000/", data=data, files=files)43 assert response.status_code == 2004440 # Test with a single-value 'data' argument, and a plain file 'files' argument.41 data = {"text": value}42 files = {"file": io.BytesIO(b"<file content>")}43 response = await client.post("http://127.0.0.1:8000/", data=data, files=files)44 assert response.status_code == 20045 # We're using the cgi module to verify the behavior here, which is a46 # bit grungy, but sufficient just for our testing purposes.47 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]48 content_length = response.request.headers["Content-Length"]49 pdict: dict = {50 "boundary": boundary.encode("ascii"),51 "CONTENT-LENGTH": content_length,52 }53 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)5446 # We're using the cgi module to verify the behavior here, which is a47 # bit grungy, but sufficient just for our testing purposes.48 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]49 content_length = response.request.headers["Content-Length"]50 pdict: dict = {51 "boundary": boundary.encode("ascii"),52 "CONTENT-LENGTH": content_length,53 }54 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)55 # Note that the expected return type for text fields56 # appears to differs from 3.6 to 3.7+57 assert multipart["text"] == [output.decode()] or multipart["text"] == [output]58 assert multipart["file"] == [b"<file content>"]5956 # Note that the expected return type for text fields57 # appears to differs from 3.6 to 3.7+58 assert multipart["text"] == [output.decode()] or multipart["text"] == [output]59 assert multipart["file"] == [b"<file content>"]606161@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))62@pytest.mark.asyncio63async def test_multipart_invalid_key(key):65 client = httpx.AsyncClient(transport=MockTransport())66 data = {key: "abc"}67 files = {"file": io.BytesIO(b"<file content>")}68 with pytest.raises(TypeError) as e:69 await client.post("http://127.0.0.1:8000/", data=data, files=files)70 assert "Invalid type for name" in str(e.value)64 async with httpx.AsyncClient(transport=MockTransport()) as client:65 data = {key: "abc"}66 files = {"file": io.BytesIO(b"<file content>")}67 with pytest.raises(TypeError) as e:68 await client.post(69 "http://127.0.0.1:8000/",70 data=data,71 files=files,72 )73 assert "Invalid type for name" in str(e.value)747576@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))77@pytest.mark.asyncio78async def test_multipart_invalid_value(value):76 client = httpx.AsyncClient(transport=MockTransport())77 data = {"text": value}78 files = {"file": io.BytesIO(b"<file content>")}79 with pytest.raises(TypeError) as e:80 await client.post("http://127.0.0.1:8000/", data=data, files=files)81 assert "Invalid type for value" in str(e.value)79 async with httpx.AsyncClient(transport=MockTransport()) as client:80 data = {"text": value}81 files = {"file": io.BytesIO(b"<file content>")}82 with pytest.raises(TypeError) as e:83 await client.post("http://127.0.0.1:8000/", data=data, files=files)84 assert "Invalid type for value" in str(e.value)858687@pytest.mark.asyncio88async def test_multipart_file_tuple():86 client = httpx.AsyncClient(transport=MockTransport())89 async with httpx.AsyncClient(transport=MockTransport()) as client:90 # Test with a list of values 'data' argument,91 # and a tuple style 'files' argument.92 data = {"text": ["abc"]}93 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}94 response = await client.post("http://127.0.0.1:8000/", data=data, files=files)95 assert response.status_code == 2009688 # Test with a list of values 'data' argument, and a tuple style 'files' argument.89 data = {"text": ["abc"]}90 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}91 response = await client.post("http://127.0.0.1:8000/", data=data, files=files)92 assert response.status_code == 20097 # We're using the cgi module to verify the behavior here, which is a98 # bit grungy, but sufficient just for our testing purposes.99 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]100 content_length = response.request.headers["Content-Length"]101 pdict: dict = {102 "boundary": boundary.encode("ascii"),103 "CONTENT-LENGTH": content_length,104 }105 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)10694 # We're using the cgi module to verify the behavior here, which is a95 # bit grungy, but sufficient just for our testing purposes.96 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]97 content_length = response.request.headers["Content-Length"]98 pdict: dict = {99 "boundary": boundary.encode("ascii"),100 "CONTENT-LENGTH": content_length,101 }102 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)107 # Note that the expected return type for text fields108 # appears to differs from 3.6 to 3.7+109 assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]110 assert multipart["file"] == [b"<file content>"]111104 # Note that the expected return type for text fields105 # appears to differs from 3.6 to 3.7+106 assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]107 assert multipart["file"] == [b"<file content>"]112109113def test_multipart_encode(tmp_path: typing.Any) -> None:114 path = str(tmp_path / "name.txt")115 with open(path, "wb") as f:116 f.write(b"<file content>")
162 unmodified lines