Differences between starlette.testclient.TestClient and httpx.AsyncClient #1877
-
Hi, I was inspired by the release docs, which mention the change in underlying library used in TestClient from By looking at the code, it seems like:
Maybe the main reason for using starlette.TestClient is that it adds support for websocket connections, which seems to be lacking out-of-the-box in httpx? If so, maybe it would be a good idea to write it in the documentation?
Thanks a lot :) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I think your analysis is correct, unless there's something I didn;t see in the switch.
yup good call |
Beta Was this translation helpful? Give feedback.
-
A comment: the docs mention async issues. I wanted to give a concrete example of how """
run `python -m unittest <this file>`
"""
from unittest import IsolatedAsyncioTestCase
import asyncio
from httpx import AsyncClient
from starlette.responses import HTMLResponse
from starlette.testclient import TestClient
task = None
async def wait_and_print():
print("sleeping")
await asyncio.sleep(5)
print("done")
async def app(scope, receive, send):
assert scope["type"] == "http"
response = HTMLResponse("<html><body>Hello, world!</body></html>")
global task
task = asyncio.create_task(wait_and_print())
await response(scope, receive, send)
class TestApp(IsolatedAsyncioTestCase):
async def test_app(self):
client = TestClient(app)
r = client.get("/")
assert r.status_code == 200
await asyncio.sleep(10) # "done" IS NOT printed
async def test_app_async(self):
async with AsyncClient(app=app, base_url="http://testserver") as client:
r = await client.get("/")
assert r.status_code == 200
await asyncio.sleep(10) # "done" IS printed |
Beta Was this translation helpful? Give feedback.
I think your analysis is correct, unless there's something I didn;t see in the switch.
I'm too using vanilla httpx for a long time now and to me the only difference with the new TestClient is the websocket part.
I dont intend on switching btw
yup good call