cptestcase.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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 3rd-party libs
  30. # pylint: disable=import-error
  31. import cherrypy # pylint: disable=3rd-party-module-not-gated
  32. import salt.utils.stringutils
  33. from salt.ext import six
  34. from salt.ext.six import BytesIO
  35. # Import Salt Testing libs
  36. from tests.support.case import TestCase
  37. # pylint: enable=import-error
  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(
  50. self,
  51. path="/",
  52. method="GET",
  53. app_path="",
  54. scheme="http",
  55. proto="HTTP/1.1",
  56. body=None,
  57. qs=None,
  58. headers=None,
  59. **kwargs
  60. ):
  61. """
  62. CherryPy does not have a facility for serverless unit testing.
  63. However this recipe demonstrates a way of doing it by
  64. calling its internal API to simulate an incoming request.
  65. This will exercise the whole stack from there.
  66. Remember a couple of things:
  67. * CherryPy is multithreaded. The response you will get
  68. from this method is a thread-data object attached to
  69. the current thread. Unless you use many threads from
  70. within a unit test, you can mostly forget
  71. about the thread data aspect of the response.
  72. * Responses are dispatched to a mounted application's
  73. page handler, if found. This is the reason why you
  74. must indicate which app you are targeting with
  75. this request by specifying its mount point.
  76. You can simulate various request settings by setting
  77. the `headers` parameter to a dictionary of headers,
  78. the request's `scheme` or `protocol`.
  79. .. seealso: http://docs.cherrypy.org/stable/refman/_cprequest.html#cherrypy._cprequest.Response
  80. """
  81. # This is a required header when running HTTP/1.1
  82. h = {"Host": "127.0.0.1"}
  83. # if we had some data passed as the request entity
  84. # let's make sure we have the content-length set
  85. fd = None
  86. if body is not None:
  87. h["content-length"] = "{0}".format(len(body))
  88. fd = BytesIO(salt.utils.stringutils.to_bytes(body))
  89. if headers is not None:
  90. h.update(headers)
  91. # Get our application and run the request against it
  92. app = cherrypy.tree.apps.get(app_path)
  93. if not app:
  94. # XXX: perhaps not the best exception to raise?
  95. raise AssertionError("No application mounted at '{0}'".format(app_path))
  96. # Cleanup any previous returned response
  97. # between calls to this method
  98. app.release_serving()
  99. # Let's fake the local and remote addresses
  100. request, response = app.get_serving(local, remote, scheme, proto)
  101. try:
  102. h = [(k, v) for k, v in six.iteritems(h)]
  103. response = request.run(method, path, qs, proto, h, fd)
  104. finally:
  105. if fd:
  106. fd.close()
  107. fd = None
  108. if response.output_status.startswith(b"500"):
  109. response_body = response.collapse_body()
  110. if six.PY3:
  111. response_body = response_body.decode(__salt_system_encoding__)
  112. print(response_body)
  113. raise AssertionError("Unexpected error")
  114. # collapse the response into a bytestring
  115. response.collapse_body()
  116. return request, response