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
Provenance
- Commit
e27d1b8- Tree
28985ca- Author
Thomas Grainger <tagrain@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
e4438a3
15 files changed+120 added−146 removed
modified:tests/client/test_async_client.py+24 added-24 removed
4 unmodified lines5 6 import httpx7 8 9-@pytest.mark.usefixtures("async_environment")9+@pytest.mark.anyio10 async def test_get(server):11 url = server.url12 async with httpx.AsyncClient(http2=True) as client:13 response = await client.get(url)12 unmodified lines26 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.anyio31 async 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)35 36 37-@pytest.mark.usefixtures("async_environment")37+@pytest.mark.anyio38 async 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 lines48 49 assert response.json()["Custom-header"] == "value"50 51 52-@pytest.mark.usefixtures("async_environment")52+@pytest.mark.anyio53 async 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 == 20058 59 60-@pytest.mark.usefixtures("async_environment")60+@pytest.mark.anyio61 async 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 == 20066 67 68-@pytest.mark.usefixtures("async_environment")68+@pytest.mark.anyio69 async 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 lines75 assert body == b"Hello, world!"76 assert response.content == b"Hello, world!"77 78 79-@pytest.mark.usefixtures("async_environment")79+@pytest.mark.anyio80 async 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 pass2 unmodified lines86 with pytest.raises(httpx.ResponseNotRead):87 response.content88 89 90-@pytest.mark.usefixtures("async_environment")90+@pytest.mark.anyio91 async def test_stream_request(server):92 async def hello_world() -> typing.AsyncIterator[bytes]:93 yield b"Hello, "94 yield b"world!"2 unmodified lines97 response = await client.post(server.url, content=hello_world())98 assert response.status_code == 20099 100 101-@pytest.mark.usefixtures("async_environment")101+@pytest.mark.anyio102 async 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 lines108 with pytest.raises(RuntimeError):109 await client.post(server.url, content=hello_world())110 111 112-@pytest.mark.usefixtures("async_environment")112+@pytest.mark.anyio113 async 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 lines124 else:125 assert response.raise_for_status() is None # type: ignore126 127 128-@pytest.mark.usefixtures("async_environment")128+@pytest.mark.anyio129 async 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!"134 135 136-@pytest.mark.usefixtures("async_environment")136+@pytest.mark.anyio137 async 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 == ""142 143 144-@pytest.mark.usefixtures("async_environment")144+@pytest.mark.anyio145 async 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 == 200149 150 151-@pytest.mark.usefixtures("async_environment")151+@pytest.mark.anyio152 async 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 == 200156 157 158-@pytest.mark.usefixtures("async_environment")158+@pytest.mark.anyio159 async 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!"164 165 166-@pytest.mark.usefixtures("async_environment")166+@pytest.mark.anyio167 async def test_100_continue(server):168 headers = {"Expect": "100-continue"}169 content = b"Echo request body"170 5 unmodified lines176 assert response.status_code == 200177 assert response.content == content178 179 180-@pytest.mark.usefixtures("async_environment")180+@pytest.mark.anyio181 async def test_context_managed_transport():182 class Transport(httpx.AsyncBaseTransport):183 def __init__(self) -> None:184 self.events: typing.List[str] = []23 unmodified lines208 "transport.__aexit__",209 ]210 211 212-@pytest.mark.usefixtures("async_environment")212+@pytest.mark.anyio213 async def test_context_managed_transport_and_mount():214 class Transport(httpx.AsyncBaseTransport):215 def __init__(self, name: str):216 self.name: str = name36 unmodified lines253 def hello_world(request):254 return httpx.Response(200, text="Hello, world!")255 256 257-@pytest.mark.usefixtures("async_environment")257+@pytest.mark.anyio258 async def test_client_closed_state_using_implicit_open():259 client = httpx.AsyncClient(transport=httpx.MockTransport(hello_world))260 261 assert not client.is_closed12 unmodified lines274 async with client:275 pass # pragma: no cover276 277 278-@pytest.mark.usefixtures("async_environment")278+@pytest.mark.anyio279 async 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 lines295 data = {"app": "mounted"}296 return httpx.Response(200, json=data)297 298 299-@pytest.mark.usefixtures("async_environment")299+@pytest.mark.anyio300 async def test_mounted_transport():301 transport = httpx.MockTransport(unmounted)302 mounts = {"custom://": httpx.MockTransport(mounted)}303 6 unmodified lines310 assert response.status_code == 200311 assert response.json() == {"app": "mounted"}312 313 314-@pytest.mark.usefixtures("async_environment")314+@pytest.mark.anyio315 async def test_async_mock_transport():316 async def hello_world(request):317 return httpx.Response(200, text="Hello, world!")318 4 unmodified lines323 assert response.status_code == 200324 assert response.text == "Hello, world!"325 326 327-@pytest.mark.usefixtures("async_environment")327+@pytest.mark.anyio328 async def test_cancellation_during_stream():329 """330 If any BaseException is raised during streaming the response, then the331 stream should be closed.31 unmodified lines363 await client.get("https://www.example.com")364 assert stream_was_closed365 366 367-@pytest.mark.usefixtures("async_environment")367+@pytest.mark.anyio368 async 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 linesmodified:tests/client/test_auth.py+30 added-30 removed
1 unmodified line2 Integration tests for authentication.3 4 Unit tests for auth classes also exist in tests/test_auth.py5 """6-import asyncio6 import hashlib7 import os8 import threading9 import typing10 from urllib.request import parse_keqv_list11 12+import anyio13 import pytest14 15 import httpx16 117 unmodified lines134 """135 136 def __init__(self) -> None:137 self._lock = threading.Lock()138- self._async_lock = asyncio.Lock()138+ self._async_lock = anyio.Lock()139 140 def sync_auth_flow(141 self, request: httpx.Request142 ) -> typing.Generator[httpx.Request, httpx.Response, None]:8 unmodified lines151 request.headers["Authorization"] = "async-auth"152 yield request153 154 155-@pytest.mark.asyncio155+@pytest.mark.anyio156 async def test_basic_auth() -> None:157 url = "https://example.org/"158 auth = ("user", "password123")159 app = App()4 unmodified lines164 assert response.status_code == 200165 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}166 167 168-@pytest.mark.asyncio168+@pytest.mark.anyio169 async def test_basic_auth_with_stream() -> None:170 """171 See: https://github.com/encode/httpx/pull/1312172 """10 unmodified lines183 assert response.status_code == 200184 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}185 186 187-@pytest.mark.asyncio187+@pytest.mark.anyio188 async def test_basic_auth_in_url() -> None:189 url = "https://user:password123@example.org/"190 app = App()191 3 unmodified lines195 assert response.status_code == 200196 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}197 198 199-@pytest.mark.asyncio199+@pytest.mark.anyio200 async def test_basic_auth_on_session() -> None:201 url = "https://example.org/"202 auth = ("user", "password123")203 app = App()6 unmodified lines210 assert response.status_code == 200211 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}212 213 214-@pytest.mark.asyncio214+@pytest.mark.anyio215 async def test_custom_auth() -> None:216 url = "https://example.org/"217 app = App()218 7 unmodified lines226 assert response.status_code == 200227 assert response.json() == {"auth": "Token 123"}228 229 230-@pytest.mark.asyncio230+@pytest.mark.anyio231 async def test_netrc_auth() -> None:232 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")233 url = "http://netrcexample.org"234 app = App()6 unmodified lines241 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"242 }243 244 245-@pytest.mark.asyncio245+@pytest.mark.anyio246 async 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 lines254 assert response.status_code == 200255 assert response.json() == {"auth": "Override"}256 257 258-@pytest.mark.asyncio258+@pytest.mark.anyio259 async def test_trust_env_auth() -> None:260 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")261 url = "http://netrcexample.org"262 app = App()16 unmodified lines279 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"280 }281 282 283-@pytest.mark.asyncio283+@pytest.mark.anyio284 async def test_auth_disable_per_request() -> None:285 url = "https://example.org/"286 auth = ("user", "password123")287 app = App()13 unmodified lines301 assert url == httpx.URL(url)302 assert expected == repr(httpx.URL(url))303 304 305-@pytest.mark.asyncio305+@pytest.mark.anyio306 async def test_auth_hidden_header() -> None:307 url = "https://example.org/"308 auth = ("example-username", "example-password")309 app = App()3 unmodified lines313 314 assert "'authorization': '[secure]'" in str(response.request.headers)315 316 317-@pytest.mark.asyncio317+@pytest.mark.anyio318 async def test_auth_property() -> None:319 app = App()320 321 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:7 unmodified lines329 assert response.status_code == 200330 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}331 332 333-@pytest.mark.asyncio333+@pytest.mark.anyio334 async def test_auth_invalid_type() -> None:335 app = App()336 337 with pytest.raises(TypeError):9 unmodified lines347 with pytest.raises(TypeError):348 client.auth = "not a tuple, not a callable" # type: ignore349 350 351-@pytest.mark.asyncio351+@pytest.mark.anyio352 async 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 lines375 assert response.json() == {"auth": None}376 assert len(response.history) == 0377 378 379-@pytest.mark.asyncio379+@pytest.mark.anyio380 async 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 lines390 assert response.json() == {"auth": None}391 assert len(response.history) == 0392 393 394-@pytest.mark.asyncio394+@pytest.mark.anyio395 async 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 lines417 ("SHA-512", 64, 128),418 ("SHA-512-SESS", 64, 128),419 ],420 )421-@pytest.mark.asyncio421+@pytest.mark.anyio422 async def test_digest_auth(423 algorithm: str, expected_hash_length: int, expected_response_length: int424 ) -> None:425 url = "https://example.org/"24 unmodified lines450 assert digest_data["nc"] == "00000001"451 assert len(digest_data["cnonce"]) == 16 + 2452 453 454-@pytest.mark.asyncio454+@pytest.mark.anyio455 async 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 lines482 assert digest_data["algorithm"] == "SHA-256"483 484 485 @pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))486-@pytest.mark.asyncio486+@pytest.mark.anyio487 async 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 lines495 assert response.status_code == 200496 assert len(response.history) == 1497 498 499-@pytest.mark.asyncio499+@pytest.mark.anyio500 async 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 lines506 with pytest.raises(NotImplementedError):507 await client.get(url, auth=auth)508 509 510-@pytest.mark.asyncio510+@pytest.mark.anyio511 async 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 lines517 with pytest.raises(httpx.ProtocolError):518 await client.get(url, auth=auth)519 520 521-@pytest.mark.asyncio521+@pytest.mark.anyio522 async 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 lines530 assert response.status_code == 401531 assert len(response.history) == 1532 533 534-@pytest.mark.asyncio534+@pytest.mark.anyio535 async 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 lines547 assert len(response_1.history) == 1548 assert len(response_2.history) == 0549 550 551-@pytest.mark.asyncio551+@pytest.mark.anyio552 async 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 lines593 '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.anyio598 async def test_async_digest_auth_raises_protocol_error_on_malformed_header(599 auth_header: str,600 ) -> None:601 url = "https://example.org/"23 unmodified lines625 with pytest.raises(httpx.ProtocolError):626 client.get(url, auth=auth)627 628 629-@pytest.mark.asyncio629+@pytest.mark.anyio630 async 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 lines685 [_ async for _ in request.stream]686 return self.handler(request)687 688 689-@pytest.mark.asyncio689+@pytest.mark.anyio690 async 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 lines699 with pytest.raises(httpx.StreamConsumed):700 await client.post(url, content=streaming_body(), auth=auth)701 702 703-@pytest.mark.asyncio703+@pytest.mark.anyio704 async 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 lines732 assert response.status_code == 200733 assert response.json() == {"auth": '{"auth": "xyz"}'}734 735 736-@pytest.mark.asyncio736+@pytest.mark.anyio737 async 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 (such26 unmodified linesmodified:tests/client/test_event_hooks.py+3 added-3 removed
61 unmodified lines62 except httpx.HTTPStatusError as exc:63 assert exc.response.is_closed64 65 66-@pytest.mark.usefixtures("async_environment")66+@pytest.mark.anyio67 async def test_async_event_hooks():68 events = []69 70 async def on_request(request):27 unmodified lines98 },99 ]100 101 102-@pytest.mark.usefixtures("async_environment")102+@pytest.mark.anyio103 async def test_async_event_hooks_raising_exception():104 async def raise_on_4xx_5xx(response):105 response.raise_for_status()106 63 unmodified lines170 },171 ]172 173 174-@pytest.mark.usefixtures("async_environment")174+@pytest.mark.anyio175 async def test_async_event_hooks_with_redirect():176 """177 A redirect request should trigger additional 'request' and 'response' event hooks.178 """50 unmodified linesmodified:tests/client/test_proxies.py+1 added-1 removed
130 unmodified lines131 assert isinstance(transport._pool, httpcore.HTTPProxy)132 assert transport._pool._proxy_url == url_to_origin(expected)133 134 135-@pytest.mark.asyncio135+@pytest.mark.anyio136 @pytest.mark.network137 async def test_async_proxy_close():138 try:139 client = httpx.AsyncClient(proxies={"https://": PROXY_URL})147 unmodified linesmodified:tests/client/test_redirects.py+3 added-3 removed
149 unmodified lines150 assert response.url == "https://example.org/"151 assert response.next_request is None152 153 154-@pytest.mark.usefixtures("async_environment")154+@pytest.mark.anyio155 async 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 lines239 assert len(response.history[0].history) == 0240 assert len(response.history[1].history) == 1241 242 243-@pytest.mark.usefixtures("async_environment")243+@pytest.mark.anyio244 async 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 lines437 client.post("https://example.org/redirect_custom_scheme", follow_redirects=True)438 assert str(e.value) == "Scheme 'market' not supported."439 440 441-@pytest.mark.usefixtures("async_environment")441+@pytest.mark.anyio442 async 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 linesmodified:tests/models/test_requests.py+2 added-2 removed
84 unmodified lines85 content = b"".join([part for part in request.stream])86 assert content == request.content87 88 89-@pytest.mark.asyncio89+@pytest.mark.anyio90 async 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 lines191 "content-length": "13",192 }193 194 195-@pytest.mark.asyncio195+@pytest.mark.anyio196 async def test_request_async_streaming_content_picklable():197 async def streaming_body(data: bytes) -> typing.AsyncIterator[bytes]:198 yield data199 29 unmodified linesmodified:tests/models/test_responses.py+17 added-17 removed
329 unmodified lines330 assert response.content == b""331 assert response.is_closed332 333 334-@pytest.mark.asyncio334+@pytest.mark.anyio335 async def test_aread():336 response = httpx.Response(337 200,338 content=b"Hello, world!",10 unmodified lines349 assert response.content == b"Hello, world!"350 assert response.is_closed351 352 353-@pytest.mark.asyncio353+@pytest.mark.anyio354 async def test_empty_aread():355 response = httpx.Response(200)356 357 assert response.status_code == 20090 unmodified lines448 assert len(part) == (response.num_bytes_downloaded - num_downloaded)449 num_downloaded = response.num_bytes_downloaded450 451 452-@pytest.mark.asyncio452+@pytest.mark.anyio453 async def test_aiter_raw():454 response = httpx.Response(200, content=async_streaming_body())455 456 raw = b""1 unmodified line458 raw += part459 assert raw == b"Hello, world!"460 461 462-@pytest.mark.asyncio462+@pytest.mark.anyio463 async def test_aiter_raw_with_chunksize():464 response = httpx.Response(200, content=async_streaming_body())465 466 parts = [part async for part in response.aiter_raw(chunk_size=5)]9 unmodified lines476 parts = [part async for part in response.aiter_raw(chunk_size=20)]477 assert parts == [b"Hello, world!"]478 479 480-@pytest.mark.asyncio480+@pytest.mark.anyio481 async def test_aiter_raw_on_sync():482 response = httpx.Response(483 200,484 content=streaming_body(),2 unmodified lines487 with pytest.raises(RuntimeError):488 [part async for part in response.aiter_raw()]489 490 491-@pytest.mark.asyncio491+@pytest.mark.anyio492 async def test_aclose_on_sync():493 response = httpx.Response(494 200,495 content=streaming_body(),2 unmodified lines498 with pytest.raises(RuntimeError):499 await response.aclose()500 501 502-@pytest.mark.asyncio502+@pytest.mark.anyio503 async def test_aiter_raw_increments_updates_counter():504 response = httpx.Response(200, content=async_streaming_body())505 506 num_downloaded = response.num_bytes_downloaded43 unmodified lines550 parts = [part for part in response.iter_bytes()]551 assert parts == [b"Hello, ", b"world!"]552 553 554-@pytest.mark.asyncio554+@pytest.mark.anyio555 async def test_aiter_bytes():556 response = httpx.Response(557 200,558 content=b"Hello, world!",4 unmodified lines563 content += part564 assert content == b"Hello, world!"565 566 567-@pytest.mark.asyncio567+@pytest.mark.anyio568 async 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 lines604 parts = [part for part in response.iter_text(chunk_size=20)]605 assert parts == ["Hello, world!"]606 607 608-@pytest.mark.asyncio608+@pytest.mark.anyio609 async def test_aiter_text():610 response = httpx.Response(611 200,612 content=b"Hello, world!",4 unmodified lines617 content += part618 assert content == "Hello, world!"619 620 621-@pytest.mark.asyncio621+@pytest.mark.anyio622 async 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 lines641 content = [line for line in response.iter_lines()]642 assert content == ["Hello,\n", "world!"]643 644 645-@pytest.mark.asyncio645+@pytest.mark.anyio646 async def test_aiter_lines():647 response = httpx.Response(648 200,649 content=b"Hello,\nworld!",20 unmodified lines670 assert response.content == b"Hello, world!"671 assert response.is_closed672 673 674-@pytest.mark.asyncio674+@pytest.mark.anyio675 async def test_async_streaming_response():676 response = httpx.Response(677 200,678 content=async_streaming_body(),22 unmodified lines701 with pytest.raises(httpx.StreamConsumed):702 response.read()703 704 705-@pytest.mark.asyncio705+@pytest.mark.anyio706 async def test_cannot_aread_after_stream_consumed():707 response = httpx.Response(708 200,709 content=async_streaming_body(),17 unmodified lines727 with pytest.raises(httpx.StreamClosed):728 response.read()729 730 731-@pytest.mark.asyncio731+@pytest.mark.anyio732 async def test_cannot_aread_after_response_closed():733 response = httpx.Response(734 200,735 content=async_streaming_body(),3 unmodified lines739 with pytest.raises(httpx.StreamClosed):740 await response.aread()741 742 743-@pytest.mark.asyncio743+@pytest.mark.anyio744 async def test_elapsed_not_available_until_closed():745 response = httpx.Response(746 200,747 content=async_streaming_body(),198 unmodified lines946 assert pickle_response.extensions == {}947 assert pickle_response.history == []948 949 950-@pytest.mark.asyncio950+@pytest.mark.anyio951 async 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 linesmodified:tests/conftest.py-24 removed
32 unmodified lines33 "SSLKEYLOGFILE",34 }35 36 37-@pytest.fixture(38- params=[39- pytest.param("asyncio", marks=pytest.mark.asyncio),40- pytest.param("trio", marks=pytest.mark.trio),41- ]42-)43-def async_environment(request: typing.Any) -> str:44- """45- Mark a test function to be run on both asyncio and trio.46-47- Equivalent to having a pair of tests, each respectively marked with48- '@pytest.mark.asyncio' and '@pytest.mark.trio'.49-50- Intended usage:51-52- ```53- @pytest.mark.usefixtures("async_environment")54- async def my_async_test():55- ...56- ```57- """58- return typing.cast(str, request.param)59-60-37 @pytest.fixture(scope="function", autouse=True)38 def clean_environ():39 """Keeps os.environ clean for every test without having to mock os.environ"""40 original_environ = os.environ.copy()265 unmodified linesmodified:tests/test_asgi.py+10 added-10 removed
68 unmodified lines69 await send({"type": "http.response.body", "body": output})70 raise RuntimeError()71 72 73-@pytest.mark.usefixtures("async_environment")73+@pytest.mark.anyio74 async 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 line79 assert response.status_code == 20080 assert response.content == b"Hello, World!"81 82 83-@pytest.mark.usefixtures("async_environment")83+@pytest.mark.anyio84 async 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 line89 assert response.status_code == 20090 assert response.content == b""91 92 93-@pytest.mark.usefixtures("async_environment")93+@pytest.mark.anyio94 async def test_asgi():95 async with httpx.AsyncClient(app=hello_world) as client:96 response = await client.get("http://www.example.org/")97 98 assert response.status_code == 20099 assert response.text == "Hello, World!"100 101 102-@pytest.mark.usefixtures("async_environment")102+@pytest.mark.anyio103 async 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 line108 assert response.status_code == 200109 assert response.json() == {"path": "/user@example.org"}110 111 112-@pytest.mark.usefixtures("async_environment")112+@pytest.mark.anyio113 async 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 line118 assert response.status_code == 200119 assert response.json() == {"raw_path": "/user%40example.org"}120 121 122-@pytest.mark.usefixtures("async_environment")122+@pytest.mark.anyio123 async 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")126 127 assert response.status_code == 200128 assert response.text == "example"129 130 131-@pytest.mark.usefixtures("async_environment")131+@pytest.mark.anyio132 async 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 lines144 ]145 }146 147 148-@pytest.mark.usefixtures("async_environment")148+@pytest.mark.anyio149 async 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/")153 154 155-@pytest.mark.usefixtures("async_environment")155+@pytest.mark.anyio156 async 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/")160 161 162-@pytest.mark.usefixtures("async_environment")162+@pytest.mark.anyio163 async def test_asgi_disconnect_after_response_complete():164 disconnect = False165 166 async def read_body(scope, receive, send):27 unmodified linesmodified:tests/test_content.py+19 added-19 removed
7 unmodified lines8 method = "POST"9 url = "https://www.example.com"10 11 12-@pytest.mark.asyncio12+@pytest.mark.anyio13 async 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 lines22 assert sync_content == b""23 assert async_content == b""24 25 26-@pytest.mark.asyncio26+@pytest.mark.anyio27 async 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 lines49 assert sync_content == b"Hello, world!"50 assert async_content == b"Hello, world!"51 52 53-@pytest.mark.asyncio53+@pytest.mark.anyio54 async 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 lines61 assert request.headers == {"Host": "www.example.com", "Content-Length": "13"}62 assert content == b"Hello, world!"63 64 65-@pytest.mark.asyncio65+@pytest.mark.anyio66 async def test_async_bytesio_content():67 class AsyncBytesIO:68 def __init__(self, content: bytes) -> None:69 self._idx = 019 unmodified lines89 }90 assert content == b"Hello, world!"91 92 93-@pytest.mark.asyncio93+@pytest.mark.anyio94 async def test_iterator_content():95 def hello_world() -> typing.Iterator[bytes]:96 yield b"Hello, "97 yield b"world!"27 unmodified lines125 }126 assert content == b"Hello, world!"127 128 129-@pytest.mark.asyncio129+@pytest.mark.anyio130 async def test_aiterator_content():131 async def hello_world() -> typing.AsyncIterator[bytes]:132 yield b"Hello, "133 yield b"world!"27 unmodified lines161 }162 assert content == b"Hello, world!"163 164 165-@pytest.mark.asyncio165+@pytest.mark.anyio166 async 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 lines179 assert sync_content == b'{"Hello": "world!"}'180 assert async_content == b'{"Hello": "world!"}'181 182 183-@pytest.mark.asyncio183+@pytest.mark.anyio184 async 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 lines197 assert sync_content == b"Hello=world%21"198 assert async_content == b"Hello=world%21"199 200 201-@pytest.mark.asyncio201+@pytest.mark.anyio202 async 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 lines215 assert sync_content == b"example=true"216 assert async_content == b"example=true"217 218 219-@pytest.mark.asyncio219+@pytest.mark.anyio220 async 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 lines233 assert sync_content == b"example="234 assert async_content == b"example="235 236 237-@pytest.mark.asyncio237+@pytest.mark.anyio238 async 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 lines251 assert sync_content == b"example=a&example=1&example=true"252 assert async_content == b"example=a&example=1&example=true"253 254 255-@pytest.mark.asyncio255+@pytest.mark.anyio256 async 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 lines294 ]295 )296 297 298-@pytest.mark.asyncio298+@pytest.mark.anyio299 async 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 lines341 ]342 )343 344 345-@pytest.mark.asyncio345+@pytest.mark.anyio346 async 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 lines363 with pytest.raises(TypeError):364 httpx.Request(method, url, content={"a": "b"}) # type: ignore365 366 367-@pytest.mark.asyncio367+@pytest.mark.anyio368 async 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 lines414 ]415 )416 417 418-@pytest.mark.asyncio418+@pytest.mark.anyio419 async 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 lines428 assert sync_content == b""429 assert async_content == b""430 431 432-@pytest.mark.asyncio432+@pytest.mark.anyio433 async 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 lines442 assert sync_content == b"Hello, world!"443 assert async_content == b"Hello, world!"444 445 446-@pytest.mark.asyncio446+@pytest.mark.anyio447 async def test_response_iterator_content():448 def hello_world() -> typing.Iterator[bytes]:449 yield b"Hello, "450 yield b"world!"10 unmodified lines461 with pytest.raises(httpx.StreamConsumed):462 [part for part in response.stream]463 464 465-@pytest.mark.asyncio465+@pytest.mark.anyio466 async def test_response_aiterator_content():467 async def hello_world() -> typing.AsyncIterator[bytes]:468 yield b"Hello, "469 yield b"world!"17 unmodified linesmodified:tests/test_decoders.py+3 added-3 removed
112 unmodified lines113 )114 assert response.content == body115 116 117-@pytest.mark.asyncio117+@pytest.mark.anyio118 async def test_streaming():119 body = b"test 123"120 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)121 50 unmodified lines172 ((b"Euro character: \x88! abcdefghijklmnopqrstuvwxyz", b""), "cp1252"),173 ((b"Accented: \xd6sterreich abcdefghijklmnopqrstuvwxyz", b""), "iso-8859-1"),174 ],175 )176-@pytest.mark.asyncio176+@pytest.mark.anyio177 async def test_text_decoder_with_autodetect(data, encoding):178 async def iterator() -> typing.AsyncIterator[bytes]:179 nonlocal data180 for chunk in data:14 unmodified lines195 text = "".join([part async for part in response.aiter_text()])196 assert text == (b"".join(data)).decode(encoding)197 198 199-@pytest.mark.asyncio199+@pytest.mark.anyio200 async def test_text_decoder_known_encoding():201 async def iterator() -> typing.AsyncIterator[bytes]:202 yield b"\x83g"203 yield b"\x83"144 unmodified linesmodified:tests/test_timeouts.py+4 added-4 removed
1 unmodified line2 3 import httpx4 5 6-@pytest.mark.usefixtures("async_environment")6+@pytest.mark.anyio7 async def test_read_timeout(server):8 timeout = httpx.Timeout(None, read=1e-6)9 10 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"))13 14 15-@pytest.mark.usefixtures("async_environment")15+@pytest.mark.anyio16 async def test_write_timeout(server):17 timeout = httpx.Timeout(None, write=1e-6)18 19 async with httpx.AsyncClient(timeout=timeout) as client:1 unmodified line21 data = b"*" * 1024 * 1024 * 10022 await client.put(server.url.copy_with(path="/slow_response"), content=data)23 24 25-@pytest.mark.usefixtures("async_environment")25+@pytest.mark.anyio26 @pytest.mark.network27 async def test_connect_timeout(server):28 timeout = httpx.Timeout(None, connect=1e-6)29 2 unmodified lines32 # See https://stackoverflow.com/questions/100841/33 await client.get("http://10.255.255.1/")34 35 36-@pytest.mark.usefixtures("async_environment")36+@pytest.mark.anyio37 async def test_pool_timeout(server):38 limits = httpx.Limits(max_connections=1)39 timeout = httpx.Timeout(None, pool=1e-4)40 4 unmodified linesmodified:tests/test_utils.py+3 added-3 removed
96 unmodified lines97 def test_parse_header_links(value, expected):98 assert parse_header_links(value) == expected99 100 101-@pytest.mark.asyncio101+@pytest.mark.anyio102 async 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 line107 stderr = capsys.readouterr().err108 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr109 110 111-@pytest.mark.asyncio111+@pytest.mark.anyio112 async 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 line117 stderr = capsys.readouterr().err118 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr119 120 121-@pytest.mark.asyncio121+@pytest.mark.anyio122 async 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 linesmodified:requirements.txt-2 removed
29 unmodified lines30 isort==5.11.431 mypy==0.98232 types-certifi==2021.10.8.233 pytest==7.2.034-pytest-asyncio==0.20.335-pytest-trio==0.7.034 trio==0.21.035 trio-typing==0.7.036 trustme==0.9.037 uvicorn==0.20.0modified:setup.cfg+1 added-1 removed
16 unmodified lines17 [tool:pytest]18 addopts = -rxXs19 filterwarnings =20 error21-asyncio_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.:RuntimeWarning22 markers =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