Test Utilities

Quite often you want to unittest your application or just check the outputfrom an interactive python session. In theory that is pretty simple becauseyou can fake a WSGI environment and call the application with a dummystart_response and iterate over the application iterator but there areargumentably better ways to interact with an application.

Diving In

Werkzeug provides a Client object which you can pass a WSGI application (andoptionally a response wrapper) which you can use to send virtual requests tothe application.

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

  1. >>> from werkzeug.test import Client
  2. >>> from werkzeug.testapp import test_app
  3. >>> from werkzeug.wrappers import BaseResponse
  4. >>> c = Client(test_app, BaseResponse)
  5. >>> resp = c.get('/')
  6. >>> resp.status_code
  7. 200
  8. >>> resp.headers
  9. Headers([('Content-Type', 'text/html; charset=utf-8'), ('Content-Length', '8339')])
  10. >>> resp.data.splitlines()[0]
  11. '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"'

Or without a wrapper defined:

  1. >>> c = Client(test_app)
  2. >>> app_iter, status, headers = c.get('/')
  3. >>> status
  4. '200 OK'
  5. >>> headers
  6. [('Content-Type', 'text/html; charset=utf-8'), ('Content-Length', '8339')]
  7. >>> ''.join(app_iter).splitlines()[0]
  8. '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"'

Environment Building

New in version 0.5.

The easiest way to interactively test applications is using theEnvironBuilder. It can create both standard WSGI environmentsand request objects.

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

  1. >>> from werkzeug.test import EnvironBuilder
  2. >>> from StringIO import StringIO
  3. >>> builder = EnvironBuilder(method='POST', data={'foo': 'this is some text',
  4. ... 'file': (StringIO('my file contents'), 'test.txt')})
  5. >>> env = builder.get_environ()

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

  1. >>> from werkzeug.wrappers import Request
  2. >>> req = Request(env)
  3. >>> req.form['foo']
  4. u'this is some text'
  5. >>> req.files['file']
  6. <FileStorage: u'test.txt' ('text/plain')>
  7. >>> req.files['file'].read()
  8. 'my file contents'

The EnvironBuilder figures out the content type automatically if youpass a dict to the constructor as data. If you provide a string or aninput stream you have to do that yourself.

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

  1. >>> builder = EnvironBuilder(method='POST', data={'foo': 'bar'})
  2. >>> builder.content_type
  3. 'application/x-www-form-urlencoded'
  4. >>> builder.files['foo'] = StringIO('contents')
  5. >>> builder.content_type
  6. 'multipart/form-data'

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

  1. >>> builder = EnvironBuilder(method='POST', data='{"json": "this is"}')
  2. >>> builder.content_type
  3. >>> builder.content_type = 'application/json'

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, json=None)
  • This class can be used to conveniently create a WSGI environmentfor testing purposes. It can be used to quickly create WSGI environmentsor request objects from arbitrary data.

The signature of this class is also used in some other places as ofWerkzeug 0.5 (create_environ(), BaseResponse.from_values(),Client.open()). Because of this most of the functionality isavailable through the constructor alone.

Files and regular form data can be manipulated independently of eachother with the form and files attributes, but arepassed with the same argument to the constructor: data.

data can be any of these values:

  • a str or bytes object: The object is converted into aninput_stream, the content_length is set and you have toprovide a content_type.
  • a dict or MultiDict: The keys have to be strings. The valueshave to be either any of the following objects, or a list of any of thefollowing objects:
    • a file-like object: These are converted intoFileStorage objects automatically.
    • a tuple: The addfile() method is calledwith the key and the unpacked _tuple items as positionalarguments.
    • a str: The string is set as form data for the associated key.
  • a file-like object: The object content is loaded in memory and thenhandled like a regular str or a bytes.

Parameters:

  • path – the path of the request. In the WSGI environment this willend up as PATH_INFO. If the query_string is not definedand there is a question mark in the path everything afterit is used as query string.
  • base_url – the base URL is a URL that is used to extract the WSGIURL scheme, host (server name + server port) and thescript root (SCRIPT_NAME).
  • query_string – an optional string or dict with URL parameters.
  • method – the HTTP method to use, defaults to GET.
  • input_stream – an optional input stream. Do not specify this anddata. As soon as an input stream is set you can’tmodify args and files unless youset the input_stream to None again.
  • content_type – The content type for the request. As of 0.5 youdon’t have to provide this when specifying filesand form data via data.
  • content_length – The content length for the request. You don’thave to specify this when providing data viadata.
  • errors_stream – an optional error stream that is used forwsgi.errors. Defaults to stderr.
  • multithread – controls wsgi.multithread. Defaults to False.
  • multiprocess – controls wsgi.multiprocess. Defaults to False.
  • run_once – controls wsgi.run_once. Defaults to False.
  • headers – an optional list or Headers object of headers.
  • data – a string or dict of form data or a file-object.See explanation above.
  • json – An object to be serialized and assigned to data.Defaults the content type to "application/json".Serialized with the function assigned to json_dumps.
  • environ_base – an optional dict of environment defaults.
  • environ_overrides – an optional dict of environment overrides.
  • charset – the charset used to encode unicode data.

New in version 0.15: The json param and json_dumps() method.

New in version 0.15: The environ has keys REQUEST_URI and RAW_URI containingthe path before perecent-decoding. This is not part of the WSGIPEP, but many WSGI servers include it.

Changed in version 0.6: path and base_url can now be unicode strings that areencoded with iri_to_uri().

  • path
  • The path of the application. (aka PATH_INFO)

  • charset

  • The charset used to encode unicode data.

  • headers

  • A Headers object with the request headers.

  • errors_stream

  • The error stream used for the wsgi.errors stream.

  • multithread

  • The value of wsgi.multithread

  • multiprocess

  • The value of wsgi.multiprocess

  • 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 / filesis mutually exclusive. Also do not provide this stream if therequest method is not POST / PUT or something comparable.

  • args

  • The URL arguments as MultiDict.

  • base_url

  • The base URL is used to extract the URL scheme, host name,port, and root path.

  • close()

  • Closes all files. If you put real file objects into thefiles dict you can call this method to automatically closethem all in one go.

  • content_length

  • The content length as integer. Reflected from and to theheaders. Do not set if you set files orform for auto detection.

  • content_type

  • The content type for the request. Reflected from and tothe headers. Do not set if you set files orform for auto detection.

  • files

  • A FileMultiDict of uploaded files. You can usethe add_file() method to add new files tothe dict.

  • form

  • A MultiDict of form values.

  • classmethod fromenviron(_environ, **kwargs)

  • Turn an environ dict back into a builder. Any extra kwargsoverride the args extracted from the environ.

New in version 0.15.

  • get_environ()
  • Return the built environ.

Changed in version 0.15: The content type and length headers are set based oninput stream detection. Previously this only set the WSGIkeys.

  • getrequest(_cls=None)
  • Returns a request with the data. If the request class is notspecified request_class is used.

Parameters:cls – The request wrapper to use.

  • input_stream
  • An optional input stream. If you set this it will clearform and files.

  • static jsondumps(_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 json is passed.

  • mimetype

  • The mimetype (content type without charset etc.)

New in version 0.14.

  • mimetype_params
  • The mimetype parameters as dict. For example if thecontent 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 stringargs will no longer be available.

  • request_class

  • alias of werkzeug.wrappers.base_request.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)

  • serverprotocol = 'HTTP/1.1'_

  • the server protocol to use. defaults to HTTP/1.1

  • wsgiversion = (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 you to send requests to a wrapped application.

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

Example:

  1. class ClientResponse(BaseResponse):
  2. ...
  3.  
  4. client = Client(MyApplication(), response_wrapper=ClientResponse)

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

If you want to request some subdomain of your application you may setallow_subdomain_redirects to True as if not no external redirectsare allowed.

New in version 0.5: use_cookies is new in this version. Older versions did not providebuiltin cookie support.

New in version 0.14: The mimetype parameter was added.

New in version 0.15: The json parameter.

  • open(*args, **kwargs)
  • Takes the same arguments as the EnvironBuilder class withsome additions: You can provide a EnvironBuilder or a WSGIenvironment as only argument instead of the EnvironBuilderarguments and two optional keyword arguments (as_tuple, buffered)that change the type of the return value or the way the application isexecuted.

Changed in version 0.5: If a dict is provided as file in the dict for the data parameterthe content type has to be called content_type now instead ofmimetype. This change was made for consistency withwerkzeug.FileWrapper.

The follow_redirects parameter was added to open().

Additional parameters:

Parameters:

  1. - **as_tuple** Returns a tuple in the form <code>(environ, result)</code>
  2. - **buffered** Set this to True to buffer the application run.This will automatically close the application foryou as well.
  3. - **follow_redirects** Set this to True if the _Client_ shouldfollow 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.createenviron([_options])
  • Create a new WSGI environ dict based on the values passed. The firstparameter should be the path of the request which defaults to ‘/’. Thesecond one can either be an absolute path (in that case the host islocalhost:80) or a full path to the request with scheme, netloc port andthe path to the script.

This accepts the same arguments as the EnvironBuilderconstructor.

Changed in version 0.5: This function is now a thin wrapper over EnvironBuilder whichwas added in 0.5. The headers, environ_base, environ_overrides_and _charset parameters were added.

  • werkzeug.test.runwsgi_app(_app, environ, buffered=False)
  • Return a tuple in the form (app_iter, status, headers) of theapplication output. This works best if you pass it an application thatreturns an iterator all the time.

Sometimes applications may use the write() callable returnedby the start_response function. This tries to resolve such edgecases automatically. But if you don’t get the expected output youshould set buffered to True which enforces buffering.

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

Parameters:

  • app – the application to execute.
  • buffered – set to True to enforce buffering.Returns:tuple in the form (app_iter, status, headers)