webtest
– WebTest¶
Routines for testing WSGI applications.
-
class
webtest.
TestApp
(app, extra_environ=None, relative_to=None, use_unicode=True, cookiejar=None, parser_features=None, json_encoder=None, lint=True)¶ Wraps a WSGI application in a more convenient interface for testing. It uses extended version of
webob.BaseRequest
andwebob.Response
.Parameters: - app (WSGI application) –
May be an WSGI application or Paste Deploy app, like
'config:filename.ini#test'
.New in version 2.0.
It can also be an actual full URL to an http server and webtest will proxy requests with WSGIProxy2.
- extra_environ (dict) – A dictionary of values that should go into the environment for each request. These can provide a communication channel with the application.
- relative_to (string) – A directory used for file
uploads are calculated relative to this. Also
config:
URIs that aren’t absolute. - cookiejar (CookieJar instance) –
cookielib.CookieJar
alike API that keeps cookies across requets.
A convenient shortcut for a dict of all cookies in
cookiejar
.
Parameters: - parser_features (string or list) – Passed to BeautifulSoup when parsing responses.
- json_encoder (A subclass of json.JSONEncoder) – Passed to json.dumps when encoding json
- lint (A boolean) – If True (default) then check that the application is WSGI compliant
-
RequestClass
¶ alias of
TestRequest
Allow to set the HTTP_AUTHORIZATION environ key. Value should looks like
('Basic', ('user', 'password'))
If value is None the the HTTP_AUTHORIZATION is removed
-
delete
(url, params=u'', headers=None, extra_environ=None, status=None, expect_errors=False, content_type=None, xhr=False)¶ Do a DELETE request. Similar to
get()
.Returns: webtest.TestResponse
instance.
-
delete_json
(url, params=<NoDefault>, **kw)¶ Do a DELETE request. Very like the
delete
method.params
are dumped to json and put in the body of the request. Content-Type is set toapplication/json
.Returns a
webtest.TestResponse
object.
-
do_request
(req, status=None, expect_errors=None)¶ Executes the given webob Request (
req
), with the expectedstatus
. Generallyget()
andpost()
are used instead.To use this:
req = webtest.TestRequest.blank('url', ...args...) resp = app.do_request(req)
Note
You can pass any keyword arguments to
TestRequest.blank()
, which will be set on the request. These can be arguments likecontent_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, mimetype)) into a typical POST body, returning the (content_type, body).
-
get
(url, params=None, headers=None, extra_environ=None, status=None, expect_errors=False, xhr=False)¶ Do a GET request given the url path.
Parameters: - params – A query string, or a dictionary that will be encoded
into a query string. You may also include a URL query
string on the
url
. - headers (dictionary) – Extra headers to send.
- extra_environ (dictionary) – Environmental variables that should be added to the request.
- status (integer or string) – The HTTP status code you expect in response (if not 200 or 3xx).
You can also use a wildcard, like
'3*'
or'*'
. - expect_errors (boolean) – If this is False, then if anything is written to
environ
wsgi.errors
it will be an error. If it is True, then non-200/3xx responses are also okay. - xhr (boolean) – If this is true, then marks response as ajax. The same as headers={‘X-REQUESTED-WITH’: ‘XMLHttpRequest’, }
Returns: webtest.TestResponse
instance.- params – A query string, or a dictionary that will be encoded
into a query string. You may also include a URL query
string on the
Allow to set the HTTP_AUTHORIZATION environ key. Value should looks like
('Basic', ('user', 'password'))
If value is None the the HTTP_AUTHORIZATION is removed
-
head
(url, headers=None, extra_environ=None, status=None, expect_errors=False, xhr=False)¶ Do a HEAD request. Similar to
get()
.Returns: webtest.TestResponse
instance.
-
options
(url, headers=None, extra_environ=None, status=None, expect_errors=False, xhr=False)¶ Do a OPTIONS request. Similar to
get()
.Returns: webtest.TestResponse
instance.
-
patch
(url, params=u'', headers=None, extra_environ=None, status=None, upload_files=None, expect_errors=False, content_type=None, xhr=False)¶ Do a PATCH request. Similar to
post()
.Returns: webtest.TestResponse
instance.
-
patch_json
(url, params=<NoDefault>, **kw)¶ Do a PATCH request. Very like the
patch
method.params
are dumped to json and put in the body of the request. Content-Type is set toapplication/json
.Returns a
webtest.TestResponse
object.
-
post
(url, params=u'', headers=None, extra_environ=None, status=None, upload_files=None, expect_errors=False, content_type=None, xhr=False)¶ Do a POST request. Similar to
get()
.Parameters: - params –
Are put in the body of the request. If params is a iterator it will be urlencoded, if it is string it will not be encoded, but placed in the body directly.
Can be a collections.OrderedDict with
webtest.forms.Upload
fields included:- app.post(‘/myurl’, collections.OrderedDict([
- (‘textfield1’, ‘value1’), (‘uploadfield’, webapp.Upload(‘filename.txt’, ‘contents’), (‘textfield2’, ‘value2’)])))
- upload_files (list) – It should be a list of
(fieldname, filename, file_content)
. You can also use just(fieldname, filename)
and the file contents will be read from disk. - content_type (string) – HTTP content type, for example application/json.
- xhr (boolean) – If this is true, then marks response as ajax. The same as headers={‘X-REQUESTED-WITH’: ‘XMLHttpRequest’, }
Returns: webtest.TestResponse
instance.- params –
-
post_json
(url, params=<NoDefault>, **kw)¶ Do a POST request. Very like the
post
method.params
are dumped to json and put in the body of the request. Content-Type is set toapplication/json
.Returns a
webtest.TestResponse
object.
-
put
(url, params=u'', headers=None, extra_environ=None, status=None, upload_files=None, expect_errors=False, content_type=None, xhr=False)¶ Do a PUT request. Similar to
post()
.Returns: webtest.TestResponse
instance.
-
put_json
(url, params=<NoDefault>, **kw)¶ Do a PUT request. Very like the
put
method.params
are dumped to json and put in the body of the request. Content-Type is set toapplication/json
.Returns a
webtest.TestResponse
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 toTestRequest.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
webtest.TestRequest
:req = webtest.TestRequest.blank('/url/', method='GET') resp = app.do_request(req)
-
reset
()¶ Resets the state of the application; currently just clears saved cookies.
Sets a cookie to be passed through with requests.
-
set_parser_features
(parser_features)¶ Changes the parser used by BeautifulSoup. See its documentation to know the supported parsers.
- app (WSGI application) –
-
class
webtest.
TestResponse
(body=None, status=None, headerlist=None, app_iter=None, content_type=None, conditional_response=None, charset=<object object>, **kw)¶ Instances of this class are returned by
TestApp
methods.-
click
(description=None, linkid=None, href=None, index=None, verbose=False, extra_environ=None)¶ Click the link as described. Each of
description
,linkid
, andurl
are patterns, meaning that they are either strings (regular expressions), compiled regular expressions (objects with asearch
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 theid
attribute of the anchor. It will receive the empty string if no id is given.href
is a pattern that matches thehref
of the anchor; the literal content of that attribute, not the fully qualified attribute.
If more than one link matches, then the
index
link is followed. Ifindex
is not given and more than one link matches, or if no link matches, thenIndexError
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 useapp.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.
Like
click()
, except looks for link-like buttons. This kind of button should look like<button onclick="...location.href='url'...">
.
-
follow
(**kw)¶ If this response is a redirect, follow that redirect. It is an error if it is not a redirect response. Any keyword arguments are passed to
webtest.app.TestApp.get
. Returns anotherTestResponse
object.
-
form
¶ If there is only one form on the page, return it as a
Form
object; raise a TypeError is there are no form or multiple forms.
-
forms
¶ Returns a dictionary containing all the forms in the pages as
Form
objects. Indexes are both in order (from zero) and by form id (if the form is given an id).See forms for more info on form objects.
-
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 thewebtest.app.TestApp.get()
orwebtest.app.TestApp.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. The content type must be one of json type 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 alxml.HTML
object will be returned.
-
maybe_follow
(**kw)¶ Follow all redirects. If this response is not a redirect, do nothing. Any keyword arguments are passed to
webtest.app.TestApp.get
. Returns anotherTestResponse
object.
-
mustcontain
(*strings, no=[])¶ Assert that the response contains all of the strings passed in as arguments.
Equivalent to:
assert string in res
Can take a no keyword argument that can be a string or a list of strings which must not be present in the response.
-
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, parser_features='html.parser')¶ This object represents a form that has been found in a page.
Parameters: - response – webob.response.TestResponse instance
- text – Unparsed html of the form
-
text
¶ the full HTML of the form.
-
action
¶ the relative URI of the action.
-
method
¶ the HTTP method (e.g.,
'GET'
).
-
id
¶ the id, or None if not given.
-
enctype
¶ encoding of the form submission
-
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.
-
field_order
¶ Ordered list of field names as found in the html.
-
FieldClass
¶ alias of
Field
-
get
(name, index=None, default=<NoDefault>)¶ Get the named/indexed field object, or
default
if no field is found. Throws an AssertionError if no field is found and nodefault
was given.
-
lint
()¶ Check that the html is valid:
- each field must have an id
- each field must have a label
-
select
(name, value=None, text=None, index=None)¶ Like
.set()
, except also confirms the target is a<select>
and allows selecting options by text.
-
select_multiple
(name, value=None, texts=None, index=None)¶ Like
.set()
, except also confirms the target is a<select multiple>
and allows selecting options by text.
-
set
(name, value, index=None)¶ Set the given name, using
index
to disambiguate.
-
submit
(name=None, index=None, value=None, **args)¶ Submits the form. If
name
is given, then also select that button (usingindex
orvalue
to disambiguate)``.Any extra keyword arguments are passed to the
webtest.TestResponse.get()
orwebtest.TestResponse.post()
method.Returns a
webtest.TestResponse
object.
-
submit_fields
(name=None, index=None, submit_value=None)¶ Return a list of
[(name, value), ...]
for the current state of the form.Parameters:
-
upload_fields
()¶ Return a list of file field tuples of the form:
(field name, file name)
or:
(field name, file name, file contents).