Перейти к содержанию

Test Client

Warning

The current page still doesn't have a translation for this language.

But you can help translating it: Contributing.

Ravyn offers an extension of the Lilya TestClient called RavynTestClient as well as a create_client that can be used for context testing.

from ravyn.testclient import RavynTestClient

ravyn.testclient.RavynTestClient

RavynTestClient(
    app,
    base_url="http://testserver",
    raise_server_exceptions=True,
    root_path="",
    backend="asyncio",
    backend_options=None,
    cookies=None,
    headers=None,
)

Bases: TestClient

Source code in ravyn/testclient.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def __init__(
    self,
    app: Ravyn,
    base_url: str = "http://testserver",
    raise_server_exceptions: bool = True,
    root_path: str = "",
    backend: "Literal['asyncio', 'trio']" = "asyncio",
    backend_options: Optional[dict[str, Any]] = None,
    cookies: Optional[CookieTypes] = None,
    headers: dict[str, str] = None,
):
    super().__init__(
        app=app,
        base_url=base_url,
        raise_server_exceptions=raise_server_exceptions,
        root_path=root_path,
        backend=backend,
        backend_options=backend_options,
        cookies=cookies,
        headers=headers,
    )

app instance-attribute

app

routes property

routes

headers property writable

headers

HTTP headers to include when sending requests.

follow_redirects instance-attribute

follow_redirects = follow_redirects

max_redirects instance-attribute

max_redirects = max_redirects

is_closed property

is_closed

Check if the client being closed

trust_env property

trust_env

timeout property writable

timeout

event_hooks property writable

event_hooks

auth property writable

auth

Authentication class used when none is passed at the request-level.

See also Authentication.

base_url property writable

base_url

Base URL to use when sending requests with relative URLs.

cookies property writable

cookies

Cookie values to include when sending requests.

params property writable

params

Query parameters to include in the URL when sending requests.

task instance-attribute

task

portal class-attribute instance-attribute

portal = None

async_backend instance-attribute

async_backend = AsyncBackend(
    backend=backend, backend_options=backend_options or {}
)

app_state instance-attribute

app_state = {}

build_request

build_request(
    method,
    url,
    *,
    content=None,
    data=None,
    files=None,
    json=None,
    params=None,
    headers=None,
    cookies=None,
    timeout=USE_CLIENT_DEFAULT,
    extensions=None,
)

Build and return a request instance.

  • The params, headers and cookies arguments are merged with any values set on the client.
  • The url argument is merged with any base_url set on the client.

See also: Request instances

Source code in httpx/_client.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
def build_request(
    self,
    method: str,
    url: URL | str,
    *,
    content: RequestContent | None = None,
    data: RequestData | None = None,
    files: RequestFiles | None = None,
    json: typing.Any | None = None,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> Request:
    """
    Build and return a request instance.

    * The `params`, `headers` and `cookies` arguments
    are merged with any values set on the client.
    * The `url` argument is merged with any `base_url` set on the client.

    See also: [Request instances][0]

    [0]: /advanced/clients/#request-instances
    """
    url = self._merge_url(url)
    headers = self._merge_headers(headers)
    cookies = self._merge_cookies(cookies)
    params = self._merge_queryparams(params)
    extensions = {} if extensions is None else extensions
    if "timeout" not in extensions:
        timeout = (
            self.timeout
            if isinstance(timeout, UseClientDefault)
            else Timeout(timeout)
        )
        extensions = dict(**extensions, timeout=timeout.as_dict())
    return Request(
        method,
        url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        extensions=extensions,
    )

request

request(
    method,
    url,
    *,
    content=None,
    data=None,
    files=None,
    json=None,
    params=None,
    headers=None,
    cookies=None,
    auth=USE_CLIENT_DEFAULT,
    follow_redirects=None,
    timeout=USE_CLIENT_DEFAULT,
    extensions=None,
    stream=False,
)

Builds and sends a network request to the ASGI application.

This method overrides the standard httpx.Client.request to provide specific handling for the TestClient, including URL merging and stream handling.

PARAMETER DESCRIPTION
method

The HTTP method to use (e.g., 'GET', 'POST').

TYPE: str

url

The URL to send the request to.

TYPE: URLTypes

content

Binary content to send in the body. Defaults to None.

TYPE: RequestContent | None DEFAULT: None

data

Form data to send in the body. Defaults to None.

TYPE: RequestData | None DEFAULT: None

files

Files to upload. Defaults to None.

TYPE: RequestFiles | None DEFAULT: None

json

JSON data to send in the body. Defaults to None.

TYPE: Any DEFAULT: None

params

Query parameters to include in the URL. Defaults to None.

TYPE: QueryParamTypes | None DEFAULT: None

headers

Headers to include in the request. Defaults to None.

TYPE: HeaderTypes | None DEFAULT: None

cookies

Cookies to include in the request. Defaults to None.

TYPE: CookieTypes | None DEFAULT: None

auth

Authentication credentials. Defaults to httpx._client.USE_CLIENT_DEFAULT.

TYPE: AuthTypes | UseClientDefault DEFAULT: USE_CLIENT_DEFAULT

follow_redirects

Whether to follow redirects. Defaults to None.

TYPE: bool | None DEFAULT: None

timeout

Timeout configuration. Defaults to httpx._client.USE_CLIENT_DEFAULT.

TYPE: TimeoutTypes | UseClientDefault DEFAULT: USE_CLIENT_DEFAULT

extensions

Extensions to include in the request. Defaults to None.

TYPE: dict[str, Any] | None DEFAULT: None

stream

Whether to stream the response content. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Response

httpx.Response: The response received from the application.

Source code in lilya/testclient/base.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
def request(
    self,
    method: str,
    url: URLTypes,
    *,
    content: RequestContent | None = None,
    data: RequestData | None = None,
    files: RequestFiles | None = None,
    json: Any = None,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: (AuthTypes | httpx._client.UseClientDefault) = httpx._client.USE_CLIENT_DEFAULT,
    follow_redirects: bool | None = None,
    timeout: (
        TimeoutTypes | httpx._client.UseClientDefault
    ) = httpx._client.USE_CLIENT_DEFAULT,
    extensions: dict[str, Any] | None = None,
    stream: bool = False,
) -> httpx.Response:
    """
    Builds and sends a network request to the ASGI application.

    This method overrides the standard `httpx.Client.request` to provide specific
    handling for the TestClient, including URL merging and stream handling.

    Args:
        method (str): The HTTP method to use (e.g., 'GET', 'POST').
        url (URLTypes): The URL to send the request to.
        content (RequestContent | None, optional): Binary content to send in the body.
            Defaults to None.
        data (RequestData | None, optional): Form data to send in the body.
            Defaults to None.
        files (RequestFiles | None, optional): Files to upload. Defaults to None.
        json (Any, optional): JSON data to send in the body. Defaults to None.
        params (QueryParamTypes | None, optional): Query parameters to include in the URL.
            Defaults to None.
        headers (HeaderTypes | None, optional): Headers to include in the request.
            Defaults to None.
        cookies (CookieTypes | None, optional): Cookies to include in the request.
            Defaults to None.
        auth (AuthTypes | httpx._client.UseClientDefault, optional): Authentication
            credentials. Defaults to httpx._client.USE_CLIENT_DEFAULT.
        follow_redirects (bool | None, optional): Whether to follow redirects.
            Defaults to None.
        timeout (TimeoutTypes | httpx._client.UseClientDefault, optional): Timeout
            configuration. Defaults to httpx._client.USE_CLIENT_DEFAULT.
        extensions (dict[str, Any] | None, optional): Extensions to include in the request.
            Defaults to None.
        stream (bool, optional): Whether to stream the response content. Defaults to False.

    Returns:
        httpx.Response: The response received from the application.
    """
    url = self._merge_url(url)
    redirect: bool | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT
    if follow_redirects is not None:
        redirect = follow_redirects

    # httpx 0.28+ deprecated per-request cookies= parameter
    # Save current cookies, merge per-request cookies, then restore after request
    if cookies is not None:
        _saved_cookies = dict(self.cookies)
        self.cookies.update(cookies)
    else:
        _saved_cookies = None

    try:
        if stream:
            return self.stream(
                method=method,
                url=url,
                content=content,
                data=data,
                files=files,
                json=json,
                params=params,
                headers=headers,
                auth=auth,
                timeout=timeout,
                extensions=extensions,
                follow_redirects=follow_redirects,
            ).__enter__()

        return super().request(
            method,
            url,
            content=content,
            data=data,
            files=files,
            json=json,
            params=params,
            headers=headers,
            auth=auth,
            follow_redirects=redirect,
            timeout=timeout,
            extensions=extensions,
        )
    finally:
        if _saved_cookies is not None:
            self.cookies.clear()
            self.cookies.update(_saved_cookies)

stream

stream(
    method,
    url,
    *,
    content=None,
    data=None,
    files=None,
    json=None,
    params=None,
    headers=None,
    cookies=None,
    auth=USE_CLIENT_DEFAULT,
    follow_redirects=USE_CLIENT_DEFAULT,
    timeout=USE_CLIENT_DEFAULT,
    extensions=None,
)

Alternative to httpx.request() that streams the response body instead of loading it into memory at once.

Parameters: See httpx.request.

See also: Streaming Responses

Source code in httpx/_client.py
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
@contextmanager
def stream(
    self,
    method: str,
    url: URL | str,
    *,
    content: RequestContent | None = None,
    data: RequestData | None = None,
    files: RequestFiles | None = None,
    json: typing.Any | None = None,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> typing.Iterator[Response]:
    """
    Alternative to `httpx.request()` that streams the response body
    instead of loading it into memory at once.

    **Parameters**: See `httpx.request`.

    See also: [Streaming Responses][0]

    [0]: /quickstart#streaming-responses
    """
    request = self.build_request(
        method=method,
        url=url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        timeout=timeout,
        extensions=extensions,
    )
    response = self.send(
        request=request,
        auth=auth,
        follow_redirects=follow_redirects,
        stream=True,
    )
    try:
        yield response
    finally:
        response.close()

send

send(
    request,
    *,
    stream=False,
    auth=USE_CLIENT_DEFAULT,
    follow_redirects=USE_CLIENT_DEFAULT,
)

Send a request.

The request is sent as-is, unmodified.

Typically you'll want to build one with Client.build_request() so that any client-level configuration is merged into the request, but passing an explicit httpx.Request() is supported as well.

See also: Request instances

Source code in httpx/_client.py
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
def send(
    self,
    request: Request,
    *,
    stream: bool = False,
    auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
) -> Response:
    """
    Send a request.

    The request is sent as-is, unmodified.

    Typically you'll want to build one with `Client.build_request()`
    so that any client-level configuration is merged into the request,
    but passing an explicit `httpx.Request()` is supported as well.

    See also: [Request instances][0]

    [0]: /advanced/clients/#request-instances
    """
    if self._state == ClientState.CLOSED:
        raise RuntimeError("Cannot send a request, as the client has been closed.")

    self._state = ClientState.OPENED
    follow_redirects = (
        self.follow_redirects
        if isinstance(follow_redirects, UseClientDefault)
        else follow_redirects
    )

    self._set_timeout(request)

    auth = self._build_request_auth(request, auth)

    response = self._send_handling_auth(
        request,
        auth=auth,
        follow_redirects=follow_redirects,
        history=[],
    )
    try:
        if not stream:
            response.read()

        return response

    except BaseException as exc:
        response.close()
        raise exc

get

get(url, **kwargs)

Sends a GET request.

PARAMETER DESCRIPTION
url

The URL to send the request to.

TYPE: URLTypes

**kwargs

Additional arguments passed to request.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
Response

httpx.Response: The response from the server.

Source code in lilya/testclient/base.py
347
348
349
350
351
352
353
354
355
356
357
358
def get(self, url: URLTypes, **kwargs: Any) -> httpx.Response:
    """
    Sends a GET request.

    Args:
        url (URLTypes): The URL to send the request to.
        **kwargs (Any): Additional arguments passed to `request`.

    Returns:
        httpx.Response: The response from the server.
    """
    return self._process_request(method="GET", url=url, **kwargs)  # type: ignore

options

options(url, **kwargs)

Sends an OPTIONS request.

PARAMETER DESCRIPTION
url

The URL to send the request to.

TYPE: URLTypes

**kwargs

Additional arguments passed to request.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
Response

httpx.Response: The response from the server.

Source code in lilya/testclient/base.py
425
426
427
428
429
430
431
432
433
434
435
436
def options(self, url: URLTypes, **kwargs: Any) -> httpx.Response:
    """
    Sends an OPTIONS request.

    Args:
        url (URLTypes): The URL to send the request to.
        **kwargs (Any): Additional arguments passed to `request`.

    Returns:
        httpx.Response: The response from the server.
    """
    return self._process_request(method="OPTIONS", url=url, **kwargs)  # type: ignore

head

head(url, **kwargs)

Sends a HEAD request.

PARAMETER DESCRIPTION
url

The URL to send the request to.

TYPE: URLTypes

**kwargs

Additional arguments passed to request.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
Response

httpx.Response: The response from the server.

Source code in lilya/testclient/base.py
360
361
362
363
364
365
366
367
368
369
370
371
def head(self, url: URLTypes, **kwargs: Any) -> httpx.Response:
    """
    Sends a HEAD request.

    Args:
        url (URLTypes): The URL to send the request to.
        **kwargs (Any): Additional arguments passed to `request`.

    Returns:
        httpx.Response: The response from the server.
    """
    return self._process_request(method="HEAD", url=url, **kwargs)  # type: ignore

post

post(url, **kwargs)

Sends a POST request.

PARAMETER DESCRIPTION
url

The URL to send the request to.

TYPE: URLTypes

**kwargs

Additional arguments passed to request.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
Response

httpx.Response: The response from the server.

Source code in lilya/testclient/base.py
373
374
375
376
377
378
379
380
381
382
383
384
def post(self, url: URLTypes, **kwargs: Any) -> httpx.Response:
    """
    Sends a POST request.

    Args:
        url (URLTypes): The URL to send the request to.
        **kwargs (Any): Additional arguments passed to `request`.

    Returns:
        httpx.Response: The response from the server.
    """
    return self._process_request(method="POST", url=url, **kwargs)  # type: ignore

put

put(url, **kwargs)

Sends a PUT request.

PARAMETER DESCRIPTION
url

The URL to send the request to.

TYPE: URLTypes

**kwargs

Additional arguments passed to request.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
Response

httpx.Response: The response from the server.

Source code in lilya/testclient/base.py
386
387
388
389
390
391
392
393
394
395
396
397
def put(self, url: URLTypes, **kwargs: Any) -> httpx.Response:
    """
    Sends a PUT request.

    Args:
        url (URLTypes): The URL to send the request to.
        **kwargs (Any): Additional arguments passed to `request`.

    Returns:
        httpx.Response: The response from the server.
    """
    return self._process_request(method="PUT", url=url, **kwargs)  # type: ignore

patch

patch(url, **kwargs)

Sends a PATCH request.

PARAMETER DESCRIPTION
url

The URL to send the request to.

TYPE: URLTypes

**kwargs

Additional arguments passed to request.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
Response

httpx.Response: The response from the server.

Source code in lilya/testclient/base.py
399
400
401
402
403
404
405
406
407
408
409
410
def patch(self, url: URLTypes, **kwargs: Any) -> httpx.Response:
    """
    Sends a PATCH request.

    Args:
        url (URLTypes): The URL to send the request to.
        **kwargs (Any): Additional arguments passed to `request`.

    Returns:
        httpx.Response: The response from the server.
    """
    return self._process_request(method="PATCH", url=url, **kwargs)  # type: ignore

delete

delete(url, **kwargs)

Sends a DELETE request.

PARAMETER DESCRIPTION
url

The URL to send the request to.

TYPE: URLTypes

**kwargs

Additional arguments passed to request.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
Response

httpx.Response: The response from the server.

Source code in lilya/testclient/base.py
412
413
414
415
416
417
418
419
420
421
422
423
def delete(self, url: URLTypes, **kwargs: Any) -> httpx.Response:
    """
    Sends a DELETE request.

    Args:
        url (URLTypes): The URL to send the request to.
        **kwargs (Any): Additional arguments passed to `request`.

    Returns:
        httpx.Response: The response from the server.
    """
    return self._process_request(method="DELETE", url=url, **kwargs)  # type: ignore

close

close()

Close transport and proxies.

Source code in httpx/_client.py
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
def close(self) -> None:
    """
    Close transport and proxies.
    """
    if self._state != ClientState.CLOSED:
        self._state = ClientState.CLOSED

        self._transport.close()
        for transport in self._mounts.values():
            if transport is not None:
                transport.close()

authenticate

authenticate(user)

Sets an authenticated user in the application state.

This helper method injects a user object into the application's state, simulating a logged-in user session for subsequent requests.

PARAMETER DESCRIPTION
user

The user object to be set as authenticated.

TYPE: Any

RETURNS DESCRIPTION
TestClient

The instance of the client, allowing for method chaining.

TYPE: TestClient

Source code in lilya/testclient/base.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def authenticate(self, user: Any) -> TestClient:
    """
    Sets an authenticated user in the application state.

    This helper method injects a user object into the application's state, simulating
    a logged-in user session for subsequent requests.

    Args:
        user (Any): The user object to be set as authenticated.

    Returns:
        TestClient: The instance of the client, allowing for method chaining.
    """
    self.app_state[_AUTH_USER_KEY] = user
    return self

logout

logout()

Removes the authenticated user from the application state.

This helper method clears any user object currently stored in the application's state, simulating a logout action.

RETURNS DESCRIPTION
TestClient

The instance of the client, allowing for method chaining.

TYPE: TestClient

Source code in lilya/testclient/base.py
147
148
149
150
151
152
153
154
155
156
157
158
def logout(self) -> TestClient:
    """
    Removes the authenticated user from the application state.

    This helper method clears any user object currently stored in the application's
    state, simulating a logout action.

    Returns:
        TestClient: The instance of the client, allowing for method chaining.
    """
    self.app_state.pop(_AUTH_USER_KEY, None)
    return self

authenticated

authenticated(user)

A context manager that temporarily authenticates a user for the duration of the block.

This is useful for testing protected endpoints without permanently altering the client's authentication state. The previous authentication state is restored when the context exits.

PARAMETER DESCRIPTION
user

The user object to be temporarily set as authenticated.

TYPE: Any

YIELDS DESCRIPTION
TestClient

The authenticated client instance.

TYPE:: TestClient

Example

async with AsyncTestClient(app) as client: with client.authenticated(user): response = await client.get("/protected")

Source code in lilya/testclient/base.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
@contextlib.contextmanager
def authenticated(self, user: Any) -> Generator[TestClient, None, None]:
    """
    A context manager that temporarily authenticates a user for the duration of the block.

    This is useful for testing protected endpoints without permanently altering the
    client's authentication state. The previous authentication state is restored
    when the context exits.

    Args:
        user (Any): The user object to be temporarily set as authenticated.

    Yields:
        TestClient: The authenticated client instance.

    Example:
        async with AsyncTestClient(app) as client:
            with client.authenticated(user):
                response = await client.get("/protected")
    """
    previous = self.app_state.get(_AUTH_USER_KEY)
    self.app_state[_AUTH_USER_KEY] = user
    try:
        yield self
    finally:
        if previous is None:
            self.app_state.pop(_AUTH_USER_KEY, None)
        else:
            self.app_state[_AUTH_USER_KEY] = previous

websocket_connect

websocket_connect(url, subprotocols=None, **kwargs)

Initiates a WebSocket connection to the application.

This method constructs the necessary headers for a WebSocket upgrade request and establishes a session if the upgrade is successful.

PARAMETER DESCRIPTION
url

The URL path for the WebSocket connection (relative to base_url).

TYPE: str

subprotocols

A list of WebSocket subprotocols to request. Defaults to None.

TYPE: Sequence[str] | None DEFAULT: None

**kwargs

Additional arguments passed to the request.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
WebSocketTestSession

An active WebSocket session object.

TYPE: WebSocketTestSession

RAISES DESCRIPTION
RuntimeError

If the server does not upgrade the connection to a WebSocket.

Source code in lilya/testclient/base.py
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
def websocket_connect(
    self,
    url: str,
    subprotocols: Sequence[str] | None = None,
    **kwargs: Any,
) -> WebSocketTestSession:
    """
    Initiates a WebSocket connection to the application.

    This method constructs the necessary headers for a WebSocket upgrade request and
    establishes a session if the upgrade is successful.

    Args:
        url (str): The URL path for the WebSocket connection (relative to base_url).
        subprotocols (Sequence[str] | None, optional): A list of WebSocket subprotocols
            to request. Defaults to None.
        **kwargs (Any): Additional arguments passed to the request.

    Returns:
        WebSocketTestSession: An active WebSocket session object.

    Raises:
        RuntimeError: If the server does not upgrade the connection to a WebSocket.
    """
    url = urljoin("ws://testserver", url)
    headers = self._prepare_websocket_headers(subprotocols, **kwargs)
    kwargs["headers"] = headers
    try:
        super().request("GET", url, **kwargs)
    except UpgradeException as exc:
        session = exc.session
    else:
        raise RuntimeError("Expected WebSocket upgrade")

    return session

lifespan async

lifespan()

Manages the ASGI lifespan protocol loop.

This method sends the lifespan context to the app and handles the receive/send channels for lifespan events.

Source code in lilya/testclient/base.py
596
597
598
599
600
601
602
603
604
605
606
607
608
async def lifespan(self) -> None:
    """
    Manages the ASGI lifespan protocol loop.

    This method sends the lifespan context to the app and handles the receive/send
    channels for lifespan events.
    """
    scope = {"type": "lifespan", "state": self.app_state}
    try:
        await self.app(scope, self.stream_receive.receive, self.stream_send.send)
    finally:
        with contextlib.suppress(anyio.ClosedResourceError):
            await self.stream_send.send(None)

wait_startup async

wait_startup()

Waits for the ASGI application to complete its startup sequence.

Sends the 'lifespan.startup' event and awaits the confirmation message.

RAISES DESCRIPTION
AssertionError

If the received message type is not a valid startup response.

Source code in lilya/testclient/base.py
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
async def wait_startup(self) -> None:
    """
    Waits for the ASGI application to complete its startup sequence.

    Sends the 'lifespan.startup' event and awaits the confirmation message.

    Raises:
        AssertionError: If the received message type is not a valid startup response.
    """
    await self.stream_receive.send({"type": "lifespan.startup"})

    async def receive() -> Any:
        message = await self.stream_send.receive()
        if message is None:
            self.task.result()
        return message

    message = await receive()
    assert message["type"] in (
        "lifespan.startup.complete",
        "lifespan.startup.failed",
    )
    if message["type"] == "lifespan.startup.failed":
        await receive()

wait_shutdown async

wait_shutdown()

Waits for the ASGI application to complete its shutdown sequence.

Sends the 'lifespan.shutdown' event and awaits the confirmation message. Handles both sync (portal) and async (task group) modes.

RAISES DESCRIPTION
AssertionError

If the received message type is not a valid shutdown response.

Source code in lilya/testclient/base.py
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
async def wait_shutdown(self) -> None:
    """
    Waits for the ASGI application to complete its shutdown sequence.

    Sends the 'lifespan.shutdown' event and awaits the confirmation message.
    Handles both sync (portal) and async (task group) modes.

    Raises:
        AssertionError: If the received message type is not a valid shutdown response.
    """

    async def receive() -> Any:
        message = await self.stream_send.receive()
        if message is None:
            self.task.result()
        return message

    async_mode = hasattr(self, "_tg")

    if async_mode:
        await self.stream_receive.send({"type": "lifespan.shutdown"})
        message = await receive()
        assert message["type"] in (
            "lifespan.shutdown.complete",
            "lifespan.shutdown.failed",
        )
        if message["type"] == "lifespan.shutdown.failed":
            await receive()
    else:
        async with self.stream_send:
            await self.stream_receive.send({"type": "lifespan.shutdown"})
            message = await receive()
            assert message["type"] in (
                "lifespan.shutdown.complete",
                "lifespan.shutdown.failed",
            )
            if message["type"] == "lifespan.shutdown.failed":
                await receive()
from ravyn.testclient import create_client

You can learn more how to use it in the documentation.

ravyn.testclient.create_client

create_client(
    routes,
    *,
    settings_module=None,
    debug=None,
    app_name=None,
    title=None,
    version=None,
    summary=None,
    description=None,
    contact=None,
    terms_of_service=None,
    license=None,
    security=None,
    servers=None,
    secret_key=get_random_secret_key(),
    allowed_hosts=None,
    allow_origins=None,
    base_url="http://testserver",
    backend="asyncio",
    backend_options=None,
    interceptors=None,
    extensions=None,
    permissions=None,
    dependencies=None,
    middleware=None,
    csrf_config=None,
    exception_handlers=None,
    openapi_config=None,
    on_shutdown=None,
    on_startup=None,
    cors_config=None,
    session_config=None,
    scheduler_config=None,
    enable_scheduler=None,
    enable_openapi=True,
    include_in_schema=True,
    openapi_version="3.1.0",
    raise_server_exceptions=True,
    root_path="",
    static_files_config=None,
    logging_config=None,
    template_config=None,
    lifespan=None,
    cookies=None,
    redirect_slashes=None,
    tags=None,
    webhooks=None,
    encoders=None,
    before_request=None,
    after_request=None,
)
Source code in ravyn/testclient.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def create_client(
    routes: Union["APIGateHandler", list["APIGateHandler"]],
    *,
    settings_module: Union[Optional["SettingsType"], Optional[str]] = None,
    debug: Optional[bool] = None,
    app_name: Optional[str] = None,
    title: Optional[str] = None,
    version: Optional[str] = None,
    summary: Optional[str] = None,
    description: Optional[str] = None,
    contact: Optional[Contact] = None,
    terms_of_service: Optional[AnyUrl] = None,
    license: Optional[License] = None,
    security: Optional[list[SecurityScheme]] = None,
    servers: Optional[list[dict[str, Union[str, Any]]]] = None,
    secret_key: Optional[str] = get_random_secret_key(),
    allowed_hosts: Optional[list[str]] = None,
    allow_origins: Optional[list[str]] = None,
    base_url: str = "http://testserver",
    backend: "Literal['asyncio', 'trio']" = "asyncio",
    backend_options: Optional[dict[str, Any]] = None,
    interceptors: Optional[list["Interceptor"]] = None,
    extensions: Optional[
        dict[str, Union["Extension", "Pluggable", type["Extension"], str]]
    ] = None,
    permissions: Optional[list["Permission"]] = None,
    dependencies: Optional["Dependencies"] = None,
    middleware: Optional[list["Middleware"]] = None,
    csrf_config: Optional["CSRFConfig"] = None,
    exception_handlers: Optional["ExceptionHandlerMap"] = None,
    openapi_config: Optional["OpenAPIConfig"] = None,
    on_shutdown: Optional[list["LifeSpanHandler"]] = None,
    on_startup: Optional[list["LifeSpanHandler"]] = None,
    cors_config: Optional["CORSConfig"] = None,
    session_config: Optional["SessionConfig"] = None,
    scheduler_config: Optional[SchedulerConfig] = None,
    enable_scheduler: bool = None,
    enable_openapi: bool = True,
    include_in_schema: bool = True,
    openapi_version: Optional[str] = "3.1.0",
    raise_server_exceptions: bool = True,
    root_path: str = "",
    static_files_config: Union[
        "StaticFilesConfig",
        list["StaticFilesConfig"],
        tuple["StaticFilesConfig", ...],
        None,
    ] = None,
    logging_config: Optional["LoggingConfig"] = None,
    template_config: Optional["TemplateConfig"] = None,
    lifespan: Optional[Callable[["Ravyn"], "AsyncContextManager"]] = None,
    cookies: Optional[CookieTypes] = None,
    redirect_slashes: Optional[bool] = None,
    tags: Optional[list[str]] = None,
    webhooks: Optional[Sequence["WebhookGateway"]] = None,
    encoders: Optional[Sequence[Encoder]] = None,
    before_request: Union[Sequence[Callable[..., Any]], None] = None,
    after_request: Union[Sequence[Callable[..., Any]], None] = None,
) -> RavynTestClient:
    return RavynTestClient(
        app=Ravyn(
            settings_module=settings_module,
            debug=debug,
            title=title,
            version=version,
            summary=summary,
            description=description,
            contact=contact,
            terms_of_service=terms_of_service,
            license=license,
            security=security,
            servers=servers,
            routes=cast("Any", routes if isinstance(routes, list) else [routes]),
            app_name=app_name,
            secret_key=secret_key,
            allowed_hosts=allowed_hosts,
            allow_origins=allow_origins,
            interceptors=interceptors,
            permissions=permissions,
            dependencies=dependencies,
            middleware=middleware,
            csrf_config=csrf_config,
            exception_handlers=exception_handlers,
            openapi_config=openapi_config,
            on_shutdown=on_shutdown,
            on_startup=on_startup,
            cors_config=cors_config,
            scheduler_config=scheduler_config,
            enable_scheduler=enable_scheduler,
            static_files_config=static_files_config,
            template_config=template_config,
            session_config=session_config,
            lifespan=lifespan,
            redirect_slashes=redirect_slashes,
            enable_openapi=enable_openapi,
            openapi_version=openapi_version,
            include_in_schema=include_in_schema,
            tags=tags,
            webhooks=webhooks,
            extensions=extensions,
            encoders=encoders,
            before_request=before_request,
            after_request=after_request,
            logging_config=logging_config,
        ),
        base_url=base_url,
        backend=backend,
        backend_options=backend_options,
        root_path=root_path,
        raise_server_exceptions=raise_server_exceptions,
        cookies=cookies,
    )