testing¶
- class litestar.testing.AsyncTestClient[源代码]¶
基类:
AsyncClient,Generic[T]- __init__(app: T, base_url: str = 'http://testserver.local', raise_server_exceptions: bool = False, root_path: str = '', timeout: float | None = None, cookies: CookieTypes | None = None, session_config: BaseBackendConfig | None = None) None[源代码]¶
An Async client implementation providing a context manager for testing applications asynchronously.
- 参数:
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.
timeout¶ -- Request timeout
cookies¶ -- Cookies to set on the client.
session_config¶ -- Session backend configuration
- async get_session_data() dict[str, Any][源代码]¶
Get session data.
- 返回:
A dictionary containing session data.
示例
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.
- 参数:
data¶ -- Session data
- 返回:
None
示例
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"}
- 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: float | None = None, extensions: Mapping[str, Any] | None = None) AsyncWebSocketTestSession[源代码]¶
Sends a GET request to establish a websocket connection.
- 参数:
- 返回:
A WebSocketTestSession <litestar.testing.WebSocketTestSession> instance.
- class litestar.testing.AsyncWebSocketTestSession[源代码]¶
基类:
object- __init__(*, app: ASGIApp, scope: WebSocketScope, connect_timeout: float | None = None, tg: anyio.abc.TaskGroup) None[源代码]¶
- async close(code: int = 1000, reason: str | None = None) None[源代码]¶
Sends an 'websocket.disconnect' event.
- async receive(block: bool = True, timeout: float | None = None) WebSocketSendMessage[源代码]¶
This is the base receive method.
- 参数:
备注
you can use one of the other receive methods to extract the data from the message.
- 返回:
A websocket message.
- async receive_bytes(block: bool = True, timeout: float | None = None) bytes[源代码]¶
Receive data in
binarymode and return bytes
- async receive_json(mode: Literal['text', 'binary'] = 'text', block: bool = True, timeout: float | None = None) Any[源代码]¶
Receive data in either
textorbinarymode and decode it as JSON.
- async receive_text(block: bool = True, timeout: float | None = None) str[源代码]¶
Receive data in
textmode and return a string
- async 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.
- async send_bytes(data: bytes, encoding: str = 'utf-8') None[源代码]¶
Sends the data using the
byteskey.
- async send_json(data: Any, mode: Literal['text', 'binary'] = 'text') None[源代码]¶
Sends the given data as JSON.
- class litestar.testing.RequestFactory[源代码]¶
基类:
objectFactory to create
Requestinstances.- app¶
- handler_kwargs¶
- port¶
- root_path¶
- scheme¶
- serializer¶
- server¶
- __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- 参数:
示例
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 )
- 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
Requestinstance.- 参数:
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.
- 返回:
A
Requestinstance
- 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
Requestinstance.- 参数:
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.
- 返回:
A
Requestinstance
- 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
Requestinstance.- 参数:
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.
- 返回:
A
Requestinstance
- 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
Requestinstance.- 参数:
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.
- 返回:
A
Requestinstance
- 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
Requestinstance.- 参数:
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.
- 返回:
A
Requestinstance
- class litestar.testing.TestClient[源代码]¶
基类:
Client,Generic[T]- __init__(app: T, base_url: str = 'http://testserver.local', raise_server_exceptions: bool = False, root_path: str = '', timeout: float | None = None, cookies: CookieTypes | None = None, backend: AnyIOBackend = 'asyncio', backend_options: dict[str, Any] | None = None, session_config: BaseBackendConfig | None = None) None[源代码]¶
A client implementation providing a context manager for testing applications.
- 参数:
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.
timeout¶ -- Request timeout
cookies¶ -- Cookies to set on the client.
backend¶ -- The async backend to use, options are "asyncio" or "trio".
backend_options¶ --
anyiooptions.session_config¶ -- Session backend configuration
- get_session_data() dict[str, Any][源代码]¶
Get session data.
- 返回:
A dictionary containing session data.
示例
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"}
- set_session_data(data: dict[str, Any]) None[源代码]¶
Set session data.
- 参数:
data¶ -- Session data
- 返回:
None
示例
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"}
- 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: float | None = None, extensions: Mapping[str, Any] | None = None) WebSocketTestSession[源代码]¶
Sends a GET request to establish a websocket connection.
- 参数:
- 返回:
A WebSocketTestSession <litestar.testing.WebSocketTestSession> instance.
- class litestar.testing.WebSocketTestSession[源代码]¶
基类:
object- __init__(client: TestClient[Any], scope: WebSocketScope, portal: anyio.abc.BlockingPortal, connect_timeout: float | None = None) None[源代码]¶
- close(code: int = 1000, reason: str | None = None) None[源代码]¶
Sends an 'websocket.disconnect' event.
- receive(block: bool = True, timeout: float | None = None) WebSocketSendMessage[源代码]¶
This is the base receive method.
- 参数:
备注
you can use one of the other receive methods to extract the data from the message.
- 返回:
A websocket message.
- receive_bytes(block: bool = True, timeout: float | None = None) bytes[源代码]¶
Receive data in
binarymode and return bytes
- receive_json(mode: Literal['text', 'binary'] = 'text', block: bool = True, timeout: float | None = None) Any[源代码]¶
Receive data in either
textorbinarymode and decode it as JSON.
- receive_text(block: bool = True, timeout: float | None = None) str[源代码]¶
Receive data in
textmode and return a string
- property scope: WebSocketScope¶
- 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_json(data: Any, mode: Literal['text', 'binary'] = 'text') None[源代码]¶
Sends the given data as JSON.
- 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, 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 = False, 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, 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='/schema', render_plugins=(<litestar.openapi.plugins.ScalarRenderPlugin object>,), openapi_router=None), 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 = False, 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, 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.
AsyncTestClientwith it.备注
- This function should be called as a context manager to ensure async startup and shutdown are
handled correctly.
示例
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"}
- 参数:
route_handlers¶ -- A single handler or a sequence of route handlers, which can include instances of
Router, subclasses ofControlleror any function decorated by the route handler decorators.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
Requestobject and should not return any values.allowed_hosts¶ -- A sequence of allowed hosts, or an
AllowedHostsConfiginstance. Enables the builtin allowed hosts middleware.before_request¶ -- A sync or async function called immediately before calling the route handler. Receives the
Requestinstance and any non-Nonereturn 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-controlheader of typeCacheControlHeaderto 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¶ --
AbstractDTOto use for (de)serializing and validation of request data.etag¶ -- An
etagheader of typeETagto 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.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
OnAppInitHandlerinstances. Handlers receive an instance ofAppConfigthat 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
LifespanHookcalled during application shutdown.on_startup¶ -- A sequence of
LifespanHookcalled during application startup.openapi_config¶ -- Defaults to
DEFAULT_OPENAPI_CONFIGopt¶ -- A string keyed mapping of arbitrary values that can be accessed in
Guardsor wherever you have access toRequestorASGI Scope.parameters¶ -- A mapping of
Parameterdefinitions available to all application paths.path¶ --
A path fragment that is prefixed to all route handlers, controllers and routers associated with the application instance.
Added 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
Requestto use for http connections.response_class¶ -- A custom subclass of
Responseto be used as the app's default response.response_headers¶ -- A string keyed mapping of
ResponseHeaderresponse_cache_config¶ -- Configures caching behavior of the application.
return_dto¶ --
AbstractDTOto use for serializing outbound response data.route_handlers¶ -- A sequence of route handlers, which can include instances of
Router, subclasses ofControlleror 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
SecurityRequirementfor details.signature_namespace¶ -- A mapping of names to types for use in forward reference resolution during signature modelling.
signature_types¶ -- A sequence of types for use in forward reference resolution during signature modelling. These types will be added to the signature namespace using their
__name__attribute.stores¶ -- Central registry of
Storethat 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
TemplateConfigtimeout¶ -- Request timeout
type_encoders¶ -- A mapping of types to callables that transform them into types supported for serialization.
websocket_class¶ -- An optional subclass of
WebSocketto use for websocket connections.experimental_features¶ -- An iterable of experimental features to enable
- 返回:
An instance of
AsyncTestClientwith 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: dict[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 = False, 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, 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='/schema', render_plugins=(<litestar.openapi.plugins.ScalarRenderPlugin object>,), openapi_router=None), 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 = False, 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, 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.
TestClientwith it.备注
- This function should be called as a context manager to ensure async startup and shutdown are
handled correctly.
示例
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"}
- 参数:
route_handlers¶ -- A single handler or a sequence of route handlers, which can include instances of
Router, subclasses ofControlleror any function decorated by the route handler decorators.backend¶ -- The async backend to use, options are "asyncio" or "trio".
backend_options¶ --
anyiooptions.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
Requestobject and should not return any values.allowed_hosts¶ -- A sequence of allowed hosts, or an
AllowedHostsConfiginstance. Enables the builtin allowed hosts middleware.before_request¶ -- A sync or async function called immediately before calling the route handler. Receives the
Requestinstance and any non-Nonereturn 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-controlheader of typeCacheControlHeaderto 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¶ --
AbstractDTOto use for (de)serializing and validation of request data.etag¶ -- An
etagheader of typeETagto 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.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
OnAppInitHandlerinstances. Handlers receive an instance ofAppConfigthat 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
LifespanHookcalled during application shutdown.on_startup¶ -- A sequence of
LifespanHookcalled during application startup.openapi_config¶ -- Defaults to
DEFAULT_OPENAPI_CONFIGopt¶ -- A string keyed mapping of arbitrary values that can be accessed in
Guardsor wherever you have access toRequestorASGI Scope.parameters¶ -- A mapping of
Parameterdefinitions available to all application paths.path¶ --
A path fragment that is prefixed to all route handlers, controllers and routers associated with the application instance.
Added 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
Requestto use for http connections.response_class¶ -- A custom subclass of
Responseto be used as the app's default response.response_headers¶ -- A string keyed mapping of
ResponseHeaderresponse_cache_config¶ -- Configures caching behavior of the application.
return_dto¶ --
AbstractDTOto use for serializing outbound response data.route_handlers¶ -- A sequence of route handlers, which can include instances of
Router, subclasses ofControlleror 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
SecurityRequirementfor details.signature_namespace¶ -- A mapping of names to types for use in forward reference resolution during signature modelling.
signature_types¶ -- A sequence of types for use in forward reference resolution during signature modelling. These types will be added to the signature namespace using their
__name__attribute.stores¶ -- Central registry of
Storethat 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
TemplateConfigtimeout¶ -- Request timeout
type_encoders¶ -- A mapping of types to callables that transform them into types supported for serialization.
websocket_class¶ -- An optional subclass of
WebSocketto use for websocket connections.experimental_features¶ -- An iterable of experimental features to enable
- 返回:
An instance of
TestClientwith a created app instance.
- litestar.testing.subprocess_async_client(workdir: Path, app: str, capture_output: bool = True) AsyncIterator[AsyncClient][源代码]¶
Provides an async httpx client for a litestar app launched in a subprocess.