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 start_response and iterate over the application iterator but there are argumentably better ways to interact with an application.
Werkzeug provides an object called Client 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.
Werkzeug provides a Client 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.
>>> from werkzeug import Client, BaseResponse, test_app
>>> c = Client(test_app, BaseResponse)
>>> resp = c.get('/')
>>> resp.status_code
200
>>> resp.headers
Headers([('Content-Type', 'text/html; charset=utf-8')])
>>> resp.data.splitlines()[:2]
['<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"',
' "http://www.w3.org/TR/html4/loose.dtd">']
Or without a wrapper defined:
>>> c = Client(test_app)
>>> app_iter, status, headers = c.get('/')
>>> status
'200 OK'
>>> headers
[('Content-Type', 'text/html; charset=utf-8')]
>>> ''.join(app_iter).splitlines()[:2]
['<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"',
' "http://www.w3.org/TR/html4/loose.dtd">']
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:
>>> from werkzeug import EnvironBuilder
>>> from StringIO import StringIO
>>> builder = EnvironBuilder(method='POST', data={'foo': 'this is some text',
... 'file': (StringIO('my file contents'), 'test.txt')})
>>> env = builder.get_environ()
The resulting environment is a regular WSGI environment that can be used for further processing:
>>> from werkzeug import Request
>>> req = Request(env)
>>> req.form['foo']
u'this is some text'
>>> req.files['file']
<FileStorage: u'test.txt' ('text/plain')>
>>> req.files['file'].read()
'my file contents'
The EnvironBuilder figures out the content type automatically if you pass a dict to the constructor as data. 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:
>>> builder = EnvironBuilder(method='POST', data={'foo': 'bar'})
>>> builder.content_type
'application/x-www-form-urlencoded'
>>> builder.files['foo'] = StringIO('contents')
>>> builder.content_type
'multipart/form-data'
If a string is provided as data (or an input stream) you have to specify the content type yourself:
>>> builder = EnvironBuilder(method='POST', data='{"json": "this is"}')
>>> builder.content_type
>>> builder.content_type = 'application/json'
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: data.
data can be any of these values:
Parameters: |
|
---|
Returns a request with the data. If the request class is not specified request_class is used.
Parameter: | cls – The request wrapper to use. |
---|
the default request class for get_request()
alias of BaseRequest
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.
New in version 0.5: use_cookies is new in this version. Older versions did not provide builtin cookie support.
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 (as_tuple, buffered) 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 data parameter the content type has to be called content_type now instead of mimetype. This change was made for consistency with werkzeug.FileWrapper.
The follow_redirects parameter was added to open().
Additional parameters:
Parameters: |
|
---|
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 headers, environ_base, environ_overrides and charset parameters were added.
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 the start_response function. This tries to resolve such edge cases automatically. But if you don’t get the expected output you should set buffered to True 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: |
|
---|---|
Returns: | tuple in the form (app_iter, status, headers) |