Ushka

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 TestResponseWhat a TestClient call returns.
class TestClientCalls an ASGI app in-process. Use it as async with TestClient(app) as client.

class TestResponse

What a TestClient call returns.

json

def json() -> Any

header_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

startupRuns the app's startup hooks (done for you by async with).
shutdownRuns the app's shutdown hooks (done for you by async with).
requestSends one request and returns a TestResponse.
get
head
options
post
put
patch
delete

startup

async def startup() -> None

Runs the app's startup hooks (done for you by async with).

shutdown

async def shutdown() -> None

Runs 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,
) -> TestResponse

Sends 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) -> TestResponse

head

async def head(url: str, **kw: Any) -> TestResponse

options

async def options(url: str, **kw: Any) -> TestResponse

post

async def post(url: str, **kw: Any) -> TestResponse

put

async def put(url: str, **kw: Any) -> TestResponse

patch

async def patch(url: str, **kw: Any) -> TestResponse

delete

async def delete(url: str, **kw: Any) -> TestResponse