cptestcase.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2011-2012, Sylvain Hellegouarch
  3. # All rights reserved.
  4. # Redistribution and use in source and binary forms, with or without modification,
  5. # are permitted provided that the following conditions are met:
  6. # * Redistributions of source code must retain the above copyright notice,
  7. # this list of conditions and the following disclaimer.
  8. # * Redistributions in binary form must reproduce the above copyright notice,
  9. # this list of conditions and the following disclaimer in the documentation
  10. # and/or other materials provided with the distribution.
  11. # * Neither the name of Sylvain Hellegouarch nor the names of his contributors
  12. # may be used to endorse or promote products derived from this software
  13. # without specific prior written permission.
  14. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  15. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  16. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  17. # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
  18. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  19. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  20. # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  21. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  22. # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  23. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24. #
  25. # Modified from the original. See the Git history of this file for details.
  26. # https://bitbucket.org/Lawouach/cherrypy-recipes/src/50aff88dc4e24206518ec32e1c32af043f2729da/testing/unit/serverless/cptestcase.py
  27. # Import Python libs
  28. from __future__ import absolute_import, print_function, unicode_literals
  29. # Import Salt Testing libs
  30. from tests.support.case import TestCase
  31. # Import 3rd-party libs
  32. # pylint: disable=import-error
  33. import cherrypy # pylint: disable=3rd-party-module-not-gated
  34. from salt.ext import six
  35. from salt.ext.six import BytesIO
  36. # pylint: enable=import-error
  37. import salt.utils.stringutils
  38. # Not strictly speaking mandatory but just makes sense
  39. cherrypy.config.update({'environment': "test_suite"})
  40. # This is mandatory so that the HTTP server isn't started
  41. # if you need to actually start (why would you?), simply
  42. # subscribe it back.
  43. cherrypy.server.unsubscribe()
  44. # simulate fake socket address... they are irrelevant in our context
  45. local = cherrypy.lib.httputil.Host('127.0.0.1', 50000, "")
  46. remote = cherrypy.lib.httputil.Host('127.0.0.1', 50001, "")
  47. __all__ = ['BaseCherryPyTestCase']
  48. class BaseCherryPyTestCase(TestCase):
  49. def request(self, path='/', method='GET', app_path='', scheme='http',
  50. proto='HTTP/1.1', body=None, qs=None, headers=None, **kwargs):
  51. """
  52. CherryPy does not have a facility for serverless unit testing.
  53. However this recipe demonstrates a way of doing it by
  54. calling its internal API to simulate an incoming request.
  55. This will exercise the whole stack from there.
  56. Remember a couple of things:
  57. * CherryPy is multithreaded. The response you will get
  58. from this method is a thread-data object attached to
  59. the current thread. Unless you use many threads from
  60. within a unit test, you can mostly forget
  61. about the thread data aspect of the response.
  62. * Responses are dispatched to a mounted application's
  63. page handler, if found. This is the reason why you
  64. must indicate which app you are targeting with
  65. this request by specifying its mount point.
  66. You can simulate various request settings by setting
  67. the `headers` parameter to a dictionary of headers,
  68. the request's `scheme` or `protocol`.
  69. .. seealso: http://docs.cherrypy.org/stable/refman/_cprequest.html#cherrypy._cprequest.Response
  70. """
  71. # This is a required header when running HTTP/1.1
  72. h = {'Host': '127.0.0.1'}
  73. # if we had some data passed as the request entity
  74. # let's make sure we have the content-length set
  75. fd = None
  76. if body is not None:
  77. h['content-length'] = '{0}'.format(len(body))
  78. fd = BytesIO(salt.utils.stringutils.to_bytes(body))
  79. if headers is not None:
  80. h.update(headers)
  81. # Get our application and run the request against it
  82. app = cherrypy.tree.apps.get(app_path)
  83. if not app:
  84. # XXX: perhaps not the best exception to raise?
  85. raise AssertionError("No application mounted at '{0}'".format(app_path))
  86. # Cleanup any previous returned response
  87. # between calls to this method
  88. app.release_serving()
  89. # Let's fake the local and remote addresses
  90. request, response = app.get_serving(local, remote, scheme, proto)
  91. try:
  92. h = [(k, v) for k, v in six.iteritems(h)]
  93. response = request.run(method, path, qs, proto, h, fd)
  94. finally:
  95. if fd:
  96. fd.close()
  97. fd = None
  98. if response.output_status.startswith(b'500'):
  99. response_body = response.collapse_body()
  100. if six.PY3:
  101. response_body = response_body.decode(__salt_system_encoding__)
  102. print(response_body)
  103. raise AssertionError("Unexpected error")
  104. # collapse the response into a bytestring
  105. response.collapse_body()
  106. return request, response