2
0

stub.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. # Copyright 2016 ksyun.com, Inc. or its affiliates. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"). You
  4. # may not use this file except in compliance with the License. A copy of
  5. # the License is located at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # or in the "license" file accompanying this file. This file is
  10. # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  11. # ANY KIND, either express or implied. See the License for the specific
  12. # language governing permissions and limitations under the License.
  13. import copy
  14. from collections import deque
  15. from kscore.validate import validate_parameters
  16. from kscore.exceptions import ParamValidationError, \
  17. StubResponseError, StubAssertionError
  18. from kscore.vendored.requests.models import Response
  19. class Stubber(object):
  20. """
  21. This class will allow you to stub out requests so you don't have to hit
  22. an endpoint to write tests. Responses are returned first in, first out.
  23. If operations are called out of order, or are called with no remaining
  24. queued responses, an error will be raised.
  25. **Example:**
  26. ::
  27. import datetime
  28. import kscore.session
  29. from kscore.stub import Stubber
  30. s3 = kscore.session.get_session().create_client('s3')
  31. stubber = Stubber(s3)
  32. response = {
  33. 'IsTruncated': False,
  34. 'Name': 'test-bucket',
  35. 'MaxKeys': 1000, 'Prefix': '',
  36. 'Contents': [{
  37. 'Key': 'test.txt',
  38. 'ETag': '"abc123"',
  39. 'StorageClass': 'STANDARD',
  40. 'LastModified': datetime.datetime(2016, 1, 20, 22, 9),
  41. 'Owner': {'ID': 'abc123', 'DisplayName': 'myname'},
  42. 'Size': 14814
  43. }],
  44. 'EncodingType': 'url',
  45. 'ResponseMetadata': {
  46. 'RequestId': 'abc123',
  47. 'HTTPStatusCode': 200,
  48. 'HostId': 'abc123'
  49. },
  50. 'Marker': ''
  51. }
  52. expected_params = {'Bucket': 'test-bucket'}
  53. stubber.add_response('list_objects', response, expected_params)
  54. stubber.activate()
  55. service_response = s3.list_objects(Bucket='test-bucket')
  56. assert service_response == response
  57. """
  58. def __init__(self, client):
  59. """
  60. :param client: The client to add your stubs to.
  61. """
  62. self.client = client
  63. self._event_id = 'ksc_stubber'
  64. self._expected_params_event_id = 'ksc_stubber_expected_params'
  65. self._queue = deque()
  66. def activate(self):
  67. """
  68. Activates the stubber on the client
  69. """
  70. self.client.meta.events.register_first(
  71. 'before-parameter-build.*.*',
  72. self._assert_expected_params,
  73. unique_id=self._expected_params_event_id)
  74. self.client.meta.events.register(
  75. 'before-call.*.*',
  76. self._get_response_handler,
  77. unique_id=self._event_id)
  78. def deactivate(self):
  79. """
  80. Deactivates the stubber on the client
  81. """
  82. self.client.meta.events.unregister(
  83. 'before-parameter-build.*.*',
  84. self._assert_expected_params,
  85. unique_id=self._expected_params_event_id)
  86. self.client.meta.events.unregister(
  87. 'before-call.*.*',
  88. self._get_response_handler,
  89. unique_id=self._event_id)
  90. def add_response(self, method, service_response, expected_params=None):
  91. """
  92. Adds a service response to the response queue. This will be validated
  93. against the service model to ensure correctness. It should be noted,
  94. however, that while missing attributes are often considered correct,
  95. your code may not function properly if you leave them out. Therefore
  96. you should always fill in every value you see in a typical response for
  97. your particular request.
  98. :param method: The name of the client method to stub.
  99. :type method: str
  100. :param service_response: A dict response stub. Provided parameters will
  101. be validated against the service model.
  102. :type service_response: dict
  103. :param expected_params: A dictionary of the expected parameters to
  104. be called for the provided service response. The parameters match
  105. the names of keyword arguments passed to that client call. If
  106. any of the parameters differ a ``StubResponseError`` is thrown.
  107. """
  108. self._add_response(method, service_response, expected_params)
  109. def _add_response(self, method, service_response, expected_params):
  110. if not hasattr(self.client, method):
  111. raise ValueError(
  112. "Client %s does not have method: %s"
  113. % (self.client.meta.service_model.service_name, method))
  114. # Create a successful http response
  115. http_response = Response()
  116. http_response.status_code = 200
  117. http_response.reason = 'OK'
  118. operation_name = self.client.meta.method_to_api_mapping.get(method)
  119. self._validate_response(operation_name, service_response)
  120. # Add the service_response to the queue for returning responses
  121. response = {
  122. 'operation_name': operation_name,
  123. 'response': (http_response, service_response),
  124. 'expected_params': expected_params
  125. }
  126. self._queue.append(response)
  127. def add_client_error(self, method, service_error_code='',
  128. service_message='', http_status_code=400):
  129. """
  130. Adds a ``ClientError`` to the response queue.
  131. :param method: The name of the service method to return the error on.
  132. :type method: str
  133. :param service_error_code: The service error code to return,
  134. e.g. ``NoSuchBucket``
  135. :type service_error_code: str
  136. :param service_message: The service message to return, e.g.
  137. 'The specified bucket does not exist.'
  138. :type service_message: str
  139. :param http_status_code: The HTTP status code to return, e.g. 404, etc
  140. :type http_status_code: int
  141. """
  142. http_response = Response()
  143. http_response.status_code = http_status_code
  144. # We don't look to the model to build this because the caller would
  145. # need to know the details of what the HTTP body would need to
  146. # look like.
  147. parsed_response = {
  148. 'ResponseMetadata': {'HTTPStatusCode': http_status_code},
  149. 'Error': {
  150. 'Message': service_message,
  151. 'Code': service_error_code
  152. }
  153. }
  154. operation_name = self.client.meta.method_to_api_mapping.get(method)
  155. # Note that we do not allow for expected_params while
  156. # adding errors into the queue yet.
  157. response = {
  158. 'operation_name': operation_name,
  159. 'response': (http_response, parsed_response),
  160. 'expected_params': None
  161. }
  162. self._queue.append(response)
  163. def assert_no_pending_responses(self):
  164. """
  165. Asserts that all expected calls were made.
  166. """
  167. remaining = len(self._queue)
  168. if remaining != 0:
  169. raise AssertionError(
  170. "%d responses remaining in queue." % remaining)
  171. def _assert_expected_call_order(self, model, params):
  172. if not self._queue:
  173. raise StubResponseError(
  174. operation_name=model.name,
  175. reason='Unexpected API Call: called with parameters %s' %
  176. params)
  177. name = self._queue[0]['operation_name']
  178. if name != model.name:
  179. raise StubResponseError(
  180. operation_name=model.name,
  181. reason='Operation mismatch: found response for %s.' % name)
  182. def _get_response_handler(self, model, params, **kwargs):
  183. self._assert_expected_call_order(model, params)
  184. # Pop off the entire response once everything has been validated
  185. return self._queue.popleft()['response']
  186. def _assert_expected_params(self, model, params, **kwargs):
  187. self._assert_expected_call_order(model, params)
  188. expected_params = self._queue[0]['expected_params']
  189. if expected_params is not None and params != expected_params:
  190. raise StubAssertionError(
  191. operation_name=model.name,
  192. reason='Expected parameters: %s, but received: %s' % (
  193. expected_params, params))
  194. def _validate_response(self, operation_name, service_response):
  195. service_model = self.client.meta.service_model
  196. operation_model = service_model.operation_model(operation_name)
  197. output_shape = operation_model.output_shape
  198. # Remove ResponseMetadata so that the validator doesn't attempt to
  199. # perform validation on it.
  200. response = service_response
  201. if 'ResponseMetadata' in response:
  202. response = copy.copy(service_response)
  203. del response['ResponseMetadata']
  204. if output_shape is not None:
  205. validate_parameters(response, output_shape)
  206. elif response:
  207. # If the output shape is None, that means the response should be
  208. # empty apart from ResponseMetadata
  209. raise ParamValidationError(
  210. report=(
  211. "Service response should only contain ResponseMetadata."))