1
# -*- coding: utf-8 -*-
3
werkzeug.contrib.testtools
4
~~~~~~~~~~~~~~~~~~~~~~~~~~
6
This module implements extended wrappers for simplified testing.
9
A response wrapper which adds various cached attributes for
10
simplified assertions on various content types.
12
:copyright: (c) 2009 by the Werkzeug Team, see AUTHORS for more details.
13
:license: BSD, see LICENSE for more details.
15
from werkzeug import Response, cached_property, import_string
18
class ContentAccessors(object):
20
A mixin class for response objects that provides a couple of useful
21
accessors for unittesting.
25
"""Get an etree if possible."""
26
if 'xml' not in self.mimetype:
28
'Not a XML response (Content-Type: %s)'
30
for module in ['xml.etree.ElementTree', 'ElementTree',
31
'elementtree.ElementTree']:
32
etree = import_string(module, silent=True)
34
return etree.XML(self.body)
35
raise RuntimeError('You must have ElementTree installed '
36
'to use TestResponse.xml')
37
xml = cached_property(xml)
40
"""Get an lxml etree if possible."""
41
if ('html' not in self.mimetype and 'xml' not in self.mimetype):
42
raise AttributeError('Not an HTML/XML response')
43
from lxml import etree
45
from lxml.html import fromstring
47
fromstring = etree.HTML
48
if self.mimetype=='text/html':
49
return fromstring(self.data)
50
return etree.XML(self.data)
51
lxml = cached_property(lxml)
54
"""Get the result of simplejson.loads if possible."""
55
if 'json' not in self.mimetype:
56
raise AttributeError('Not a JSON response')
58
from simplejson import loads
60
from json import loads
61
return loads(self.data)
62
json = cached_property(json)
65
class TestResponse(Response, ContentAccessors):
66
"""Pass this to `werkzeug.test.Client` for easier unittesting."""