Skip to content

Commit 8f0ba1f

Browse files
committed
test: fix the warnings in the tests by not using deprecated APIs from httpx
1 parent 4a7f4b9 commit 8f0ba1f

File tree

5 files changed

+70
-57
lines changed

5 files changed

+70
-57
lines changed

tests/app/tool.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ def contx_socket_url(self) -> httpx.URL:
213213
)
214214

215215

216-
class TestServer:
216+
class AutoServer:
217217
"""An AsyncContext to launch and shutdown Hypercorn or Uvicorn server automatically."""
218218

219219
def __init__(

tests/conftest.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131

3232
from .app.echo_http_app import get_app as get_http_test_app
3333
from .app.echo_ws_app import get_app as get_ws_test_app
34-
from .app.tool import AppDataclass4Test, TestServer
34+
from .app.tool import AppDataclass4Test, AutoServer
3535

3636
# ASGI types.
3737
# Copied from: https://github.com/florimondmanca/asgi-lifespan/blob/fbb0f440337314be97acaae1a3c0c7a2ec8298dd/src/asgi_lifespan/_types.py
@@ -62,14 +62,14 @@ class LifeAppDataclass4Test(AppDataclass4Test):
6262
"""The lifespan of app will be managed automatically by pytest."""
6363

6464

65-
class TestServerFixture(Protocol): # noqa: D101
65+
class AutoServerFixture(Protocol): # noqa: D101
6666
def __call__( # noqa: D102
6767
self,
6868
app: FastAPI,
6969
host: str,
7070
port: int,
7171
server_type: Optional[Literal["uvicorn", "hypercorn"]] = None,
72-
) -> Coroutine[None, None, TestServer]: ...
72+
) -> Coroutine[None, None, AutoServer]: ...
7373

7474

7575
# https://anyio.readthedocs.io/en/stable/testing.html#specifying-the-backends-to-run-on
@@ -203,22 +203,22 @@ def reverse_ws_app_fct(
203203

204204

205205
@pytest.fixture()
206-
async def test_server_fixture() -> AsyncIterator[TestServerFixture]:
207-
"""Fixture for TestServer.
206+
async def auto_server_fixture() -> AsyncIterator[AutoServerFixture]:
207+
"""Fixture for AutoServer.
208208
209209
Will launch and shutdown automatically.
210210
"""
211211
async with AsyncExitStack() as exit_stack:
212212

213-
async def test_server_fct(
213+
async def auto_server_fct(
214214
app: FastAPI,
215215
host: str,
216216
port: int,
217217
server_type: Optional[Literal["uvicorn", "hypercorn"]] = None,
218-
) -> TestServer:
219-
test_server = await exit_stack.enter_async_context(
220-
TestServer(app=app, host=host, port=port, server_type=server_type)
218+
) -> AutoServer:
219+
auto_server = await exit_stack.enter_async_context(
220+
AutoServer(app=app, host=host, port=port, server_type=server_type)
221221
)
222-
return test_server
222+
return auto_server
223223

224-
yield test_server_fct
224+
yield auto_server_fct

tests/test_core_lib.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,10 @@ async def _() -> JSONResponse:
7070
# }
7171
# }
7272

73-
client = httpx.AsyncClient(app=app, base_url="http://www.example.com")
73+
client = httpx.AsyncClient(
74+
transport=httpx.ASGITransport(app), # pyright: ignore[reportArgumentType]
75+
base_url="http://www.example.com",
76+
)
7477
resp = await client.get("http://www.example.com/exception")
7578
assert resp.status_code == 0
7679
assert resp.json()["detail"] == test_err_msg

tests/test_http.py

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,10 @@ async def tool_4_test_fixture( # pyright: ignore[reportIncompatibleMethodOverri
3232
) -> Tool4TestFixture:
3333
"""目标服务器请参考`tests.app.echo_http_app.get_app`."""
3434
client_for_conn_to_target_server = httpx.AsyncClient(
35-
app=echo_http_test_model.app, base_url=DEFAULT_TARGET_SERVER_BASE_URL
35+
transport=httpx.ASGITransport(
36+
echo_http_test_model.app # pyright: ignore[reportArgumentType]
37+
),
38+
base_url=DEFAULT_TARGET_SERVER_BASE_URL,
3639
)
3740

3841
reverse_http_app = await reverse_http_app_fct(
@@ -41,7 +44,10 @@ async def tool_4_test_fixture( # pyright: ignore[reportIncompatibleMethodOverri
4144
)
4245

4346
client_for_conn_to_proxy_server = httpx.AsyncClient(
44-
app=reverse_http_app, base_url=DEFAULT_PROXY_SERVER_BASE_URL
47+
transport=httpx.ASGITransport(
48+
reverse_http_app # pyright: ignore[reportArgumentType]
49+
),
50+
base_url=DEFAULT_PROXY_SERVER_BASE_URL,
4551
)
4652

4753
get_request = echo_http_test_model.get_request
@@ -198,7 +204,10 @@ async def test_bad_url_request(
198204
)
199205

200206
client_for_conn_to_proxy_server = httpx.AsyncClient(
201-
app=reverse_http_app, base_url=DEFAULT_PROXY_SERVER_BASE_URL
207+
transport=httpx.ASGITransport(
208+
reverse_http_app # pyright: ignore[reportArgumentType]
209+
),
210+
base_url=DEFAULT_PROXY_SERVER_BASE_URL,
202211
)
203212

204213
r = await client_for_conn_to_proxy_server.get(DEFAULT_PROXY_SERVER_BASE_URL)
@@ -233,9 +242,9 @@ async def test_cookie_leakage(
233242
assert not client_for_conn_to_proxy_server.cookies
234243

235244
# check if cookie is not leaked
245+
client_for_conn_to_proxy_server.cookies.set("a", "b")
236246
r = await client_for_conn_to_proxy_server.get(
237-
proxy_server_base_url + "get/cookies",
238-
cookies={"a": "b"},
247+
proxy_server_base_url + "get/cookies"
239248
)
240249
assert "foo" not in r.json() # not leaked
241250
assert r.json()["a"] == "b" # send cookies normally
@@ -252,15 +261,21 @@ async def tool_4_test_fixture( # pyright: ignore[reportIncompatibleMethodOverri
252261
) -> Tool4TestFixture:
253262
"""目标服务器请参考`tests.app.echo_http_app.get_app`."""
254263
client_for_conn_to_target_server = httpx.AsyncClient(
255-
app=echo_http_test_model.app, base_url=DEFAULT_TARGET_SERVER_BASE_URL
264+
transport=httpx.ASGITransport(
265+
echo_http_test_model.app # pyright: ignore[reportArgumentType]
266+
),
267+
base_url=DEFAULT_TARGET_SERVER_BASE_URL,
256268
)
257269

258270
forward_http_app = await forward_http_app_fct(
259271
client=client_for_conn_to_target_server, proxy_filter=default_proxy_filter
260272
)
261273

262274
client_for_conn_to_proxy_server = httpx.AsyncClient(
263-
app=forward_http_app, base_url=DEFAULT_PROXY_SERVER_BASE_URL
275+
transport=httpx.ASGITransport(
276+
forward_http_app # pyright: ignore[reportArgumentType]
277+
),
278+
base_url=DEFAULT_PROXY_SERVER_BASE_URL,
264279
)
265280

266281
get_request = echo_http_test_model.get_request
@@ -310,7 +325,10 @@ async def test_bad_url_request(
310325
)
311326

312327
client_for_conn_to_proxy_server = httpx.AsyncClient(
313-
app=forward_http_app, base_url=DEFAULT_PROXY_SERVER_BASE_URL
328+
transport=httpx.ASGITransport(
329+
forward_http_app # pyright: ignore[reportArgumentType]
330+
),
331+
base_url=DEFAULT_PROXY_SERVER_BASE_URL,
314332
)
315333

316334
# 错误的无法发出请求的URL
@@ -356,7 +374,10 @@ async def connect_error_mock_handler(
356374
)
357375

358376
client_for_conn_to_proxy_server = httpx.AsyncClient(
359-
app=forward_http_app, base_url=DEFAULT_PROXY_SERVER_BASE_URL
377+
transport=httpx.ASGITransport(
378+
forward_http_app # pyright: ignore[reportArgumentType]
379+
),
380+
base_url=DEFAULT_PROXY_SERVER_BASE_URL,
360381
)
361382

362383
r = await client_for_conn_to_proxy_server.get(
@@ -385,7 +406,9 @@ async def test_denial_http2(
385406
)
386407

387408
client_for_conn_to_proxy_server = httpx.AsyncClient(
388-
app=forward_http_app,
409+
transport=httpx.ASGITransport(
410+
forward_http_app
411+
), # pyright: ignore[reportArgumentType]
389412
base_url=proxy_server_base_url,
390413
http2=True,
391414
http1=False,

tests/test_ws.py

Lines changed: 21 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
from contextlib import AsyncExitStack
55
from multiprocessing import Process, Queue
6-
from typing import Any, Dict, Optional
6+
from typing import Any, Dict
77

88
import anyio
99
import httpx
@@ -15,8 +15,8 @@
1515
from typing_extensions import override
1616

1717
from .app.echo_ws_app import get_app as get_ws_test_app
18-
from .app.tool import TestServer
19-
from .conftest import TestServerFixture
18+
from .app.tool import AutoServer
19+
from .conftest import AutoServerFixture
2020
from .tool import (
2121
AbstractTestProxy,
2222
Tool4TestFixture,
@@ -25,7 +25,8 @@
2525
DEFAULT_HOST = "127.0.0.1"
2626
DEFAULT_PORT = 0 # random port
2727

28-
# https://www.python-httpx.org/advanced/#http-proxying
28+
# https://www.python-httpx.org/advanced/proxies/
29+
# NOTE: Foce to connect directly, avoid using system proxies
2930
NO_PROXIES: Dict[Any, Any] = {"all://": None}
3031

3132

@@ -36,7 +37,7 @@ def _subprocess_run_echo_ws_server(queue: "Queue[str]"):
3637
queue: The queue for subprocess to put the url of echo ws app.
3738
After the server is started, the url will be put into the queue.
3839
"""
39-
target_ws_server = TestServer(
40+
target_ws_server = AutoServer(
4041
app=get_ws_test_app().app,
4142
host=DEFAULT_HOST,
4243
port=DEFAULT_PORT,
@@ -55,29 +56,22 @@ async def run():
5556

5657
def _subprocess_run_httpx_ws(
5758
queue: "Queue[str]",
58-
kwargs_async_client: Optional[Dict[str, Any]] = None,
59-
kwargs_aconnect_ws: Optional[Dict[str, Any]] = None,
59+
aconnect_ws_url: str,
6060
):
6161
"""Run aconnect_ws in subprocess.
6262
6363
Args:
6464
queue: The queue for subprocess to put something for flag of ws connection established.
65-
kwargs_async_client: The kwargs for `httpx.AsyncClient`
66-
kwargs_aconnect_ws: The kwargs for `httpx_ws.aconnect_ws`
65+
aconnect_ws_url: The websocket url for aconnect_ws.
6766
"""
68-
kwargs_async_client = kwargs_async_client or {}
69-
kwargs_aconnect_ws = kwargs_aconnect_ws or {}
70-
71-
kwargs_async_client.pop("proxies", None)
72-
kwargs_aconnect_ws.pop("client", None)
7367

7468
async def run():
7569
_exit_stack = AsyncExitStack()
76-
_temp_client = httpx.AsyncClient(proxies=NO_PROXIES, **kwargs_async_client)
70+
_temp_client = httpx.AsyncClient(mounts=NO_PROXIES)
7771
_ = await _exit_stack.enter_async_context(
7872
aconnect_ws(
7973
client=_temp_client,
80-
**kwargs_aconnect_ws,
74+
url=aconnect_ws_url,
8175
)
8276
)
8377
queue.put("done")
@@ -95,32 +89,32 @@ class TestReverseWsProxy(AbstractTestProxy):
9589
@pytest.fixture()
9690
async def tool_4_test_fixture( # pyright: ignore[reportIncompatibleMethodOverride]
9791
self,
98-
test_server_fixture: TestServerFixture,
92+
auto_server_fixture: AutoServerFixture,
9993
) -> Tool4TestFixture:
10094
"""目标服务器请参考`tests.app.echo_ws_app.get_app`."""
10195
echo_ws_test_model = get_ws_test_app()
10296
echo_ws_app = echo_ws_test_model.app
10397
echo_ws_get_request = echo_ws_test_model.get_request
10498

105-
target_ws_server = await test_server_fixture(
99+
target_ws_server = await auto_server_fixture(
106100
app=echo_ws_app, port=DEFAULT_PORT, host=DEFAULT_HOST
107101
)
108102

109103
target_server_base_url = str(target_ws_server.contx_socket_url)
110104

111-
client_for_conn_to_target_server = httpx.AsyncClient(proxies=NO_PROXIES)
105+
client_for_conn_to_target_server = httpx.AsyncClient(mounts=NO_PROXIES)
112106

113107
reverse_ws_app = get_reverse_ws_app(
114108
client=client_for_conn_to_target_server, base_url=target_server_base_url
115109
)
116110

117-
proxy_ws_server = await test_server_fixture(
111+
proxy_ws_server = await auto_server_fixture(
118112
app=reverse_ws_app, port=DEFAULT_PORT, host=DEFAULT_HOST
119113
)
120114

121115
proxy_server_base_url = str(proxy_ws_server.contx_socket_url)
122116

123-
client_for_conn_to_proxy_server = httpx.AsyncClient(proxies=NO_PROXIES)
117+
client_for_conn_to_proxy_server = httpx.AsyncClient(mounts=NO_PROXIES)
124118

125119
return Tool4TestFixture(
126120
client_for_conn_to_target_server=client_for_conn_to_target_server,
@@ -189,18 +183,11 @@ async def test_ws_proxy(self, tool_4_test_fixture: Tool4TestFixture) -> None:
189183
# 是因为这里已经有现成的target server,放在这里测试可以节省启动服务器时间
190184

191185
aconnect_ws_subprocess_queue: "Queue[str]" = Queue()
192-
193-
kwargs_async_client = {"proxies": NO_PROXIES}
194-
kwargs_aconnect_ws = {"url": proxy_server_base_url + "do_nothing"}
195-
kwargs = {
196-
"kwargs_async_client": kwargs_async_client,
197-
"kwargs_aconnect_ws": kwargs_aconnect_ws,
198-
}
186+
aconnect_ws_url = proxy_server_base_url + "do_nothing"
199187

200188
aconnect_ws_subprocess = Process(
201189
target=_subprocess_run_httpx_ws,
202-
args=(aconnect_ws_subprocess_queue,),
203-
kwargs=kwargs,
190+
args=(aconnect_ws_subprocess_queue, aconnect_ws_url),
204191
)
205192
aconnect_ws_subprocess.start()
206193

@@ -246,13 +233,13 @@ async def test_target_server_shutdown_abnormally(self) -> None:
246233
await anyio.sleep(0.1)
247234
target_server_base_url = subprocess_queue.get()
248235

249-
client_for_conn_to_target_server = httpx.AsyncClient(proxies=NO_PROXIES)
236+
client_for_conn_to_target_server = httpx.AsyncClient(mounts=NO_PROXIES)
250237

251238
reverse_ws_app = get_reverse_ws_app(
252239
client=client_for_conn_to_target_server, base_url=target_server_base_url
253240
)
254241

255-
async with TestServer(
242+
async with AutoServer(
256243
app=reverse_ws_app,
257244
port=DEFAULT_PORT,
258245
host=DEFAULT_HOST,
@@ -261,10 +248,10 @@ async def test_target_server_shutdown_abnormally(self) -> None:
261248

262249
async with aconnect_ws(
263250
proxy_server_base_url + "do_nothing",
264-
httpx.AsyncClient(proxies=NO_PROXIES),
251+
httpx.AsyncClient(mounts=NO_PROXIES),
265252
) as ws0, aconnect_ws(
266253
proxy_server_base_url + "do_nothing",
267-
httpx.AsyncClient(proxies=NO_PROXIES),
254+
httpx.AsyncClient(mounts=NO_PROXIES),
268255
) as ws1:
269256
# force shutdown target server
270257
target_ws_server_subprocess.terminate()

0 commit comments

Comments
 (0)