ushka.testing
A test client for Ushka apps, on the standard library only.
:
from ushka.testing import TestClient
async def test_signup():
async with TestClient(app) as client: # runs on_startup / on_shutdown
res = await client.post("/signup", data={"email": "a@b.c"})
assert res.status_code == 200
assert (await client.get("/me")).json()["email"] == "a@b.c" # the cookie stayed
It speaks ASGI to the app directly (no socket), keeps cookies between requests
like a browser would, and runs the ASGI lifespan, which httpx.ASGITransport
does not: on_startup hooks never fire there.
By default requests look like they come from a script (no Origin or
Sec-Fetch-Site), which the CSRF check lets through. TestClient(app, browser=True)
makes every request look like a same-origin browser request instead; pass
headers={"Sec-Fetch-Site": "cross-site"} to simulate an attack.
In this module
class TestResponse | What a TestClient call returns. |
class TestClient | Calls an ASGI app in-process. Use it as async with TestClient(app) as client. |
class TestResponse
What a TestClient call returns.
json
def json() -> Anyheader_list
def header_list(name: str) -> list[str]Every value of a header that may repeat (set-cookie).
class TestClient
Calls an ASGI app in-process. Use it as async with TestClient(app) as client.
Methods
startup | Runs the app's startup hooks (done for you by async with). |
shutdown | Runs the app's shutdown hooks (done for you by async with). |
request | Sends one request and returns a TestResponse. |
get | |
head | |
options | |
post | |
put | |
patch | |
delete |
startup
async def startup() -> NoneRuns the app's startup hooks (done for you by async with).
shutdown
async def shutdown() -> NoneRuns the app's shutdown hooks (done for you by async with).
request
async def request(
method: str,
url: str,
*,
params: dict | None = None,
json: Any = None,
data: dict | bytes | str | None = None,
files: dict | None = None,
headers: dict[str, str] | None = None,
cookies: dict[str, str] | None = None,
follow_redirects: bool = False,
) -> TestResponseSends one request and returns a TestResponse.
json sends a JSON body; data a form (a dict becomes urlencoded, or
multipart when files is given); files maps a field name to
(filename, bytes) or (filename, bytes, content_type).
get
async def get(url: str, **kw: Any) -> TestResponsehead
async def head(url: str, **kw: Any) -> TestResponseoptions
async def options(url: str, **kw: Any) -> TestResponsepost
async def post(url: str, **kw: Any) -> TestResponseput
async def put(url: str, **kw: Any) -> TestResponsepatch
async def patch(url: str, **kw: Any) -> TestResponsedelete
async def delete(url: str, **kw: Any) -> TestResponse