Toggle navigation

Test Utilities

Quite often you want to unittest your application or just check the output from an interactive python session. In theory that is pretty simple because you can fake a WSGI environment and call the application with a dummy [UNKNOWN NODE title_reference] and iterate over the application iterator but there are argumentably better ways to interact with an application.

Diving In

Werkzeug provides a [UNKNOWN NODE title_reference] object which you can pass a WSGI application (and optionally a response wrapper) which you can use to send virtual requests to the application.

A response wrapper is a callable that takes three arguments: the application iterator, the status and finally a list of headers. The default response wrapper returns a tuple. Because response objects have the same signature, you can use them as response wrapper, ideally by subclassing them and hooking in test functionality.

[UNKNOWN NODE doctest_block]

Or without a wrapper defined:

[UNKNOWN NODE doctest_block]

Environment Building

New in version 0.5.

The easiest way to interactively test applications is using the EnvironBuilder. It can create both standard WSGI environments and request objects.

The following example creates a WSGI environment with one uploaded file and a form field:

[UNKNOWN NODE doctest_block]

The resulting environment is a regular WSGI environment that can be used for further processing:

[UNKNOWN NODE doctest_block]

The EnvironBuilder figures out the content type automatically if you pass a dict to the constructor as [UNKNOWN NODE title_reference]. If you provide a string or an input stream you have to do that yourself.

By default it will try to use application/x-www-form-urlencoded and only use multipart/form-data if files are uploaded:

[UNKNOWN NODE doctest_block]

If a string is provided as data (or an input stream) you have to specify the content type yourself:

[UNKNOWN NODE doctest_block]

Testing API

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, charset='utf-8', mimetype=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(), BaseResponse.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 form and files attributes, but are passed with the same argument to the constructor: [UNKNOWN NODE title_reference].

[UNKNOWN NODE title_reference] can be any of these values:

  • a [UNKNOWN NODE title_reference] or [UNKNOWN NODE title_reference] object: The object is converted into an input_stream, the content_length is set and you have to provide a content_type.
  • a [UNKNOWN NODE title_reference] or MultiDict: 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 into FileStorage objects automatically.
    • a [UNKNOWN NODE title_reference]: The add_file() method is called with the key and the unpacked [UNKNOWN NODE title_reference] items as positional arguments.
    • a [UNKNOWN NODE title_reference]: The string is set as form data for the associated key.
  • a file-like object: The object content is loaded in memory and then handled like a regular [UNKNOWN NODE title_reference] or a [UNKNOWN NODE title_reference].

New in version 0.6: [UNKNOWN NODE title_reference] and [UNKNOWN NODE title_reference] can now be unicode strings that are encoded using the iri_to_uri() function.

Parameters
  • path – the path of the request. In the WSGI environment this will end up as [UNKNOWN NODE title_reference]. If the [UNKNOWN NODE title_reference] is not defined and there is a question mark in the [UNKNOWN NODE title_reference] everything after it is used as query string.
  • base_url – the base URL is a URL that is used to extract the WSGI URL scheme, host (server name + server port) and the script root ([UNKNOWN NODE title_reference]).
  • query_string – an optional string or dict with URL parameters.
  • method – the HTTP method to use, defaults to [UNKNOWN NODE title_reference].
  • input_stream – an optional input stream. Do not specify this and [UNKNOWN NODE title_reference]. As soon as an input stream is set you can’t modify args and files unless you set the input_stream to [UNKNOWN NODE title_reference] again.
  • content_type – The content type for the request. As of 0.5 you don’t have to provide this when specifying files and form data via [UNKNOWN NODE title_reference].
  • content_length – The content length for the request. You don’t have to specify this when providing data via [UNKNOWN NODE title_reference].
  • errors_stream – an optional error stream that is used for [UNKNOWN NODE title_reference]. Defaults to stderr.
  • multithread – controls [UNKNOWN NODE title_reference]. Defaults to [UNKNOWN NODE title_reference].
  • multiprocess – controls [UNKNOWN NODE title_reference]. Defaults to [UNKNOWN NODE title_reference].
  • run_once – controls [UNKNOWN NODE title_reference]. Defaults to [UNKNOWN NODE title_reference].
  • headers – an optional list or Headers object of headers.
  • data – a string or dict of form data or a file-object. See explanation above.
  • environ_base – an optional dict of environment defaults.
  • environ_overrides – an optional dict of environment overrides.
  • charset – the charset used to encode unicode data.
path

The path of the application. (aka [UNKNOWN NODE title_reference])

charset

The charset used to encode unicode data.

headers

A Headers object with the request headers.

errors_stream

The error stream used for the [UNKNOWN NODE title_reference] stream.

multithread

The value of [UNKNOWN NODE title_reference]

multiprocess

The value of [UNKNOWN NODE title_reference]

environ_base

The dict used as base for the newly create environ.

environ_overrides

A dict with values that are used to override the generated environ.

input_stream

The optional input stream. This and form / files is mutually exclusive. Also do not provide this stream if the request method is not [UNKNOWN NODE title_reference] / [UNKNOWN NODE title_reference] or something comparable.

args

The URL arguments as MultiDict.

base_url

The base URL is a URL that is used to extract the WSGI URL scheme, host (server name + server port) and the script root ([UNKNOWN NODE title_reference]).

close()

Closes all files. If you put real file objects into the files dict you can call this method to automatically close them all in one go.

content_length

The content length as integer. Reflected from and to the headers. Do not set if you set files or form for auto detection.

content_type

The content type for the request. Reflected from and to the headers. Do not set if you set files or form for auto detection.

files

A FileMultiDict of uploaded files. You can use the add_file() method to add new files to the dict.

form

A MultiDict of form values.

get_environ()

Return the built environ.

get_request(cls=None)

Returns a request with the data. If the request class is not specified request_class is used.

Parameters
cls – The request wrapper to use.
input_stream

An optional input stream. If you set this it will clear form and files.

mimetype

The mimetype (content type without charset etc.)

New in version 0.14.

mimetype_params

The mimetype parameters as dict. For example if the content type is text/html; charset=utf-8 the params would be {'charset': 'utf-8'}.

New in version 0.14.

query_string

The query string. If you set this to a string args will no longer be available.

request_class

alias of werkzeug.wrappers.BaseRequest

server_name

The server name (read-only, use host to set)

server_port

The server port as integer (read-only, use host to set)

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)

class werkzeug.test.Client(application, response_wrapper=None, use_cookies=True, allow_subdomain_redirects=False)

This class allows to send requests to a wrapped application.

The response wrapper can be a class or factory function that takes three arguments: app_iter, status and headers. The default response wrapper just returns a tuple.

Example:

class ClientResponse(BaseResponse):
    ...

client = Client(MyApplication(), response_wrapper=ClientResponse)

The use_cookies parameter indicates whether cookies should be stored and sent for subsequent requests. This is True by default, but passing False will disable this behaviour.

If you want to request some subdomain of your application you may set [UNKNOWN NODE title_reference] to [UNKNOWN NODE title_reference] as if not no external redirects are allowed.

New in version 0.5: [UNKNOWN NODE title_reference] is new in this version. Older versions did not provide builtin cookie support.

New in version 0.14: The [UNKNOWN NODE title_reference] parameter was added.

open(*args, **kwargs)

Takes the same arguments as the EnvironBuilder class with some additions: You can provide a EnvironBuilder or a WSGI environment as only argument instead of the EnvironBuilder arguments and two optional keyword arguments ([UNKNOWN NODE title_reference], [UNKNOWN NODE title_reference]) that change the type of the return value or the way the application is executed.

Changed in version 0.5: If a dict is provided as file in the dict for the [UNKNOWN NODE title_reference] parameter the content type has to be called [UNKNOWN NODE title_reference] now instead of [UNKNOWN NODE title_reference]. This change was made for consistency with werkzeug.FileWrapper.

The [UNKNOWN NODE title_reference] parameter was added to open().

Additional parameters:

Parameters
  • as_tuple – Returns a tuple in the form (environ, result)
  • buffered – Set this to True to buffer the application run. This will automatically close the application for you as well.
  • follow_redirects – Set this to True if the [UNKNOWN NODE title_reference] should follow HTTP redirects.

Shortcut methods are available for many HTTP methods:

get(*args, **kw)

Like open but method is enforced to GET.

patch(*args, **kw)

Like open but method is enforced to PATCH.

post(*args, **kw)

Like open but method is enforced to POST.

head(*args, **kw)

Like open but method is enforced to HEAD.

put(*args, **kw)

Like open but method is enforced to PUT.

delete(*args, **kw)

Like open but method is enforced to DELETE.

options(*args, **kw)

Like open but method is enforced to OPTIONS.

trace(*args, **kw)

Like open but method is enforced to TRACE.

werkzeug.test.create_environ([options])

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 EnvironBuilder constructor.

Changed in version 0.5: This function is now a thin wrapper over EnvironBuilder which was added in 0.5. The [UNKNOWN NODE title_reference], [UNKNOWN NODE title_reference], [UNKNOWN NODE title_reference] and [UNKNOWN NODE title_reference] parameters were added.

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 [UNKNOWN NODE title_reference] callable returned by the [UNKNOWN NODE title_reference] function. This tries to resolve such edge cases automatically. But if you don’t get the expected output you should set [UNKNOWN NODE title_reference] to [UNKNOWN NODE title_reference] which enforces buffering.

If passed an invalid WSGI application the behavior of this function is undefined. Never pass non-conforming WSGI applications to this function.

Parameters
  • app – the application to execute.
  • buffered – set to [UNKNOWN NODE title_reference] to enforce buffering.
Returns
tuple in the form (app_iter, status, headers)