On this page
Testing WSGI Applications
Test Client
Werkzeug provides a Client to simulate requests to a WSGI application without starting a server. The client has methods for making different types of requests, as well as managing cookies across requests.
>>> from werkzeug.test import Client
>>> from werkzeug.testapp import test_app
>>> c = Client(test_app)
>>> response = c.get("/")
>>> response.status_code
200
>>> response.headers
Headers([('Content-Type', 'text/html; charset=utf-8'), ('Content-Length', '5211')])
>>> response.get_data(as_text=True)
'<!doctype html>...'
   The client’s request methods return instances of TestResponse. This provides extra attributes and methods on top of Response that are useful for testing.
Request Body
By passing a dict to data, the client will construct a request body with file and form data. It will set the content type to application/x-www-form-urlencoded if there are no files, or multipart/form-data there are.
import io
response = client.post(data={
    "name": "test",
    "file": (BytesIO("file contents".encode("utf8")), "test.txt")
})
   Pass a string, bytes, or file-like object to data to use that as the raw request body. In that case, you should set the content type appropriately. For example, to post YAML:
response = client.post(
    data="a: value\nb: 1\n", content_type="application/yaml"
)
   A shortcut when testing JSON APIs is to pass a dict to json instead of using data. This will automatically call json.dumps() and set the content type to application/json. Additionally, if the app returns JSON, response.json will automatically call json.loads().
response = client.post("/api", json={"a": "value", "b": 1})
obj = response.json()
  Environment Builder
EnvironBuilder is used to construct a WSGI environ dict. The test client uses this internally to prepare its requests. The arguments passed to the client request methods are the same as the builder.
Sometimes, it can be useful to construct a WSGI environment manually. An environ builder or dict can be passed to the test client request methods in place of other arguments to use a custom environ.
from werkzeug.test import EnvironBuilder
builder = EnvironBuilder(...)
# build an environ dict
environ = builder.get_environ()
# build an environ dict wrapped in a request
request = builder.get_request()
   The test client responses make this available through TestResponse.request and response.request.environ.
API
class werkzeug.test.Client(application, response_wrapper=None, use_cookies=True, allow_subdomain_redirects=False)- 
     
Simulate sending requests to a WSGI application without running a WSGI or HTTP server.
- Parameters:
 - 
       
- application (WSGIApplication) – The WSGI application to make requests to.
 - response_wrapper (type[Response] | None) – A 
Responseclass to wrap response data with. Defaults toTestResponse. If it’s not a subclass ofTestResponse, one will be created. - use_cookies (bool) – Persist cookies from 
Set-Cookieresponse headers to theCookieheader in subsequent requests. Domain and path matching is supported, but other cookie parameters are ignored. - allow_subdomain_redirects (bool) – Allow requests to follow redirects to subdomains. Enable this if the application handles subdomains and redirects between them.
 
 
Changelog
Changed in version 2.3: Simplify cookie implementation, support domain and path matching.
Changed in version 2.1: All data is available as properties on the returned response object. The response cannot be returned as a tuple.
Changed in version 2.0:
response_wrapperis always a subclass of :class:TestResponse.Changed in version 0.5: Added the
use_cookiesparameter.get_cookie(key, domain='localhost', path='/')- 
       
Return a
Cookieif it exists. Cookies are uniquely identified by(domain, path, key).- Parameters:
 - Return type:
 - 
         
Cookie | None
 
Changelog
New in version 2.3.
 
set_cookie(key, value='', *, domain='localhost', origin_only=True, path='/', **kwargs)- 
       
Set a cookie to be sent in subsequent requests.
This is a convenience to skip making a test request to a route that would set the cookie. To test the cookie, make a test request to a route that uses the cookie value.
The client uses
domain,origin_only, andpathto determine which cookies to send with a request. It does not use other cookie parameters that browsers use, since they’re not applicable in tests.- Parameters:
 - 
         
- key (str) – The key part of the cookie.
 - value (str) – The value part of the cookie.
 - domain (str) – Send this cookie with requests that match this domain. If 
origin_onlyis true, it must be an exact match, otherwise it may be a suffix match. - origin_only (bool) – Whether the domain must be an exact match to the request.
 - path (str) – Send this cookie with requests that match this path either exactly or as a prefix.
 - kwargs (Any) – Passed to 
dump_cookie(). 
 - Return type:
 - 
         
None
 
Changed in version 3.0: The parameter
server_nameis removed. The first parameter iskey. Use thedomainandorigin_onlyparameters instead.Changelog
Changed in version 2.3: The
origin_onlyparameter was added.Changed in version 2.3: The
domainparameter defaults tolocalhost. 
delete_cookie(key, *, domain='localhost', path='/')- 
       
Delete a cookie if it exists. Cookies are uniquely identified by
(domain, path, key).- Parameters:
 - Return type:
 - 
         
None
 
Changed in version 3.0: The
server_nameparameter is removed. The first parameter iskey. Use thedomainparameter instead.Changed in version 3.0: The
secure,httponlyandsamesiteparameters are removed.Changelog
Changed in version 2.3: The
domainparameter defaults tolocalhost. 
open(*args, buffered=False, follow_redirects=False, **kwargs)- 
       
Generate an environ dict from the given arguments, make a request to the application using it, and return the response.
- Parameters:
 - 
         
- args (Any) – Passed to 
EnvironBuilderto create the environ for the request. If a single arg is passed, it can be an existingEnvironBuilderor an environ dict. - buffered (bool) – Convert the iterator returned by the app into a list. If the iterator has a 
close()method, it is called automatically. - follow_redirects (bool) – Make additional requests to follow HTTP redirects until a non-redirect status is returned. 
TestResponse.historylists the intermediate responses. - kwargs (Any) –
 
 - args (Any) – Passed to 
 - Return type:
 
Changelog
Changed in version 2.1: Removed the
as_tupleparameter.Changed in version 2.0: The request input stream is closed when calling
response.close(). Input streams for redirects are automatically closed.Changed in version 0.5: If a dict is provided as file in the dict for the
dataparameter the content type has to be calledcontent_typeinstead ofmimetype. This change was made for consistency withwerkzeug.FileWrapper.Changed in version 0.5: Added the
follow_redirectsparameter. 
get(*args, **kw)- 
       
Call
open()withmethodset toGET.- Parameters:
 - Return type:
 
 
post(*args, **kw)- 
       
Call
open()withmethodset toPOST.- Parameters:
 - Return type:
 
 
put(*args, **kw)- 
       
Call
open()withmethodset toPUT.- Parameters:
 - Return type:
 
 
delete(*args, **kw)- 
       
Call
open()withmethodset toDELETE.- Parameters:
 - Return type:
 
 
patch(*args, **kw)- 
       
Call
open()withmethodset toPATCH.- Parameters:
 - Return type:
 
 
options(*args, **kw)- 
       
Call
open()withmethodset toOPTIONS.- Parameters:
 - Return type:
 
 
head(*args, **kw)- 
       
Call
open()withmethodset toHEAD.- Parameters:
 - Return type:
 
 
trace(*args, **kw)- 
       
Call
open()withmethodset toTRACE.- Parameters:
 - Return type:
 
 
 
class werkzeug.test.TestResponse(response, status, headers, request, history=(), **kwargs)- 
     
Responsesubclass that provides extra information about requests made with the testClient.Test client requests will always return an instance of this class. If a custom response class is passed to the client, it is subclassed along with this to support test information.
If the test request included large files, or if the application is serving a file, call
close()to close any open files and prevent Python showing aResourceWarning.Changelog
Changed in version 2.2: Set the
default_mimetypeto None to prevent a mimetype being assumed if missing.Changed in version 2.1: Response instances cannot be treated as tuples.
New in version 2.0: Test client methods always return instances of this class.
- Parameters:
 
default_mimetype: str | None = None- 
       
the default mimetype if none is provided.
 
request: Request- 
       
A request object with the environ used to make the request that resulted in this response.
 
history: tuple[werkzeug.test.TestResponse, ...]- 
       
A list of intermediate responses. Populated when the test request is made with
follow_redirectsenabled. 
property text: str- 
       
The response data as text. A shortcut for
response.get_data(as_text=True).Changelog
New in version 2.1.
 
 
class werkzeug.test.Cookie(key, value, decoded_key, decoded_value, expires, max_age, domain, origin_only, path, secure, http_only, same_site)- 
     
A cookie key, value, and parameters.
The class itself is not a public API. Its attributes are documented for inspection with
Client.get_cookie()only.Changelog
New in version 2.3.
- Parameters:
 
key: str- 
       
The cookie key, encoded as a client would see it.
 
value: str- 
       
The cookie key, encoded as a client would see it.
 
decoded_key: str- 
       
The cookie key, decoded as the application would set and see it.
 
decoded_value: str- 
       
The cookie value, decoded as the application would set and see it.
 
expires: datetime | None- 
       
The time at which the cookie is no longer valid.
 
max_age: int | None- 
       
The number of seconds from when the cookie was set at which it is no longer valid.
 
domain: str- 
       
The domain that the cookie was set for, or the request domain if not set.
 
origin_only: bool- 
       
Whether the cookie will be sent for exact domain matches only. This is
Trueif theDomainparameter was not present. 
path: str- 
       
The path that the cookie was set for.
 
secure: bool | None- 
       
The
Secureparameter. 
http_only: bool | None- 
       
The
HttpOnlyparameter. 
same_site: str | None- 
       
The
SameSiteparameter. 
 
class werkzeug.test.EnvironBuilder(path='/', base_url=None, query_string=None, method='GET', input_stream=None, content_type=None, content_length=None, errors_stream=None, multithread=False, multiprocess=False, run_once=False, headers=None, data=None, environ_base=None, environ_overrides=None, mimetype=None, json=None, auth=None)- 
     
This class can be used to conveniently create a WSGI environment for testing purposes. It can be used to quickly create WSGI environments or request objects from arbitrary data.
The signature of this class is also used in some other places as of Werkzeug 0.5 (
create_environ(),Response.from_values(),Client.open()). Because of this most of the functionality is available through the constructor alone.Files and regular form data can be manipulated independently of each other with the
formandfilesattributes, but are passed with the same argument to the constructor:data.datacan be any of these values:- a 
strorbytesobject: The object is converted into aninput_stream, thecontent_lengthis set and you have to provide acontent_type. a
dictorMultiDict: The keys have to be strings. The values have to be either any of the following objects, or a list of any of the following objects:- a 
file-like object: These are converted intoFileStorageobjects automatically. - a 
tuple: Theadd_file()method is called with the key and the unpackedtupleitems as positional arguments. - a 
str: The string is set as form data for the associated key. 
- a 
 - a file-like object: The object content is loaded in memory and then handled like a regular 
stror abytes. 
- Parameters:
 - 
       
- path (str) – the path of the request. In the WSGI environment this will end up as 
PATH_INFO. If thequery_stringis not defined and there is a question mark in thepatheverything after it is used as query string. - base_url (str | None) – the base URL is a URL that is used to extract the WSGI URL scheme, host (server name + server port) and the script root (
SCRIPT_NAME). - query_string (t.Mapping[str, str] | str | None) – an optional string or dict with URL parameters.
 - method (str) – the HTTP method to use, defaults to 
GET. - input_stream (t.IO[bytes] | None) – an optional input stream. Do not specify this and 
data. As soon as an input stream is set you can’t modifyargsandfilesunless you set theinput_streamtoNoneagain. - content_type (str | None) – The content type for the request. As of 0.5 you don’t have to provide this when specifying files and form data via 
data. - content_length (int | None) – The content length for the request. You don’t have to specify this when providing data via 
data. - errors_stream (t.IO[str] | None) – an optional error stream that is used for 
wsgi.errors. Defaults tostderr. - multithread (bool) – controls 
wsgi.multithread. Defaults toFalse. - multiprocess (bool) – controls 
wsgi.multiprocess. Defaults toFalse. - run_once (bool) – controls 
wsgi.run_once. Defaults toFalse. - headers (Headers | t.Iterable[tuple[str, str]] | None) – an optional list or 
Headersobject of headers. - data (None | (t.IO[bytes] | str | bytes | t.Mapping[str, t.Any])) – a string or dict of form data or a file-object. See explanation above.
 - json (t.Mapping[str, t.Any] | None) – An object to be serialized and assigned to 
data. Defaults the content type to"application/json". Serialized with the function assigned tojson_dumps. - environ_base (t.Mapping[str, t.Any] | None) – an optional dict of environment defaults.
 - environ_overrides (t.Mapping[str, t.Any] | None) – an optional dict of environment overrides.
 - auth (Authorization | tuple[str, str] | None) – An authorization object to use for the 
Authorizationheader value. A(username, password)tuple is a shortcut forBasicauthorization. - mimetype (str | None) –
 
 - path (str) – the path of the request. In the WSGI environment this will end up as 
 
Changed in version 3.0: The
charsetparameter was removed.Changelog
Changed in version 2.1:
CONTENT_TYPEandCONTENT_LENGTHare not duplicated as header keys in the environ.Changed in version 2.0:
REQUEST_URIandRAW_URIis the full raw URI including the query string, not only the path.Changed in version 2.0: The default
request_classisRequestinstead ofBaseRequest.New in version 2.0: Added the
authparameter.New in version 0.15: The
jsonparam andjson_dumps()method.New in version 0.15: The environ has keys
REQUEST_URIandRAW_URIcontaining the path before percent-decoding. This is not part of the WSGI PEP, but many WSGI servers include it.Changed in version 0.6:
pathandbase_urlcan now be unicode strings that are encoded withiri_to_uri().server_protocol = 'HTTP/1.1'- 
       
the server protocol to use. defaults to HTTP/1.1
 
wsgi_version = (1, 0)- 
       
the wsgi version to use. defaults to (1, 0)
 
request_class- 
       
The default request class used by
get_request().alias of
Request 
static json_dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)- 
       
The serialization function used when
jsonis passed. 
classmethod from_environ(environ, **kwargs)- 
       
Turn an environ dict back into a builder. Any extra kwargs override the args extracted from the environ.
Changelog
Changed in version 2.0: Path and query values are passed through the WSGI decoding dance to avoid double encoding.
New in version 0.15.
- Parameters:
 - 
         
- environ (WSGIEnvironment) –
 - kwargs (t.Any) –
 
 - Return type:
 
 
property base_url: str- 
       
The base URL is used to extract the URL scheme, host name, port, and root path.
 
property content_type: str | None- 
       
The content type for the request. Reflected from and to the
headers. Do not set if you setfilesorformfor auto detection. 
property mimetype: str | None- 
       
The mimetype (content type without charset etc.)
Changelog
New in version 0.14.
 
property mimetype_params: Mapping[str, str]- 
       
The mimetype parameters as dict. For example if the content type is
text/html; charset=utf-8the params would be{'charset': 'utf-8'}.Changelog
New in version 0.14.
 
property content_length: int | None- 
       
The content length as integer. Reflected from and to the
headers. Do not set if you setfilesorformfor auto detection. 
property form: MultiDict- 
       
A
MultiDictof form values. 
property files: FileMultiDict- 
       
A
FileMultiDictof uploaded files. Useadd_file()to add new files. 
property input_stream: IO[bytes] | None- 
       
An optional input stream. This is mutually exclusive with setting
formandfiles, setting it will clear those. Do not provide this if the method is notPOSTor another method that has a body. 
property query_string: str- 
       
The query string. If you set this to a string
argswill no longer be available. 
property args: MultiDict- 
       
The URL arguments as
MultiDict. 
property server_name: str- 
       
The server name (read-only, use
hostto set) 
property server_port: int- 
       
The server port as integer (read-only, use
hostto set) 
close()- 
       
Closes all files. If you put real
fileobjects into thefilesdict you can call this method to automatically close them all in one go.- Return type:
 - 
         
None
 
 
get_environ()- 
       
Return the built environ.
Changelog
Changed in version 0.15: The content type and length headers are set based on input stream detection. Previously this only set the WSGI keys.
- Return type:
 - 
         
WSGIEnvironment
 
 
get_request(cls=None)- 
       
Returns a request with the data. If the request class is not specified
request_classis used.- Parameters:
 - 
         
cls (type[werkzeug.wrappers.request.Request] | None) – The request wrapper to use.
 - Return type:
 
 
 - a 
 
werkzeug.test.create_environ(*args, **kwargs)- 
     
Create a new WSGI environ dict based on the values passed. The first parameter should be the path of the request which defaults to ‘/’. The second one can either be an absolute path (in that case the host is localhost:80) or a full path to the request with scheme, netloc port and the path to the script.
This accepts the same arguments as the
EnvironBuilderconstructor.Changelog
Changed in version 0.5: This function is now a thin wrapper over
EnvironBuilderwhich was added in 0.5. Theheaders,environ_base,environ_overridesandcharsetparameters were added.- Parameters:
 - 
       
- args (t.Any) –
 - kwargs (t.Any) –
 
 - Return type:
 - 
       
WSGIEnvironment
 
 
werkzeug.test.run_wsgi_app(app, environ, buffered=False)- 
     
Return a tuple in the form (app_iter, status, headers) of the application output. This works best if you pass it an application that returns an iterator all the time.
Sometimes applications may use the
write()callable returned by thestart_responsefunction. This tries to resolve such edge cases automatically. But if you don’t get the expected output you should setbufferedtoTruewhich enforces buffering.If passed an invalid WSGI application the behavior of this function is undefined. Never pass non-conforming WSGI applications to this function.
 
© 2007 Pallets
Licensed under the BSD 3-clause License.
 https://werkzeug.palletsprojects.com/en/3.0.x/test/