]> git.ipfire.org Git - thirdparty/starlette.git/commitdiff
Document using httpx for async tests (#1728)
authorAdrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>
Wed, 6 Jul 2022 16:43:04 +0000 (11:43 -0500)
committerGitHub <noreply@github.com>
Wed, 6 Jul 2022 16:43:04 +0000 (11:43 -0500)
docs/testclient.md

index f42093030f56f40eb71926329789ed4959f94297..64c766df8e09605b6fcecdbc07613027a28c2e66 100644 (file)
@@ -154,3 +154,41 @@ May raise `starlette.websockets.WebSocketDisconnect`.
 #### Closing the connection
 
 * `.close(code=1000)` - Perform a client-side close of the websocket connection.
+
+### 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 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 starlette.applications import Starlette
+from starlette.routing import Route
+from starlette.requests import Request
+from starlette.responses import PlainTextResponse
+
+
+def hello(request: Request) -> PlainTextResponse:
+    return PlainTextResponse("Hello World!")
+
+
+app = Starlette(routes=[Route("/", hello)])
+
+
+# if you're using pytest, you'll need to to add an async marker like:
+# @pytest.mark.anyio  # using https://github.com/agronholm/anyio
+# 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:
+        r = await client.get("/")
+        assert r.status_code == 200
+        assert r.text == "Hello World!"
+```
+
+[httpx.AsyncClient]: https://www.python-httpx.org/advanced/#calling-into-python-web-apps