We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Feature request:  Add ability to ignore params in stubber
It would be nice if the stubber had a solution for being able to ignore randomly generated values in the input.  For example:
- idempotency tokens
- statement ids

And really anything that typically is a random value.  

There's a few ways I can think of to accomplish this.  In `mock`, you can use `mock.ANY` to indicate that you don't care about the value.   In the CLI we have an `ignore_params` for `assert_params_for_cmd`, though this only works for top level params (which typically is sufficient).


--- END ISSUE ---

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

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/botocore/stub.py b/botocore/stub.py
--- a/botocore/stub.py
+++ b/botocore/stub.py
@@ -20,6 +20,9 @@
 from botocore.vendored.requests.models import Response
 
 
+ANY = object()
+
+
 class Stubber(object):
     """
     This class will allow you to stub out requests so you don't have to hit
@@ -96,6 +99,50 @@
             service_response = s3.list_buckets()
 
         assert service_response == response
+
+
+    If you have an input paramter that is a randomly generated value, or you
+    otherwise don't care about its value, you can use stub.ANY to ignore it in
+    validation.
+
+    **Example:**
+    ::
+        import datetime
+        import botocore.session
+        from botocore.stub import Stubber, ANY
+
+
+        s3 = botocore.session.get_session().create_client('s3')
+        stubber = Stubber(s3)
+
+        response = {
+            'IsTruncated': False,
+            'Name': 'test-bucket',
+            'MaxKeys': 1000, 'Prefix': '',
+            'Contents': [{
+                'Key': 'test.txt',
+                'ETag': '"abc123"',
+                'StorageClass': 'STANDARD',
+                'LastModified': datetime.datetime(2016, 1, 20, 22, 9),
+                'Owner': {'ID': 'abc123', 'DisplayName': 'myname'},
+                'Size': 14814
+            }],
+            'EncodingType': 'url',
+            'ResponseMetadata': {
+                'RequestId': 'abc123',
+                'HTTPStatusCode': 200,
+                'HostId': 'abc123'
+            },
+            'Marker': ''
+        }
+
+        expected_params = {'Bucket': ANY}
+        stubber.add_response('list_objects', response, expected_params)
+
+        with stubber:
+            service_response = s3.list_objects(Bucket='test-bucket')
+
+        assert service_response == response
     """
     def __init__(self, client):
         """
@@ -159,6 +206,8 @@
             be called for the provided service response. The parameters match
             the names of keyword arguments passed to that client call. If
             any of the parameters differ a ``StubResponseError`` is thrown.
+            You can use stub.ANY to indicate a particular parameter to ignore
+            in validation. stub.ANY is only valid for top level params.
         """
         self._add_response(method, service_response, expected_params)
 
@@ -265,7 +314,22 @@
     def _assert_expected_params(self, model, params, **kwargs):
         self._assert_expected_call_order(model, params)
         expected_params = self._queue[0]['expected_params']
-        if expected_params is not None and params != expected_params:
+        if expected_params is None:
+            return
+
+        # Validate the parameters are equal
+        for param, value in expected_params.items():
+            if value is ANY:
+                continue
+            elif param not in params or \
+                    expected_params[param] != params[param]:
+                raise StubAssertionError(
+                    operation_name=model.name,
+                    reason='Expected parameters:\n%s,\nbut received:\n%s' % (
+                        pformat(expected_params), pformat(params)))
+
+        # Ensure there are no extra params hanging around
+        if expected_params.keys() != params.keys():
             raise StubAssertionError(
                 operation_name=model.name,
                 reason='Expected parameters:\n%s,\nbut received:\n%s' % (

{"golden_diff": "diff --git a/botocore/stub.py b/botocore/stub.py\n--- a/botocore/stub.py\n+++ b/botocore/stub.py\n@@ -20,6 +20,9 @@\n from botocore.vendored.requests.models import Response\n \n \n+ANY = object()\n+\n+\n class Stubber(object):\n     \"\"\"\n     This class will allow you to stub out requests so you don't have to hit\n@@ -96,6 +99,50 @@\n             service_response = s3.list_buckets()\n \n         assert service_response == response\n+\n+\n+    If you have an input paramter that is a randomly generated value, or you\n+    otherwise don't care about its value, you can use stub.ANY to ignore it in\n+    validation.\n+\n+    **Example:**\n+    ::\n+        import datetime\n+        import botocore.session\n+        from botocore.stub import Stubber, ANY\n+\n+\n+        s3 = botocore.session.get_session().create_client('s3')\n+        stubber = Stubber(s3)\n+\n+        response = {\n+            'IsTruncated': False,\n+            'Name': 'test-bucket',\n+            'MaxKeys': 1000, 'Prefix': '',\n+            'Contents': [{\n+                'Key': 'test.txt',\n+                'ETag': '\"abc123\"',\n+                'StorageClass': 'STANDARD',\n+                'LastModified': datetime.datetime(2016, 1, 20, 22, 9),\n+                'Owner': {'ID': 'abc123', 'DisplayName': 'myname'},\n+                'Size': 14814\n+            }],\n+            'EncodingType': 'url',\n+            'ResponseMetadata': {\n+                'RequestId': 'abc123',\n+                'HTTPStatusCode': 200,\n+                'HostId': 'abc123'\n+            },\n+            'Marker': ''\n+        }\n+\n+        expected_params = {'Bucket': ANY}\n+        stubber.add_response('list_objects', response, expected_params)\n+\n+        with stubber:\n+            service_response = s3.list_objects(Bucket='test-bucket')\n+\n+        assert service_response == response\n     \"\"\"\n     def __init__(self, client):\n         \"\"\"\n@@ -159,6 +206,8 @@\n             be called for the provided service response. The parameters match\n             the names of keyword arguments passed to that client call. If\n             any of the parameters differ a ``StubResponseError`` is thrown.\n+            You can use stub.ANY to indicate a particular parameter to ignore\n+            in validation. stub.ANY is only valid for top level params.\n         \"\"\"\n         self._add_response(method, service_response, expected_params)\n \n@@ -265,7 +314,22 @@\n     def _assert_expected_params(self, model, params, **kwargs):\n         self._assert_expected_call_order(model, params)\n         expected_params = self._queue[0]['expected_params']\n-        if expected_params is not None and params != expected_params:\n+        if expected_params is None:\n+            return\n+\n+        # Validate the parameters are equal\n+        for param, value in expected_params.items():\n+            if value is ANY:\n+                continue\n+            elif param not in params or \\\n+                    expected_params[param] != params[param]:\n+                raise StubAssertionError(\n+                    operation_name=model.name,\n+                    reason='Expected parameters:\\n%s,\\nbut received:\\n%s' % (\n+                        pformat(expected_params), pformat(params)))\n+\n+        # Ensure there are no extra params hanging around\n+        if expected_params.keys() != params.keys():\n             raise StubAssertionError(\n                 operation_name=model.name,\n                 reason='Expected parameters:\\n%s,\\nbut received:\\n%s' % (\n", "issue": "Feature request:  Add ability to ignore params in stubber\nIt would be nice if the stubber had a solution for being able to ignore randomly generated values in the input.  For example:\n- idempotency tokens\n- statement ids\n\nAnd really anything that typically is a random value.  \n\nThere's a few ways I can think of to accomplish this.  In `mock`, you can use `mock.ANY` to indicate that you don't care about the value.   In the CLI we have an `ignore_params` for `assert_params_for_cmd`, though this only works for top level params (which typically is sufficient).\n\n", "before_files": [{"content": "# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\nimport copy\nfrom collections import deque\nfrom pprint import pformat\n\nfrom botocore.validate import validate_parameters\nfrom botocore.exceptions import ParamValidationError, \\\n    StubResponseError, StubAssertionError\nfrom botocore.vendored.requests.models import Response\n\n\nclass Stubber(object):\n    \"\"\"\n    This class will allow you to stub out requests so you don't have to hit\n    an endpoint to write tests. Responses are returned first in, first out.\n    If operations are called out of order, or are called with no remaining\n    queued responses, an error will be raised.\n\n    **Example:**\n    ::\n        import datetime\n        import botocore.session\n        from botocore.stub import Stubber\n\n\n        s3 = botocore.session.get_session().create_client('s3')\n        stubber = Stubber(s3)\n\n        response = {\n            'IsTruncated': False,\n            'Name': 'test-bucket',\n            'MaxKeys': 1000, 'Prefix': '',\n            'Contents': [{\n                'Key': 'test.txt',\n                'ETag': '\"abc123\"',\n                'StorageClass': 'STANDARD',\n                'LastModified': datetime.datetime(2016, 1, 20, 22, 9),\n                'Owner': {'ID': 'abc123', 'DisplayName': 'myname'},\n                'Size': 14814\n            }],\n            'EncodingType': 'url',\n            'ResponseMetadata': {\n                'RequestId': 'abc123',\n                'HTTPStatusCode': 200,\n                'HostId': 'abc123'\n            },\n            'Marker': ''\n        }\n\n        expected_params = {'Bucket': 'test-bucket'}\n\n        stubber.add_response('list_objects', response, expected_params)\n        stubber.activate()\n\n        service_response = s3.list_objects(Bucket='test-bucket')\n        assert service_response == response\n\n\n    This class can also be called as a context manager, which will handle\n    activation / deactivation for you.\n\n    **Example:**\n    ::\n        import datetime\n        import botocore.session\n        from botocore.stub import Stubber\n\n\n        s3 = botocore.session.get_session().create_client('s3')\n\n        response = {\n            \"Owner\": {\n                \"ID\": \"foo\",\n                \"DisplayName\": \"bar\"\n            },\n            \"Buckets\": [{\n                \"CreationDate\": datetime.datetime(2016, 1, 20, 22, 9),\n                \"Name\": \"baz\"\n            }]\n        }\n\n\n        with Stubber(s3) as stubber:\n            stubber.add_response('list_buckets', response, {})\n            service_response = s3.list_buckets()\n\n        assert service_response == response\n    \"\"\"\n    def __init__(self, client):\n        \"\"\"\n        :param client: The client to add your stubs to.\n        \"\"\"\n        self.client = client\n        self._event_id = 'boto_stubber'\n        self._expected_params_event_id = 'boto_stubber_expected_params'\n        self._queue = deque()\n\n    def __enter__(self):\n        self.activate()\n        return self\n\n    def __exit__(self, exception_type, exception_value, traceback):\n        self.deactivate()\n\n    def activate(self):\n        \"\"\"\n        Activates the stubber on the client\n        \"\"\"\n        self.client.meta.events.register_first(\n            'before-parameter-build.*.*',\n            self._assert_expected_params,\n            unique_id=self._expected_params_event_id)\n        self.client.meta.events.register(\n            'before-call.*.*',\n            self._get_response_handler,\n            unique_id=self._event_id)\n\n    def deactivate(self):\n        \"\"\"\n        Deactivates the stubber on the client\n        \"\"\"\n        self.client.meta.events.unregister(\n            'before-parameter-build.*.*',\n            self._assert_expected_params,\n            unique_id=self._expected_params_event_id)\n        self.client.meta.events.unregister(\n            'before-call.*.*',\n            self._get_response_handler,\n            unique_id=self._event_id)\n\n    def add_response(self, method, service_response, expected_params=None):\n        \"\"\"\n        Adds a service response to the response queue. This will be validated\n        against the service model to ensure correctness. It should be noted,\n        however, that while missing attributes are often considered correct,\n        your code may not function properly if you leave them out. Therefore\n        you should always fill in every value you see in a typical response for\n        your particular request.\n\n        :param method: The name of the client method to stub.\n        :type method: str\n\n        :param service_response: A dict response stub. Provided parameters will\n            be validated against the service model.\n        :type service_response: dict\n\n        :param expected_params: A dictionary of the expected parameters to\n            be called for the provided service response. The parameters match\n            the names of keyword arguments passed to that client call. If\n            any of the parameters differ a ``StubResponseError`` is thrown.\n        \"\"\"\n        self._add_response(method, service_response, expected_params)\n\n    def _add_response(self, method, service_response, expected_params):\n        if not hasattr(self.client, method):\n            raise ValueError(\n                \"Client %s does not have method: %s\"\n                % (self.client.meta.service_model.service_name, method))\n\n        # Create a successful http response\n        http_response = Response()\n        http_response.status_code = 200\n        http_response.reason = 'OK'\n\n        operation_name = self.client.meta.method_to_api_mapping.get(method)\n        self._validate_response(operation_name, service_response)\n\n        # Add the service_response to the queue for returning responses\n        response = {\n            'operation_name': operation_name,\n            'response': (http_response, service_response),\n            'expected_params': expected_params\n        }\n        self._queue.append(response)\n\n    def add_client_error(self, method, service_error_code='',\n                         service_message='', http_status_code=400,\n                         service_error_meta=None):\n        \"\"\"\n        Adds a ``ClientError`` to the response queue.\n\n        :param method: The name of the service method to return the error on.\n        :type method: str\n\n        :param service_error_code: The service error code to return,\n                                   e.g. ``NoSuchBucket``\n        :type service_error_code: str\n\n        :param service_message: The service message to return, e.g.\n                        'The specified bucket does not exist.'\n        :type service_message: str\n\n        :param http_status_code: The HTTP status code to return, e.g. 404, etc\n        :type http_status_code: int\n\n        :param service_error_meta: Additional keys to be added to the\n            service Error\n        :type service_error_meta: dict\n        \"\"\"\n        http_response = Response()\n        http_response.status_code = http_status_code\n\n        # We don't look to the model to build this because the caller would\n        # need to know the details of what the HTTP body would need to\n        # look like.\n        parsed_response = {\n            'ResponseMetadata': {'HTTPStatusCode': http_status_code},\n            'Error': {\n                'Message': service_message,\n                'Code': service_error_code\n            }\n        }\n\n        if service_error_meta is not None:\n            parsed_response['Error'].update(service_error_meta)\n\n        operation_name = self.client.meta.method_to_api_mapping.get(method)\n        # Note that we do not allow for expected_params while\n        # adding errors into the queue yet.\n        response = {\n            'operation_name': operation_name,\n            'response': (http_response, parsed_response),\n            'expected_params': None\n        }\n        self._queue.append(response)\n\n    def assert_no_pending_responses(self):\n        \"\"\"\n        Asserts that all expected calls were made.\n        \"\"\"\n        remaining = len(self._queue)\n        if remaining != 0:\n            raise AssertionError(\n                \"%d responses remaining in queue.\" % remaining)\n\n    def _assert_expected_call_order(self, model, params):\n        if not self._queue:\n            raise StubResponseError(\n                operation_name=model.name,\n                reason=('Unexpected API Call: called with parameters:\\n%s' %\n                        pformat(params)))\n\n        name = self._queue[0]['operation_name']\n        if name != model.name:\n            raise StubResponseError(\n                operation_name=model.name,\n                reason='Operation mismatch: found response for %s.' % name)\n\n    def _get_response_handler(self, model, params, **kwargs):\n        self._assert_expected_call_order(model, params)\n        # Pop off the entire response once everything has been validated\n        return self._queue.popleft()['response']\n\n    def _assert_expected_params(self, model, params, **kwargs):\n        self._assert_expected_call_order(model, params)\n        expected_params = self._queue[0]['expected_params']\n        if expected_params is not None and params != expected_params:\n            raise StubAssertionError(\n                operation_name=model.name,\n                reason='Expected parameters:\\n%s,\\nbut received:\\n%s' % (\n                    pformat(expected_params), pformat(params)))\n\n    def _validate_response(self, operation_name, service_response):\n        service_model = self.client.meta.service_model\n        operation_model = service_model.operation_model(operation_name)\n        output_shape = operation_model.output_shape\n\n        # Remove ResponseMetadata so that the validator doesn't attempt to\n        # perform validation on it.\n        response = service_response\n        if 'ResponseMetadata' in response:\n            response = copy.copy(service_response)\n            del response['ResponseMetadata']\n\n        if output_shape is not None:\n            validate_parameters(response, output_shape)\n        elif response:\n            # If the output shape is None, that means the response should be\n            # empty apart from ResponseMetadata\n            raise ParamValidationError(\n                report=(\n                    \"Service response should only contain ResponseMetadata.\"))\n", "path": "botocore/stub.py"}], "after_files": [{"content": "# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\nimport copy\nfrom collections import deque\nfrom pprint import pformat\n\nfrom botocore.validate import validate_parameters\nfrom botocore.exceptions import ParamValidationError, \\\n    StubResponseError, StubAssertionError\nfrom botocore.vendored.requests.models import Response\n\n\nANY = object()\n\n\nclass Stubber(object):\n    \"\"\"\n    This class will allow you to stub out requests so you don't have to hit\n    an endpoint to write tests. Responses are returned first in, first out.\n    If operations are called out of order, or are called with no remaining\n    queued responses, an error will be raised.\n\n    **Example:**\n    ::\n        import datetime\n        import botocore.session\n        from botocore.stub import Stubber\n\n\n        s3 = botocore.session.get_session().create_client('s3')\n        stubber = Stubber(s3)\n\n        response = {\n            'IsTruncated': False,\n            'Name': 'test-bucket',\n            'MaxKeys': 1000, 'Prefix': '',\n            'Contents': [{\n                'Key': 'test.txt',\n                'ETag': '\"abc123\"',\n                'StorageClass': 'STANDARD',\n                'LastModified': datetime.datetime(2016, 1, 20, 22, 9),\n                'Owner': {'ID': 'abc123', 'DisplayName': 'myname'},\n                'Size': 14814\n            }],\n            'EncodingType': 'url',\n            'ResponseMetadata': {\n                'RequestId': 'abc123',\n                'HTTPStatusCode': 200,\n                'HostId': 'abc123'\n            },\n            'Marker': ''\n        }\n\n        expected_params = {'Bucket': 'test-bucket'}\n\n        stubber.add_response('list_objects', response, expected_params)\n        stubber.activate()\n\n        service_response = s3.list_objects(Bucket='test-bucket')\n        assert service_response == response\n\n\n    This class can also be called as a context manager, which will handle\n    activation / deactivation for you.\n\n    **Example:**\n    ::\n        import datetime\n        import botocore.session\n        from botocore.stub import Stubber\n\n\n        s3 = botocore.session.get_session().create_client('s3')\n\n        response = {\n            \"Owner\": {\n                \"ID\": \"foo\",\n                \"DisplayName\": \"bar\"\n            },\n            \"Buckets\": [{\n                \"CreationDate\": datetime.datetime(2016, 1, 20, 22, 9),\n                \"Name\": \"baz\"\n            }]\n        }\n\n\n        with Stubber(s3) as stubber:\n            stubber.add_response('list_buckets', response, {})\n            service_response = s3.list_buckets()\n\n        assert service_response == response\n\n\n    If you have an input paramter that is a randomly generated value, or you\n    otherwise don't care about its value, you can use stub.ANY to ignore it in\n    validation.\n\n    **Example:**\n    ::\n        import datetime\n        import botocore.session\n        from botocore.stub import Stubber, ANY\n\n\n        s3 = botocore.session.get_session().create_client('s3')\n        stubber = Stubber(s3)\n\n        response = {\n            'IsTruncated': False,\n            'Name': 'test-bucket',\n            'MaxKeys': 1000, 'Prefix': '',\n            'Contents': [{\n                'Key': 'test.txt',\n                'ETag': '\"abc123\"',\n                'StorageClass': 'STANDARD',\n                'LastModified': datetime.datetime(2016, 1, 20, 22, 9),\n                'Owner': {'ID': 'abc123', 'DisplayName': 'myname'},\n                'Size': 14814\n            }],\n            'EncodingType': 'url',\n            'ResponseMetadata': {\n                'RequestId': 'abc123',\n                'HTTPStatusCode': 200,\n                'HostId': 'abc123'\n            },\n            'Marker': ''\n        }\n\n        expected_params = {'Bucket': ANY}\n        stubber.add_response('list_objects', response, expected_params)\n\n        with stubber:\n            service_response = s3.list_objects(Bucket='test-bucket')\n\n        assert service_response == response\n    \"\"\"\n    def __init__(self, client):\n        \"\"\"\n        :param client: The client to add your stubs to.\n        \"\"\"\n        self.client = client\n        self._event_id = 'boto_stubber'\n        self._expected_params_event_id = 'boto_stubber_expected_params'\n        self._queue = deque()\n\n    def __enter__(self):\n        self.activate()\n        return self\n\n    def __exit__(self, exception_type, exception_value, traceback):\n        self.deactivate()\n\n    def activate(self):\n        \"\"\"\n        Activates the stubber on the client\n        \"\"\"\n        self.client.meta.events.register_first(\n            'before-parameter-build.*.*',\n            self._assert_expected_params,\n            unique_id=self._expected_params_event_id)\n        self.client.meta.events.register(\n            'before-call.*.*',\n            self._get_response_handler,\n            unique_id=self._event_id)\n\n    def deactivate(self):\n        \"\"\"\n        Deactivates the stubber on the client\n        \"\"\"\n        self.client.meta.events.unregister(\n            'before-parameter-build.*.*',\n            self._assert_expected_params,\n            unique_id=self._expected_params_event_id)\n        self.client.meta.events.unregister(\n            'before-call.*.*',\n            self._get_response_handler,\n            unique_id=self._event_id)\n\n    def add_response(self, method, service_response, expected_params=None):\n        \"\"\"\n        Adds a service response to the response queue. This will be validated\n        against the service model to ensure correctness. It should be noted,\n        however, that while missing attributes are often considered correct,\n        your code may not function properly if you leave them out. Therefore\n        you should always fill in every value you see in a typical response for\n        your particular request.\n\n        :param method: The name of the client method to stub.\n        :type method: str\n\n        :param service_response: A dict response stub. Provided parameters will\n            be validated against the service model.\n        :type service_response: dict\n\n        :param expected_params: A dictionary of the expected parameters to\n            be called for the provided service response. The parameters match\n            the names of keyword arguments passed to that client call. If\n            any of the parameters differ a ``StubResponseError`` is thrown.\n            You can use stub.ANY to indicate a particular parameter to ignore\n            in validation. stub.ANY is only valid for top level params.\n        \"\"\"\n        self._add_response(method, service_response, expected_params)\n\n    def _add_response(self, method, service_response, expected_params):\n        if not hasattr(self.client, method):\n            raise ValueError(\n                \"Client %s does not have method: %s\"\n                % (self.client.meta.service_model.service_name, method))\n\n        # Create a successful http response\n        http_response = Response()\n        http_response.status_code = 200\n        http_response.reason = 'OK'\n\n        operation_name = self.client.meta.method_to_api_mapping.get(method)\n        self._validate_response(operation_name, service_response)\n\n        # Add the service_response to the queue for returning responses\n        response = {\n            'operation_name': operation_name,\n            'response': (http_response, service_response),\n            'expected_params': expected_params\n        }\n        self._queue.append(response)\n\n    def add_client_error(self, method, service_error_code='',\n                         service_message='', http_status_code=400,\n                         service_error_meta=None):\n        \"\"\"\n        Adds a ``ClientError`` to the response queue.\n\n        :param method: The name of the service method to return the error on.\n        :type method: str\n\n        :param service_error_code: The service error code to return,\n                                   e.g. ``NoSuchBucket``\n        :type service_error_code: str\n\n        :param service_message: The service message to return, e.g.\n                        'The specified bucket does not exist.'\n        :type service_message: str\n\n        :param http_status_code: The HTTP status code to return, e.g. 404, etc\n        :type http_status_code: int\n\n        :param service_error_meta: Additional keys to be added to the\n            service Error\n        :type service_error_meta: dict\n        \"\"\"\n        http_response = Response()\n        http_response.status_code = http_status_code\n\n        # We don't look to the model to build this because the caller would\n        # need to know the details of what the HTTP body would need to\n        # look like.\n        parsed_response = {\n            'ResponseMetadata': {'HTTPStatusCode': http_status_code},\n            'Error': {\n                'Message': service_message,\n                'Code': service_error_code\n            }\n        }\n\n        if service_error_meta is not None:\n            parsed_response['Error'].update(service_error_meta)\n\n        operation_name = self.client.meta.method_to_api_mapping.get(method)\n        # Note that we do not allow for expected_params while\n        # adding errors into the queue yet.\n        response = {\n            'operation_name': operation_name,\n            'response': (http_response, parsed_response),\n            'expected_params': None\n        }\n        self._queue.append(response)\n\n    def assert_no_pending_responses(self):\n        \"\"\"\n        Asserts that all expected calls were made.\n        \"\"\"\n        remaining = len(self._queue)\n        if remaining != 0:\n            raise AssertionError(\n                \"%d responses remaining in queue.\" % remaining)\n\n    def _assert_expected_call_order(self, model, params):\n        if not self._queue:\n            raise StubResponseError(\n                operation_name=model.name,\n                reason=('Unexpected API Call: called with parameters:\\n%s' %\n                        pformat(params)))\n\n        name = self._queue[0]['operation_name']\n        if name != model.name:\n            raise StubResponseError(\n                operation_name=model.name,\n                reason='Operation mismatch: found response for %s.' % name)\n\n    def _get_response_handler(self, model, params, **kwargs):\n        self._assert_expected_call_order(model, params)\n        # Pop off the entire response once everything has been validated\n        return self._queue.popleft()['response']\n\n    def _assert_expected_params(self, model, params, **kwargs):\n        self._assert_expected_call_order(model, params)\n        expected_params = self._queue[0]['expected_params']\n        if expected_params is None:\n            return\n\n        # Validate the parameters are equal\n        for param, value in expected_params.items():\n            if value is ANY:\n                continue\n            elif param not in params or \\\n                    expected_params[param] != params[param]:\n                raise StubAssertionError(\n                    operation_name=model.name,\n                    reason='Expected parameters:\\n%s,\\nbut received:\\n%s' % (\n                        pformat(expected_params), pformat(params)))\n\n        # Ensure there are no extra params hanging around\n        if expected_params.keys() != params.keys():\n            raise StubAssertionError(\n                operation_name=model.name,\n                reason='Expected parameters:\\n%s,\\nbut received:\\n%s' % (\n                    pformat(expected_params), pformat(params)))\n\n    def _validate_response(self, operation_name, service_response):\n        service_model = self.client.meta.service_model\n        operation_model = service_model.operation_model(operation_name)\n        output_shape = operation_model.output_shape\n\n        # Remove ResponseMetadata so that the validator doesn't attempt to\n        # perform validation on it.\n        response = service_response\n        if 'ResponseMetadata' in response:\n            response = copy.copy(service_response)\n            del response['ResponseMetadata']\n\n        if output_shape is not None:\n            validate_parameters(response, output_shape)\n        elif response:\n            # If the output shape is None, that means the response should be\n            # empty apart from ResponseMetadata\n            raise ParamValidationError(\n                report=(\n                    \"Service response should only contain ResponseMetadata.\"))\n", "path": "botocore/stub.py"}]}