Back to index

moin  1.9.0~rc2
testtools.py
Go to the documentation of this file.
00001 # -*- coding: utf-8 -*-
00002 """
00003     werkzeug.contrib.testtools
00004     ~~~~~~~~~~~~~~~~~~~~~~~~~~
00005 
00006     This module implements extended wrappers for simplified testing.
00007 
00008     `TestResponse`
00009         A response wrapper which adds various cached attributes for
00010         simplified assertions on various content types.
00011 
00012     :copyright: (c) 2009 by the Werkzeug Team, see AUTHORS for more details.
00013     :license: BSD, see LICENSE for more details.
00014 """
00015 from werkzeug import Response, cached_property, import_string
00016 
00017 
00018 class ContentAccessors(object):
00019     """
00020     A mixin class for response objects that provides a couple of useful
00021     accessors for unittesting.
00022     """
00023 
00024     def xml(self):
00025         """Get an etree if possible."""
00026         if 'xml' not in self.mimetype:
00027             raise AttributeError(
00028                 'Not a XML response (Content-Type: %s)'
00029                 % self.mimetype)
00030         for module in ['xml.etree.ElementTree', 'ElementTree',
00031                        'elementtree.ElementTree']:
00032             etree = import_string(module, silent=True)
00033             if etree is not None:
00034                 return etree.XML(self.body)
00035         raise RuntimeError('You must have ElementTree installed '
00036                            'to use TestResponse.xml')
00037     xml = cached_property(xml)
00038 
00039     def lxml(self):
00040         """Get an lxml etree if possible."""
00041         if ('html' not in self.mimetype and 'xml' not in self.mimetype):
00042             raise AttributeError('Not an HTML/XML response')
00043         from lxml import etree
00044         try:
00045             from lxml.html import fromstring
00046         except ImportError:
00047             fromstring = etree.HTML
00048         if self.mimetype=='text/html':
00049             return fromstring(self.data)
00050         return etree.XML(self.data)
00051     lxml = cached_property(lxml)
00052 
00053     def json(self):
00054         """Get the result of simplejson.loads if possible."""
00055         if 'json' not in self.mimetype:
00056             raise AttributeError('Not a JSON response')
00057         try:
00058             from simplejson import loads
00059         except:
00060             from json import loads
00061         return loads(self.data)
00062     json = cached_property(json)
00063 
00064 
00065 class TestResponse(Response, ContentAccessors):
00066     """Pass this to `werkzeug.test.Client` for easier unittesting."""