Parametrize tests with concurrency backend (#273)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Parametrize tests with concurrency backend * Refactor server restart * Add no-backend test
authored by Florimond Manca · committed by GitHub · parent 1872ae8 · Browse files · 12 files·+207 added−201 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+207 added−201 removed
- tests:+196 added−195 removed
- other:+11 added−6 removed
Provenance
- Commit
3674058- Tree
8b390c0- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
1872ae8
12 files changed+207 added−201 removed
modified:httpx/client.py+11 added-6 removed
631 unmodified lines632 # This is relatively cheap on asyncio, but cannot be guaranteed for all633 # concurrency backends.634 # The sync client performs I/O on its own, so it doesn't need to support635 # arbitrary concurrency backends.636- # Therefore, we kept the `backend` parameter (for testing/mocking), but enforce637- # that the concurrency backend derives from the asyncio one.638- if not isinstance(backend, AsyncioBackend):639- raise ValueError(640- "'Client' only supports asyncio-based concurrency backends"641- )636+ # Therefore, we keep the `backend` parameter (for testing/mocking), but require637+ # that the concurrency backend relies on asyncio.638 639+ if isinstance(backend, AsyncioBackend):640+ return641+642+ if hasattr(backend, "loop"):643+ # Most likely a proxy class.644+ return645+646+ raise ValueError("'Client' only supports asyncio-based concurrency backends")647+648 def _async_request_data(649 self, data: RequestData = None650 ) -> typing.Optional[AsyncRequestData]:651 """341 unmodified linesmodified:tests/client/test_async_client.py+39 added-37 removed
1 unmodified line2 3 import httpx4 5 6-@pytest.mark.asyncio7-async def test_get(server):6+async def test_get(server, backend):7 url = "http://127.0.0.1:8000/"9- async with httpx.AsyncClient() as client:8+ async with httpx.AsyncClient(backend=backend) as client:9 response = await client.get(url)10 assert response.status_code == 20011 assert response.text == "Hello, world!"12 assert response.http_version == "HTTP/1.1"1 unmodified line14 assert repr(response) == "<Response [200 OK]>"15 16 17 @pytest.mark.asyncio19-async def test_post(server):18+async def test_get_no_backend(server):19+ """20+ Verify that the client is capable of making a simple request if not given a backend.21+ """22 url = "http://127.0.0.1:8000/"23 async with httpx.AsyncClient() as client:24+ response = await client.get(url)25+ assert response.status_code == 20026+ assert response.text == "Hello, world!"27+ assert response.http_version == "HTTP/1.1"28+ assert response.headers29+ assert repr(response) == "<Response [200 OK]>"30+31+32+async def test_post(server, backend):33+ url = "http://127.0.0.1:8000/"34+ async with httpx.AsyncClient(backend=backend) as client:35 response = await client.post(url, data=b"Hello, world!")36 assert response.status_code == 20037 38 26-@pytest.mark.asyncio27-async def test_post_json(server):39+async def test_post_json(server, backend):40 url = "http://127.0.0.1:8000/"29- async with httpx.AsyncClient() as client:41+ async with httpx.AsyncClient(backend=backend) as client:42 response = await client.post(url, json={"text": "Hello, world!"})43 assert response.status_code == 20044 45 34-@pytest.mark.asyncio35-async def test_stream_response(server):36- async with httpx.AsyncClient() as client:46+async def test_stream_response(server, backend):47+ async with httpx.AsyncClient(backend=backend) as client:48 response = await client.request("GET", "http://127.0.0.1:8000/", stream=True)49 assert response.status_code == 20050 body = await response.read()51 assert body == b"Hello, world!"52 assert response.content == b"Hello, world!"53 54 44-@pytest.mark.asyncio45-async def test_access_content_stream_response(server):46- async with httpx.AsyncClient() as client:55+async def test_access_content_stream_response(server, backend):56+ async with httpx.AsyncClient(backend=backend) as client:57 response = await client.request("GET", "http://127.0.0.1:8000/", stream=True)58 assert response.status_code == 20059 with pytest.raises(httpx.ResponseNotRead):60 response.content61 62 53-@pytest.mark.asyncio54-async def test_stream_request(server):63+async def test_stream_request(server, backend):64 async def hello_world():65 yield b"Hello, "66 yield b"world!"67 59- async with httpx.AsyncClient() as client:68+ async with httpx.AsyncClient(backend=backend) as client:69 response = await client.request(70 "POST", "http://127.0.0.1:8000/", data=hello_world()71 )72 assert response.status_code == 20073 74 66-@pytest.mark.asyncio67-async def test_raise_for_status(server):68- async with httpx.AsyncClient() as client:75+async def test_raise_for_status(server, backend):76+ async with httpx.AsyncClient(backend=backend) as client:77 for status_code in (200, 400, 404, 500, 505):78 response = await client.request(79 "GET", f"http://127.0.0.1:8000/status/{status_code}"80 )5 unmodified lines86 else:87 assert response.raise_for_status() is None88 89 82-@pytest.mark.asyncio83-async def test_options(server):90+async def test_options(server, backend):91 url = "http://127.0.0.1:8000/"85- async with httpx.AsyncClient() as client:92+ async with httpx.AsyncClient(backend=backend) as client:93 response = await client.options(url)94 assert response.status_code == 20095 assert response.text == "Hello, world!"96 97 91-@pytest.mark.asyncio92-async def test_head(server):98+async def test_head(server, backend):99 url = "http://127.0.0.1:8000/"94- async with httpx.AsyncClient() as client:100+ async with httpx.AsyncClient(backend=backend) as client:101 response = await client.head(url)102 assert response.status_code == 200103 assert response.text == ""104 105 100-@pytest.mark.asyncio101-async def test_put(server):106+async def test_put(server, backend):107 url = "http://127.0.0.1:8000/"103- async with httpx.AsyncClient() as client:108+ async with httpx.AsyncClient(backend=backend) as client:109 response = await client.put(url, data=b"Hello, world!")110 assert response.status_code == 200111 112 108-@pytest.mark.asyncio109-async def test_patch(server):113+async def test_patch(server, backend):114 url = "http://127.0.0.1:8000/"111- async with httpx.AsyncClient() as client:115+ async with httpx.AsyncClient(backend=backend) as client:116 response = await client.patch(url, data=b"Hello, world!")117 assert response.status_code == 200118 119 116-@pytest.mark.asyncio117-async def test_delete(server):120+async def test_delete(server, backend):121 url = "http://127.0.0.1:8000/"119- async with httpx.AsyncClient() as client:122+ async with httpx.AsyncClient(backend=backend) as client:123 response = await client.delete(url)124 assert response.status_code == 200125 assert response.text == "Hello, world!"126 127 125-@pytest.mark.asyncio126-async def test_100_continue(server):128+async def test_100_continue(server, backend):129 url = "http://127.0.0.1:8000/echo_body"130 headers = {"Expect": "100-continue"}131 data = b"Echo request body"132 131- async with httpx.AsyncClient() as client:133+ async with httpx.AsyncClient(backend=backend) as client:134 response = await client.post(url, headers=headers, data=data)135 136 assert response.status_code == 200137 assert response.content == datamodified:tests/client/test_redirects.py+34 added-51 removed
98 unmodified lines99 100 return AsyncResponse(codes.OK, content=b"Hello, world!", request=request)101 102 103-@pytest.mark.asyncio104-async def test_redirect_301():105- client = AsyncClient(dispatch=MockDispatch())103+async def test_redirect_301(backend):104+ client = AsyncClient(dispatch=MockDispatch(), backend=backend)105 response = await client.post("https://example.org/redirect_301")106 assert response.status_code == codes.OK107 assert response.url == URL("https://example.org/")108 assert len(response.history) == 1109 110 112-@pytest.mark.asyncio113-async def test_redirect_302():114- client = AsyncClient(dispatch=MockDispatch())111+async def test_redirect_302(backend):112+ client = AsyncClient(dispatch=MockDispatch(), backend=backend)113 response = await client.post("https://example.org/redirect_302")114 assert response.status_code == codes.OK115 assert response.url == URL("https://example.org/")116 assert len(response.history) == 1117 118 121-@pytest.mark.asyncio122-async def test_redirect_303():123- client = AsyncClient(dispatch=MockDispatch())119+async def test_redirect_303(backend):120+ client = AsyncClient(dispatch=MockDispatch(), backend=backend)121 response = await client.get("https://example.org/redirect_303")122 assert response.status_code == codes.OK123 assert response.url == URL("https://example.org/")124 assert len(response.history) == 1125 126 130-@pytest.mark.asyncio131-async def test_disallow_redirects():132- client = AsyncClient(dispatch=MockDispatch())127+async def test_disallow_redirects(backend):128+ client = AsyncClient(dispatch=MockDispatch(), backend=backend)129 response = await client.post(130 "https://example.org/redirect_303", allow_redirects=False131 )132 assert response.status_code == codes.SEE_OTHER7 unmodified lines140 assert response.is_redirect is False141 assert len(response.history) == 1142 143 148-@pytest.mark.asyncio149-async def test_relative_redirect():150- client = AsyncClient(dispatch=MockDispatch())144+async def test_relative_redirect(backend):145+ client = AsyncClient(dispatch=MockDispatch(), backend=backend)146 response = await client.get("https://example.org/relative_redirect")147 assert response.status_code == codes.OK148 assert response.url == URL("https://example.org/")149 assert len(response.history) == 1150 151 157-@pytest.mark.asyncio158-async def test_no_scheme_redirect():159- client = AsyncClient(dispatch=MockDispatch())152+async def test_no_scheme_redirect(backend):153+ client = AsyncClient(dispatch=MockDispatch(), backend=backend)154 response = await client.get("https://example.org/no_scheme_redirect")155 assert response.status_code == codes.OK156 assert response.url == URL("https://example.org/")157 assert len(response.history) == 1158 159 166-@pytest.mark.asyncio167-async def test_fragment_redirect():168- client = AsyncClient(dispatch=MockDispatch())160+async def test_fragment_redirect(backend):161+ client = AsyncClient(dispatch=MockDispatch(), backend=backend)162 response = await client.get("https://example.org/relative_redirect#fragment")163 assert response.status_code == codes.OK164 assert response.url == URL("https://example.org/#fragment")165 assert len(response.history) == 1166 167 175-@pytest.mark.asyncio176-async def test_multiple_redirects():177- client = AsyncClient(dispatch=MockDispatch())168+async def test_multiple_redirects(backend):169+ client = AsyncClient(dispatch=MockDispatch(), backend=backend)170 response = await client.get("https://example.org/multiple_redirects?count=20")171 assert response.status_code == codes.OK172 assert response.url == URL("https://example.org/multiple_redirects")173 assert len(response.history) == 206 unmodified lines180 assert len(response.history[0].history) == 0181 assert len(response.history[1].history) == 1182 183 192-@pytest.mark.asyncio193-async def test_too_many_redirects():194- client = AsyncClient(dispatch=MockDispatch())184+async def test_too_many_redirects(backend):185+ client = AsyncClient(dispatch=MockDispatch(), backend=backend)186 with pytest.raises(TooManyRedirects):187 await client.get("https://example.org/multiple_redirects?count=21")188 189 199-@pytest.mark.asyncio200-async def test_too_many_redirects_calling_next():201- client = AsyncClient(dispatch=MockDispatch())190+async def test_too_many_redirects_calling_next(backend):191+ client = AsyncClient(dispatch=MockDispatch(), backend=backend)192 url = "https://example.org/multiple_redirects?count=21"193 response = await client.get(url, allow_redirects=False)194 with pytest.raises(TooManyRedirects):195 while response.is_redirect:196 response = await response.next()197 198 209-@pytest.mark.asyncio210-async def test_redirect_loop():211- client = AsyncClient(dispatch=MockDispatch())199+async def test_redirect_loop(backend):200+ client = AsyncClient(dispatch=MockDispatch(), backend=backend)201 with pytest.raises(RedirectLoop):202 await client.get("https://example.org/redirect_loop")203 204 216-@pytest.mark.asyncio217-async def test_redirect_loop_calling_next():218- client = AsyncClient(dispatch=MockDispatch())205+async def test_redirect_loop_calling_next(backend):206+ client = AsyncClient(dispatch=MockDispatch(), backend=backend)207 url = "https://example.org/redirect_loop"208 response = await client.get(url, allow_redirects=False)209 with pytest.raises(RedirectLoop):210 while response.is_redirect:211 response = await response.next()212 213 226-@pytest.mark.asyncio227-async def test_cross_domain_redirect():228- client = AsyncClient(dispatch=MockDispatch())214+async def test_cross_domain_redirect(backend):215+ client = AsyncClient(dispatch=MockDispatch(), backend=backend)216 url = "https://example.com/cross_domain"217 headers = {"Authorization": "abc"}218 response = await client.get(url, headers=headers)219 assert response.url == URL("https://example.org/cross_domain_target")220 assert "authorization" not in response.json()["headers"]221 222 236-@pytest.mark.asyncio237-async def test_same_domain_redirect():238- client = AsyncClient(dispatch=MockDispatch())223+async def test_same_domain_redirect(backend):224+ client = AsyncClient(dispatch=MockDispatch(), backend=backend)225 url = "https://example.org/cross_domain"226 headers = {"Authorization": "abc"}227 response = await client.get(url, headers=headers)228 assert response.url == URL("https://example.org/cross_domain_target")229 assert response.json()["headers"]["authorization"] == "abc"230 231 246-@pytest.mark.asyncio247-async def test_body_redirect():248- client = AsyncClient(dispatch=MockDispatch())232+async def test_body_redirect(backend):233+ client = AsyncClient(dispatch=MockDispatch(), backend=backend)234 url = "https://example.org/redirect_body"235 data = b"Example request body"236 response = await client.post(url, data=data)237 assert response.url == URL("https://example.org/redirect_body_target")238 assert response.json() == {"body": "Example request body"}239 240 256-@pytest.mark.asyncio257-async def test_cannot_redirect_streaming_body():258- client = AsyncClient(dispatch=MockDispatch())241+async def test_cannot_redirect_streaming_body(backend):242+ client = AsyncClient(dispatch=MockDispatch(), backend=backend)243 url = "https://example.org/redirect_body"244 245 async def streaming_body():246 yield b"Example request body"1 unmodified line248 with pytest.raises(RedirectBodyUnavailable):249 await client.post(url, data=streaming_body())250 251 268-@pytest.mark.asyncio269-async def test_cross_dubdomain_redirect():270- client = AsyncClient(dispatch=MockDispatch())252+async def test_cross_dubdomain_redirect(backend):253+ client = AsyncClient(dispatch=MockDispatch(), backend=backend)254 url = "https://example.com/cross_subdomain"255 response = await client.get(url)256 assert response.url == URL("https://www.example.org/cross_subdomain")modified:tests/dispatch/test_connection_pools.py+28 added-40 removed
1-import pytest2-1 import httpx2 3 6-@pytest.mark.asyncio7-async def test_keepalive_connections(server):4+async def test_keepalive_connections(server, backend):5 """6 Connections should default to staying in a keep-alive state.7 """11- async with httpx.ConnectionPool() as http:8+ async with httpx.ConnectionPool(backend=backend) as http:9 response = await http.request("GET", "http://127.0.0.1:8000/")10 await response.read()11 assert len(http.active_connections) == 012 assert len(http.keepalive_connections) == 13 unmodified lines16 assert len(http.active_connections) == 017 assert len(http.keepalive_connections) == 118 19 23-@pytest.mark.asyncio24-async def test_differing_connection_keys(server):20+async def test_differing_connection_keys(server, backend):21 """22 Connections to differing connection keys should result in multiple connections.23 """28- async with httpx.ConnectionPool() as http:24+ async with httpx.ConnectionPool(backend=backend) as http:25 response = await http.request("GET", "http://127.0.0.1:8000/")26 await response.read()27 assert len(http.active_connections) == 028 assert len(http.keepalive_connections) == 13 unmodified lines32 assert len(http.active_connections) == 033 assert len(http.keepalive_connections) == 234 35 40-@pytest.mark.asyncio41-async def test_soft_limit(server):36+async def test_soft_limit(server, backend):37 """38 The soft_limit config should limit the maximum number of keep-alive connections.39 """40 pool_limits = httpx.PoolLimits(soft_limit=1)41 47- async with httpx.ConnectionPool(pool_limits=pool_limits) as http:42+ async with httpx.ConnectionPool(pool_limits=pool_limits, backend=backend) as http:43 response = await http.request("GET", "http://127.0.0.1:8000/")44 await response.read()45 assert len(http.active_connections) == 046 assert len(http.keepalive_connections) == 13 unmodified lines50 assert len(http.active_connections) == 051 assert len(http.keepalive_connections) == 152 53 59-@pytest.mark.asyncio60-async def test_streaming_response_holds_connection(server):54+async def test_streaming_response_holds_connection(server, backend):55 """56 A streaming request should hold the connection open until the response is read.57 """64- async with httpx.ConnectionPool() as http:58+ async with httpx.ConnectionPool(backend=backend) as http:59 response = await http.request("GET", "http://127.0.0.1:8000/")60 assert len(http.active_connections) == 161 assert len(http.keepalive_connections) == 062 2 unmodified lines65 assert len(http.active_connections) == 066 assert len(http.keepalive_connections) == 167 68 75-@pytest.mark.asyncio76-async def test_multiple_concurrent_connections(server):69+async def test_multiple_concurrent_connections(server, backend):70 """71 Multiple conncurrent requests should open multiple conncurrent connections.72 """80- async with httpx.ConnectionPool() as http:73+ async with httpx.ConnectionPool(backend=backend) as http:74 response_a = await http.request("GET", "http://127.0.0.1:8000/")75 assert len(http.active_connections) == 176 assert len(http.keepalive_connections) == 077 9 unmodified lines87 assert len(http.active_connections) == 088 assert len(http.keepalive_connections) == 289 90 98-@pytest.mark.asyncio99-async def test_close_connections(server):91+async def test_close_connections(server, backend):92 """93 Using a `Connection: close` header should close the connection.94 """95 headers = [(b"connection", b"close")]104- async with httpx.ConnectionPool() as http:96+ async with httpx.ConnectionPool(backend=backend) as http:97 response = await http.request("GET", "http://127.0.0.1:8000/", headers=headers)98 await response.read()99 assert len(http.active_connections) == 0100 assert len(http.keepalive_connections) == 0101 102 111-@pytest.mark.asyncio112-async def test_standard_response_close(server):103+async def test_standard_response_close(server, backend):104 """105 A standard close should keep the connection open.106 """116- async with httpx.ConnectionPool() as http:107+ async with httpx.ConnectionPool(backend=backend) as http:108 response = await http.request("GET", "http://127.0.0.1:8000/")109 await response.read()110 await response.close()111 assert len(http.active_connections) == 0112 assert len(http.keepalive_connections) == 1113 114 124-@pytest.mark.asyncio125-async def test_premature_response_close(server):115+async def test_premature_response_close(server, backend):116 """117 A premature close should close the connection.118 """129- async with httpx.ConnectionPool() as http:119+ async with httpx.ConnectionPool(backend=backend) as http:120 response = await http.request("GET", "http://127.0.0.1:8000/")121 await response.close()122 assert len(http.active_connections) == 0123 assert len(http.keepalive_connections) == 0124 125 136-@pytest.mark.asyncio137-async def test_keepalive_connection_closed_by_server_is_reestablished(server):126+async def test_keepalive_connection_closed_by_server_is_reestablished(127+ server, restart, backend128+):129 """130 Upon keep-alive connection closed by remote a new connection131 should be reestablished.132 """142- async with httpx.ConnectionPool() as http:133+ async with httpx.ConnectionPool(backend=backend) as http:134 response = await http.request("GET", "http://127.0.0.1:8000/")135 await response.read()136 137 # shutdown the server to close the keep-alive connection147- await server.shutdown()148- await server.startup()138+ await restart(server)139 140 response = await http.request("GET", "http://127.0.0.1:8000/")141 await response.read()142 assert len(http.active_connections) == 0143 assert len(http.keepalive_connections) == 1144 145 156-@pytest.mark.asyncio157-async def test_keepalive_http2_connection_closed_by_server_is_reestablished(server):146+async def test_keepalive_http2_connection_closed_by_server_is_reestablished(147+ server, restart, backend148+):149 """150 Upon keep-alive connection closed by remote a new connection151 should be reestablished.152 """162- async with httpx.ConnectionPool() as http:153+ async with httpx.ConnectionPool(backend=backend) as http:154 response = await http.request("GET", "http://127.0.0.1:8000/")155 await response.read()156 157 # shutdown the server to close the keep-alive connection167- await server.shutdown()168- await server.startup()158+ await restart(server)159 160 response = await http.request("GET", "http://127.0.0.1:8000/")161 await response.read()162 assert len(http.active_connections) == 0163 assert len(http.keepalive_connections) == 1164 165 176-@pytest.mark.asyncio177-async def test_connection_closed_free_semaphore_on_acquire(server):166+async def test_connection_closed_free_semaphore_on_acquire(server, restart, backend):167 """168 Verify that max_connections semaphore is released169 properly on a disconnected connection.170 """1 unmodified line172 response = await http.request("GET", "http://127.0.0.1:8000/")173 await response.read()174 175 # Close the connection so we're forced to recycle it187- await server.shutdown()188- await server.startup()176+ await restart(server)177 178 response = await http.request("GET", "http://127.0.0.1:8000/")179 assert response.status_code == 200modified:tests/dispatch/test_connections.py+10 added-14 removed
1-import pytest2-1 from httpx import HTTPConnection2 3 6-@pytest.mark.asyncio7-async def test_get(server):8- conn = HTTPConnection(origin="http://127.0.0.1:8000/")4+async def test_get(server, backend):5+ conn = HTTPConnection(origin="http://127.0.0.1:8000/", backend=backend)6 response = await conn.request("GET", "http://127.0.0.1:8000/")7 await response.read()8 assert response.status_code == 2009 assert response.content == b"Hello, world!"10 11 15-@pytest.mark.asyncio16-async def test_post(server):17- conn = HTTPConnection(origin="http://127.0.0.1:8000/")12+async def test_post(server, backend):13+ conn = HTTPConnection(origin="http://127.0.0.1:8000/", backend=backend)14 response = await conn.request(15 "GET", "http://127.0.0.1:8000/", data=b"Hello, world!"16 )17 assert response.status_code == 20018 19 24-@pytest.mark.asyncio25-async def test_https_get_with_ssl_defaults(https_server):20+async def test_https_get_with_ssl_defaults(https_server, backend):21 """22 An HTTPS request, with default SSL configuration set on the client.23 """29- conn = HTTPConnection(origin="https://127.0.0.1:8001/", verify=False)24+ conn = HTTPConnection(25+ origin="https://127.0.0.1:8001/", verify=False, backend=backend26+ )27 response = await conn.request("GET", "https://127.0.0.1:8001/")28 await response.read()29 assert response.status_code == 20030 assert response.content == b"Hello, world!"31 32 36-@pytest.mark.asyncio37-async def test_https_get_with_sll_overrides(https_server):33+async def test_https_get_with_sll_overrides(https_server, backend):34 """35 An HTTPS request, with SSL configuration set on the request.36 """41- conn = HTTPConnection(origin="https://127.0.0.1:8001/")37+ conn = HTTPConnection(origin="https://127.0.0.1:8001/", backend=backend)38 response = await conn.request("GET", "https://127.0.0.1:8001/", verify=False)39 await response.read()40 assert response.status_code == 20041 assert response.content == b"Hello, world!"modified:tests/dispatch/test_http2.py+8 added-14 removed
1 import json2 3-import pytest4-3 from httpx import AsyncClient, Client, Response4 5 from .utils import MockHTTP2Backend6 19 unmodified lines26 assert response.status_code == 20027 assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}28 29 32-@pytest.mark.asyncio33-async def test_async_http2_get_request():34- backend = MockHTTP2Backend(app=app)30+async def test_async_http2_get_request(backend):31+ backend = MockHTTP2Backend(app=app, backend=backend)32 33 async with AsyncClient(backend=backend) as client:34 response = await client.get("http://example.org")35 14 unmodified lines50 "body": "<data>",51 }52 53 57-@pytest.mark.asyncio58-async def test_async_http2_post_request():59- backend = MockHTTP2Backend(app=app)54+async def test_async_http2_post_request(backend):55+ backend = MockHTTP2Backend(app=app, backend=backend)56 57 async with AsyncClient(backend=backend) as client:58 response = await client.post("http://example.org", data=b"<data>")59 22 unmodified lines82 assert response_3.status_code == 20083 assert json.loads(response_3.content) == {"method": "GET", "path": "/3", "body": ""}84 85 90-@pytest.mark.asyncio91-async def test_async_http2_multiple_requests():92- backend = MockHTTP2Backend(app=app)86+async def test_async_http2_multiple_requests(backend):87+ backend = MockHTTP2Backend(app=app, backend=backend)88 89 async with AsyncClient(backend=backend) as client:90 response_1 = await client.get("http://example.org/1")91 response_2 = await client.get("http://example.org/2")27 unmodified lines119 assert response_2.status_code == 200120 assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}121 122 128-@pytest.mark.asyncio129-async def test_async_http2_reconnect():123+async def test_async_http2_reconnect(backend):124 """125 If a connection has been dropped between requests, then we should126 be seemlessly reconnected.127 """134- backend = MockHTTP2Backend(app=app)128+ backend = MockHTTP2Backend(app=app, backend=backend)129 130 async with AsyncClient(backend=backend) as client:131 response_1 = await client.get("http://example.org/1")132 backend.server.close_connection = True7 unmodified linesmodified:tests/dispatch/test_threaded.py+2 added-5 removed
1 import json2 3-import pytest4-3 from httpx import (4 AsyncClient,5 CertTypes,6 Client,43 unmodified lines50 assert response.status_code == 20051 assert response.json() == {"hello": "world"}52 53 56-@pytest.mark.asyncio57-async def test_async_threaded_dispatch():54+async def test_async_threaded_dispatch(backend):55 """56 Use a synchronous 'Dispatcher' class with the async client.57 Calls to the dispatcher will end up running within a thread pool.58 """59 url = "https://example.org/"63- async with AsyncClient(dispatch=MockDispatch()) as client:60+ async with AsyncClient(dispatch=MockDispatch(), backend=backend) as client:61 response = await client.get(url)62 63 assert response.status_code == 20064 assert response.json() == {"hello": "world"}48 unmodified linesmodified:tests/dispatch/utils.py+12 added-6 removed
1-import asyncio1 import ssl2 import typing3 4 import h2.config5 import h2.connection6 import h2.events7 8 from httpx import AsyncioBackend, BaseStream, Request, TimeoutConfig9+from tests.concurrency import sleep10 11 12-class MockHTTP2Backend(AsyncioBackend):13- def __init__(self, app):12+class MockHTTP2Backend:13+ def __init__(self, app, backend=None):14 self.app = app15+ self.backend = AsyncioBackend() if backend is None else backend16 self.server = None17 18 async def connect(19 self,1 unmodified line21 port: int,22 ssl_context: typing.Optional[ssl.SSLContext],23 timeout: TimeoutConfig,24 ) -> BaseStream:24- self.server = MockHTTP2Server(self.app)25+ self.server = MockHTTP2Server(self.app, backend=self.backend)26 return self.server27 28+ # Defer all other attributes and methods to the underlying backend.29+ def __getattr__(self, name: str) -> typing.Any:30+ return getattr(self.backend, name)31 32+33 class MockHTTP2Server(BaseStream):29- def __init__(self, app):34+ def __init__(self, app, backend):35 config = h2.config.H2Configuration(client_side=False)36 self.conn = h2.connection.H2Connection(config=config)37 self.app = app38+ self.backend = backend39 self.buffer = b""40 self.requests = {}41 self.close_connection = False42 2 unmodified lines45 def get_http_version(self) -> str:46 return "HTTP/2"47 48 async def read(self, n, timeout, flag=None) -> bytes:43- await asyncio.sleep(0)49+ await sleep(self.backend, 0)50 send, self.buffer = self.buffer[:n], self.buffer[n:]51 return send52 53 def write_no_block(self, data: bytes) -> None:65 unmodified linesadded:tests/concurrency.py+19 added
1+"""2+This module contains concurrency utilities that are only used in tests, thus not3+required as part of the ConcurrencyBackend API.4+"""5+6+import asyncio7+import functools8+9+from httpx import AsyncioBackend10+11+12+@functools.singledispatch13+async def sleep(backend, seconds: int):14+ raise NotImplementedError # pragma: no cover15+16+17+@sleep.register(AsyncioBackend)18+async def _sleep_asyncio(backend, seconds: int):19+ await asyncio.sleep(seconds)modified:tests/conftest.py+24 added
8 unmodified lines9 )10 from uvicorn.config import Config11 from uvicorn.main import Server12 13+from httpx import AsyncioBackend14 15+16+@pytest.fixture(params=[pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)])17+def backend(request):18+ backend_cls = request.param19+ return backend_cls()20+21+22 async def app(scope, receive, send):23 assert scope["type"] == "http"24 if scope["path"] == "/slow_response":25 await slow_response(scope, receive, send)131 unmodified lines157 yield server158 finally:159 server.should_exit = True160 await task161+162+163+@pytest.fixture164+def restart(backend):165+ async def asyncio_restart(server):166+ await server.shutdown()167+ await server.startup()168+169+ if isinstance(backend, AsyncioBackend):170+ return asyncio_restart171+172+ # The uvicorn server runs under asyncio, so we will need to figure out173+ # how to restart it under a different I/O library.174+ # This will most likely require running `asyncio_restart` in the threadpool,175+ # but that might not be sufficient.176+ raise NotImplementedErrormodified:tests/test_asgi.py+8 added-12 removed
44 unmodified lines45 assert response.status_code == 20046 assert response.text == "Hello, World!"47 48 49-@pytest.mark.asyncio50-async def test_asgi_async():51- client = httpx.AsyncClient(app=hello_world)49+async def test_asgi_async(backend):50+ client = httpx.AsyncClient(app=hello_world, backend=backend)51 response = await client.get("http://www.example.org/")52 assert response.status_code == 20053 assert response.text == "Hello, World!"54 4 unmodified lines59 assert response.status_code == 20060 assert response.text == "example"61 62 64-@pytest.mark.asyncio65-async def test_asgi_upload_async():66- client = httpx.AsyncClient(app=echo_body)63+async def test_asgi_upload_async(backend):64+ client = httpx.AsyncClient(app=echo_body, backend=backend)65 response = await client.post("http://www.example.org/", data=b"example")66 assert response.status_code == 20067 assert response.text == "example"68 3 unmodified lines72 with pytest.raises(ValueError):73 client.get("http://www.example.org/")74 75 78-@pytest.mark.asyncio79-async def test_asgi_exc_async():80- client = httpx.AsyncClient(app=raise_exc)76+async def test_asgi_exc_async(backend):77+ client = httpx.AsyncClient(app=raise_exc, backend=backend)78 with pytest.raises(ValueError):79 await client.get("http://www.example.org/")80 81 2 unmodified lines84 with pytest.raises(ValueError):85 client.get("http://www.example.org/")86 87 91-@pytest.mark.asyncio92-async def test_asgi_exc_after_response_async():93- client = httpx.AsyncClient(app=raise_exc_after_response)88+async def test_asgi_exc_after_response_async(backend):89+ client = httpx.AsyncClient(app=raise_exc_after_response, backend=backend)90 with pytest.raises(ValueError):91 await client.get("http://www.example.org/")modified:tests/test_timeouts.py+12 added-16 removed
9 unmodified lines10 WriteTimeout,11 )12 13 14-@pytest.mark.asyncio15-async def test_read_timeout(server):16- timeout = TimeoutConfig(read_timeout=0.000001)14+async def test_read_timeout(server, backend):15+ timeout = TimeoutConfig(read_timeout=1e-6)16 18- async with AsyncClient(timeout=timeout) as client:17+ async with AsyncClient(timeout=timeout, backend=backend) as client:18 with pytest.raises(ReadTimeout):19 await client.get("http://127.0.0.1:8000/slow_response")20 21 23-@pytest.mark.asyncio24-async def test_write_timeout(server):25- timeout = TimeoutConfig(write_timeout=0.000001)22+async def test_write_timeout(server, backend):23+ timeout = TimeoutConfig(write_timeout=1e-6)24 27- async with AsyncClient(timeout=timeout) as client:25+ async with AsyncClient(timeout=timeout, backend=backend) as client:26 with pytest.raises(WriteTimeout):27 data = b"*" * 1024 * 1024 * 10028 await client.put("http://127.0.0.1:8000/slow_response", data=data)29 30 33-@pytest.mark.asyncio34-async def test_connect_timeout(server):35- timeout = TimeoutConfig(connect_timeout=0.000001)31+async def test_connect_timeout(server, backend):32+ timeout = TimeoutConfig(connect_timeout=1e-6)33 37- async with AsyncClient(timeout=timeout) as client:34+ async with AsyncClient(timeout=timeout, backend=backend) as client:35 with pytest.raises(ConnectTimeout):36 # See https://stackoverflow.com/questions/100841/37 await client.get("http://10.255.255.1/")38 39 43-@pytest.mark.asyncio44-async def test_pool_timeout(server):45- pool_limits = PoolLimits(hard_limit=1, pool_timeout=0.000001)40+async def test_pool_timeout(server, backend):41+ pool_limits = PoolLimits(hard_limit=1, pool_timeout=1e-6)42 47- async with AsyncClient(pool_limits=pool_limits) as client:43+ async with AsyncClient(pool_limits=pool_limits, backend=backend) as client:44 response = await client.get("http://127.0.0.1:8000/", stream=True)45 46 with pytest.raises(PoolTimeout):47 await client.get("http://localhost:8000/")2 unmodified lines