stub.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. # Copyright 2016 Amazon.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://aws.amazon.com/apache2.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 pprint import pformat
  16. from botocore.validate import validate_parameters
  17. from botocore.exceptions import ParamValidationError, \
  18. StubResponseError, StubAssertionError, UnStubbedResponseError
  19. from botocore.awsrequest import AWSResponse
  20. class _ANY(object):
  21. """
  22. A helper object that compares equal to everything. Copied from
  23. unittest.mock
  24. """
  25. def __eq__(self, other):
  26. return True
  27. def __ne__(self, other):
  28. return False
  29. def __repr__(self):
  30. return '<ANY>'
  31. ANY = _ANY()
  32. class Stubber(object):
  33. """
  34. This class will allow you to stub out requests so you don't have to hit
  35. an endpoint to write tests. Responses are returned first in, first out.
  36. If operations are called out of order, or are called with no remaining
  37. queued responses, an error will be raised.
  38. **Example:**
  39. ::
  40. import datetime
  41. import botocore.session
  42. from botocore.stub import Stubber
  43. s3 = botocore.session.get_session().create_client('s3')
  44. stubber = Stubber(s3)
  45. response = {
  46. 'IsTruncated': False,
  47. 'Name': 'test-bucket',
  48. 'MaxKeys': 1000, 'Prefix': '',
  49. 'Contents': [{
  50. 'Key': 'test.txt',
  51. 'ETag': '"abc123"',
  52. 'StorageClass': 'STANDARD',
  53. 'LastModified': datetime.datetime(2016, 1, 20, 22, 9),
  54. 'Owner': {'ID': 'abc123', 'DisplayName': 'myname'},
  55. 'Size': 14814
  56. }],
  57. 'EncodingType': 'url',
  58. 'ResponseMetadata': {
  59. 'RequestId': 'abc123',
  60. 'HTTPStatusCode': 200,
  61. 'HostId': 'abc123'
  62. },
  63. 'Marker': ''
  64. }
  65. expected_params = {'Bucket': 'test-bucket'}
  66. stubber.add_response('list_objects', response, expected_params)
  67. stubber.activate()
  68. service_response = s3.list_objects(Bucket='test-bucket')
  69. assert service_response == response
  70. This class can also be called as a context manager, which will handle
  71. activation / deactivation for you.
  72. **Example:**
  73. ::
  74. import datetime
  75. import botocore.session
  76. from botocore.stub import Stubber
  77. s3 = botocore.session.get_session().create_client('s3')
  78. response = {
  79. "Owner": {
  80. "ID": "foo",
  81. "DisplayName": "bar"
  82. },
  83. "Buckets": [{
  84. "CreationDate": datetime.datetime(2016, 1, 20, 22, 9),
  85. "Name": "baz"
  86. }]
  87. }
  88. with Stubber(s3) as stubber:
  89. stubber.add_response('list_buckets', response, {})
  90. service_response = s3.list_buckets()
  91. assert service_response == response
  92. If you have an input parameter that is a randomly generated value, or you
  93. otherwise don't care about its value, you can use ``stub.ANY`` to ignore
  94. it in validation.
  95. **Example:**
  96. ::
  97. import datetime
  98. import botocore.session
  99. from botocore.stub import Stubber, ANY
  100. s3 = botocore.session.get_session().create_client('s3')
  101. stubber = Stubber(s3)
  102. response = {
  103. 'IsTruncated': False,
  104. 'Name': 'test-bucket',
  105. 'MaxKeys': 1000, 'Prefix': '',
  106. 'Contents': [{
  107. 'Key': 'test.txt',
  108. 'ETag': '"abc123"',
  109. 'StorageClass': 'STANDARD',
  110. 'LastModified': datetime.datetime(2016, 1, 20, 22, 9),
  111. 'Owner': {'ID': 'abc123', 'DisplayName': 'myname'},
  112. 'Size': 14814
  113. }],
  114. 'EncodingType': 'url',
  115. 'ResponseMetadata': {
  116. 'RequestId': 'abc123',
  117. 'HTTPStatusCode': 200,
  118. 'HostId': 'abc123'
  119. },
  120. 'Marker': ''
  121. }
  122. expected_params = {'Bucket': ANY}
  123. stubber.add_response('list_objects', response, expected_params)
  124. with stubber:
  125. service_response = s3.list_objects(Bucket='test-bucket')
  126. assert service_response == response
  127. """
  128. def __init__(self, client):
  129. """
  130. :param client: The client to add your stubs to.
  131. """
  132. self.client = client
  133. self._event_id = 'boto_stubber'
  134. self._expected_params_event_id = 'boto_stubber_expected_params'
  135. self._queue = deque()
  136. def __enter__(self):
  137. self.activate()
  138. return self
  139. def __exit__(self, exception_type, exception_value, traceback):
  140. self.deactivate()
  141. def activate(self):
  142. """
  143. Activates the stubber on the client
  144. """
  145. self.client.meta.events.register_first(
  146. 'before-parameter-build.*.*',
  147. self._assert_expected_params,
  148. unique_id=self._expected_params_event_id)
  149. self.client.meta.events.register(
  150. 'before-call.*.*',
  151. self._get_response_handler,
  152. unique_id=self._event_id)
  153. def deactivate(self):
  154. """
  155. Deactivates the stubber on the client
  156. """
  157. self.client.meta.events.unregister(
  158. 'before-parameter-build.*.*',
  159. self._assert_expected_params,
  160. unique_id=self._expected_params_event_id)
  161. self.client.meta.events.unregister(
  162. 'before-call.*.*',
  163. self._get_response_handler,
  164. unique_id=self._event_id)
  165. def add_response(self, method, service_response, expected_params=None):
  166. """
  167. Adds a service response to the response queue. This will be validated
  168. against the service model to ensure correctness. It should be noted,
  169. however, that while missing attributes are often considered correct,
  170. your code may not function properly if you leave them out. Therefore
  171. you should always fill in every value you see in a typical response for
  172. your particular request.
  173. :param method: The name of the client method to stub.
  174. :type method: str
  175. :param service_response: A dict response stub. Provided parameters will
  176. be validated against the service model.
  177. :type service_response: dict
  178. :param expected_params: A dictionary of the expected parameters to
  179. be called for the provided service response. The parameters match
  180. the names of keyword arguments passed to that client call. If
  181. any of the parameters differ a ``StubResponseError`` is thrown.
  182. You can use stub.ANY to indicate a particular parameter to ignore
  183. in validation. stub.ANY is only valid for top level params.
  184. """
  185. self._add_response(method, service_response, expected_params)
  186. def _add_response(self, method, service_response, expected_params):
  187. if not hasattr(self.client, method):
  188. raise ValueError(
  189. "Client %s does not have method: %s"
  190. % (self.client.meta.service_model.service_name, method))
  191. # Create a successful http response
  192. http_response = AWSResponse(None, 200, {}, None)
  193. operation_name = self.client.meta.method_to_api_mapping.get(method)
  194. self._validate_response(operation_name, service_response)
  195. # Add the service_response to the queue for returning responses
  196. response = {
  197. 'operation_name': operation_name,
  198. 'response': (http_response, service_response),
  199. 'expected_params': expected_params
  200. }
  201. self._queue.append(response)
  202. def add_client_error(self, method, service_error_code='',
  203. service_message='', http_status_code=400,
  204. service_error_meta=None, expected_params=None,
  205. response_meta=None):
  206. """
  207. Adds a ``ClientError`` to the response queue.
  208. :param method: The name of the service method to return the error on.
  209. :type method: str
  210. :param service_error_code: The service error code to return,
  211. e.g. ``NoSuchBucket``
  212. :type service_error_code: str
  213. :param service_message: The service message to return, e.g.
  214. 'The specified bucket does not exist.'
  215. :type service_message: str
  216. :param http_status_code: The HTTP status code to return, e.g. 404, etc
  217. :type http_status_code: int
  218. :param service_error_meta: Additional keys to be added to the
  219. service Error
  220. :type service_error_meta: dict
  221. :param expected_params: A dictionary of the expected parameters to
  222. be called for the provided service response. The parameters match
  223. the names of keyword arguments passed to that client call. If
  224. any of the parameters differ a ``StubResponseError`` is thrown.
  225. You can use stub.ANY to indicate a particular parameter to ignore
  226. in validation.
  227. :param response_meta: Additional keys to be added to the
  228. response's ResponseMetadata
  229. :type response_meta: dict
  230. """
  231. http_response = AWSResponse(None, http_status_code, {}, None)
  232. # We don't look to the model to build this because the caller would
  233. # need to know the details of what the HTTP body would need to
  234. # look like.
  235. parsed_response = {
  236. 'ResponseMetadata': {'HTTPStatusCode': http_status_code},
  237. 'Error': {
  238. 'Message': service_message,
  239. 'Code': service_error_code
  240. }
  241. }
  242. if service_error_meta is not None:
  243. parsed_response['Error'].update(service_error_meta)
  244. if response_meta is not None:
  245. parsed_response['ResponseMetadata'].update(response_meta)
  246. operation_name = self.client.meta.method_to_api_mapping.get(method)
  247. # Note that we do not allow for expected_params while
  248. # adding errors into the queue yet.
  249. response = {
  250. 'operation_name': operation_name,
  251. 'response': (http_response, parsed_response),
  252. 'expected_params': expected_params,
  253. }
  254. self._queue.append(response)
  255. def assert_no_pending_responses(self):
  256. """
  257. Asserts that all expected calls were made.
  258. """
  259. remaining = len(self._queue)
  260. if remaining != 0:
  261. raise AssertionError(
  262. "%d responses remaining in queue." % remaining)
  263. def _assert_expected_call_order(self, model, params):
  264. if not self._queue:
  265. raise UnStubbedResponseError(
  266. operation_name=model.name,
  267. reason=(
  268. 'Unexpected API Call: A call was made but no additional calls expected. '
  269. 'Either the API Call was not stubbed or it was called multiple times.'
  270. )
  271. )
  272. name = self._queue[0]['operation_name']
  273. if name != model.name:
  274. raise StubResponseError(
  275. operation_name=model.name,
  276. reason='Operation mismatch: found response for %s.' % name)
  277. def _get_response_handler(self, model, params, context, **kwargs):
  278. self._assert_expected_call_order(model, params)
  279. # Pop off the entire response once everything has been validated
  280. return self._queue.popleft()['response']
  281. def _assert_expected_params(self, model, params, context, **kwargs):
  282. if self._should_not_stub(context):
  283. return
  284. self._assert_expected_call_order(model, params)
  285. expected_params = self._queue[0]['expected_params']
  286. if expected_params is None:
  287. return
  288. # Validate the parameters are equal
  289. for param, value in expected_params.items():
  290. if param not in params or expected_params[param] != params[param]:
  291. raise StubAssertionError(
  292. operation_name=model.name,
  293. reason='Expected parameters:\n%s,\nbut received:\n%s' % (
  294. pformat(expected_params), pformat(params)))
  295. # Ensure there are no extra params hanging around
  296. if sorted(expected_params.keys()) != sorted(params.keys()):
  297. raise StubAssertionError(
  298. operation_name=model.name,
  299. reason='Expected parameters:\n%s,\nbut received:\n%s' % (
  300. pformat(expected_params), pformat(params)))
  301. def _should_not_stub(self, context):
  302. # Do not include presign requests when processing stubbed client calls
  303. # as a presign request will never have an HTTP request sent over the
  304. # wire for it and therefore not receive a response back.
  305. if context and context.get('is_presign_request'):
  306. return True
  307. def _validate_response(self, operation_name, service_response):
  308. service_model = self.client.meta.service_model
  309. operation_model = service_model.operation_model(operation_name)
  310. output_shape = operation_model.output_shape
  311. # Remove ResponseMetadata so that the validator doesn't attempt to
  312. # perform validation on it.
  313. response = service_response
  314. if 'ResponseMetadata' in response:
  315. response = copy.copy(service_response)
  316. del response['ResponseMetadata']
  317. if output_shape is not None:
  318. validate_parameters(response, output_shape)
  319. elif response:
  320. # If the output shape is None, that means the response should be
  321. # empty apart from ResponseMetadata
  322. raise ParamValidationError(
  323. report=(
  324. "Service response should only contain ResponseMetadata."))