Skip to content
Myr

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

11 files+155 added−108 removed

modified:tests/client/test_async_client.py+29 added-15 removed
5 unmodified lines
678async 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 lines
1920async 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 lines
474849async 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 == 200545556async 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 == 200616263async 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()6768 assert response.status_code == 200
1 unmodified line
70 assert response.content == b"Hello, world!"717273async 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 pass7778 assert response.status_code == 200
5 unmodified lines
84 async def hello_world():85 yield b"Hello, "86 yield b"world!"8788 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 == 200919293async 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 lines
105 assert response.raise_for_status() is None106107108async 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!"113114115async 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 == ""120121122async 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 == 200126127128async 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 == 200132133134async 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 line
141async def test_100_continue(server, backend):142 headers = {"Expect": "100-continue"}143 data = b"Echo request body"144145 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 lines
154async 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"163164165@pytest.mark.parametrize(166 "backend",167 [168 pytest.param("asyncio", marks=pytest.mark.asyncio),169 pytest.param("trio", marks=pytest.mark.trio),170 ],171)172async 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 lines
104 return Response(codes.OK, content=b"Hello, world!", request=request)105106107async 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()114115116async 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) == 1122123124async 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) == 1130131132async 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) == 1138139140async 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_OTHER
8 unmodified lines
154 assert len(response.history) == 1155156157async 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) == 1163164165async 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) == 1171172173async 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) == 1179180181async 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) == 20
7 unmodified lines
194 assert len(response.history[1].history) == 1195196197async 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")201202203async 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()210211212async 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")216217218async 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()225226227async 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"]234235236async 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 lines
245async 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 lines
258async 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 line
268 assert "content-length" not in response.json()["headers"]269270271async 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"274275 async def streaming_body():276 yield b"Example request body"
2 unmodified lines
279 await client.post(url, data=streaming_body())280281282async 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 lines
325 return Response(status_code, headers=headers, request=request)326327328async def test_redirect_cookie_behavior(backend):329 client = Client(dispatch=MockCookieDispatch(), backend=backend)329 client = Client(dispatch=MockCookieDispatch())330331 # The client is not logged in.332 response = await client.get("https://example.com/")333 assert response.url == "https://example.com/"
21 unmodified lines
modified:tests/dispatch/test_connection_pools.py+11 added-13 removed
4 unmodified lines
5async 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) == 1
7 unmodified lines
21async 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) == 1
9 unmodified lines
39 The soft_limit config should limit the maximum number of keep-alive connections.40 """41 pool_limits = httpx.PoolLimits(soft_limit=1)4243 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) == 1
7 unmodified lines
55async 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 lines
70async 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 lines
93 """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) == 0
2 unmodified lines
104async 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) == 0
3 unmodified lines
116async 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) == 0
5 unmodified lines
130 """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()137138 # Shutdown the server to close the keep-alive connection
11 unmodified lines
150 """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()157158 # Shutdown the server to close the keep-alive connection
9 unmodified lines
168 """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()175176 # Close the connection so we're forced to recycle it
4 unmodified lines
modified:tests/dispatch/test_connections.py+5 added-7 removed
3 unmodified lines
4from httpx.dispatch.connection import HTTPConnection567async 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!"131415async 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 == 200192021async 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 lines
30async 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 lines
41async 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 lines
103 assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}104105106async def test_http2_settings_in_handshake(backend):107 backend = MockHTTP2Backend(app=app, backend=backend)107 backend = MockHTTP2Backend(app=app)108109 async with Client(backend=backend, http2=True) as client:110 await client.get("http://example.org")111
26 unmodified lines
138 assert changed_setting.new_value == expected_settings[setting_code]139140141async 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 lines
modified:tests/dispatch/test_proxy_http.py-4 removed
17 unmodified lines
18 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 lines
51 b"Server: proxy-server\r\n"52 b"\r\n",53 ]54 ),56 backend=backend,55 )5657 with pytest.raises(httpx.ProxyError) as e:58 async with httpx.HTTPProxy(
43 unmodified lines
102 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 lines
151 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 lines
modified:tests/dispatch/utils.py+5 added-6 removed
4 unmodified lines
5import h2.connection6import h2.events78from httpx import Request, Timeout9from httpx.concurrency.asyncio import AsyncioBackend10from httpx.concurrency.base import BaseSocketStream9from httpx.concurrency.base import BaseSocketStream, lookup_backend10from tests.concurrency import sleep111213class 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 = None1819 async def open_tcp_stream(20 self,
145 unmodified lines
166 self.buffer += self.conn.data_to_send()167168169class 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 lines
modified:tests/concurrency.py+31 added
8 unmodified lines
910import trio1112from httpx.concurrency.asyncio import AsyncioBackend13from httpx.concurrency.auto import AutoBackend14from httpx.concurrency.trio import TrioBackend151617@functools.singledispatch18async def sleep(backend, seconds: int):19 raise NotImplementedError # pragma: no cover202122@sleep.register(AutoBackend)23async def _sleep_auto(backend, seconds: int):24 return await sleep(backend.backend, seconds=seconds)252627@sleep.register(AsyncioBackend)28async def _sleep_asyncio(backend, seconds: int):29 await asyncio.sleep(seconds)30
7 unmodified lines
38async def run_concurrently(backend, *coroutines: typing.Callable[[], typing.Awaitable]):39 raise NotImplementedError # pragma: no cover404142@run_concurrently.register(AutoBackend)43async def _run_concurrently_auto(backend, *coroutines):44 await run_concurrently(backend.backend, *coroutines)454647@run_concurrently.register(AsyncioBackend)48async def _run_concurrently_asyncio(backend, *coroutines):49 coros = (coroutine() for coroutine in coroutines)50 await asyncio.gather(*coros)
3 unmodified lines
54async def _run_concurrently_trio(backend, *coroutines):55 async with trio.open_nursery() as nursery:56 for coroutine in coroutines:57 nursery.start_soon(coroutine)585960@functools.singledispatch61def get_cipher(backend, stream):62 raise NotImplementedError # pragma: no cover636465@get_cipher.register(AutoBackend)66def _get_cipher_auto(backend, stream):67 return get_cipher(backend.backend, stream)686970@get_cipher.register(AsyncioBackend)71def _get_cipher_asyncio(backend, stream):72 return stream.stream_writer.get_extra_info("cipher", default=None)737475@get_cipher.register(TrioBackend)76def get_trio_cipher(backend, stream):77 return stream.stream.cipher() if isinstance(stream.stream, trio.SSLStream) else None
modified:tests/conftest.py+14 added-6 removed
17 unmodified lines
18from uvicorn.main import Server1920from httpx import URL21from httpx.concurrency.asyncio import AsyncioBackend22from httpx.concurrency.trio import TrioBackend22from httpx.concurrency.base import lookup_backend2324ENVIRONMENT_VARIABLES = {25 "SSL_CERT_FILE",26 "SSL_CERT_DIR",
23 unmodified lines
505152@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)63def backend(request):59 backend_cls = request.param60 return backend_cls()64 return request.param656667async def app(scope, receive, send):68 assert scope["type"] == "http"
205 unmodified lines
274275 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)280281 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 )285286 return restart287288
57 unmodified lines
modified:tests/test_concurrency.py+34 added-29 removed
1import asyncio23import pytest4import trio56from httpx import Timeout7from httpx.concurrency.asyncio import AsyncioBackend8from httpx.concurrency.base import lookup_backend9from httpx.concurrency.trio import TrioBackend10from httpx.config import SSLConfig8from tests.concurrency import run_concurrently, sleep11from tests.concurrency import get_cipher, run_concurrently, sleep121311def get_asyncio_cipher(stream):12 return stream.stream_writer.get_extra_info("cipher", default=None)131415def get_trio_cipher(stream):16 return stream.stream.cipher() if isinstance(stream.stream, trio.SSLStream) else None171814async 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 lines
28 assert ended29 return response303137@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)44async def test_start_tls_on_tcp_socket_stream(https_server, backend, get_cipher):32async 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)3637 stream = await backend.open_tcp_stream(
1 unmodified line
39 )4041 try:42 assert stream.is_connection_dropped() is False54 assert get_cipher(stream) is None43 assert get_cipher(backend, stream) is None4445 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 None4849 await stream.write(b"GET / HTTP/1.1\r\n\r\n", timeout)5051 response = await read_response(stream, timeout, should_contain=b"Hello, world")
2 unmodified lines
54 finally:55 await stream.close()565769@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)76async def test_start_tls_on_uds_socket_stream(https_uds_server, backend, get_cipher):58async 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)6263 stream = await backend.open_uds_stream(
1 unmodified line
65 )6667 try:68 assert stream.is_connection_dropped() is False86 assert get_cipher(stream) is None69 assert get_cipher(backend, stream) is None7071 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 None7475 await stream.write(b"GET / HTTP/1.1\r\n\r\n", timeout)7677 response = await read_response(stream, timeout, should_contain=b"Hello, world")
6 unmodified lines
84async 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 lines
99 await stream.close()100101102async def test_fork(backend):103 backend = lookup_backend(backend)104 ok_counter = 0105106 async def ok(delay: int) -> None:107 nonlocal ok_counter
35 unmodified lines
143144 # 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])147148149def test_lookup_backend():150 assert isinstance(lookup_backend("asyncio"), AsyncioBackend)151 assert isinstance(lookup_backend("trio"), TrioBackend)152 assert isinstance(lookup_backend(AsyncioBackend()), AsyncioBackend)153154 async def get_backend_from_auto():155 auto_backend = lookup_backend("auto")156 return auto_backend.backend157158 loop = asyncio.get_event_loop()159 backend = loop.run_until_complete(get_backend_from_auto())160 assert isinstance(backend, AsyncioBackend)161162 backend = trio.run(get_backend_from_auto)163 assert isinstance(backend, TrioBackend)164165 with pytest.raises(Exception, match="unknownio"):166 lookup_backend("unknownio")
modified:tests/test_timeouts.py+4 added-6 removed
4 unmodified lines
56async def test_read_timeout(server, backend):7 timeout = httpx.Timeout(read_timeout=1e-6)89 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"))121314async def test_write_timeout(server, backend):15 timeout = httpx.Timeout(write_timeout=1e-6)1617 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)212223async def test_connect_timeout(server, backend):24 timeout = httpx.Timeout(connect_timeout=1e-6)2526 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 line
32async def test_pool_timeout(server, backend):33 pool_limits = httpx.PoolLimits(hard_limit=1)34 timeout = httpx.Timeout(pool_timeout=1e-4)3536 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/")