testtools.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # -*- coding: utf-8 -*-
  2. """
  3. werkzeug.contrib.testtools
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. This module implements extended wrappers for simplified testing.
  6. `TestResponse`
  7. A response wrapper which adds various cached attributes for
  8. simplified assertions on various content types.
  9. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
  10. :license: BSD, see LICENSE for more details.
  11. """
  12. from werkzeug.utils import cached_property, import_string
  13. from werkzeug.wrappers import Response
  14. from warnings import warn
  15. warn(DeprecationWarning('werkzeug.contrib.testtools is deprecated and '
  16. 'will be removed with Werkzeug 1.0'))
  17. class ContentAccessors(object):
  18. """
  19. A mixin class for response objects that provides a couple of useful
  20. accessors for unittesting.
  21. """
  22. def xml(self):
  23. """Get an etree if possible."""
  24. if 'xml' not in self.mimetype:
  25. raise AttributeError(
  26. 'Not a XML response (Content-Type: %s)'
  27. % self.mimetype)
  28. for module in ['xml.etree.ElementTree', 'ElementTree',
  29. 'elementtree.ElementTree']:
  30. etree = import_string(module, silent=True)
  31. if etree is not None:
  32. return etree.XML(self.body)
  33. raise RuntimeError('You must have ElementTree installed '
  34. 'to use TestResponse.xml')
  35. xml = cached_property(xml)
  36. def lxml(self):
  37. """Get an lxml etree if possible."""
  38. if ('html' not in self.mimetype and 'xml' not in self.mimetype):
  39. raise AttributeError('Not an HTML/XML response')
  40. from lxml import etree
  41. try:
  42. from lxml.html import fromstring
  43. except ImportError:
  44. fromstring = etree.HTML
  45. if self.mimetype == 'text/html':
  46. return fromstring(self.data)
  47. return etree.XML(self.data)
  48. lxml = cached_property(lxml)
  49. def json(self):
  50. """Get the result of simplejson.loads if possible."""
  51. if 'json' not in self.mimetype:
  52. raise AttributeError('Not a JSON response')
  53. try:
  54. from simplejson import loads
  55. except ImportError:
  56. from json import loads
  57. return loads(self.data)
  58. json = cached_property(json)
  59. class TestResponse(Response, ContentAccessors):
  60. """Pass this to `werkzeug.test.Client` for easier unittesting."""