webtest – WebTest

Routines for testing WSGI applications.

Most interesting is app

class webtest.TestApp(app, extra_environ=None, relative_to=None, use_unicode=True)

Wraps a WSGI application in a more convenient interface for testing.

app may be an application, or a Paste Deploy app URI, like 'config:filename.ini#test'.

extra_environ is a dictionary of values that should go into the environment for each request. These can provide a communication channel with the application.

relative_to is a directory, and filenames used for file uploads are calculated relative to this. Also config: URIs that aren’t absolute.

delete(url, params='', headers=None, extra_environ=None, status=None, expect_errors=False, content_type=None)

Do a DELETE request. Very like the .get() method.

Returns a webob.Response object.

delete_json(url, params=<class 'webtest.app.NoDefault'>, headers=None, extra_environ=None, status=None, expect_errors=False)

Do a DELETE request. Very like the .get() method. Content-Type is set to application/json.

Returns a webob.Response object.

do_request(req, status, expect_errors)

Executes the given request (req), with the expected status. Generally .get() and .post() are used instead.

To use this:

resp = app.do_request(webtest.TestRequest.blank(
    'url', ...args...))

Note you can pass any keyword arguments to TestRequest.blank(), which will be set on the request. These can be arguments like content_type, accept, etc.

encode_multipart(params, files)

Encodes a set of parameters (typically a name/value list) and a set of files (a list of (name, filename, file_body)) into a typical POST body, returning the (content_type, body).

get(url, params=None, headers=None, extra_environ=None, status=None, expect_errors=False)

Get the given url (well, actually a path like '/page.html').

params:
A query string, or a dictionary that will be encoded into a query string. You may also include a query string on the url.
headers:
A dictionary of extra headers to send.
extra_environ:
A dictionary of environmental variables that should be added to the request.
status:
The integer status code you expect (if not 200 or 3xx). If you expect a 404 response, for instance, you must give status=404 or it will be an error. You can also give a wildcard, like '3*' or '*'.
expect_errors:
If this is not true, then if anything is written to wsgi.errors it will be an error. If it is true, then non-200/3xx responses are also okay.

Returns a webtest.TestResponse object.

head(url, headers=None, extra_environ=None, status=None, expect_errors=False)

Do a HEAD request. Very like the .get() method.

Returns a webob.Response object.

options(url, headers=None, extra_environ=None, status=None, expect_errors=False)

Do a OPTIONS request. Very like the .get() method.

Returns a webob.Response object.

post(url, params='', headers=None, extra_environ=None, status=None, upload_files=None, expect_errors=False, content_type=None)

Do a POST request. Very like the .get() method. params are put in the body of the request.

upload_files is for file uploads. It should be a list of [(fieldname, filename, file_content)]. You can also use just [(fieldname, filename)] and the file content will be read from disk.

For post requests params could be a collections.OrderedDict with Upload fields included in order:

app.post(‘/myurl’, collections.OrderedDict([
(‘textfield1’, ‘value1’), (‘uploadfield’, webapp.Upload(‘filename.txt’, ‘contents’), (‘textfield2’, ‘value2’)])))

Returns a webob.Response object.

post_json(url, params=<class 'webtest.app.NoDefault'>, headers=None, extra_environ=None, status=None, expect_errors=False)

Do a POST request. Very like the .get() method. params are dumps to json and put in the body of the request. Content-Type is set to application/json.

Returns a webob.Response object.

put(url, params='', headers=None, extra_environ=None, status=None, upload_files=None, expect_errors=False, content_type=None)

Do a PUT request. Very like the .post() method. params are put in the body of the request, if params is a tuple, dictionary, list, or iterator it will be urlencoded and placed in the body as with a POST, if it is string it will not be encoded, but placed in the body directly.

Returns a webob.Response object.

put_json(url, params=<class 'webtest.app.NoDefault'>, headers=None, extra_environ=None, status=None, expect_errors=False)

Do a PUT request. Very like the .post() method. params are dumps to json and put in the body of the request. Content-Type is set to application/json.

Returns a webob.Response object.

request(url_or_req, status=None, expect_errors=False, **req_params)

Creates and executes a request. You may either pass in an instantiated TestRequest object, or you may pass in a URL and keyword arguments to be passed to TestRequest.blank().

You can use this to run a request without the intermediary functioning of TestApp.get() etc. For instance, to test a WebDAV method:

resp = app.request('/new-col', method='MKCOL')

Note that the request won’t have a body unless you specify it, like:

resp = app.request('/test.txt', method='PUT', body='test')

You can use POST={args} to set the request body to the serialized arguments, and simultaneously set the request method to POST

reset()

Resets the state of the application; currently just clears saved cookies.

class webtest.TestResponse(body=None, status=None, headerlist=None, app_iter=None, content_type=None, conditional_response=None, **kw)

Instances of this class are return by TestApp

click(description=None, linkid=None, href=None, anchor=None, index=None, verbose=False, extra_environ=None)

Click the link as described. Each of description, linkid, and url are patterns, meaning that they are either strings (regular expressions), compiled regular expressions (objects with a search method), or callables returning true or false.

All the given patterns are ANDed together:

  • description is a pattern that matches the contents of the anchor (HTML and all – everything between <a...> and </a>)
  • linkid is a pattern that matches the id attribute of the anchor. It will receive the empty string if no id is given.
  • href is a pattern that matches the href of the anchor; the literal content of that attribute, not the fully qualified attribute.
  • anchor is a pattern that matches the entire anchor, with its contents.

If more than one link matches, then the index link is followed. If index is not given and more than one link matches, or if no link matches, then IndexError will be raised.

If you give verbose then messages will be printed about each link, and why it does or doesn’t match. If you use app.click(verbose=True) you’ll see a list of all the links.

You can use multiple criteria to essentially assert multiple aspects about the link, e.g., where the link’s destination is.

clickbutton(description=None, buttonid=None, href=None, button=None, index=None, verbose=False)

Like .click(), except looks for link-like buttons. This kind of button should look like <button onclick="...location.href='url'...">.

follow(**kw)

If this request is a redirect, follow that redirect. It is an error if this is not a redirect response. Returns another response object.

form

Returns a single Form instance; it is an error if there are multiple forms on the page.

forms

A list of :class:`~webtest.Form`s found on the page

forms__get()

Returns a dictionary of Form objects. Indexes are both in order (from zero) and by form id (if the form is given an id).

goto(href, method='get', **args)

Go to the (potentially relative) link href, using the given method ('get' or 'post') and any extra arguments you want to pass to the app.get() or app.post() methods.

All hostnames and schemes will be ignored.

html

Returns the response as a BeautifulSoup object.

Only works with HTML responses; other content-types raise AttributeError.

json

Return the response as a JSON response. You must have simplejson installed to use this, or be using a Python version with the json module.

The content type must be application/json to use this.

lxml

Returns the response as an lxml object. You must have lxml installed to use this.

If this is an HTML response and you have lxml 2.x installed, then an lxml.html.HTML object will be returned; if you have an earlier version of lxml then a lxml.HTML object will be returned.

mustcontain(*strings, **kw)

Assert that the response contains all of the strings passed in as arguments.

Equivalent to:

assert string in res
normal_body

Return the whitespace-normalized body

pyquery

Returns the response as a PyQuery object.

Only works with HTML and XML responses; other content-types raise AttributeError.

showbrowser()

Show this response in a browser window (for debugging purposes, when it’s hard to read the HTML).

unicode_normal_body

Return the whitespace-normalized body, as unicode

xml

Returns the response as an ElementTree object.

Only works with XML responses; other content-types raise AttributeError

class webtest.Form(response, text)

This object represents a form that has been found in a page. This has a couple useful attributes:

text:
the full HTML of the form.
action:
the relative URI of the action.
method:
the method (e.g., 'GET').
id:
the id, or None if not given.
fields:
a dictionary of fields, each value is a list of fields by that name. <input type="radio"> and <select> are both represented as single fields with multiple options.
FieldClass

alias of Field

get(name, index=None, default=<class 'webtest.app.NoDefault'>)

Get the named/indexed field object, or default if no field is found.

lint()

Check that the html is valid:

  • each field must have an id
  • each field must have a label
select(name, value, index=None)

Like .set(), except also confirms the target is a <select>.

set(name, value, index=None)

Set the given name, using index to disambiguate.

submit(name=None, index=None, **args)

Submits the form. If name is given, then also select that button (using index to disambiguate)``.

Any extra keyword arguments are passed to the .get() or .post() method.

Returns a webtest.TestResponse object.

submit_fields(name=None, index=None)

Return a list of [(name, value), ...] for the current state of the form.

upload_fields()
Return a list of file field tuples of the form:
(field name, file name)
or
(field name, file name, file contents).

Project Versions

Previous topic

rails WebHelpers Rails (deprecated)

Next topic

webob – WebOb

This Page