testing#
- class litestar.testing.AsyncTestClient#
Bases:
AsyncClient
,BaseTestClient
,Generic
[T
]- lifespan_handler: LifeSpanHandler[Any]#
- exit_stack: AsyncExitStack#
- __init__(app: T, base_url: str = 'http://testserver.local', raise_server_exceptions: bool = True, root_path: str = '', backend: AnyIOBackend = 'asyncio', backend_options: Mapping[str, Any] | None = None, session_config: BaseBackendConfig | None = None, timeout: float | None = None, cookies: CookieTypes | None = None) None #
An Async client implementation providing a context manager for testing applications asynchronously.
- Parameters:
base_url¶ – URL scheme and domain for test request paths, e.g.
http://testserver
.raise_server_exceptions¶ – Flag for the underlying test client to raise server exceptions instead of wrapping them in an HTTP response.
root_path¶ – Path prefix for requests.
backend¶ – The async backend to use, options are “asyncio” or “trio”.
backend_options¶ – ‘anyio’ options.
session_config¶ – Configuration for Session Middleware class to create raw session cookies for request to the route handlers.
timeout¶ – Request timeout
cookies¶ – Cookies to set on the client.
- async websocket_connect(url: str, subprotocols: Sequence[str] | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = <httpx._client.UseClientDefault object>, follow_redirects: bool | UseClientDefault = <httpx._client.UseClientDefault object>, timeout: TimeoutTypes | UseClientDefault = <httpx._client.UseClientDefault object>, extensions: Mapping[str, Any] | None = None) WebSocketTestSession #
Sends a GET request to establish a websocket connection.
- Parameters:
- Returns:
A WebSocketTestSession <litestar.testing.WebSocketTestSession> instance.
- async get_session_data() dict[str, Any] #
Get session data.
- Returns:
A dictionary containing session data.
Examples
from litestar import Litestar, post from litestar.middleware.session.memory_backend import MemoryBackendConfig session_config = MemoryBackendConfig() @post(path="/test") def set_session_data(request: Request) -> None: request.session["foo"] == "bar" app = Litestar( route_handlers=[set_session_data], middleware=[session_config.middleware] ) async with AsyncTestClient(app=app, session_config=session_config) as client: await client.post("/test") assert await client.get_session_data() == {"foo": "bar"}
- async set_session_data(data: dict[str, Any]) None #
Set session data.
- Parameters:
data¶ – Session data
- Returns:
None
Examples
from litestar import Litestar, get from litestar.middleware.session.memory_backend import MemoryBackendConfig session_config = MemoryBackendConfig() @get(path="/test") def get_session_data(request: Request) -> Dict[str, Any]: return request.session app = Litestar( route_handlers=[get_session_data], middleware=[session_config.middleware] ) async with AsyncTestClient(app=app, session_config=session_config) as client: await client.set_session_data({"foo": "bar"}) assert await client.get("/test").json() == {"foo": "bar"}
- app#
- base_url#
- backend#
- backend_options#
- session_config#
- cookies#
- class litestar.testing.BaseTestClient#
Bases:
Generic
[T
]- blocking_portal: BlockingPortal#
- __init__(app: T, base_url: str = 'http://testserver.local', backend: AnyIOBackend = 'asyncio', backend_options: Mapping[str, Any] | None = None, session_config: BaseBackendConfig | None = None, cookies: CookieTypes | None = None) None #
- app#
- base_url#
- backend#
- backend_options#
- cookies#
- property session_backend: BaseSessionBackend[Any]#
- portal() Generator[BlockingPortal, None, None] #
Get a BlockingPortal.
- Returns:
A contextmanager for a BlockingPortal.
- session_config#
- litestar.testing.create_async_test_client(route_handlers: ControllerRouterHandler | Sequence[ControllerRouterHandler] | None = None, *, after_exception: Sequence[AfterExceptionHookHandler] | None = None, after_request: AfterRequestHookHandler | None = None, after_response: AfterResponseHookHandler | None = None, allowed_hosts: Sequence[str] | AllowedHostsConfig | None = None, backend: Literal['asyncio', 'trio'] = 'asyncio', backend_options: Mapping[str, Any] | None = None, base_url: str = 'http://testserver.local', before_request: BeforeRequestHookHandler | None = None, before_send: Sequence[BeforeMessageSendHookHandler] | None = None, cache_control: CacheControlHeader | None = None, compression_config: CompressionConfig | None = None, cors_config: CORSConfig | None = None, csrf_config: CSRFConfig | None = None, debug: bool = True, dependencies: Dependencies | None = None, dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, etag: ETag | None = None, event_emitter_backend: type[BaseEventEmitterBackend] = <class 'litestar.events.emitter.SimpleEventEmitter'>, exception_handlers: ExceptionHandlersMap | None = None, guards: Sequence[Guard] | None = None, include_in_schema: bool | EmptyType = _EmptyEnum.EMPTY, lifespan: list[Callable[[Litestar], AbstractAsyncContextManager] | AbstractAsyncContextManager] | None = None, listeners: Sequence[EventListener] | None = None, logging_config: BaseLoggingConfig | EmptyType | None = _EmptyEnum.EMPTY, middleware: Sequence[Middleware] | None = None, multipart_form_part_limit: int = 1000, on_app_init: Sequence[OnAppInitHandler] | None = None, on_shutdown: Sequence[LifespanHook] | None = None, on_startup: Sequence[LifespanHook] | None = None, openapi_config: OpenAPIConfig | None = OpenAPIConfig(title='Litestar API', version='1.0.0', create_examples=False, random_seed=10, contact=None, description=None, external_docs=None, license=None, security=None, components=Components(schemas={}, responses=None, parameters=None, examples=None, request_bodies=None, headers=None, security_schemes=None, links=None, callbacks=None, path_items=None), servers=[Server(url='/', description=None, variables=None)], summary=None, tags=None, terms_of_service=None, use_handler_docstrings=False, webhooks=None, operation_id_creator=<function default_operation_id_creator>, path=None, render_plugins=[<litestar.openapi.plugins.SwaggerRenderPlugin object>, <litestar.openapi.plugins.RedocRenderPlugin object>, <litestar.openapi.plugins.YamlRenderPlugin object>, <litestar.openapi.plugins.YamlRenderPlugin object>, <litestar.openapi.plugins.StoplightRenderPlugin object>, <litestar.openapi.plugins.JsonRenderPlugin object>, <litestar.openapi.plugins.RapidocRenderPlugin object>], openapi_router=None, openapi_controller=None, root_schema_site='redoc', enabled_endpoints={'swagger', 'redoc', 'oauth2-redirect.html', 'openapi.yml', 'openapi.yaml', 'elements', 'openapi.json', 'rapidoc'}), opt: Mapping[str, Any] | None = None, parameters: ParametersMap | None = None, pdb_on_exception: bool | None = None, path: str | None = None, plugins: Sequence[PluginProtocol] | None = None, raise_server_exceptions: bool = True, request_class: type[Request] | None = None, response_cache_config: ResponseCacheConfig | None = None, response_class: type[Response] | None = None, response_cookies: ResponseCookies | None = None, response_headers: ResponseHeaders | None = None, return_dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, root_path: str = '', security: Sequence[SecurityRequirement] | None = None, session_config: BaseBackendConfig | None = None, signature_namespace: Mapping[str, Any] | None = None, signature_types: Sequence[Any] | None = None, state: State | None = None, static_files_config: Sequence[StaticFilesConfig] | None = None, stores: StoreRegistry | dict[str, Store] | None = None, tags: Sequence[str] | None = None, template_config: TemplateConfig | None = None, timeout: float | None = None, type_encoders: TypeEncodersMap | None = None, websocket_class: type[WebSocket] | None = None, experimental_features: list[ExperimentalFeatures] | None = None) AsyncTestClient[Litestar] #
Create a Litestar app instance and initializes it.
AsyncTestClient
with it.Notes
- This function should be called as a context manager to ensure async startup and shutdown are
handled correctly.
Examples
from litestar import get from litestar.testing import create_async_test_client @get("/some-path") def my_handler() -> dict[str, str]: return {"hello": "world"} async def test_my_handler() -> None: async with create_async_test_client(my_handler) as client: response = await client.get("/some-path") assert response.json() == {"hello": "world"}
- Parameters:
route_handlers¶ – A single handler or a sequence of route handlers, which can include instances of
Router
, subclasses ofController
or any function decorated by the route handler decorators.backend¶ – The async backend to use, options are “asyncio” or “trio”.
backend_options¶ –
anyio
options.base_url¶ – URL scheme and domain for test request paths, e.g.
http://testserver
.raise_server_exceptions¶ – Flag for underlying the test client to raise server exceptions instead of wrapping them in an HTTP response.
root_path¶ – Path prefix for requests.
session_config¶ – Configuration for Session Middleware class to create raw session cookies for request to the route handlers.
after_exception¶ – A sequence of
exception hook handlers
. This hook is called after an exception occurs. In difference to exception handlers, it is not meant to return a response - only to process the exception (e.g. log it, send it to Sentry etc.).after_request¶ – A sync or async function executed after the route handler function returned and the response object has been resolved. Receives the response object.
after_response¶ – A sync or async function called after the response has been awaited. It receives the
Request
object and should not return any values.allowed_hosts¶ – A sequence of allowed hosts, or an
AllowedHostsConfig
instance. Enables the builtin allowed hosts middleware.before_request¶ – A sync or async function called immediately before calling the route handler. Receives the
Request
instance and any non-None
return value is used for the response, bypassing the route handler.before_send¶ – A sequence of
before send hook handlers
. Called when the ASGI send function is called.cache_control¶ – A
cache-control
header of typeCacheControlHeader
to add to route handlers of this app. Can be overridden by route handlers.compression_config¶ – Configures compression behaviour of the application, this enabled a builtin or user defined Compression middleware.
cors_config¶ – If set, configures CORS handling for the application.
csrf_config¶ – If set, configures
CSRFMiddleware
.debug¶ – If
True
, app errors rendered as HTML with a stack trace.dependencies¶ – A string keyed mapping of dependency
Providers
.dto¶ –
AbstractDTO
to use for (de)serializing and validation of request data.etag¶ – An
etag
header of typeETag
to add to route handlers of this app. Can be overridden by route handlers.event_emitter_backend¶ – A subclass of
BaseEventEmitterBackend
.exception_handlers¶ – A mapping of status codes and/or exception types to handler functions.
include_in_schema¶ – A boolean flag dictating whether the route handler should be documented in the OpenAPI schema.
lifespan¶ – A list of callables returning async context managers, wrapping the lifespan of the ASGI application
listeners¶ – A sequence of
EventListener
.logging_config¶ – A subclass of
BaseLoggingConfig
.middleware¶ – A sequence of
Middleware
.multipart_form_part_limit¶ – The maximal number of allowed parts in a multipart/formdata request. This limit is intended to protect from DoS attacks.
on_app_init¶ – A sequence of
OnAppInitHandler
instances. Handlers receive an instance ofAppConfig
that will have been initially populated with the parameters passed toLitestar
, and must return an instance of same. If more than one handler is registered they are called in the order they are provided.on_shutdown¶ – A sequence of
LifespanHook
called during application shutdown.on_startup¶ – A sequence of
LifespanHook
called during application startup.openapi_config¶ – Defaults to
DEFAULT_OPENAPI_CONFIG
opt¶ – A string keyed mapping of arbitrary values that can be accessed in
Guards
or wherever you have access toRequest
orASGI Scope
.parameters¶ – A mapping of
Parameter
definitions available to all application paths.path¶ –
A path fragment that is prefixed to all route handlers, controllers and routers associated with the application instance.
New in version 2.8.0.
pdb_on_exception¶ – Drop into the PDB when an exception occurs.
plugins¶ – Sequence of plugins.
request_class¶ – An optional subclass of
Request
to use for http connections.response_class¶ – A custom subclass of
Response
to be used as the app’s default response.response_headers¶ – A string keyed mapping of
ResponseHeader
response_cache_config¶ – Configures caching behavior of the application.
return_dto¶ –
AbstractDTO
to use for serializing outbound response data.route_handlers¶ – A sequence of route handlers, which can include instances of
Router
, subclasses ofController
or any callable decorated by the route handler decorators.security¶ – A sequence of dicts that will be added to the schema of all route handlers in the application. See
SecurityRequirement
for details.signature_namespace¶ – A mapping of names to types for use in forward reference resolution during signature modeling.
signature_types¶ – A sequence of types for use in forward reference resolution during signature modeling. These types will be added to the signature namespace using their
__name__
attribute.static_files_config¶ – A sequence of
StaticFilesConfig
stores¶ – Central registry of
Store
that will be available throughout the application. If this is a dictionary to it will be passed to aStoreRegistry
. If it is aStoreRegistry
, this instance will be used directly.tags¶ – A sequence of string tags that will be appended to the schema of all route handlers under the application.
template_config¶ – An instance of
TemplateConfig
timeout¶ – Request timeout
type_encoders¶ – A mapping of types to callables that transform them into types supported for serialization.
websocket_class¶ – An optional subclass of
WebSocket
to use for websocket connections.experimental_features¶ – An iterable of experimental features to enable
- Returns:
An instance of
AsyncTestClient
with a created app instance.
- litestar.testing.create_test_client(route_handlers: ControllerRouterHandler | Sequence[ControllerRouterHandler] | None = None, *, after_exception: Sequence[AfterExceptionHookHandler] | None = None, after_request: AfterRequestHookHandler | None = None, after_response: AfterResponseHookHandler | None = None, allowed_hosts: Sequence[str] | AllowedHostsConfig | None = None, backend: Literal['asyncio', 'trio'] = 'asyncio', backend_options: Mapping[str, Any] | None = None, base_url: str = 'http://testserver.local', before_request: BeforeRequestHookHandler | None = None, before_send: Sequence[BeforeMessageSendHookHandler] | None = None, cache_control: CacheControlHeader | None = None, compression_config: CompressionConfig | None = None, cors_config: CORSConfig | None = None, csrf_config: CSRFConfig | None = None, debug: bool = True, dependencies: Dependencies | None = None, dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, etag: ETag | None = None, event_emitter_backend: type[BaseEventEmitterBackend] = <class 'litestar.events.emitter.SimpleEventEmitter'>, exception_handlers: ExceptionHandlersMap | None = None, guards: Sequence[Guard] | None = None, include_in_schema: bool | EmptyType = _EmptyEnum.EMPTY, listeners: Sequence[EventListener] | None = None, logging_config: BaseLoggingConfig | EmptyType | None = _EmptyEnum.EMPTY, middleware: Sequence[Middleware] | None = None, multipart_form_part_limit: int = 1000, on_app_init: Sequence[OnAppInitHandler] | None = None, on_shutdown: Sequence[LifespanHook] | None = None, on_startup: Sequence[LifespanHook] | None = None, openapi_config: OpenAPIConfig | None = OpenAPIConfig(title='Litestar API', version='1.0.0', create_examples=False, random_seed=10, contact=None, description=None, external_docs=None, license=None, security=None, components=Components(schemas={}, responses=None, parameters=None, examples=None, request_bodies=None, headers=None, security_schemes=None, links=None, callbacks=None, path_items=None), servers=[Server(url='/', description=None, variables=None)], summary=None, tags=None, terms_of_service=None, use_handler_docstrings=False, webhooks=None, operation_id_creator=<function default_operation_id_creator>, path=None, render_plugins=[<litestar.openapi.plugins.SwaggerRenderPlugin object>, <litestar.openapi.plugins.RedocRenderPlugin object>, <litestar.openapi.plugins.YamlRenderPlugin object>, <litestar.openapi.plugins.YamlRenderPlugin object>, <litestar.openapi.plugins.StoplightRenderPlugin object>, <litestar.openapi.plugins.JsonRenderPlugin object>, <litestar.openapi.plugins.RapidocRenderPlugin object>], openapi_router=None, openapi_controller=None, root_schema_site='redoc', enabled_endpoints={'swagger', 'redoc', 'oauth2-redirect.html', 'openapi.yml', 'openapi.yaml', 'elements', 'openapi.json', 'rapidoc'}), opt: Mapping[str, Any] | None = None, parameters: ParametersMap | None = None, path: str | None = None, plugins: Sequence[PluginProtocol] | None = None, lifespan: list[Callable[[Litestar], AbstractAsyncContextManager] | AbstractAsyncContextManager] | None = None, raise_server_exceptions: bool = True, pdb_on_exception: bool | None = None, request_class: type[Request] | None = None, response_cache_config: ResponseCacheConfig | None = None, response_class: type[Response] | None = None, response_cookies: ResponseCookies | None = None, response_headers: ResponseHeaders | None = None, return_dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, root_path: str = '', security: Sequence[SecurityRequirement] | None = None, session_config: BaseBackendConfig | None = None, signature_namespace: Mapping[str, Any] | None = None, signature_types: Sequence[Any] | None = None, state: State | None = None, static_files_config: Sequence[StaticFilesConfig] | None = None, stores: StoreRegistry | dict[str, Store] | None = None, tags: Sequence[str] | None = None, template_config: TemplateConfig | None = None, timeout: float | None = None, type_encoders: TypeEncodersMap | None = None, websocket_class: type[WebSocket] | None = None, experimental_features: list[ExperimentalFeatures] | None = None) TestClient[Litestar] #
Create a Litestar app instance and initializes it.
TestClient
with it.Notes
- This function should be called as a context manager to ensure async startup and shutdown are
handled correctly.
Examples
from litestar import get from litestar.testing import create_test_client @get("/some-path") def my_handler() -> dict[str, str]: return {"hello": "world"} def test_my_handler() -> None: with create_test_client(my_handler) as client: response = client.get("/some-path") assert response.json() == {"hello": "world"}
- Parameters:
route_handlers¶ – A single handler or a sequence of route handlers, which can include instances of
Router
, subclasses ofController
or any function decorated by the route handler decorators.backend¶ – The async backend to use, options are “asyncio” or “trio”.
backend_options¶ –
anyio
options.base_url¶ – URL scheme and domain for test request paths, e.g.
http://testserver
.raise_server_exceptions¶ – Flag for underlying the test client to raise server exceptions instead of wrapping them in an HTTP response.
root_path¶ – Path prefix for requests.
session_config¶ – Configuration for Session Middleware class to create raw session cookies for request to the route handlers.
after_exception¶ – A sequence of
exception hook handlers
. This hook is called after an exception occurs. In difference to exception handlers, it is not meant to return a response - only to process the exception (e.g. log it, send it to Sentry etc.).after_request¶ – A sync or async function executed after the route handler function returned and the response object has been resolved. Receives the response object.
after_response¶ – A sync or async function called after the response has been awaited. It receives the
Request
object and should not return any values.allowed_hosts¶ – A sequence of allowed hosts, or an
AllowedHostsConfig
instance. Enables the builtin allowed hosts middleware.before_request¶ – A sync or async function called immediately before calling the route handler. Receives the
Request
instance and any non-None
return value is used for the response, bypassing the route handler.before_send¶ – A sequence of
before send hook handlers
. Called when the ASGI send function is called.cache_control¶ – A
cache-control
header of typeCacheControlHeader
to add to route handlers of this app. Can be overridden by route handlers.compression_config¶ – Configures compression behaviour of the application, this enabled a builtin or user defined Compression middleware.
cors_config¶ – If set, configures CORS handling for the application.
csrf_config¶ – If set, configures
CSRFMiddleware
.debug¶ – If
True
, app errors rendered as HTML with a stack trace.dependencies¶ – A string keyed mapping of dependency
Providers
.dto¶ –
AbstractDTO
to use for (de)serializing and validation of request data.etag¶ – An
etag
header of typeETag
to add to route handlers of this app. Can be overridden by route handlers.event_emitter_backend¶ – A subclass of
BaseEventEmitterBackend
.exception_handlers¶ – A mapping of status codes and/or exception types to handler functions.
include_in_schema¶ – A boolean flag dictating whether the route handler should be documented in the OpenAPI schema.
lifespan¶ – A list of callables returning async context managers, wrapping the lifespan of the ASGI application
listeners¶ – A sequence of
EventListener
.logging_config¶ – A subclass of
BaseLoggingConfig
.middleware¶ – A sequence of
Middleware
.multipart_form_part_limit¶ – The maximal number of allowed parts in a multipart/formdata request. This limit is intended to protect from DoS attacks.
on_app_init¶ – A sequence of
OnAppInitHandler
instances. Handlers receive an instance ofAppConfig
that will have been initially populated with the parameters passed toLitestar
, and must return an instance of same. If more than one handler is registered they are called in the order they are provided.on_shutdown¶ – A sequence of
LifespanHook
called during application shutdown.on_startup¶ – A sequence of
LifespanHook
called during application startup.openapi_config¶ – Defaults to
DEFAULT_OPENAPI_CONFIG
opt¶ – A string keyed mapping of arbitrary values that can be accessed in
Guards
or wherever you have access toRequest
orASGI Scope
.parameters¶ – A mapping of
Parameter
definitions available to all application paths.path¶ –
A path fragment that is prefixed to all route handlers, controllers and routers associated with the application instance.
New in version 2.8.0.
pdb_on_exception¶ – Drop into the PDB when an exception occurs.
plugins¶ – Sequence of plugins.
request_class¶ – An optional subclass of
Request
to use for http connections.response_class¶ – A custom subclass of
Response
to be used as the app’s default response.response_headers¶ – A string keyed mapping of
ResponseHeader
response_cache_config¶ – Configures caching behavior of the application.
return_dto¶ –
AbstractDTO
to use for serializing outbound response data.route_handlers¶ – A sequence of route handlers, which can include instances of
Router
, subclasses ofController
or any callable decorated by the route handler decorators.security¶ – A sequence of dicts that will be added to the schema of all route handlers in the application. See
SecurityRequirement
for details.signature_namespace¶ – A mapping of names to types for use in forward reference resolution during signature modeling.
signature_types¶ – A sequence of types for use in forward reference resolution during signature modeling. These types will be added to the signature namespace using their
__name__
attribute.static_files_config¶ – A sequence of
StaticFilesConfig
stores¶ – Central registry of
Store
that will be available throughout the application. If this is a dictionary to it will be passed to aStoreRegistry
. If it is aStoreRegistry
, this instance will be used directly.tags¶ – A sequence of string tags that will be appended to the schema of all route handlers under the application.
template_config¶ – An instance of
TemplateConfig
timeout¶ – Request timeout
type_encoders¶ – A mapping of types to callables that transform them into types supported for serialization.
websocket_class¶ – An optional subclass of
WebSocket
to use for websocket connections.experimental_features¶ – An iterable of experimental features to enable
- Returns:
An instance of
TestClient
with a created app instance.
- class litestar.testing.RequestFactory#
Bases:
object
Factory to create
Request
instances.- __init__(app: Litestar | None = None, server: str = 'test.org', port: int = 3000, root_path: str = '', scheme: str = 'http', handler_kwargs: dict[str, Any] | None = None) None #
Initialize
RequestFactory
- Parameters:
Examples
from litestar import Litestar from litestar.enums import RequestEncodingType from litestar.testing import RequestFactory from tests import PersonFactory my_app = Litestar(route_handlers=[]) my_server = "litestar.org" # Create a GET request query_params = {"id": 1} get_user_request = RequestFactory(app=my_app, server=my_server).get( "/person", query_params=query_params ) # Create a POST request new_person = PersonFactory.build() create_user_request = RequestFactory(app=my_app, server=my_server).post( "/person", data=person ) # Create a request with a special header headers = {"header1": "value1"} request_with_header = RequestFactory(app=my_app, server=my_server).get( "/person", query_params=query_params, headers=headers ) # Create a request with a media type request_with_media_type = RequestFactory(app=my_app, server=my_server).post( "/person", data=person, request_media_type=RequestEncodingType.MULTI_PART )
- app#
- server#
- port#
- root_path#
- scheme#
- handler_kwargs#
- serializer#
- get(path: str = '/', headers: dict[str, str] | None = None, cookies: list[Cookie] | str | None = None, session: dict[str, Any] | None = None, user: Any = None, auth: Any = None, query_params: dict[str, str | list[str]] | None = None, state: dict[str, Any] | None = None, path_params: dict[str, str] | None = None, http_version: str | None = '1.1', route_handler: RouteHandlerType | None = None) Request[Any, Any, Any] #
Create a GET
Request
instance.- Parameters:
path¶ – The request’s path.
headers¶ – A dictionary of headers.
cookies¶ – A string representing the cookie header or a list of “Cookie” instances. This value can include multiple cookies.
session¶ – A dictionary of session data.
user¶ – A value for request.scope[“user”].
auth¶ – A value for request.scope[“auth”].
query_params¶ – A dictionary of values from which the request’s query will be generated.
state¶ – Arbitrary request state.
path_params¶ – A string keyed dictionary of path parameter values.
http_version¶ – HTTP version. Defaults to “1.1”.
route_handler¶ – A route handler instance or method. If not provided a default handler is set.
- Returns:
A
Request
instance
- post(path: str = '/', headers: dict[str, str] | None = None, cookies: list[Cookie] | str | None = None, session: dict[str, Any] | None = None, user: Any = None, auth: Any = None, request_media_type: RequestEncodingType = RequestEncodingType.JSON, data: dict[str, Any] | DataContainerType | None = None, query_params: dict[str, str | list[str]] | None = None, state: dict[str, Any] | None = None, path_params: dict[str, str] | None = None, http_version: str | None = '1.1', route_handler: RouteHandlerType | None = None) Request[Any, Any, Any] #
Create a POST
Request
instance.- Parameters:
path¶ – The request’s path.
headers¶ – A dictionary of headers.
cookies¶ – A string representing the cookie header or a list of “Cookie” instances. This value can include multiple cookies.
session¶ – A dictionary of session data.
user¶ – A value for request.scope[“user”].
auth¶ – A value for request.scope[“auth”].
request_media_type¶ – The ‘Content-Type’ header of the request.
data¶ – A value for the request’s body. Can be any supported serializable type.
query_params¶ – A dictionary of values from which the request’s query will be generated.
state¶ – Arbitrary request state.
path_params¶ – A string keyed dictionary of path parameter values.
http_version¶ – HTTP version. Defaults to “1.1”.
route_handler¶ – A route handler instance or method. If not provided a default handler is set.
- Returns:
A
Request
instance
- put(path: str = '/', headers: dict[str, str] | None = None, cookies: list[Cookie] | str | None = None, session: dict[str, Any] | None = None, user: Any = None, auth: Any = None, request_media_type: RequestEncodingType = RequestEncodingType.JSON, data: dict[str, Any] | DataContainerType | None = None, query_params: dict[str, str | list[str]] | None = None, state: dict[str, Any] | None = None, path_params: dict[str, str] | None = None, http_version: str | None = '1.1', route_handler: RouteHandlerType | None = None) Request[Any, Any, Any] #
Create a PUT
Request
instance.- Parameters:
path¶ – The request’s path.
headers¶ – A dictionary of headers.
cookies¶ – A string representing the cookie header or a list of “Cookie” instances. This value can include multiple cookies.
session¶ – A dictionary of session data.
user¶ – A value for request.scope[“user”].
auth¶ – A value for request.scope[“auth”].
request_media_type¶ – The ‘Content-Type’ header of the request.
data¶ – A value for the request’s body. Can be any supported serializable type.
query_params¶ – A dictionary of values from which the request’s query will be generated.
state¶ – Arbitrary request state.
path_params¶ – A string keyed dictionary of path parameter values.
http_version¶ – HTTP version. Defaults to “1.1”.
route_handler¶ – A route handler instance or method. If not provided a default handler is set.
- Returns:
A
Request
instance
- patch(path: str = '/', headers: dict[str, str] | None = None, cookies: list[Cookie] | str | None = None, session: dict[str, Any] | None = None, user: Any = None, auth: Any = None, request_media_type: RequestEncodingType = RequestEncodingType.JSON, data: dict[str, Any] | DataContainerType | None = None, query_params: dict[str, str | list[str]] | None = None, state: dict[str, Any] | None = None, path_params: dict[str, str] | None = None, http_version: str | None = '1.1', route_handler: RouteHandlerType | None = None) Request[Any, Any, Any] #
Create a PATCH
Request
instance.- Parameters:
path¶ – The request’s path.
headers¶ – A dictionary of headers.
cookies¶ – A string representing the cookie header or a list of “Cookie” instances. This value can include multiple cookies.
session¶ – A dictionary of session data.
user¶ – A value for request.scope[“user”].
auth¶ – A value for request.scope[“auth”].
request_media_type¶ – The ‘Content-Type’ header of the request.
data¶ – A value for the request’s body. Can be any supported serializable type.
query_params¶ – A dictionary of values from which the request’s query will be generated.
state¶ – Arbitrary request state.
path_params¶ – A string keyed dictionary of path parameter values.
http_version¶ – HTTP version. Defaults to “1.1”.
route_handler¶ – A route handler instance or method. If not provided a default handler is set.
- Returns:
A
Request
instance
- delete(path: str = '/', headers: dict[str, str] | None = None, cookies: list[Cookie] | str | None = None, session: dict[str, Any] | None = None, user: Any = None, auth: Any = None, query_params: dict[str, str | list[str]] | None = None, state: dict[str, Any] | None = None, path_params: dict[str, str] | None = None, http_version: str | None = '1.1', route_handler: RouteHandlerType | None = None) Request[Any, Any, Any] #
Create a POST
Request
instance.- Parameters:
path¶ – The request’s path.
headers¶ – A dictionary of headers.
cookies¶ – A string representing the cookie header or a list of “Cookie” instances. This value can include multiple cookies.
session¶ – A dictionary of session data.
user¶ – A value for request.scope[“user”].
auth¶ – A value for request.scope[“auth”].
query_params¶ – A dictionary of values from which the request’s query will be generated.
state¶ – Arbitrary request state.
path_params¶ – A string keyed dictionary of path parameter values.
http_version¶ – HTTP version. Defaults to “1.1”.
route_handler¶ – A route handler instance or method. If not provided a default handler is set.
- Returns:
A
Request
instance
- class litestar.testing.TestClient#
Bases:
Client
,BaseTestClient
,Generic
[T
]- lifespan_handler: LifeSpanHandler[Any]#
- exit_stack: ExitStack#
- __init__(app: T, base_url: str = 'http://testserver.local', raise_server_exceptions: bool = True, root_path: str = '', backend: AnyIOBackend = 'asyncio', backend_options: Mapping[str, Any] | None = None, session_config: BaseBackendConfig | None = None, timeout: float | None = None, cookies: CookieTypes | None = None) None #
A client implementation providing a context manager for testing applications.
- Parameters:
base_url¶ – URL scheme and domain for test request paths, e.g.
http://testserver
.raise_server_exceptions¶ – Flag for the underlying test client to raise server exceptions instead of wrapping them in an HTTP response.
root_path¶ – Path prefix for requests.
backend¶ – The async backend to use, options are “asyncio” or “trio”.
backend_options¶ –
anyio
options.session_config¶ – Configuration for Session Middleware class to create raw session cookies for request to the route handlers.
timeout¶ – Request timeout
cookies¶ – Cookies to set on the client.
- websocket_connect(url: str, subprotocols: Sequence[str] | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = <httpx._client.UseClientDefault object>, follow_redirects: bool | UseClientDefault = <httpx._client.UseClientDefault object>, timeout: TimeoutTypes | UseClientDefault = <httpx._client.UseClientDefault object>, extensions: Mapping[str, Any] | None = None) WebSocketTestSession #
Sends a GET request to establish a websocket connection.
- Parameters:
- Returns:
A WebSocketTestSession <litestar.testing.WebSocketTestSession> instance.
- set_session_data(data: dict[str, Any]) None #
Set session data.
- Parameters:
data¶ – Session data
- Returns:
None
Examples
from litestar import Litestar, get from litestar.middleware.session.memory_backend import MemoryBackendConfig session_config = MemoryBackendConfig() @get(path="/test") def get_session_data(request: Request) -> Dict[str, Any]: return request.session app = Litestar( route_handlers=[get_session_data], middleware=[session_config.middleware] ) with TestClient(app=app, session_config=session_config) as client: client.set_session_data({"foo": "bar"}) assert client.get("/test").json() == {"foo": "bar"}
- get_session_data() dict[str, Any] #
Get session data.
- Returns:
A dictionary containing session data.
Examples
from litestar import Litestar, post from litestar.middleware.session.memory_backend import MemoryBackendConfig session_config = MemoryBackendConfig() @post(path="/test") def set_session_data(request: Request) -> None: request.session["foo"] == "bar" app = Litestar( route_handlers=[set_session_data], middleware=[session_config.middleware] ) with TestClient(app=app, session_config=session_config) as client: client.post("/test") assert client.get_session_data() == {"foo": "bar"}
- app#
- base_url#
- backend#
- backend_options#
- session_config#
- cookies#
- class litestar.testing.WebSocketTestSession#
Bases:
object
- exit_stack: ExitStack#
- __init__(client: TestClient[Any], scope: WebSocketScope) None #
- send(data: str | bytes, mode: Literal['text', 'binary'] = 'text', encoding: str = 'utf-8') None #
Sends a “receive” event. This is the inverse of the ASGI send method.
- send_msgpack(data: Any) None #
Sends the given data as MessagePack.
- Parameters:
data¶ – The data to send.
- Returns:
None
- close(code: int = 1000) None #
Sends an ‘websocket.disconnect’ event.
- Parameters:
code¶ – status code for closing the connection.
- Returns:
None.
- receive(block: bool = True, timeout: float | None = None) WebSocketSendMessage #
This is the base receive method.
- Parameters:
Notes
you can use one of the other receive methods to extract the data from the message.
- Returns:
A websocket message.
- receive_text(block: bool = True, timeout: float | None = None) str #
Receive data in
text
mode and return a string
- receive_bytes(block: bool = True, timeout: float | None = None) bytes #
Receive data in
binary
mode and return bytes