Skip to content
Myr

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

12 files+207 added−201 removed

modified:httpx/client.py+11 added-6 removed
631 unmodified lines
632 # 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.638639 if isinstance(backend, AsyncioBackend):640 return641642 if hasattr(backend, "loop"):643 # Most likely a proxy class.644 return645646 raise ValueError("'Client' only supports asyncio-based concurrency backends")647648 def _async_request_data(649 self, data: RequestData = None650 ) -> typing.Optional[AsyncRequestData]:651 """
341 unmodified lines
modified:tests/client/test_async_client.py+39 added-37 removed
1 unmodified line
23import httpx456@pytest.mark.asyncio7async def test_get(server):6async 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 line
14 assert repr(response) == "<Response [200 OK]>"151617@pytest.mark.asyncio19async def test_post(server):18async 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]>"303132async 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 == 200373826@pytest.mark.asyncio27async def test_post_json(server):39async 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 == 200444534@pytest.mark.asyncio35async def test_stream_response(server):36 async with httpx.AsyncClient() as client:46async 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!"535444@pytest.mark.asyncio45async def test_access_content_stream_response(server):46 async with httpx.AsyncClient() as client:55async 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.content616253@pytest.mark.asyncio54async def test_stream_request(server):63async def test_stream_request(server, backend):64 async def hello_world():65 yield b"Hello, "66 yield b"world!"6759 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 == 200737466@pytest.mark.asyncio67async def test_raise_for_status(server):68 async with httpx.AsyncClient() as client:75async 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 lines
86 else:87 assert response.raise_for_status() is None888982@pytest.mark.asyncio83async def test_options(server):90async 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!"969791@pytest.mark.asyncio92async def test_head(server):98async 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 == ""104105100@pytest.mark.asyncio101async def test_put(server):106async 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 == 200111112108@pytest.mark.asyncio109async def test_patch(server):113async 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 == 200118119116@pytest.mark.asyncio117async def test_delete(server):120async 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!"126127125@pytest.mark.asyncio126async def test_100_continue(server):128async 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"132131 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)135136 assert response.status_code == 200137 assert response.content == data
modified:tests/client/test_redirects.py+34 added-51 removed
98 unmodified lines
99100 return AsyncResponse(codes.OK, content=b"Hello, world!", request=request)101102103@pytest.mark.asyncio104async def test_redirect_301():105 client = AsyncClient(dispatch=MockDispatch())103async 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) == 1109110112@pytest.mark.asyncio113async def test_redirect_302():114 client = AsyncClient(dispatch=MockDispatch())111async 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) == 1117118121@pytest.mark.asyncio122async def test_redirect_303():123 client = AsyncClient(dispatch=MockDispatch())119async 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) == 1125126130@pytest.mark.asyncio131async def test_disallow_redirects():132 client = AsyncClient(dispatch=MockDispatch())127async 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_OTHER
7 unmodified lines
140 assert response.is_redirect is False141 assert len(response.history) == 1142143148@pytest.mark.asyncio149async def test_relative_redirect():150 client = AsyncClient(dispatch=MockDispatch())144async 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) == 1150151157@pytest.mark.asyncio158async def test_no_scheme_redirect():159 client = AsyncClient(dispatch=MockDispatch())152async 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) == 1158159166@pytest.mark.asyncio167async def test_fragment_redirect():168 client = AsyncClient(dispatch=MockDispatch())160async 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) == 1166167175@pytest.mark.asyncio176async def test_multiple_redirects():177 client = AsyncClient(dispatch=MockDispatch())168async 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) == 20
6 unmodified lines
180 assert len(response.history[0].history) == 0181 assert len(response.history[1].history) == 1182183192@pytest.mark.asyncio193async def test_too_many_redirects():194 client = AsyncClient(dispatch=MockDispatch())184async 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")188189199@pytest.mark.asyncio200async def test_too_many_redirects_calling_next():201 client = AsyncClient(dispatch=MockDispatch())190async 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()197198209@pytest.mark.asyncio210async def test_redirect_loop():211 client = AsyncClient(dispatch=MockDispatch())199async 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")203204216@pytest.mark.asyncio217async def test_redirect_loop_calling_next():218 client = AsyncClient(dispatch=MockDispatch())205async 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()212213226@pytest.mark.asyncio227async def test_cross_domain_redirect():228 client = AsyncClient(dispatch=MockDispatch())214async 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"]221222236@pytest.mark.asyncio237async def test_same_domain_redirect():238 client = AsyncClient(dispatch=MockDispatch())223async 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"230231246@pytest.mark.asyncio247async def test_body_redirect():248 client = AsyncClient(dispatch=MockDispatch())232async 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"}239240256@pytest.mark.asyncio257async def test_cannot_redirect_streaming_body():258 client = AsyncClient(dispatch=MockDispatch())241async def test_cannot_redirect_streaming_body(backend):242 client = AsyncClient(dispatch=MockDispatch(), backend=backend)243 url = "https://example.org/redirect_body"244245 async def streaming_body():246 yield b"Example request body"
1 unmodified line
248 with pytest.raises(RedirectBodyUnavailable):249 await client.post(url, data=streaming_body())250251268@pytest.mark.asyncio269async def test_cross_dubdomain_redirect():270 client = AsyncClient(dispatch=MockDispatch())252async 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
1import pytest21import httpx236@pytest.mark.asyncio7async def test_keepalive_connections(server):4async 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) == 1
3 unmodified lines
16 assert len(http.active_connections) == 017 assert len(http.keepalive_connections) == 1181923@pytest.mark.asyncio24async def test_differing_connection_keys(server):20async 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) == 1
3 unmodified lines
32 assert len(http.active_connections) == 033 assert len(http.keepalive_connections) == 2343540@pytest.mark.asyncio41async def test_soft_limit(server):36async 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)4147 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) == 1
3 unmodified lines
50 assert len(http.active_connections) == 051 assert len(http.keepalive_connections) == 1525359@pytest.mark.asyncio60async def test_streaming_response_holds_connection(server):54async 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 lines
65 assert len(http.active_connections) == 066 assert len(http.keepalive_connections) == 1676875@pytest.mark.asyncio76async def test_multiple_concurrent_connections(server):69async 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 lines
87 assert len(http.active_connections) == 088 assert len(http.keepalive_connections) == 2899098@pytest.mark.asyncio99async def test_close_connections(server):91async 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) == 0101102111@pytest.mark.asyncio112async def test_standard_response_close(server):103async 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) == 1113114124@pytest.mark.asyncio125async def test_premature_response_close(server):115async 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) == 0124125136@pytest.mark.asyncio137async def test_keepalive_connection_closed_by_server_is_reestablished(server):126async 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()136137 # shutdown the server to close the keep-alive connection147 await server.shutdown()148 await server.startup()138 await restart(server)139140 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) == 1144145156@pytest.mark.asyncio157async def test_keepalive_http2_connection_closed_by_server_is_reestablished(server):146async 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()156157 # shutdown the server to close the keep-alive connection167 await server.shutdown()168 await server.startup()158 await restart(server)159160 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) == 1164165176@pytest.mark.asyncio177async def test_connection_closed_free_semaphore_on_acquire(server):166async 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 line
172 response = await http.request("GET", "http://127.0.0.1:8000/")173 await response.read()174175 # Close the connection so we're forced to recycle it187 await server.shutdown()188 await server.startup()176 await restart(server)177178 response = await http.request("GET", "http://127.0.0.1:8000/")179 assert response.status_code == 200
modified:tests/dispatch/test_connections.py+10 added-14 removed
1import pytest21from httpx import HTTPConnection236@pytest.mark.asyncio7async def test_get(server):8 conn = HTTPConnection(origin="http://127.0.0.1:8000/")4async 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!"101115@pytest.mark.asyncio16async def test_post(server):17 conn = HTTPConnection(origin="http://127.0.0.1:8000/")12async 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 == 200181924@pytest.mark.asyncio25async def test_https_get_with_ssl_defaults(https_server):20async 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!"313236@pytest.mark.asyncio37async def test_https_get_with_sll_overrides(https_server):33async 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
1import json23import pytest43from httpx import AsyncClient, Client, Response45from .utils import MockHTTP2Backend6
19 unmodified lines
26 assert response.status_code == 20027 assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}282932@pytest.mark.asyncio33async def test_async_http2_get_request():34 backend = MockHTTP2Backend(app=app)30async def test_async_http2_get_request(backend):31 backend = MockHTTP2Backend(app=app, backend=backend)3233 async with AsyncClient(backend=backend) as client:34 response = await client.get("http://example.org")35
14 unmodified lines
50 "body": "<data>",51 }525357@pytest.mark.asyncio58async def test_async_http2_post_request():59 backend = MockHTTP2Backend(app=app)54async def test_async_http2_post_request(backend):55 backend = MockHTTP2Backend(app=app, backend=backend)5657 async with AsyncClient(backend=backend) as client:58 response = await client.post("http://example.org", data=b"<data>")59
22 unmodified lines
82 assert response_3.status_code == 20083 assert json.loads(response_3.content) == {"method": "GET", "path": "/3", "body": ""}848590@pytest.mark.asyncio91async def test_async_http2_multiple_requests():92 backend = MockHTTP2Backend(app=app)86async def test_async_http2_multiple_requests(backend):87 backend = MockHTTP2Backend(app=app, backend=backend)8889 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 lines
119 assert response_2.status_code == 200120 assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}121122128@pytest.mark.asyncio129async def test_async_http2_reconnect():123async 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)129130 async with AsyncClient(backend=backend) as client:131 response_1 = await client.get("http://example.org/1")132 backend.server.close_connection = True
7 unmodified lines
modified:tests/dispatch/test_threaded.py+2 added-5 removed
1import json23import pytest43from httpx import (4 AsyncClient,5 CertTypes,6 Client,
43 unmodified lines
50 assert response.status_code == 20051 assert response.json() == {"hello": "world"}525356@pytest.mark.asyncio57async def test_async_threaded_dispatch():54async 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)6263 assert response.status_code == 20064 assert response.json() == {"hello": "world"}
48 unmodified lines
modified:tests/dispatch/utils.py+12 added-6 removed
1import asyncio1import ssl2import typing34import h2.config5import h2.connection6import h2.events78from httpx import AsyncioBackend, BaseStream, Request, TimeoutConfig9from tests.concurrency import sleep101112class MockHTTP2Backend(AsyncioBackend):13 def __init__(self, app):12class MockHTTP2Backend:13 def __init__(self, app, backend=None):14 self.app = app15 self.backend = AsyncioBackend() if backend is None else backend16 self.server = None1718 async def connect(19 self,
1 unmodified line
21 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.server2728 # Defer all other attributes and methods to the underlying backend.29 def __getattr__(self, name: str) -> typing.Any:30 return getattr(self.backend, name)313233class 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 lines
45 def get_http_version(self) -> str:46 return "HTTP/2"4748 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 send5253 def write_no_block(self, data: bytes) -> None:
65 unmodified lines
added:tests/concurrency.py+19 added
1"""2This module contains concurrency utilities that are only used in tests, thus not3required as part of the ConcurrencyBackend API.4"""56import asyncio7import functools89from httpx import AsyncioBackend101112@functools.singledispatch13async def sleep(backend, seconds: int):14 raise NotImplementedError # pragma: no cover151617@sleep.register(AsyncioBackend)18async def _sleep_asyncio(backend, seconds: int):19 await asyncio.sleep(seconds)
modified:tests/conftest.py+24 added
8 unmodified lines
9)10from uvicorn.config import Config11from uvicorn.main import Server1213from httpx import AsyncioBackend141516@pytest.fixture(params=[pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)])17def backend(request):18 backend_cls = request.param19 return backend_cls()202122async 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 lines
157 yield server158 finally:159 server.should_exit = True160 await task161162163@pytest.fixture164def restart(backend):165 async def asyncio_restart(server):166 await server.shutdown()167 await server.startup()168169 if isinstance(backend, AsyncioBackend):170 return asyncio_restart171172 # 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 NotImplementedError
modified:tests/test_asgi.py+8 added-12 removed
44 unmodified lines
45 assert response.status_code == 20046 assert response.text == "Hello, World!"474849@pytest.mark.asyncio50async def test_asgi_async():51 client = httpx.AsyncClient(app=hello_world)49async 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 lines
59 assert response.status_code == 20060 assert response.text == "example"616264@pytest.mark.asyncio65async def test_asgi_upload_async():66 client = httpx.AsyncClient(app=echo_body)63async 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 lines
72 with pytest.raises(ValueError):73 client.get("http://www.example.org/")747578@pytest.mark.asyncio79async def test_asgi_exc_async():80 client = httpx.AsyncClient(app=raise_exc)76async 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/")8081
2 unmodified lines
84 with pytest.raises(ValueError):85 client.get("http://www.example.org/")868791@pytest.mark.asyncio92async def test_asgi_exc_after_response_async():93 client = httpx.AsyncClient(app=raise_exc_after_response)88async 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 lines
10 WriteTimeout,11)121314@pytest.mark.asyncio15async def test_read_timeout(server):16 timeout = TimeoutConfig(read_timeout=0.000001)14async def test_read_timeout(server, backend):15 timeout = TimeoutConfig(read_timeout=1e-6)1618 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")202123@pytest.mark.asyncio24async def test_write_timeout(server):25 timeout = TimeoutConfig(write_timeout=0.000001)22async def test_write_timeout(server, backend):23 timeout = TimeoutConfig(write_timeout=1e-6)2427 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)293033@pytest.mark.asyncio34async def test_connect_timeout(server):35 timeout = TimeoutConfig(connect_timeout=0.000001)31async def test_connect_timeout(server, backend):32 timeout = TimeoutConfig(connect_timeout=1e-6)3337 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/")383943@pytest.mark.asyncio44async def test_pool_timeout(server):45 pool_limits = PoolLimits(hard_limit=1, pool_timeout=0.000001)40async def test_pool_timeout(server, backend):41 pool_limits = PoolLimits(hard_limit=1, pool_timeout=1e-6)4247 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)4546 with pytest.raises(PoolTimeout):47 await client.get("http://localhost:8000/")
2 unmodified lines