]> git.ipfire.org Git - thirdparty/starlette.git/commitdiff
docs: use `transport` instead of directly pass the app to AsyncClient (#2784)
authorMarcelo Trylesinski <marcelotryle@gmail.com>
Thu, 5 Dec 2024 08:53:54 +0000 (09:53 +0100)
committerGitHub <noreply@github.com>
Thu, 5 Dec 2024 08:53:54 +0000 (09:53 +0100)
docs/testclient.md

index 33da3348bb157a3f92d21e46852cd600bb5c1c8b..99346af8bfa543fd0919b1fb042f4c7c971f9a94 100644 (file)
@@ -165,15 +165,17 @@ May raise `starlette.websockets.WebSocketDisconnect`.
 ### Asynchronous tests
 
 Sometimes you will want to do async things outside of your application.
-For example, you might want to check the state of your database after calling your app using your existing async database client / infrastructure.
+For example, you might want to check the state of your database after calling your app
+using your existing async database client/infrastructure.
 
-For these situations, using `TestClient` is difficult because it creates it's own event loop and async resources (like a database connection) often cannot be shared across event loops.
+For these situations, using `TestClient` is difficult because it creates it's own event loop and async
+resources (like a database connection) often cannot be shared across event loops.
 The simplest way to work around this is to just make your entire test async and use an async client, like [httpx.AsyncClient].
 
 Here is an example of such a test:
 
 ```python
-from httpx import AsyncClient
+from httpx import AsyncClient, ASGITransport
 from starlette.applications import Starlette
 from starlette.routing import Route
 from starlette.requests import Request
@@ -192,7 +194,8 @@ app = Starlette(routes=[Route("/", hello)])
 # or install and configure pytest-asyncio (https://github.com/pytest-dev/pytest-asyncio)
 async def test_app() -> None:
     # note: you _must_ set `base_url` for relative urls like "/" to work
-    async with AsyncClient(app=app, base_url="http://testserver") as client:
+    transport = ASGITransport(app=app)
+    async with AsyncClient(transport=transport, base_url="http://testserver") as client:
         r = await client.get("/")
         assert r.status_code == 200
         assert r.text == "Hello World!"