Skip to content
Myr

replace pytest-asyncio and pytest-trio with anyio (#2512)

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

* replace pytest-asyncio with anyio * remove pytest-trio also * Update setup.cfg * use anyio.Lock in test_auth

authored by Thomas Grainger · committed by GitHub · parent e4438a3 · Browse files · 15 files+120 added−146 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: Tom Christie <tom@tomchristie.com>

Diff stats

15 files+120 added−146 removed

  • tests:+119 added−143 removed
  • other:+1 added−3 removed

15 files+120 added−146 removed

modified:tests/client/test_async_client.py+24 added-24 removed
4 unmodified lines
56import httpx789@pytest.mark.usefixtures("async_environment")9@pytest.mark.anyio10async def test_get(server):11 url = server.url12 async with httpx.AsyncClient(http2=True) as client:13 response = await client.get(url)
12 unmodified lines
26 pytest.param("://example.org", id="no-scheme"),27 pytest.param("http://", id="no-host"),28 ],29)30@pytest.mark.usefixtures("async_environment")30@pytest.mark.anyio31async def test_get_invalid_url(server, url):32 async with httpx.AsyncClient() as client:33 with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):34 await client.get(url)353637@pytest.mark.usefixtures("async_environment")37@pytest.mark.anyio38async def test_build_request(server):39 url = server.url.copy_with(path="/echo_headers")40 headers = {"Custom-header": "value"}41 async with httpx.AsyncClient() as client:
6 unmodified lines
4849 assert response.json()["Custom-header"] == "value"505152@pytest.mark.usefixtures("async_environment")52@pytest.mark.anyio53async def test_post(server):54 url = server.url55 async with httpx.AsyncClient() as client:56 response = await client.post(url, content=b"Hello, world!")57 assert response.status_code == 200585960@pytest.mark.usefixtures("async_environment")60@pytest.mark.anyio61async def test_post_json(server):62 url = server.url63 async with httpx.AsyncClient() as client:64 response = await client.post(url, json={"text": "Hello, world!"})65 assert response.status_code == 200666768@pytest.mark.usefixtures("async_environment")68@pytest.mark.anyio69async def test_stream_response(server):70 async with httpx.AsyncClient() as client:71 async with client.stream("GET", server.url) as response:72 body = await response.aread()
2 unmodified lines
75 assert body == b"Hello, world!"76 assert response.content == b"Hello, world!"777879@pytest.mark.usefixtures("async_environment")79@pytest.mark.anyio80async def test_access_content_stream_response(server):81 async with httpx.AsyncClient() as client:82 async with client.stream("GET", server.url) as response:83 pass
2 unmodified lines
86 with pytest.raises(httpx.ResponseNotRead):87 response.content888990@pytest.mark.usefixtures("async_environment")90@pytest.mark.anyio91async def test_stream_request(server):92 async def hello_world() -> typing.AsyncIterator[bytes]:93 yield b"Hello, "94 yield b"world!"
2 unmodified lines
97 response = await client.post(server.url, content=hello_world())98 assert response.status_code == 20099100101@pytest.mark.usefixtures("async_environment")101@pytest.mark.anyio102async def test_cannot_stream_sync_request(server):103 def hello_world() -> typing.Iterator[bytes]: # pragma: no cover104 yield b"Hello, "105 yield b"world!"
2 unmodified lines
108 with pytest.raises(RuntimeError):109 await client.post(server.url, content=hello_world())110111112@pytest.mark.usefixtures("async_environment")112@pytest.mark.anyio113async def test_raise_for_status(server):114 async with httpx.AsyncClient() as client:115 for status_code in (200, 400, 404, 500, 505):116 response = await client.request(
7 unmodified lines
124 else:125 assert response.raise_for_status() is None # type: ignore126127128@pytest.mark.usefixtures("async_environment")128@pytest.mark.anyio129async def test_options(server):130 async with httpx.AsyncClient() as client:131 response = await client.options(server.url)132 assert response.status_code == 200133 assert response.text == "Hello, world!"134135136@pytest.mark.usefixtures("async_environment")136@pytest.mark.anyio137async def test_head(server):138 async with httpx.AsyncClient() as client:139 response = await client.head(server.url)140 assert response.status_code == 200141 assert response.text == ""142143144@pytest.mark.usefixtures("async_environment")144@pytest.mark.anyio145async def test_put(server):146 async with httpx.AsyncClient() as client:147 response = await client.put(server.url, content=b"Hello, world!")148 assert response.status_code == 200149150151@pytest.mark.usefixtures("async_environment")151@pytest.mark.anyio152async def test_patch(server):153 async with httpx.AsyncClient() as client:154 response = await client.patch(server.url, content=b"Hello, world!")155 assert response.status_code == 200156157158@pytest.mark.usefixtures("async_environment")158@pytest.mark.anyio159async def test_delete(server):160 async with httpx.AsyncClient() as client:161 response = await client.delete(server.url)162 assert response.status_code == 200163 assert response.text == "Hello, world!"164165166@pytest.mark.usefixtures("async_environment")166@pytest.mark.anyio167async def test_100_continue(server):168 headers = {"Expect": "100-continue"}169 content = b"Echo request body"170
5 unmodified lines
176 assert response.status_code == 200177 assert response.content == content178179180@pytest.mark.usefixtures("async_environment")180@pytest.mark.anyio181async def test_context_managed_transport():182 class Transport(httpx.AsyncBaseTransport):183 def __init__(self) -> None:184 self.events: typing.List[str] = []
23 unmodified lines
208 "transport.__aexit__",209 ]210211212@pytest.mark.usefixtures("async_environment")212@pytest.mark.anyio213async def test_context_managed_transport_and_mount():214 class Transport(httpx.AsyncBaseTransport):215 def __init__(self, name: str):216 self.name: str = name
36 unmodified lines
253def hello_world(request):254 return httpx.Response(200, text="Hello, world!")255256257@pytest.mark.usefixtures("async_environment")257@pytest.mark.anyio258async def test_client_closed_state_using_implicit_open():259 client = httpx.AsyncClient(transport=httpx.MockTransport(hello_world))260261 assert not client.is_closed
12 unmodified lines
274 async with client:275 pass # pragma: no cover276277278@pytest.mark.usefixtures("async_environment")278@pytest.mark.anyio279async def test_client_closed_state_using_with_block():280 async with httpx.AsyncClient(transport=httpx.MockTransport(hello_world)) as client:281 assert not client.is_closed282 await client.get("http://example.com")
12 unmodified lines
295 data = {"app": "mounted"}296 return httpx.Response(200, json=data)297298299@pytest.mark.usefixtures("async_environment")299@pytest.mark.anyio300async def test_mounted_transport():301 transport = httpx.MockTransport(unmounted)302 mounts = {"custom://": httpx.MockTransport(mounted)}303
6 unmodified lines
310 assert response.status_code == 200311 assert response.json() == {"app": "mounted"}312313314@pytest.mark.usefixtures("async_environment")314@pytest.mark.anyio315async def test_async_mock_transport():316 async def hello_world(request):317 return httpx.Response(200, text="Hello, world!")318
4 unmodified lines
323 assert response.status_code == 200324 assert response.text == "Hello, world!"325326327@pytest.mark.usefixtures("async_environment")327@pytest.mark.anyio328async def test_cancellation_during_stream():329 """330 If any BaseException is raised during streaming the response, then the331 stream should be closed.
31 unmodified lines
363 await client.get("https://www.example.com")364 assert stream_was_closed365366367@pytest.mark.usefixtures("async_environment")367@pytest.mark.anyio368async def test_server_extensions(server):369 url = server.url370 async with httpx.AsyncClient(http2=True) as client:371 response = await client.get(url)
2 unmodified lines
modified:tests/client/test_auth.py+30 added-30 removed
1 unmodified line
2Integration tests for authentication.34Unit tests for auth classes also exist in tests/test_auth.py5"""6import asyncio6import hashlib7import os8import threading9import typing10from urllib.request import parse_keqv_list1112import anyio13import pytest1415import httpx16
117 unmodified lines
134 """135136 def __init__(self) -> None:137 self._lock = threading.Lock()138 self._async_lock = asyncio.Lock()138 self._async_lock = anyio.Lock()139140 def sync_auth_flow(141 self, request: httpx.Request142 ) -> typing.Generator[httpx.Request, httpx.Response, None]:
8 unmodified lines
151 request.headers["Authorization"] = "async-auth"152 yield request153154155@pytest.mark.asyncio155@pytest.mark.anyio156async def test_basic_auth() -> None:157 url = "https://example.org/"158 auth = ("user", "password123")159 app = App()
4 unmodified lines
164 assert response.status_code == 200165 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}166167168@pytest.mark.asyncio168@pytest.mark.anyio169async def test_basic_auth_with_stream() -> None:170 """171 See: https://github.com/encode/httpx/pull/1312172 """
10 unmodified lines
183 assert response.status_code == 200184 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}185186187@pytest.mark.asyncio187@pytest.mark.anyio188async def test_basic_auth_in_url() -> None:189 url = "https://user:password123@example.org/"190 app = App()191
3 unmodified lines
195 assert response.status_code == 200196 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}197198199@pytest.mark.asyncio199@pytest.mark.anyio200async def test_basic_auth_on_session() -> None:201 url = "https://example.org/"202 auth = ("user", "password123")203 app = App()
6 unmodified lines
210 assert response.status_code == 200211 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}212213214@pytest.mark.asyncio214@pytest.mark.anyio215async def test_custom_auth() -> None:216 url = "https://example.org/"217 app = App()218
7 unmodified lines
226 assert response.status_code == 200227 assert response.json() == {"auth": "Token 123"}228229230@pytest.mark.asyncio230@pytest.mark.anyio231async def test_netrc_auth() -> None:232 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")233 url = "http://netrcexample.org"234 app = App()
6 unmodified lines
241 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"242 }243244245@pytest.mark.asyncio245@pytest.mark.anyio246async def test_auth_header_has_priority_over_netrc() -> None:247 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")248 url = "http://netrcexample.org"249 app = App()
4 unmodified lines
254 assert response.status_code == 200255 assert response.json() == {"auth": "Override"}256257258@pytest.mark.asyncio258@pytest.mark.anyio259async def test_trust_env_auth() -> None:260 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")261 url = "http://netrcexample.org"262 app = App()
16 unmodified lines
279 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"280 }281282283@pytest.mark.asyncio283@pytest.mark.anyio284async def test_auth_disable_per_request() -> None:285 url = "https://example.org/"286 auth = ("user", "password123")287 app = App()
13 unmodified lines
301 assert url == httpx.URL(url)302 assert expected == repr(httpx.URL(url))303304305@pytest.mark.asyncio305@pytest.mark.anyio306async def test_auth_hidden_header() -> None:307 url = "https://example.org/"308 auth = ("example-username", "example-password")309 app = App()
3 unmodified lines
313314 assert "'authorization': '[secure]'" in str(response.request.headers)315316317@pytest.mark.asyncio317@pytest.mark.anyio318async def test_auth_property() -> None:319 app = App()320321 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
7 unmodified lines
329 assert response.status_code == 200330 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}331332333@pytest.mark.asyncio333@pytest.mark.anyio334async def test_auth_invalid_type() -> None:335 app = App()336337 with pytest.raises(TypeError):
9 unmodified lines
347 with pytest.raises(TypeError):348 client.auth = "not a tuple, not a callable" # type: ignore349350351@pytest.mark.asyncio351@pytest.mark.anyio352async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:353 url = "https://example.org/"354 auth = httpx.DigestAuth(username="user", password="password123")355 app = App()
19 unmodified lines
375 assert response.json() == {"auth": None}376 assert len(response.history) == 0377378379@pytest.mark.asyncio379@pytest.mark.anyio380async def test_digest_auth_200_response_including_digest_auth_header() -> None:381 url = "https://example.org/"382 auth = httpx.DigestAuth(username="user", password="password123")383 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'
6 unmodified lines
390 assert response.json() == {"auth": None}391 assert len(response.history) == 0392393394@pytest.mark.asyncio394@pytest.mark.anyio395async def test_digest_auth_401_response_without_digest_auth_header() -> None:396 url = "https://example.org/"397 auth = httpx.DigestAuth(username="user", password="password123")398 app = App(auth_header="", status_code=401)
18 unmodified lines
417 ("SHA-512", 64, 128),418 ("SHA-512-SESS", 64, 128),419 ],420)421@pytest.mark.asyncio421@pytest.mark.anyio422async def test_digest_auth(423 algorithm: str, expected_hash_length: int, expected_response_length: int424) -> None:425 url = "https://example.org/"
24 unmodified lines
450 assert digest_data["nc"] == "00000001"451 assert len(digest_data["cnonce"]) == 16 + 2452453454@pytest.mark.asyncio454@pytest.mark.anyio455async def test_digest_auth_no_specified_qop() -> None:456 url = "https://example.org/"457 auth = httpx.DigestAuth(username="user", password="password123")458 app = DigestApp(qop="")
23 unmodified lines
482 assert digest_data["algorithm"] == "SHA-256"483484485@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))486@pytest.mark.asyncio486@pytest.mark.anyio487async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:488 url = "https://example.org/"489 auth = httpx.DigestAuth(username="user", password="password123")490 app = DigestApp(qop=qop)
4 unmodified lines
495 assert response.status_code == 200496 assert len(response.history) == 1497498499@pytest.mark.asyncio499@pytest.mark.anyio500async def test_digest_auth_qop_auth_int_not_implemented() -> None:501 url = "https://example.org/"502 auth = httpx.DigestAuth(username="user", password="password123")503 app = DigestApp(qop="auth-int")
2 unmodified lines
506 with pytest.raises(NotImplementedError):507 await client.get(url, auth=auth)508509510@pytest.mark.asyncio510@pytest.mark.anyio511async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:512 url = "https://example.org/"513 auth = httpx.DigestAuth(username="user", password="password123")514 app = DigestApp(qop="not-auth")
2 unmodified lines
517 with pytest.raises(httpx.ProtocolError):518 await client.get(url, auth=auth)519520521@pytest.mark.asyncio521@pytest.mark.anyio522async def test_digest_auth_incorrect_credentials() -> None:523 url = "https://example.org/"524 auth = httpx.DigestAuth(username="user", password="password123")525 app = DigestApp(send_response_after_attempt=2)
4 unmodified lines
530 assert response.status_code == 401531 assert len(response.history) == 1532533534@pytest.mark.asyncio534@pytest.mark.anyio535async def test_digest_auth_reuses_challenge() -> None:536 url = "https://example.org/"537 auth = httpx.DigestAuth(username="user", password="password123")538 app = DigestApp()
8 unmodified lines
547 assert len(response_1.history) == 1548 assert len(response_2.history) == 0549550551@pytest.mark.asyncio551@pytest.mark.anyio552async def test_digest_auth_resets_nonce_count_after_401() -> None:553 url = "https://example.org/"554 auth = httpx.DigestAuth(username="user", password="password123")555 app = DigestApp()
37 unmodified lines
593 'Digest realm="httpx@example.org", qop="auth"', # missing fields594 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list595 ],596)597@pytest.mark.asyncio597@pytest.mark.anyio598async def test_async_digest_auth_raises_protocol_error_on_malformed_header(599 auth_header: str,600) -> None:601 url = "https://example.org/"
23 unmodified lines
625 with pytest.raises(httpx.ProtocolError):626 client.get(url, auth=auth)627628629@pytest.mark.asyncio629@pytest.mark.anyio630async def test_async_auth_history() -> None:631 """632 Test that intermediate requests sent as part of an authentication flow633 are recorded in the response history.
51 unmodified lines
685 [_ async for _ in request.stream]686 return self.handler(request)687688689@pytest.mark.asyncio689@pytest.mark.anyio690async def test_digest_auth_unavailable_streaming_body():691 url = "https://example.org/"692 auth = httpx.DigestAuth(username="user", password="password123")693 app = DigestApp()
5 unmodified lines
699 with pytest.raises(httpx.StreamConsumed):700 await client.post(url, content=streaming_body(), auth=auth)701702703@pytest.mark.asyncio703@pytest.mark.anyio704async def test_async_auth_reads_response_body() -> None:705 """706 Test that we can read the response body in an auth flow if `requires_response_body`707 is set.
24 unmodified lines
732 assert response.status_code == 200733 assert response.json() == {"auth": '{"auth": "xyz"}'}734735736@pytest.mark.asyncio736@pytest.mark.anyio737async def test_async_auth() -> None:738 """739 Test that we can use an auth implementation specific to the async case, to740 support cases that require performing I/O or using concurrency primitives (such
26 unmodified lines
modified:tests/client/test_event_hooks.py+3 added-3 removed
61 unmodified lines
62 except httpx.HTTPStatusError as exc:63 assert exc.response.is_closed646566@pytest.mark.usefixtures("async_environment")66@pytest.mark.anyio67async def test_async_event_hooks():68 events = []6970 async def on_request(request):
27 unmodified lines
98 },99 ]100101102@pytest.mark.usefixtures("async_environment")102@pytest.mark.anyio103async def test_async_event_hooks_raising_exception():104 async def raise_on_4xx_5xx(response):105 response.raise_for_status()106
63 unmodified lines
170 },171 ]172173174@pytest.mark.usefixtures("async_environment")174@pytest.mark.anyio175async def test_async_event_hooks_with_redirect():176 """177 A redirect request should trigger additional 'request' and 'response' event hooks.178 """
50 unmodified lines
modified:tests/client/test_proxies.py+1 added-1 removed
130 unmodified lines
131 assert isinstance(transport._pool, httpcore.HTTPProxy)132 assert transport._pool._proxy_url == url_to_origin(expected)133134135@pytest.mark.asyncio135@pytest.mark.anyio136@pytest.mark.network137async def test_async_proxy_close():138 try:139 client = httpx.AsyncClient(proxies={"https://": PROXY_URL})
147 unmodified lines
modified:tests/client/test_redirects.py+3 added-3 removed
149 unmodified lines
150 assert response.url == "https://example.org/"151 assert response.next_request is None152153154@pytest.mark.usefixtures("async_environment")154@pytest.mark.anyio155async def test_async_next_request():156 async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client:157 request = client.build_request("POST", "https://example.org/redirect_303")158 response = await client.send(request, follow_redirects=False)
80 unmodified lines
239 assert len(response.history[0].history) == 0240 assert len(response.history[1].history) == 1241242243@pytest.mark.usefixtures("async_environment")243@pytest.mark.anyio244async def test_async_too_many_redirects():245 async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client:246 with pytest.raises(httpx.TooManyRedirects):247 await client.get(
189 unmodified lines
437 client.post("https://example.org/redirect_custom_scheme", follow_redirects=True)438 assert str(e.value) == "Scheme 'market' not supported."439440441@pytest.mark.usefixtures("async_environment")441@pytest.mark.anyio442async def test_async_invalid_redirect():443 async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client:444 with pytest.raises(httpx.RemoteProtocolError):445 await client.get(
2 unmodified lines
modified:tests/models/test_requests.py+2 added-2 removed
84 unmodified lines
85 content = b"".join([part for part in request.stream])86 assert content == request.content878889@pytest.mark.asyncio89@pytest.mark.anyio90async def test_aread_and_stream_data():91 # Ensure a request may still be streamed if it has been read.92 # Needed for cases such as authentication classes that read the request body.93 request = httpx.Request("POST", "http://example.org", json={"test": 123})
97 unmodified lines
191 "content-length": "13",192 }193194195@pytest.mark.asyncio195@pytest.mark.anyio196async def test_request_async_streaming_content_picklable():197 async def streaming_body(data: bytes) -> typing.AsyncIterator[bytes]:198 yield data199
29 unmodified lines
modified:tests/models/test_responses.py+17 added-17 removed
329 unmodified lines
330 assert response.content == b""331 assert response.is_closed332333334@pytest.mark.asyncio334@pytest.mark.anyio335async def test_aread():336 response = httpx.Response(337 200,338 content=b"Hello, world!",
10 unmodified lines
349 assert response.content == b"Hello, world!"350 assert response.is_closed351352353@pytest.mark.asyncio353@pytest.mark.anyio354async def test_empty_aread():355 response = httpx.Response(200)356357 assert response.status_code == 200
90 unmodified lines
448 assert len(part) == (response.num_bytes_downloaded - num_downloaded)449 num_downloaded = response.num_bytes_downloaded450451452@pytest.mark.asyncio452@pytest.mark.anyio453async def test_aiter_raw():454 response = httpx.Response(200, content=async_streaming_body())455456 raw = b""
1 unmodified line
458 raw += part459 assert raw == b"Hello, world!"460461462@pytest.mark.asyncio462@pytest.mark.anyio463async def test_aiter_raw_with_chunksize():464 response = httpx.Response(200, content=async_streaming_body())465466 parts = [part async for part in response.aiter_raw(chunk_size=5)]
9 unmodified lines
476 parts = [part async for part in response.aiter_raw(chunk_size=20)]477 assert parts == [b"Hello, world!"]478479480@pytest.mark.asyncio480@pytest.mark.anyio481async def test_aiter_raw_on_sync():482 response = httpx.Response(483 200,484 content=streaming_body(),
2 unmodified lines
487 with pytest.raises(RuntimeError):488 [part async for part in response.aiter_raw()]489490491@pytest.mark.asyncio491@pytest.mark.anyio492async def test_aclose_on_sync():493 response = httpx.Response(494 200,495 content=streaming_body(),
2 unmodified lines
498 with pytest.raises(RuntimeError):499 await response.aclose()500501502@pytest.mark.asyncio502@pytest.mark.anyio503async def test_aiter_raw_increments_updates_counter():504 response = httpx.Response(200, content=async_streaming_body())505506 num_downloaded = response.num_bytes_downloaded
43 unmodified lines
550 parts = [part for part in response.iter_bytes()]551 assert parts == [b"Hello, ", b"world!"]552553554@pytest.mark.asyncio554@pytest.mark.anyio555async def test_aiter_bytes():556 response = httpx.Response(557 200,558 content=b"Hello, world!",
4 unmodified lines
563 content += part564 assert content == b"Hello, world!"565566567@pytest.mark.asyncio567@pytest.mark.anyio568async def test_aiter_bytes_with_chunk_size():569 response = httpx.Response(200, content=async_streaming_body())570 parts = [part async for part in response.aiter_bytes(chunk_size=5)]571 assert parts == [b"Hello", b", wor", b"ld!"]
32 unmodified lines
604 parts = [part for part in response.iter_text(chunk_size=20)]605 assert parts == ["Hello, world!"]606607608@pytest.mark.asyncio608@pytest.mark.anyio609async def test_aiter_text():610 response = httpx.Response(611 200,612 content=b"Hello, world!",
4 unmodified lines
617 content += part618 assert content == "Hello, world!"619620621@pytest.mark.asyncio621@pytest.mark.anyio622async def test_aiter_text_with_chunk_size():623 response = httpx.Response(200, content=b"Hello, world!")624 parts = [part async for part in response.aiter_text(chunk_size=5)]625 assert parts == ["Hello", ", wor", "ld!"]
15 unmodified lines
641 content = [line for line in response.iter_lines()]642 assert content == ["Hello,\n", "world!"]643644645@pytest.mark.asyncio645@pytest.mark.anyio646async def test_aiter_lines():647 response = httpx.Response(648 200,649 content=b"Hello,\nworld!",
20 unmodified lines
670 assert response.content == b"Hello, world!"671 assert response.is_closed672673674@pytest.mark.asyncio674@pytest.mark.anyio675async def test_async_streaming_response():676 response = httpx.Response(677 200,678 content=async_streaming_body(),
22 unmodified lines
701 with pytest.raises(httpx.StreamConsumed):702 response.read()703704705@pytest.mark.asyncio705@pytest.mark.anyio706async def test_cannot_aread_after_stream_consumed():707 response = httpx.Response(708 200,709 content=async_streaming_body(),
17 unmodified lines
727 with pytest.raises(httpx.StreamClosed):728 response.read()729730731@pytest.mark.asyncio731@pytest.mark.anyio732async def test_cannot_aread_after_response_closed():733 response = httpx.Response(734 200,735 content=async_streaming_body(),
3 unmodified lines
739 with pytest.raises(httpx.StreamClosed):740 await response.aread()741742743@pytest.mark.asyncio743@pytest.mark.anyio744async def test_elapsed_not_available_until_closed():745 response = httpx.Response(746 200,747 content=async_streaming_body(),
198 unmodified lines
946 assert pickle_response.extensions == {}947 assert pickle_response.history == []948949950@pytest.mark.asyncio950@pytest.mark.anyio951async def test_response_async_streaming_picklable():952 response = httpx.Response(200, content=async_streaming_body())953 pickle_response = pickle.loads(pickle.dumps(response))954 with pytest.raises(httpx.ResponseNotRead):
57 unmodified lines
modified:tests/conftest.py-24 removed
32 unmodified lines
33 "SSLKEYLOGFILE",34}353637@pytest.fixture(38 params=[39 pytest.param("asyncio", marks=pytest.mark.asyncio),40 pytest.param("trio", marks=pytest.mark.trio),41 ]42)43def async_environment(request: typing.Any) -> str:44 """45 Mark a test function to be run on both asyncio and trio.4647 Equivalent to having a pair of tests, each respectively marked with48 '@pytest.mark.asyncio' and '@pytest.mark.trio'.4950 Intended usage:5152 ```53 @pytest.mark.usefixtures("async_environment")54 async def my_async_test():55 ...56 ```57 """58 return typing.cast(str, request.param)596037@pytest.fixture(scope="function", autouse=True)38def clean_environ():39 """Keeps os.environ clean for every test without having to mock os.environ"""40 original_environ = os.environ.copy()
265 unmodified lines
modified:tests/test_asgi.py+10 added-10 removed
68 unmodified lines
69 await send({"type": "http.response.body", "body": output})70 raise RuntimeError()717273@pytest.mark.usefixtures("async_environment")73@pytest.mark.anyio74async def test_asgi_transport():75 async with httpx.ASGITransport(app=hello_world) as transport:76 request = httpx.Request("GET", "http://www.example.com/")77 response = await transport.handle_async_request(request)
1 unmodified line
79 assert response.status_code == 20080 assert response.content == b"Hello, World!"818283@pytest.mark.usefixtures("async_environment")83@pytest.mark.anyio84async def test_asgi_transport_no_body():85 async with httpx.ASGITransport(app=echo_body) as transport:86 request = httpx.Request("GET", "http://www.example.com/")87 response = await transport.handle_async_request(request)
1 unmodified line
89 assert response.status_code == 20090 assert response.content == b""919293@pytest.mark.usefixtures("async_environment")93@pytest.mark.anyio94async def test_asgi():95 async with httpx.AsyncClient(app=hello_world) as client:96 response = await client.get("http://www.example.org/")9798 assert response.status_code == 20099 assert response.text == "Hello, World!"100101102@pytest.mark.usefixtures("async_environment")102@pytest.mark.anyio103async def test_asgi_urlencoded_path():104 async with httpx.AsyncClient(app=echo_path) as client:105 url = httpx.URL("http://www.example.org/").copy_with(path="/user@example.org")106 response = await client.get(url)
1 unmodified line
108 assert response.status_code == 200109 assert response.json() == {"path": "/user@example.org"}110111112@pytest.mark.usefixtures("async_environment")112@pytest.mark.anyio113async def test_asgi_raw_path():114 async with httpx.AsyncClient(app=echo_raw_path) as client:115 url = httpx.URL("http://www.example.org/").copy_with(path="/user@example.org")116 response = await client.get(url)
1 unmodified line
118 assert response.status_code == 200119 assert response.json() == {"raw_path": "/user%40example.org"}120121122@pytest.mark.usefixtures("async_environment")122@pytest.mark.anyio123async def test_asgi_upload():124 async with httpx.AsyncClient(app=echo_body) as client:125 response = await client.post("http://www.example.org/", content=b"example")126127 assert response.status_code == 200128 assert response.text == "example"129130131@pytest.mark.usefixtures("async_environment")131@pytest.mark.anyio132async def test_asgi_headers():133 async with httpx.AsyncClient(app=echo_headers) as client:134 response = await client.get("http://www.example.org/")135
8 unmodified lines
144 ]145 }146147148@pytest.mark.usefixtures("async_environment")148@pytest.mark.anyio149async def test_asgi_exc():150 async with httpx.AsyncClient(app=raise_exc) as client:151 with pytest.raises(RuntimeError):152 await client.get("http://www.example.org/")153154155@pytest.mark.usefixtures("async_environment")155@pytest.mark.anyio156async def test_asgi_exc_after_response():157 async with httpx.AsyncClient(app=raise_exc_after_response) as client:158 with pytest.raises(RuntimeError):159 await client.get("http://www.example.org/")160161162@pytest.mark.usefixtures("async_environment")162@pytest.mark.anyio163async def test_asgi_disconnect_after_response_complete():164 disconnect = False165166 async def read_body(scope, receive, send):
27 unmodified lines
modified:tests/test_content.py+19 added-19 removed
7 unmodified lines
8method = "POST"9url = "https://www.example.com"101112@pytest.mark.asyncio12@pytest.mark.anyio13async def test_empty_content():14 request = httpx.Request(method, url)15 assert isinstance(request.stream, httpx.SyncByteStream)16 assert isinstance(request.stream, httpx.AsyncByteStream)
5 unmodified lines
22 assert sync_content == b""23 assert async_content == b""242526@pytest.mark.asyncio26@pytest.mark.anyio27async def test_bytes_content():28 request = httpx.Request(method, url, content=b"Hello, world!")29 assert isinstance(request.stream, typing.Iterable)30 assert isinstance(request.stream, typing.AsyncIterable)
18 unmodified lines
49 assert sync_content == b"Hello, world!"50 assert async_content == b"Hello, world!"515253@pytest.mark.asyncio53@pytest.mark.anyio54async def test_bytesio_content():55 request = httpx.Request(method, url, content=io.BytesIO(b"Hello, world!"))56 assert isinstance(request.stream, typing.Iterable)57 assert not isinstance(request.stream, typing.AsyncIterable)
3 unmodified lines
61 assert request.headers == {"Host": "www.example.com", "Content-Length": "13"}62 assert content == b"Hello, world!"636465@pytest.mark.asyncio65@pytest.mark.anyio66async def test_async_bytesio_content():67 class AsyncBytesIO:68 def __init__(self, content: bytes) -> None:69 self._idx = 0
19 unmodified lines
89 }90 assert content == b"Hello, world!"919293@pytest.mark.asyncio93@pytest.mark.anyio94async def test_iterator_content():95 def hello_world() -> typing.Iterator[bytes]:96 yield b"Hello, "97 yield b"world!"
27 unmodified lines
125 }126 assert content == b"Hello, world!"127128129@pytest.mark.asyncio129@pytest.mark.anyio130async def test_aiterator_content():131 async def hello_world() -> typing.AsyncIterator[bytes]:132 yield b"Hello, "133 yield b"world!"
27 unmodified lines
161 }162 assert content == b"Hello, world!"163164165@pytest.mark.asyncio165@pytest.mark.anyio166async def test_json_content():167 request = httpx.Request(method, url, json={"Hello": "world!"})168 assert isinstance(request.stream, typing.Iterable)169 assert isinstance(request.stream, typing.AsyncIterable)
9 unmodified lines
179 assert sync_content == b'{"Hello": "world!"}'180 assert async_content == b'{"Hello": "world!"}'181182183@pytest.mark.asyncio183@pytest.mark.anyio184async def test_urlencoded_content():185 request = httpx.Request(method, url, data={"Hello": "world!"})186 assert isinstance(request.stream, typing.Iterable)187 assert isinstance(request.stream, typing.AsyncIterable)
9 unmodified lines
197 assert sync_content == b"Hello=world%21"198 assert async_content == b"Hello=world%21"199200201@pytest.mark.asyncio201@pytest.mark.anyio202async def test_urlencoded_boolean():203 request = httpx.Request(method, url, data={"example": True})204 assert isinstance(request.stream, typing.Iterable)205 assert isinstance(request.stream, typing.AsyncIterable)
9 unmodified lines
215 assert sync_content == b"example=true"216 assert async_content == b"example=true"217218219@pytest.mark.asyncio219@pytest.mark.anyio220async def test_urlencoded_none():221 request = httpx.Request(method, url, data={"example": None})222 assert isinstance(request.stream, typing.Iterable)223 assert isinstance(request.stream, typing.AsyncIterable)
9 unmodified lines
233 assert sync_content == b"example="234 assert async_content == b"example="235236237@pytest.mark.asyncio237@pytest.mark.anyio238async def test_urlencoded_list():239 request = httpx.Request(method, url, data={"example": ["a", 1, True]})240 assert isinstance(request.stream, typing.Iterable)241 assert isinstance(request.stream, typing.AsyncIterable)
9 unmodified lines
251 assert sync_content == b"example=a&example=1&example=true"252 assert async_content == b"example=a&example=1&example=true"253254255@pytest.mark.asyncio255@pytest.mark.anyio256async def test_multipart_files_content():257 files = {"file": io.BytesIO(b"<file content>")}258 headers = {"Content-Type": "multipart/form-data; boundary=+++"}259 request = httpx.Request(
34 unmodified lines
294 ]295 )296297298@pytest.mark.asyncio298@pytest.mark.anyio299async def test_multipart_data_and_files_content():300 data = {"message": "Hello, world!"}301 files = {"file": io.BytesIO(b"<file content>")}302 headers = {"Content-Type": "multipart/form-data; boundary=+++"}
38 unmodified lines
341 ]342 )343344345@pytest.mark.asyncio345@pytest.mark.anyio346async def test_empty_request():347 request = httpx.Request(method, url, data={}, files={})348 assert isinstance(request.stream, typing.Iterable)349 assert isinstance(request.stream, typing.AsyncIterable)
13 unmodified lines
363 with pytest.raises(TypeError):364 httpx.Request(method, url, content={"a": "b"}) # type: ignore365366367@pytest.mark.asyncio367@pytest.mark.anyio368async def test_multipart_multiple_files_single_input_content():369 files = [370 ("file", io.BytesIO(b"<file content 1>")),371 ("file", io.BytesIO(b"<file content 2>")),
42 unmodified lines
414 ]415 )416417418@pytest.mark.asyncio418@pytest.mark.anyio419async def test_response_empty_content():420 response = httpx.Response(200)421 assert isinstance(response.stream, typing.Iterable)422 assert isinstance(response.stream, typing.AsyncIterable)
5 unmodified lines
428 assert sync_content == b""429 assert async_content == b""430431432@pytest.mark.asyncio432@pytest.mark.anyio433async def test_response_bytes_content():434 response = httpx.Response(200, content=b"Hello, world!")435 assert isinstance(response.stream, typing.Iterable)436 assert isinstance(response.stream, typing.AsyncIterable)
5 unmodified lines
442 assert sync_content == b"Hello, world!"443 assert async_content == b"Hello, world!"444445446@pytest.mark.asyncio446@pytest.mark.anyio447async def test_response_iterator_content():448 def hello_world() -> typing.Iterator[bytes]:449 yield b"Hello, "450 yield b"world!"
10 unmodified lines
461 with pytest.raises(httpx.StreamConsumed):462 [part for part in response.stream]463464465@pytest.mark.asyncio465@pytest.mark.anyio466async def test_response_aiterator_content():467 async def hello_world() -> typing.AsyncIterator[bytes]:468 yield b"Hello, "469 yield b"world!"
17 unmodified lines
modified:tests/test_decoders.py+3 added-3 removed
112 unmodified lines
113 )114 assert response.content == body115116117@pytest.mark.asyncio117@pytest.mark.anyio118async def test_streaming():119 body = b"test 123"120 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)121
50 unmodified lines
172 ((b"Euro character: \x88! abcdefghijklmnopqrstuvwxyz", b""), "cp1252"),173 ((b"Accented: \xd6sterreich abcdefghijklmnopqrstuvwxyz", b""), "iso-8859-1"),174 ],175)176@pytest.mark.asyncio176@pytest.mark.anyio177async def test_text_decoder_with_autodetect(data, encoding):178 async def iterator() -> typing.AsyncIterator[bytes]:179 nonlocal data180 for chunk in data:
14 unmodified lines
195 text = "".join([part async for part in response.aiter_text()])196 assert text == (b"".join(data)).decode(encoding)197198199@pytest.mark.asyncio199@pytest.mark.anyio200async def test_text_decoder_known_encoding():201 async def iterator() -> typing.AsyncIterator[bytes]:202 yield b"\x83g"203 yield b"\x83"
144 unmodified lines
modified:tests/test_timeouts.py+4 added-4 removed
1 unmodified line
23import httpx456@pytest.mark.usefixtures("async_environment")6@pytest.mark.anyio7async def test_read_timeout(server):8 timeout = httpx.Timeout(None, read=1e-6)910 async with httpx.AsyncClient(timeout=timeout) as client:11 with pytest.raises(httpx.ReadTimeout):12 await client.get(server.url.copy_with(path="/slow_response"))131415@pytest.mark.usefixtures("async_environment")15@pytest.mark.anyio16async def test_write_timeout(server):17 timeout = httpx.Timeout(None, write=1e-6)1819 async with httpx.AsyncClient(timeout=timeout) as client:
1 unmodified line
21 data = b"*" * 1024 * 1024 * 10022 await client.put(server.url.copy_with(path="/slow_response"), content=data)232425@pytest.mark.usefixtures("async_environment")25@pytest.mark.anyio26@pytest.mark.network27async def test_connect_timeout(server):28 timeout = httpx.Timeout(None, connect=1e-6)29
2 unmodified lines
32 # See https://stackoverflow.com/questions/100841/33 await client.get("http://10.255.255.1/")343536@pytest.mark.usefixtures("async_environment")36@pytest.mark.anyio37async def test_pool_timeout(server):38 limits = httpx.Limits(max_connections=1)39 timeout = httpx.Timeout(None, pool=1e-4)40
4 unmodified lines
modified:tests/test_utils.py+3 added-3 removed
96 unmodified lines
97def test_parse_header_links(value, expected):98 assert parse_header_links(value) == expected99100101@pytest.mark.asyncio101@pytest.mark.anyio102async def test_logs_debug(server, capsys):103 with override_log_level("debug"):104 async with httpx.AsyncClient() as client:105 response = await client.get(server.url)
1 unmodified line
107 stderr = capsys.readouterr().err108 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr109110111@pytest.mark.asyncio111@pytest.mark.anyio112async def test_logs_trace(server, capsys):113 with override_log_level("trace"):114 async with httpx.AsyncClient() as client:115 response = await client.get(server.url)
1 unmodified line
117 stderr = capsys.readouterr().err118 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr119120121@pytest.mark.asyncio121@pytest.mark.anyio122async def test_logs_redirect_chain(server, capsys):123 with override_log_level("debug"):124 async with httpx.AsyncClient(follow_redirects=True) as client:125 response = await client.get(server.url.copy_with(path="/redirect_301"))
153 unmodified lines
modified:requirements.txt-2 removed
29 unmodified lines
30isort==5.11.431mypy==0.98232types-certifi==2021.10.8.233pytest==7.2.034pytest-asyncio==0.20.335pytest-trio==0.7.034trio==0.21.035trio-typing==0.7.036trustme==0.9.037uvicorn==0.20.0
modified:setup.cfg+1 added-1 removed
16 unmodified lines
17[tool:pytest]18addopts = -rxXs19filterwarnings =20 error21asyncio_mode = strict21 ignore: You seem to already have a custom sys.excepthook handler installed. I'll skip installing Trio's custom handler, but this means MultiErrors will not show full tracebacks.:RuntimeWarning22markers =23 copied_from(source, changes=None): mark test as copied from somewhere else, along with a description of changes made to accodomate e.g. our test setup24 network: marks tests which require network connection. Used in 3rd-party build environments that have network disabled.25
3 unmodified lines