starlite.testing#
- class starlite.testing.TestClient#
Bases:
Client
,BaseTestClient
,Generic
[T
]- __init__(app: T, base_url: str = 'http://testserver.local', raise_server_exceptions: bool = True, root_path: str = '', backend: Literal['asyncio', 'trio'] = 'asyncio', backend_options: Optional[Dict[str, Any]] = None, session_config: Optional[BaseBackendConfig] = None, cookies: Optional[CookieTypes] = None) None #
A client implementation providing a context manager for testing applications.
- Parameters:
app – The instance of
Starlite
under test.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.
cookies – Cookies to set on the client.
- request(method: str, url: URLTypes, *, content: ~typing.Optional[RequestContent] = None, data: ~typing.Optional[RequestData] = None, files: ~typing.Optional[RequestFiles] = None, json: ~typing.Optional[~typing.Any] = None, params: ~typing.Optional[QueryParamTypes] = None, headers: ~typing.Optional[HeaderTypes] = None, cookies: ~typing.Optional[CookieTypes] = None, auth: ~typing.Optional[~typing.Union[AuthTypes, UseClientDefault]] = <httpx._client.UseClientDefault object>, follow_redirects: ~typing.Union[bool, UseClientDefault] = <httpx._client.UseClientDefault object>, timeout: ~typing.Union[TimeoutTypes, UseClientDefault] = <httpx._client.UseClientDefault object>, extensions: ~typing.Optional[~typing.Mapping[str, ~typing.Any]] = None) Response #
Sends a request.
- Parameters:
method – An HTTP method.
url – URL or path for the request.
content – Request content.
data – Form encoded data.
files – Multipart files to send.
json – JSON data to send.
params – Query parameters.
headers – Request headers.
cookies – Request cookies.
auth – Auth headers.
follow_redirects – Whether to follow redirects.
timeout – Request timeout.
extensions – Dictionary of ASGI extensions.
- Returns:
An HTTPX Response.
- get(url: URLTypes, *, params: ~typing.Optional[QueryParamTypes] = None, headers: ~typing.Optional[HeaderTypes] = None, cookies: ~typing.Optional[CookieTypes] = None, auth: ~typing.Union[AuthTypes, UseClientDefault] = <httpx._client.UseClientDefault object>, follow_redirects: ~typing.Union[bool, UseClientDefault] = <httpx._client.UseClientDefault object>, timeout: ~typing.Union[TimeoutTypes, UseClientDefault] = <httpx._client.UseClientDefault object>, extensions: ~typing.Optional[~typing.Mapping[str, ~typing.Any]] = None) Response #
Sends a GET request.
- Parameters:
url – URL or path for the request.
params – Query parameters.
headers – Request headers.
cookies – Request cookies.
auth – Auth headers.
follow_redirects – Whether to follow redirects.
timeout – Request timeout.
extensions – Dictionary of ASGI extensions.
- Returns:
An HTTPX Response.
- options(url: URLTypes, *, params: ~typing.Optional[QueryParamTypes] = None, headers: ~typing.Optional[HeaderTypes] = None, cookies: ~typing.Optional[CookieTypes] = None, auth: ~typing.Union[AuthTypes, UseClientDefault] = <httpx._client.UseClientDefault object>, follow_redirects: ~typing.Union[bool, UseClientDefault] = <httpx._client.UseClientDefault object>, timeout: ~typing.Union[TimeoutTypes, UseClientDefault] = <httpx._client.UseClientDefault object>, extensions: ~typing.Optional[~typing.Mapping[str, ~typing.Any]] = None) Response #
Sends an OPTIONS request.
- Parameters:
url – URL or path for the request.
params – Query parameters.
headers – Request headers.
cookies – Request cookies.
auth – Auth headers.
follow_redirects – Whether to follow redirects.
timeout – Request timeout.
extensions – Dictionary of ASGI extensions.
- Returns:
An HTTPX Response.
- head(url: URLTypes, *, params: ~typing.Optional[QueryParamTypes] = None, headers: ~typing.Optional[HeaderTypes] = None, cookies: ~typing.Optional[CookieTypes] = None, auth: ~typing.Union[AuthTypes, UseClientDefault] = <httpx._client.UseClientDefault object>, follow_redirects: ~typing.Union[bool, UseClientDefault] = <httpx._client.UseClientDefault object>, timeout: ~typing.Union[TimeoutTypes, UseClientDefault] = <httpx._client.UseClientDefault object>, extensions: ~typing.Optional[~typing.Mapping[str, ~typing.Any]] = None) Response #
Sends a HEAD request.
- Parameters:
url – URL or path for the request.
params – Query parameters.
headers – Request headers.
cookies – Request cookies.
auth – Auth headers.
follow_redirects – Whether to follow redirects.
timeout – Request timeout.
extensions – Dictionary of ASGI extensions.
- Returns:
An HTTPX Response.
- post(url: URLTypes, *, content: ~typing.Optional[RequestContent] = None, data: ~typing.Optional[RequestData] = None, files: ~typing.Optional[RequestFiles] = None, json: ~typing.Optional[~typing.Any] = None, params: ~typing.Optional[QueryParamTypes] = None, headers: ~typing.Optional[HeaderTypes] = None, cookies: ~typing.Optional[CookieTypes] = None, auth: ~typing.Union[AuthTypes, UseClientDefault] = <httpx._client.UseClientDefault object>, follow_redirects: ~typing.Union[bool, UseClientDefault] = <httpx._client.UseClientDefault object>, timeout: ~typing.Union[TimeoutTypes, UseClientDefault] = <httpx._client.UseClientDefault object>, extensions: ~typing.Optional[~typing.Mapping[str, ~typing.Any]] = None) Response #
Sends a POST request.
- Parameters:
url – URL or path for the request.
content – Request content.
data – Form encoded data.
files – Multipart files to send.
json – JSON data to send.
params – Query parameters.
headers – Request headers.
cookies – Request cookies.
auth – Auth headers.
follow_redirects – Whether to follow redirects.
timeout – Request timeout.
extensions – Dictionary of ASGI extensions.
- Returns:
An HTTPX Response.
- put(url: URLTypes, *, content: ~typing.Optional[RequestContent] = None, data: ~typing.Optional[RequestData] = None, files: ~typing.Optional[RequestFiles] = None, json: ~typing.Optional[~typing.Any] = None, params: ~typing.Optional[QueryParamTypes] = None, headers: ~typing.Optional[HeaderTypes] = None, cookies: ~typing.Optional[CookieTypes] = None, auth: ~typing.Union[AuthTypes, UseClientDefault] = <httpx._client.UseClientDefault object>, follow_redirects: ~typing.Union[bool, UseClientDefault] = <httpx._client.UseClientDefault object>, timeout: ~typing.Union[TimeoutTypes, UseClientDefault] = <httpx._client.UseClientDefault object>, extensions: ~typing.Optional[~typing.Mapping[str, ~typing.Any]] = None) Response #
Sends a PUT request.
- Parameters:
url – URL or path for the request.
content – Request content.
data – Form encoded data.
files – Multipart files to send.
json – JSON data to send.
params – Query parameters.
headers – Request headers.
cookies – Request cookies.
auth – Auth headers.
follow_redirects – Whether to follow redirects.
timeout – Request timeout.
extensions – Dictionary of ASGI extensions.
- Returns:
An HTTPX Response.
- patch(url: URLTypes, *, content: ~typing.Optional[RequestContent] = None, data: ~typing.Optional[RequestData] = None, files: ~typing.Optional[RequestFiles] = None, json: ~typing.Optional[~typing.Any] = None, params: ~typing.Optional[QueryParamTypes] = None, headers: ~typing.Optional[HeaderTypes] = None, cookies: ~typing.Optional[CookieTypes] = None, auth: ~typing.Union[AuthTypes, UseClientDefault] = <httpx._client.UseClientDefault object>, follow_redirects: ~typing.Union[bool, UseClientDefault] = <httpx._client.UseClientDefault object>, timeout: ~typing.Union[TimeoutTypes, UseClientDefault] = <httpx._client.UseClientDefault object>, extensions: ~typing.Optional[~typing.Mapping[str, ~typing.Any]] = None) Response #
Sends a PATCH request.
- Parameters:
url – URL or path for the request.
content – Request content.
data – Form encoded data.
files – Multipart files to send.
json – JSON data to send.
params – Query parameters.
headers – Request headers.
cookies – Request cookies.
auth – Auth headers.
follow_redirects – Whether to follow redirects.
timeout – Request timeout.
extensions – Dictionary of ASGI extensions.
- Returns:
An HTTPX Response.
- delete(url: URLTypes, *, params: ~typing.Optional[QueryParamTypes] = None, headers: ~typing.Optional[HeaderTypes] = None, cookies: ~typing.Optional[CookieTypes] = None, auth: ~typing.Union[AuthTypes, UseClientDefault] = <httpx._client.UseClientDefault object>, follow_redirects: ~typing.Union[bool, UseClientDefault] = <httpx._client.UseClientDefault object>, timeout: ~typing.Union[TimeoutTypes, UseClientDefault] = <httpx._client.UseClientDefault object>, extensions: ~typing.Optional[~typing.Mapping[str, ~typing.Any]] = None) Response #
Sends a DELETE request.
- Parameters:
url – URL or path for the request.
params – Query parameters.
headers – Request headers.
cookies – Request cookies.
auth – Auth headers.
follow_redirects – Whether to follow redirects.
timeout – Request timeout.
extensions – Dictionary of ASGI extensions.
- Returns:
An HTTPX Response.
- websocket_connect(url: str, subprotocols: ~typing.Optional[~typing.Sequence[str]] = None, params: ~typing.Optional[QueryParamTypes] = None, headers: ~typing.Optional[HeaderTypes] = None, cookies: ~typing.Optional[CookieTypes] = None, auth: ~typing.Union[AuthTypes, UseClientDefault] = <httpx._client.UseClientDefault object>, follow_redirects: ~typing.Union[bool, UseClientDefault] = <httpx._client.UseClientDefault object>, timeout: ~typing.Union[TimeoutTypes, UseClientDefault] = <httpx._client.UseClientDefault object>, extensions: ~typing.Optional[~typing.Mapping[str, ~typing.Any]] = None) WebSocketTestSession #
Sends a GET request to establish a websocket connection.
- Parameters:
url – Request URL.
subprotocols – Websocket subprotocols.
params – Query parameters.
headers – Request headers.
cookies – Request cookies.
auth – Auth headers.
follow_redirects – Whether to follow redirects.
timeout – Request timeout.
extensions – Dictionary of ASGI extensions.
- Returns:
An
WebSocketTestSession
instance.
- create_session_cookies(session_data: Dict[str, Any]) Dict[str, str] #
Creates raw session cookies that are loaded into the session by the Session Middleware. It creates cookies the same way as if they are coming from the browser. Your tests must set up session middleware to load raw session cookies into the session.
- Parameters:
session_data – Dictionary to create raw session cookies from.
- Returns:
A dictionary with cookie name as key and cookie value as value.
Deprecated since version 1.34.0: Use the explicit
TestClient.set_session_data()
methodExamples
- get_session_from_cookies() Dict[str, Any] #
Raw session cookies are a serialized image of session which are created by session middleware and sent with the response. To assert data in session, this method deserializes the raw session cookies and creates session from them.
- Returns:
A dictionary containing session data.
Deprecated since version 1.34.0: Use the explicit
TestClient.get_session_data()
methodExamples
- class starlite.testing.RequestFactory#
Bases:
object
Factory to create
Request
instances.- __init__(app: Optional[Starlite] = None, server: str = 'test.org', port: int = 3000, root_path: str = '', scheme: str = 'http') None #
Initialize
RequestFactory
- Parameters:
app – An instance of
Starlite
to set asrequest.scope["app"]
.server – The server’s domain.
port – The server’s port.
root_path – Root path for the server.
scheme – Scheme for the server.
Examples
- get(path: str = '/', headers: Optional[Dict[str, str]] = None, cookies: Optional[Union[List[Cookie], str]] = None, session: Optional[Dict[str, Any]] = None, user: Any = None, auth: Any = None, query_params: Optional[Dict[str, Union[str, List[str]]]] = None, state: Optional[Dict[str, Any]] = None, path_params: Optional[Dict[str, str]] = None, http_version: Optional[str] = '1.1', route_handler: Optional[Any] = None) Request[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: Optional[Dict[str, str]] = None, cookies: Optional[Union[List[Cookie], str]] = None, session: Optional[Dict[str, Any]] = None, user: Any = None, auth: Any = None, request_media_type: RequestEncodingType = RequestEncodingType.JSON, data: Optional[Union[Dict[str, Any], BaseModel]] = None, query_params: Optional[Dict[str, Union[str, List[str]]]] = None, state: Optional[Dict[str, Any]] = None, path_params: Optional[Dict[str, str]] = None, http_version: Optional[str] = '1.1', route_handler: Optional[Any] = None) Request[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 either a pydantic model instance or a string keyed dictionary.
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: Optional[Dict[str, str]] = None, cookies: Optional[Union[List[Cookie], str]] = None, session: Optional[Dict[str, Any]] = None, user: Any = None, auth: Any = None, request_media_type: RequestEncodingType = RequestEncodingType.JSON, data: Optional[Union[Dict[str, Any], BaseModel]] = None, query_params: Optional[Dict[str, Union[str, List[str]]]] = None, state: Optional[Dict[str, Any]] = None, path_params: Optional[Dict[str, str]] = None, http_version: Optional[str] = '1.1', route_handler: Optional[Any] = None) Request[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 either a pydantic model instance or a string keyed dictionary.
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: Optional[Dict[str, str]] = None, cookies: Optional[Union[List[Cookie], str]] = None, session: Optional[Dict[str, Any]] = None, user: Any = None, auth: Any = None, request_media_type: RequestEncodingType = RequestEncodingType.JSON, data: Optional[Union[Dict[str, Any], BaseModel]] = None, query_params: Optional[Dict[str, Union[str, List[str]]]] = None, state: Optional[Dict[str, Any]] = None, path_params: Optional[Dict[str, str]] = None, http_version: Optional[str] = '1.1', route_handler: Optional[Any] = None) Request[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 either a pydantic model instance or a string keyed dictionary.
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: Optional[Dict[str, str]] = None, cookies: Optional[Union[List[Cookie], str]] = None, session: Optional[Dict[str, Any]] = None, user: Any = None, auth: Any = None, query_params: Optional[Dict[str, Union[str, List[str]]]] = None, state: Optional[Dict[str, Any]] = None, path_params: Optional[Dict[str, str]] = None, http_version: Optional[str] = '1.1', route_handler: Optional[Any] = None) Request[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
- starlite.testing.create_test_client(route_handlers: ~typing.Union[ControllerRouterHandler, ~typing.List[ControllerRouterHandler]], *, after_exception: ~typing.Optional[SingleOrList[AfterExceptionHookHandler]] = None, after_request: ~typing.Optional[AfterRequestHookHandler] = None, after_response: ~typing.Optional[AfterResponseHookHandler] = None, after_shutdown: ~typing.Optional[SingleOrList[LifeSpanHookHandler]] = None, after_startup: ~typing.Optional[SingleOrList[LifeSpanHookHandler]] = None, allowed_hosts: ~typing.Optional[~typing.Union[~typing.List[str], AllowedHostsConfig]] = None, backend: ~typing.Literal['asyncio', 'trio'] = 'asyncio', backend_options: ~typing.Optional[~typing.Dict[str, ~typing.Any]] = None, base_url: str = 'http://testserver.local', before_request: ~typing.Optional[BeforeRequestHookHandler] = None, before_send: ~typing.Optional[SingleOrList[BeforeMessageSendHookHandler]] = None, before_shutdown: ~typing.Optional[SingleOrList[LifeSpanHookHandler]] = None, before_startup: ~typing.Optional[SingleOrList[LifeSpanHookHandler]] = None, cache_config: CacheConfig = CacheConfig(backend=None, expiration=60, cache_key_builder=<function default_cache_key_builder>), compression_config: ~typing.Optional[CompressionConfig] = None, cors_config: ~typing.Optional[CORSConfig] = None, csrf_config: ~typing.Optional[CSRFConfig] = None, dependencies: ~typing.Optional[Dependencies] = None, exception_handlers: ~typing.Optional[ExceptionHandlersMap] = None, guards: ~typing.Optional[~typing.List[Guard]] = None, initial_state: ~typing.Optional[~typing.Union[ImmutableState, ~typing.Dict[str, ~typing.Any], ~typing.Iterable[~typing.Tuple[str, ~typing.Any]]]] = None, logging_config: ~typing.Optional[BaseLoggingConfig] = None, middleware: ~typing.Optional[~typing.List[Middleware]] = None, multipart_form_part_limit: int = 1000, on_app_init: ~typing.Optional[~typing.List[OnAppInitHandler]] = None, on_shutdown: ~typing.Optional[~typing.List[LifeSpanHandler]] = None, on_startup: ~typing.Optional[~typing.List[LifeSpanHandler]] = None, openapi_config: ~typing.Optional[OpenAPIConfig] = None, parameters: ~typing.Optional[ParametersMap] = None, plugins: ~typing.Optional[~typing.List[PluginProtocol]] = None, raise_server_exceptions: bool = True, request_class: ~typing.Optional[~typing.Type[Request]] = None, response_class: ~typing.Optional[ResponseType] = None, root_path: str = '', session_config: ~typing.Optional[BaseBackendConfig] = None, static_files_config: ~typing.Optional[~typing.Union[StaticFilesConfig, ~typing.List[StaticFilesConfig]]] = None, template_config: ~typing.Optional[TemplateConfig] = None, websocket_class: ~typing.Optional[~typing.Type[WebSocket]] = None) TestClient[Starlite] #
Create a Starlite 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
- Parameters:
route_handlers – A single handler or a list of route handlers, which can include instances of
Router
, subclasses ofController
or any function decorated by the route handler decorators.after_exception – An application level
exception event handler
. 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 which may be any subclass of
Response
.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.after_shutdown – An application level
LifeSpan hook handler
. This hook is called during the ASGI shutdown, after all callables in theon_shutdown
list have been called.after_startup – An application level
LifeSpan hook handler
. This hook is called during the ASGI startup, after all callables in theon_startup
list have been called.allowed_hosts – A list of allowed hosts - enables the builtin allowed hosts middleware.
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’.
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 – An application level
before send hook handler
or list thereof. This hook is called when the ASGI send function is called.before_shutdown – An application level
LifeSpan hook handler
. This hook is called during the ASGI shutdown, before any callables in theon_shutdown
list have been called.before_startup – An application level
LifeSpan hook handler
. This hook is called during the ASGI startup, before any callables in theon_startup
list have been called.cache_config – Configures caching behavior of the application.
compression_config – Configures compression behaviour of the application, this enabled a builtin or user defined Compression middleware.
cors_config – If set this enables the builtin CORS middleware.
csrf_config – If set this enables the builtin CSRF middleware.
dependencies – A string keyed dictionary of dependency
Provider
instances.exception_handlers – A dictionary that maps handler functions to status codes and/or exception types.
guards – A list of
Guard
callables.initial_state – An object from which to initialize the app state.
logging_config – A subclass of
BaseLoggingConfig
.middleware – A list 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 toStarlite
, 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 list of
LifeSpanHandler
called during application shutdown.on_startup – A list of
LifeSpanHandler
called during application startup.openapi_config – Defaults to
DEFAULT_OPENAPI_CONFIG
parameters – A mapping of
Parameter
definitions available to all application paths.plugins – List of plugins.
request_class – An optional subclass of
Request
to use for http connections.raise_server_exceptions – Flag for underlying the test client to raise server exceptions instead of wrapping them in an HTTP response.
response_class – A custom subclass of [starlite.response.Response] to be used as the app’s default response.
root_path – Path prefix for requests.
static_files_config – An instance or list of
StaticFilesConfig
session_config – Configuration for Session Middleware class to create raw session cookies for request to the route handlers.
template_config – An instance of
TemplateConfig
websocket_class – An optional subclass of
WebSocket
to use for websocket connections.
- Returns:
An instance of
TestClient
with a created app instance.