Refactor tests in the light of backend auto-detection (#615)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Refactor tests in the light of backend auto-detection * Test passing explicit backend separately * Drop 'backend=backend' * Fix usage of asyncio.run() on 3.6
authored by Florimond Manca · committed by GitHub · parent f57bb2f · Browse files · 11 files·+155 added−108 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+155 added−108 removed
- tests:+155 added−108 removed
Provenance
- Commit
ab41a5d- Tree
f2084ec- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
f57bb2f
11 files changed+155 added−108 removed
modified:tests/client/test_async_client.py+29 added-15 removed
5 unmodified lines6 7 8 async def test_get(server, backend):9 url = server.url10- async with httpx.Client(backend=backend) as client:10+ async with httpx.Client() as client:11 response = await client.get(url)12 assert response.status_code == 20013 assert response.text == "Hello, world!"14 assert response.http_version == "HTTP/1.1"4 unmodified lines19 20 async def test_build_request(server, backend):21 url = server.url.copy_with(path="/echo_headers")22 headers = {"Custom-header": "value"}23- async with httpx.Client(backend=backend) as client:23+ async with httpx.Client() as client:24 request = client.build_request("GET", url)25 request.headers.update(headers)26 response = await client.send(request)27 19 unmodified lines47 48 49 async def test_post(server, backend):50 url = server.url51- async with httpx.Client(backend=backend) as client:51+ async with httpx.Client() as client:52 response = await client.post(url, data=b"Hello, world!")53 assert response.status_code == 20054 55 56 async def test_post_json(server, backend):57 url = server.url58- async with httpx.Client(backend=backend) as client:58+ async with httpx.Client() as client:59 response = await client.post(url, json={"text": "Hello, world!"})60 assert response.status_code == 20061 62 63 async def test_stream_response(server, backend):64- async with httpx.Client(backend=backend) as client:64+ async with httpx.Client() as client:65 async with client.stream("GET", server.url) as response:66 body = await response.read()67 68 assert response.status_code == 2001 unmodified line70 assert response.content == b"Hello, world!"71 72 73 async def test_access_content_stream_response(server, backend):74- async with httpx.Client(backend=backend) as client:74+ async with httpx.Client() as client:75 async with client.stream("GET", server.url) as response:76 pass77 78 assert response.status_code == 2005 unmodified lines84 async def hello_world():85 yield b"Hello, "86 yield b"world!"87 88- async with httpx.Client(backend=backend) as client:88+ async with httpx.Client() as client:89 response = await client.request("POST", server.url, data=hello_world())90 assert response.status_code == 20091 92 93 async def test_raise_for_status(server, backend):94- async with httpx.Client(backend=backend) as client:94+ async with httpx.Client() as client:95 for status_code in (200, 400, 404, 500, 505):96 response = await client.request(97 "GET", server.url.copy_with(path=f"/status/{status_code}")98 )6 unmodified lines105 assert response.raise_for_status() is None106 107 108 async def test_options(server, backend):109- async with httpx.Client(backend=backend) as client:109+ async with httpx.Client() as client:110 response = await client.options(server.url)111 assert response.status_code == 200112 assert response.text == "Hello, world!"113 114 115 async def test_head(server, backend):116- async with httpx.Client(backend=backend) as client:116+ async with httpx.Client() as client:117 response = await client.head(server.url)118 assert response.status_code == 200119 assert response.text == ""120 121 122 async def test_put(server, backend):123- async with httpx.Client(backend=backend) as client:123+ async with httpx.Client() as client:124 response = await client.put(server.url, data=b"Hello, world!")125 assert response.status_code == 200126 127 128 async def test_patch(server, backend):129- async with httpx.Client(backend=backend) as client:129+ async with httpx.Client() as client:130 response = await client.patch(server.url, data=b"Hello, world!")131 assert response.status_code == 200132 133 134 async def test_delete(server, backend):135- async with httpx.Client(backend=backend) as client:135+ async with httpx.Client() as client:136 response = await client.delete(server.url)137 assert response.status_code == 200138 assert response.text == "Hello, world!"139 1 unmodified line141 async def test_100_continue(server, backend):142 headers = {"Expect": "100-continue"}143 data = b"Echo request body"144 145- async with httpx.Client(backend=backend) as client:145+ async with httpx.Client() as client:146 response = await client.post(147 server.url.copy_with(path="/echo_body"), headers=headers, data=data148 )149 4 unmodified lines154 async def test_uds(uds_server, backend):155 url = uds_server.url156 uds = uds_server.config.uds157 assert uds is not None158- async with httpx.Client(backend=backend, uds=uds) as client:158+ async with httpx.Client(uds=uds) as client:159 response = await client.get(url)160 assert response.status_code == 200161 assert response.text == "Hello, world!"162 assert response.encoding == "iso-8859-1"163+164+165+@pytest.mark.parametrize(166+ "backend",167+ [168+ pytest.param("asyncio", marks=pytest.mark.asyncio),169+ pytest.param("trio", marks=pytest.mark.trio),170+ ],171+)172+async def test_explicit_backend(server, backend):173+ async with httpx.Client(backend=backend) as client:174+ response = await client.get(server.url)175+ assert response.status_code == 200176+ assert response.text == "Hello, world!"modified:tests/client/test_redirects.py+20 added-20 removed
103 unmodified lines104 return Response(codes.OK, content=b"Hello, world!", request=request)105 106 107 async def test_no_redirect(backend):108- client = Client(dispatch=MockDispatch(), backend=backend)108+ client = Client(dispatch=MockDispatch())109 url = "https://example.com/no_redirect"110 response = await client.get(url)111 assert response.status_code == 200112 with pytest.raises(NotRedirectResponse):113 await response.next()114 115 116 async def test_redirect_301(backend):117- client = Client(dispatch=MockDispatch(), backend=backend)117+ client = Client(dispatch=MockDispatch())118 response = await client.post("https://example.org/redirect_301")119 assert response.status_code == codes.OK120 assert response.url == URL("https://example.org/")121 assert len(response.history) == 1122 123 124 async def test_redirect_302(backend):125- client = Client(dispatch=MockDispatch(), backend=backend)125+ client = Client(dispatch=MockDispatch())126 response = await client.post("https://example.org/redirect_302")127 assert response.status_code == codes.OK128 assert response.url == URL("https://example.org/")129 assert len(response.history) == 1130 131 132 async def test_redirect_303(backend):133- client = Client(dispatch=MockDispatch(), backend=backend)133+ client = Client(dispatch=MockDispatch())134 response = await client.get("https://example.org/redirect_303")135 assert response.status_code == codes.OK136 assert response.url == URL("https://example.org/")137 assert len(response.history) == 1138 139 140 async def test_disallow_redirects(backend):141- client = Client(dispatch=MockDispatch(), backend=backend)141+ client = Client(dispatch=MockDispatch())142 response = await client.post(143 "https://example.org/redirect_303", allow_redirects=False144 )145 assert response.status_code == codes.SEE_OTHER8 unmodified lines154 assert len(response.history) == 1155 156 157 async def test_relative_redirect(backend):158- client = Client(dispatch=MockDispatch(), backend=backend)158+ client = Client(dispatch=MockDispatch())159 response = await client.get("https://example.org/relative_redirect")160 assert response.status_code == codes.OK161 assert response.url == URL("https://example.org/")162 assert len(response.history) == 1163 164 165 async def test_no_scheme_redirect(backend):166- client = Client(dispatch=MockDispatch(), backend=backend)166+ client = Client(dispatch=MockDispatch())167 response = await client.get("https://example.org/no_scheme_redirect")168 assert response.status_code == codes.OK169 assert response.url == URL("https://example.org/")170 assert len(response.history) == 1171 172 173 async def test_fragment_redirect(backend):174- client = Client(dispatch=MockDispatch(), backend=backend)174+ client = Client(dispatch=MockDispatch())175 response = await client.get("https://example.org/relative_redirect#fragment")176 assert response.status_code == codes.OK177 assert response.url == URL("https://example.org/#fragment")178 assert len(response.history) == 1179 180 181 async def test_multiple_redirects(backend):182- client = Client(dispatch=MockDispatch(), backend=backend)182+ client = Client(dispatch=MockDispatch())183 response = await client.get("https://example.org/multiple_redirects?count=20")184 assert response.status_code == codes.OK185 assert response.url == URL("https://example.org/multiple_redirects")186 assert len(response.history) == 207 unmodified lines194 assert len(response.history[1].history) == 1195 196 197 async def test_too_many_redirects(backend):198- client = Client(dispatch=MockDispatch(), backend=backend)198+ client = Client(dispatch=MockDispatch())199 with pytest.raises(TooManyRedirects):200 await client.get("https://example.org/multiple_redirects?count=21")201 202 203 async def test_too_many_redirects_calling_next(backend):204- client = Client(dispatch=MockDispatch(), backend=backend)204+ client = Client(dispatch=MockDispatch())205 url = "https://example.org/multiple_redirects?count=21"206 response = await client.get(url, allow_redirects=False)207 with pytest.raises(TooManyRedirects):208 while response.is_redirect:209 response = await response.next()210 211 212 async def test_redirect_loop(backend):213- client = Client(dispatch=MockDispatch(), backend=backend)213+ client = Client(dispatch=MockDispatch())214 with pytest.raises(RedirectLoop):215 await client.get("https://example.org/redirect_loop")216 217 218 async def test_redirect_loop_calling_next(backend):219- client = Client(dispatch=MockDispatch(), backend=backend)219+ client = Client(dispatch=MockDispatch())220 url = "https://example.org/redirect_loop"221 response = await client.get(url, allow_redirects=False)222 with pytest.raises(RedirectLoop):223 while response.is_redirect:224 response = await response.next()225 226 227 async def test_cross_domain_redirect(backend):228- client = Client(dispatch=MockDispatch(), backend=backend)228+ client = Client(dispatch=MockDispatch())229 url = "https://example.com/cross_domain"230 headers = {"Authorization": "abc"}231 response = await client.get(url, headers=headers)232 assert response.url == URL("https://example.org/cross_domain_target")233 assert "authorization" not in response.json()["headers"]234 235 236 async def test_same_domain_redirect(backend):237- client = Client(dispatch=MockDispatch(), backend=backend)237+ client = Client(dispatch=MockDispatch())238 url = "https://example.org/cross_domain"239 headers = {"Authorization": "abc"}240 response = await client.get(url, headers=headers)241 assert response.url == URL("https://example.org/cross_domain_target")3 unmodified lines245 async def test_body_redirect(backend):246 """247 A 308 redirect should preserve the request body.248 """249- client = Client(dispatch=MockDispatch(), backend=backend)249+ client = Client(dispatch=MockDispatch())250 url = "https://example.org/redirect_body"251 data = b"Example request body"252 response = await client.post(url, data=data)253 assert response.url == URL("https://example.org/redirect_body_target")4 unmodified lines258 async def test_no_body_redirect(backend):259 """260 A 303 redirect should remove the request body.261 """262- client = Client(dispatch=MockDispatch(), backend=backend)262+ client = Client(dispatch=MockDispatch())263 url = "https://example.org/redirect_no_body"264 data = b"Example request body"265 response = await client.post(url, data=data)266 assert response.url == URL("https://example.org/redirect_body_target")1 unmodified line268 assert "content-length" not in response.json()["headers"]269 270 271 async def test_cannot_redirect_streaming_body(backend):272- client = Client(dispatch=MockDispatch(), backend=backend)272+ client = Client(dispatch=MockDispatch())273 url = "https://example.org/redirect_body"274 275 async def streaming_body():276 yield b"Example request body"2 unmodified lines279 await client.post(url, data=streaming_body())280 281 282 async def test_cross_subdomain_redirect(backend):283- client = Client(dispatch=MockDispatch(), backend=backend)283+ client = Client(dispatch=MockDispatch())284 url = "https://example.com/cross_subdomain"285 response = await client.get(url)286 assert response.url == URL("https://www.example.org/cross_subdomain")287 37 unmodified lines325 return Response(status_code, headers=headers, request=request)326 327 328 async def test_redirect_cookie_behavior(backend):329- client = Client(dispatch=MockCookieDispatch(), backend=backend)329+ client = Client(dispatch=MockCookieDispatch())330 331 # The client is not logged in.332 response = await client.get("https://example.com/")333 assert response.url == "https://example.com/"21 unmodified linesmodified:tests/dispatch/test_connection_pools.py+11 added-13 removed
4 unmodified lines5 async def test_keepalive_connections(server, backend):6 """7 Connections should default to staying in a keep-alive state.8 """9- async with ConnectionPool(backend=backend) as http:9+ async with ConnectionPool() as http:10 response = await http.request("GET", server.url)11 await response.read()12 assert len(http.active_connections) == 013 assert len(http.keepalive_connections) == 17 unmodified lines21 async def test_differing_connection_keys(server, backend):22 """23 Connections to differing connection keys should result in multiple connections.24 """25- async with ConnectionPool(backend=backend) as http:25+ async with ConnectionPool() as http:26 response = await http.request("GET", server.url)27 await response.read()28 assert len(http.active_connections) == 029 assert len(http.keepalive_connections) == 19 unmodified lines39 The soft_limit config should limit the maximum number of keep-alive connections.40 """41 pool_limits = httpx.PoolLimits(soft_limit=1)42 43- async with ConnectionPool(pool_limits=pool_limits, backend=backend) as http:43+ async with ConnectionPool(pool_limits=pool_limits) as http:44 response = await http.request("GET", server.url)45 await response.read()46 assert len(http.active_connections) == 047 assert len(http.keepalive_connections) == 17 unmodified lines55 async def test_streaming_response_holds_connection(server, backend):56 """57 A streaming request should hold the connection open until the response is read.58 """59- async with ConnectionPool(backend=backend) as http:59+ async with ConnectionPool() as http:60 response = await http.request("GET", server.url)61 assert len(http.active_connections) == 162 assert len(http.keepalive_connections) == 063 6 unmodified lines70 async def test_multiple_concurrent_connections(server, backend):71 """72 Multiple conncurrent requests should open multiple conncurrent connections.73 """74- async with ConnectionPool(backend=backend) as http:74+ async with ConnectionPool() as http:75 response_a = await http.request("GET", server.url)76 assert len(http.active_connections) == 177 assert len(http.keepalive_connections) == 078 14 unmodified lines93 """94 Using a `Connection: close` header should close the connection.95 """96 headers = [(b"connection", b"close")]97- async with ConnectionPool(backend=backend) as http:97+ async with ConnectionPool() as http:98 response = await http.request("GET", server.url, headers=headers)99 await response.read()100 assert len(http.active_connections) == 0101 assert len(http.keepalive_connections) == 02 unmodified lines104 async def test_standard_response_close(server, backend):105 """106 A standard close should keep the connection open.107 """108- async with ConnectionPool(backend=backend) as http:108+ async with ConnectionPool() as http:109 response = await http.request("GET", server.url)110 await response.read()111 await response.close()112 assert len(http.active_connections) == 03 unmodified lines116 async def test_premature_response_close(server, backend):117 """118 A premature close should close the connection.119 """120- async with ConnectionPool(backend=backend) as http:120+ async with ConnectionPool() as http:121 response = await http.request("GET", server.url)122 await response.close()123 assert len(http.active_connections) == 0124 assert len(http.keepalive_connections) == 05 unmodified lines130 """131 Upon keep-alive connection closed by remote a new connection132 should be reestablished.133 """134- async with ConnectionPool(backend=backend) as http:134+ async with ConnectionPool() as http:135 response = await http.request("GET", server.url)136 await response.read()137 138 # Shutdown the server to close the keep-alive connection11 unmodified lines150 """151 Upon keep-alive connection closed by remote a new connection152 should be reestablished.153 """154- async with ConnectionPool(backend=backend) as http:154+ async with ConnectionPool() as http:155 response = await http.request("GET", server.url)156 await response.read()157 158 # Shutdown the server to close the keep-alive connection9 unmodified lines168 """169 Verify that max_connections semaphore is released170 properly on a disconnected connection.171 """172- async with ConnectionPool(173- pool_limits=httpx.PoolLimits(hard_limit=1), backend=backend174- ) as http:172+ async with ConnectionPool(pool_limits=httpx.PoolLimits(hard_limit=1)) as http:173 response = await http.request("GET", server.url)174 await response.read()175 176 # Close the connection so we're forced to recycle it4 unmodified linesmodified:tests/dispatch/test_connections.py+5 added-7 removed
3 unmodified lines4 from httpx.dispatch.connection import HTTPConnection5 6 7 async def test_get(server, backend):8- async with HTTPConnection(origin=server.url, backend=backend) as conn:8+ async with HTTPConnection(origin=server.url) as conn:9 response = await conn.request("GET", server.url)10 await response.read()11 assert response.status_code == 20012 assert response.content == b"Hello, world!"13 14 15 async def test_post(server, backend):16- async with HTTPConnection(origin=server.url, backend=backend) as conn:16+ async with HTTPConnection(origin=server.url) as conn:17 response = await conn.request("GET", server.url, data=b"Hello, world!")18 assert response.status_code == 20019 20 21 async def test_premature_close(server, backend):22 with pytest.raises(httpx.ConnectionClosed):23- async with HTTPConnection(origin=server.url, backend=backend) as conn:23+ async with HTTPConnection(origin=server.url) as conn:24 response = await conn.request(25 "GET", server.url.copy_with(path="/premature_close")26 )27 await response.read()2 unmodified lines30 async def test_https_get_with_ssl_defaults(https_server, ca_cert_pem_file, backend):31 """32 An HTTPS request, with default SSL configuration set on the client.33 """34- async with HTTPConnection(35- origin=https_server.url, verify=ca_cert_pem_file, backend=backend36- ) as conn:34+ async with HTTPConnection(origin=https_server.url, verify=ca_cert_pem_file) as conn:35 response = await conn.request("GET", https_server.url)36 await response.read()37 assert response.status_code == 20038 assert response.content == b"Hello, world!"2 unmodified lines41 async def test_https_get_with_sll_overrides(https_server, ca_cert_pem_file, backend):42 """43 An HTTPS request, with SSL configuration set on the request.44 """47- async with HTTPConnection(origin=https_server.url, backend=backend) as conn:45+ async with HTTPConnection(origin=https_server.url) as conn:46 response = await conn.request("GET", https_server.url, verify=ca_cert_pem_file)47 await response.read()48 assert response.status_code == 20049 assert response.content == b"Hello, world!"modified:tests/dispatch/test_http2.py+2 added-2 removed
102 unmodified lines103 assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}104 105 106 async def test_http2_settings_in_handshake(backend):107- backend = MockHTTP2Backend(app=app, backend=backend)107+ backend = MockHTTP2Backend(app=app)108 109 async with Client(backend=backend, http2=True) as client:110 await client.get("http://example.org")111 26 unmodified lines138 assert changed_setting.new_value == expected_settings[setting_code]139 140 141 async def test_http2_live_request(backend):142- async with Client(backend=backend, http2=True) as client:142+ async with Client(http2=True) as client:143 try:144 resp = await client.get("https://nghttp2.org/httpbin/anything")145 except TimeoutException:146 pytest.xfail(reason="nghttp2.org appears to be unresponsive")4 unmodified linesmodified:tests/dispatch/test_proxy_http.py-4 removed
17 unmodified lines18 b"Server: origin-server\r\n"19 b"\r\n",20 ]21 ),22- backend=backend,22 )23 async with httpx.HTTPProxy(24 proxy_url="http://127.0.0.1:8000", backend=raw_io, proxy_mode="TUNNEL_ONLY",25 ) as proxy:25 unmodified lines51 b"Server: proxy-server\r\n"52 b"\r\n",53 ]54 ),56- backend=backend,55 )56 57 with pytest.raises(httpx.ProxyError) as e:58 async with httpx.HTTPProxy(43 unmodified lines102 b"Content-Length: 0\r\n"103 b"\r\n",104 ]105 ),108- backend=backend,106 )107 async with httpx.HTTPProxy(108 proxy_url="http://127.0.0.1:8000", backend=raw_io, proxy_mode="TUNNEL_ONLY",109 ) as proxy:41 unmodified lines151 b"Server: origin-server\r\n"152 b"\r\n"153 ]154 ),158- backend=backend,155 )156 async with httpx.HTTPProxy(157 proxy_url="http://127.0.0.1:8000",158 backend=raw_io,44 unmodified linesmodified:tests/dispatch/utils.py+5 added-6 removed
4 unmodified lines5 import h2.connection6 import h2.events7 8 from httpx import Request, Timeout9-from httpx.concurrency.asyncio import AsyncioBackend10-from httpx.concurrency.base import BaseSocketStream9+from httpx.concurrency.base import BaseSocketStream, lookup_backend10 from tests.concurrency import sleep11 12 13 class MockHTTP2Backend:15- def __init__(self, app, backend=None):14+ def __init__(self, app, backend="auto"):15 self.app = app17- self.backend = AsyncioBackend() if backend is None else backend16+ self.backend = lookup_backend(backend)17 self.server = None18 19 async def open_tcp_stream(20 self,145 unmodified lines166 self.buffer += self.conn.data_to_send()167 168 169 class MockRawSocketBackend:171- def __init__(self, data_to_send=b"", backend=None):172- self.backend = AsyncioBackend() if backend is None else backend170+ def __init__(self, data_to_send=b"", backend="auto"):171+ self.backend = lookup_backend(backend)172 self.data_to_send = data_to_send173 self.received_data = []174 self.stream = MockRawSocketStream(self)175 48 unmodified linesmodified:tests/concurrency.py+31 added
8 unmodified lines9 10 import trio11 12 from httpx.concurrency.asyncio import AsyncioBackend13+from httpx.concurrency.auto import AutoBackend14 from httpx.concurrency.trio import TrioBackend15 16 17 @functools.singledispatch18 async def sleep(backend, seconds: int):19 raise NotImplementedError # pragma: no cover20 21 22+@sleep.register(AutoBackend)23+async def _sleep_auto(backend, seconds: int):24+ return await sleep(backend.backend, seconds=seconds)25+26+27 @sleep.register(AsyncioBackend)28 async def _sleep_asyncio(backend, seconds: int):29 await asyncio.sleep(seconds)30 7 unmodified lines38 async def run_concurrently(backend, *coroutines: typing.Callable[[], typing.Awaitable]):39 raise NotImplementedError # pragma: no cover40 41 42+@run_concurrently.register(AutoBackend)43+async def _run_concurrently_auto(backend, *coroutines):44+ await run_concurrently(backend.backend, *coroutines)45+46+47 @run_concurrently.register(AsyncioBackend)48 async def _run_concurrently_asyncio(backend, *coroutines):49 coros = (coroutine() for coroutine in coroutines)50 await asyncio.gather(*coros)3 unmodified lines54 async def _run_concurrently_trio(backend, *coroutines):55 async with trio.open_nursery() as nursery:56 for coroutine in coroutines:57 nursery.start_soon(coroutine)58+59+60+@functools.singledispatch61+def get_cipher(backend, stream):62+ raise NotImplementedError # pragma: no cover63+64+65+@get_cipher.register(AutoBackend)66+def _get_cipher_auto(backend, stream):67+ return get_cipher(backend.backend, stream)68+69+70+@get_cipher.register(AsyncioBackend)71+def _get_cipher_asyncio(backend, stream):72+ return stream.stream_writer.get_extra_info("cipher", default=None)73+74+75+@get_cipher.register(TrioBackend)76+def get_trio_cipher(backend, stream):77+ return stream.stream.cipher() if isinstance(stream.stream, trio.SSLStream) else Nonemodified:tests/conftest.py+14 added-6 removed
17 unmodified lines18 from uvicorn.main import Server19 20 from httpx import URL21 from httpx.concurrency.asyncio import AsyncioBackend22-from httpx.concurrency.trio import TrioBackend22+from httpx.concurrency.base import lookup_backend23 24 ENVIRONMENT_VARIABLES = {25 "SSL_CERT_FILE",26 "SSL_CERT_DIR",23 unmodified lines50 51 52 @pytest.fixture(53 params=[54+ # pytest uses the marks to set up the specified async environment and run55+ # 'async def' test functions. The "auto" backend should then auto-detect56+ # the environment it's running in.57+ # Passing the backend explicitly, e.g. `backend="asyncio"`,58+ # is tested separately.54- pytest.param(AsyncioBackend, marks=pytest.mark.asyncio),55- pytest.param(TrioBackend, marks=pytest.mark.trio),59+ pytest.param("auto", marks=pytest.mark.asyncio),60+ pytest.param("auto", marks=pytest.mark.trio),61 ]62 )63 def backend(request):59- backend_cls = request.param60- return backend_cls()64+ return request.param65 66 67 async def app(scope, receive, send):68 assert scope["type"] == "http"205 unmodified lines274 275 This fixture deals with possible differences between the environment of the276 test function and that of the server.277 """278+ asyncio_backend = AsyncioBackend()279+ backend_implementation = lookup_backend(backend)280 281 async def restart(server):276- await backend.run_in_threadpool(AsyncioBackend().run, server.restart)282+ await backend_implementation.run_in_threadpool(283+ asyncio_backend.run, server.restart284+ )285 286 return restart287 288 57 unmodified linesmodified:tests/test_concurrency.py+34 added-29 removed
1+import asyncio2+3 import pytest4 import trio5 6 from httpx import Timeout7 from httpx.concurrency.asyncio import AsyncioBackend8+from httpx.concurrency.base import lookup_backend9 from httpx.concurrency.trio import TrioBackend10 from httpx.config import SSLConfig8-from tests.concurrency import run_concurrently, sleep11+from tests.concurrency import get_cipher, run_concurrently, sleep12 13 11-def get_asyncio_cipher(stream):12- return stream.stream_writer.get_extra_info("cipher", default=None)13-14-15-def get_trio_cipher(stream):16- return stream.stream.cipher() if isinstance(stream.stream, trio.SSLStream) else None17-18-14 async def read_response(stream, timeout: Timeout, should_contain: bytes) -> bytes:15 # stream.read() only gives us *up to* as much data as we ask for. In order to16 # cleanly close the stream, we must read until the end of the HTTP response.17 response = b""10 unmodified lines28 assert ended29 return response30 31 37-@pytest.mark.parametrize(38- "backend, get_cipher",39- [40- pytest.param(AsyncioBackend(), get_asyncio_cipher, marks=pytest.mark.asyncio),41- pytest.param(TrioBackend(), get_trio_cipher, marks=pytest.mark.trio),42- ],43-)44-async def test_start_tls_on_tcp_socket_stream(https_server, backend, get_cipher):32+async def test_start_tls_on_tcp_socket_stream(https_server, backend):33+ backend = lookup_backend(backend)34 ctx = SSLConfig().load_ssl_context_no_verify()35 timeout = Timeout(5)36 37 stream = await backend.open_tcp_stream(1 unmodified line39 )40 41 try:42 assert stream.is_connection_dropped() is False54- assert get_cipher(stream) is None43+ assert get_cipher(backend, stream) is None44 45 stream = await stream.start_tls(https_server.url.host, ctx, timeout)46 assert stream.is_connection_dropped() is False58- assert get_cipher(stream) is not None47+ assert get_cipher(backend, stream) is not None48 49 await stream.write(b"GET / HTTP/1.1\r\n\r\n", timeout)50 51 response = await read_response(stream, timeout, should_contain=b"Hello, world")2 unmodified lines54 finally:55 await stream.close()56 57 69-@pytest.mark.parametrize(70- "backend, get_cipher",71- [72- pytest.param(AsyncioBackend(), get_asyncio_cipher, marks=pytest.mark.asyncio),73- pytest.param(TrioBackend(), get_trio_cipher, marks=pytest.mark.trio),74- ],75-)76-async def test_start_tls_on_uds_socket_stream(https_uds_server, backend, get_cipher):58+async def test_start_tls_on_uds_socket_stream(https_uds_server, backend):59+ backend = lookup_backend(backend)60 ctx = SSLConfig().load_ssl_context_no_verify()61 timeout = Timeout(5)62 63 stream = await backend.open_uds_stream(1 unmodified line65 )66 67 try:68 assert stream.is_connection_dropped() is False86- assert get_cipher(stream) is None69+ assert get_cipher(backend, stream) is None70 71 stream = await stream.start_tls(https_uds_server.url.host, ctx, timeout)72 assert stream.is_connection_dropped() is False90- assert get_cipher(stream) is not None73+ assert get_cipher(backend, stream) is not None74 75 await stream.write(b"GET / HTTP/1.1\r\n\r\n", timeout)76 77 response = await read_response(stream, timeout, should_contain=b"Hello, world")6 unmodified lines84 async def test_concurrent_read(server, backend):85 """86 Regression test for: https://github.com/encode/httpx/issues/52787 """88+ backend = lookup_backend(backend)89 stream = await backend.open_tcp_stream(90 server.url.host, server.url.port, ssl_context=None, timeout=Timeout(5)91 )92 timeout = Timeout(5)6 unmodified lines99 await stream.close()100 101 102 async def test_fork(backend):103+ backend = lookup_backend(backend)104 ok_counter = 0105 106 async def ok(delay: int) -> None:107 nonlocal ok_counter35 unmodified lines143 144 # No 'match', since we can't know which will be raised first.145 with pytest.raises(RuntimeError):146 await backend.fork(fail, ["My bad", 0], fail, ["Oops", 0])147+148+149+def test_lookup_backend():150+ assert isinstance(lookup_backend("asyncio"), AsyncioBackend)151+ assert isinstance(lookup_backend("trio"), TrioBackend)152+ assert isinstance(lookup_backend(AsyncioBackend()), AsyncioBackend)153+154+ async def get_backend_from_auto():155+ auto_backend = lookup_backend("auto")156+ return auto_backend.backend157+158+ loop = asyncio.get_event_loop()159+ backend = loop.run_until_complete(get_backend_from_auto())160+ assert isinstance(backend, AsyncioBackend)161+162+ backend = trio.run(get_backend_from_auto)163+ assert isinstance(backend, TrioBackend)164+165+ with pytest.raises(Exception, match="unknownio"):166+ lookup_backend("unknownio")modified:tests/test_timeouts.py+4 added-6 removed
4 unmodified lines5 6 async def test_read_timeout(server, backend):7 timeout = httpx.Timeout(read_timeout=1e-6)8 9- async with httpx.Client(timeout=timeout, backend=backend) as client:9+ async with httpx.Client(timeout=timeout) as client:10 with pytest.raises(httpx.ReadTimeout):11 await client.get(server.url.copy_with(path="/slow_response"))12 13 14 async def test_write_timeout(server, backend):15 timeout = httpx.Timeout(write_timeout=1e-6)16 17- async with httpx.Client(timeout=timeout, backend=backend) as client:17+ async with httpx.Client(timeout=timeout) as client:18 with pytest.raises(httpx.WriteTimeout):19 data = b"*" * 1024 * 1024 * 10020 await client.put(server.url.copy_with(path="/slow_response"), data=data)21 22 23 async def test_connect_timeout(server, backend):24 timeout = httpx.Timeout(connect_timeout=1e-6)25 26- async with httpx.Client(timeout=timeout, backend=backend) as client:26+ async with httpx.Client(timeout=timeout) as client:27 with pytest.raises(httpx.ConnectTimeout):28 # See https://stackoverflow.com/questions/100841/29 await client.get("http://10.255.255.1/")30 1 unmodified line32 async def test_pool_timeout(server, backend):33 pool_limits = httpx.PoolLimits(hard_limit=1)34 timeout = httpx.Timeout(pool_timeout=1e-4)35 36- async with httpx.Client(37- pool_limits=pool_limits, timeout=timeout, backend=backend38- ) as client:36+ async with httpx.Client(pool_limits=pool_limits, timeout=timeout) as client:37 async with client.stream("GET", server.url):38 with pytest.raises(httpx.PoolTimeout):39 await client.get("http://localhost:8000/")