We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
can't use responses
with v1, since moto vendors in `responses`, it's impossible to use `responses` for mocking non-aws calls. example:

```py
with _responses.RequestsMock() as rsps:
    rsps.add(rsps.GET, 'http://foo')
    with moto.mock_sns():
       requests.get('http://foo')
```

this used to work on < v1, on v1 it raises a connection refused error because basically requests is patched twice by two different modules

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `moto/packages/responses/responses.py`
Content:
```
1 from __future__ import (
2     absolute_import, print_function, division, unicode_literals
3 )
4 
5 import inspect
6 import json as json_module
7 import re
8 import six
9 
10 from collections import namedtuple, Sequence, Sized
11 from functools import update_wrapper
12 from cookies import Cookies
13 from requests.utils import cookiejar_from_dict
14 from requests.exceptions import ConnectionError
15 from requests.sessions import REDIRECT_STATI
16 
17 try:
18     from requests.packages.urllib3.response import HTTPResponse
19 except ImportError:
20     from urllib3.response import HTTPResponse
21 
22 if six.PY2:
23     from urlparse import urlparse, parse_qsl
24 else:
25     from urllib.parse import urlparse, parse_qsl
26 
27 if six.PY2:
28     try:
29         from six import cStringIO as BufferIO
30     except ImportError:
31         from six import StringIO as BufferIO
32 else:
33     from io import BytesIO as BufferIO
34 
35 
36 Call = namedtuple('Call', ['request', 'response'])
37 
38 _wrapper_template = """\
39 def wrapper%(signature)s:
40     with responses:
41         return func%(funcargs)s
42 """
43 
44 
45 def _is_string(s):
46     return isinstance(s, (six.string_types, six.text_type))
47 
48 
49 def _is_redirect(response):
50     try:
51         # 2.0.0 <= requests <= 2.2
52         return response.is_redirect
53     except AttributeError:
54         # requests > 2.2
55         return (
56             # use request.sessions conditional
57             response.status_code in REDIRECT_STATI and
58             'location' in response.headers
59         )
60 
61 
62 def get_wrapped(func, wrapper_template, evaldict):
63     # Preserve the argspec for the wrapped function so that testing
64     # tools such as pytest can continue to use their fixture injection.
65     args, a, kw, defaults = inspect.getargspec(func)
66 
67     signature = inspect.formatargspec(args, a, kw, defaults)
68     is_bound_method = hasattr(func, '__self__')
69     if is_bound_method:
70         args = args[1:]     # Omit 'self'
71     callargs = inspect.formatargspec(args, a, kw, None)
72 
73     ctx = {'signature': signature, 'funcargs': callargs}
74     six.exec_(wrapper_template % ctx, evaldict)
75 
76     wrapper = evaldict['wrapper']
77 
78     update_wrapper(wrapper, func)
79     if is_bound_method:
80         wrapper = wrapper.__get__(func.__self__, type(func.__self__))
81     return wrapper
82 
83 
84 class CallList(Sequence, Sized):
85 
86     def __init__(self):
87         self._calls = []
88 
89     def __iter__(self):
90         return iter(self._calls)
91 
92     def __len__(self):
93         return len(self._calls)
94 
95     def __getitem__(self, idx):
96         return self._calls[idx]
97 
98     def add(self, request, response):
99         self._calls.append(Call(request, response))
100 
101     def reset(self):
102         self._calls = []
103 
104 
105 def _ensure_url_default_path(url, match_querystring):
106     if _is_string(url) and url.count('/') == 2:
107         if match_querystring:
108             return url.replace('?', '/?', 1)
109         else:
110             return url + '/'
111     return url
112 
113 
114 class RequestsMock(object):
115     DELETE = 'DELETE'
116     GET = 'GET'
117     HEAD = 'HEAD'
118     OPTIONS = 'OPTIONS'
119     PATCH = 'PATCH'
120     POST = 'POST'
121     PUT = 'PUT'
122 
123     def __init__(self, assert_all_requests_are_fired=True):
124         self._calls = CallList()
125         self.reset()
126         self.assert_all_requests_are_fired = assert_all_requests_are_fired
127 
128     def reset(self):
129         self._urls = []
130         self._calls.reset()
131 
132     def add(self, method, url, body='', match_querystring=False,
133             status=200, adding_headers=None, stream=False,
134             content_type='text/plain', json=None):
135 
136         # if we were passed a `json` argument,
137         # override the body and content_type
138         if json is not None:
139             body = json_module.dumps(json)
140             content_type = 'application/json'
141 
142         # ensure the url has a default path set if the url is a string
143         url = _ensure_url_default_path(url, match_querystring)
144 
145         # body must be bytes
146         if isinstance(body, six.text_type):
147             body = body.encode('utf-8')
148 
149         self._urls.append({
150             'url': url,
151             'method': method,
152             'body': body,
153             'content_type': content_type,
154             'match_querystring': match_querystring,
155             'status': status,
156             'adding_headers': adding_headers,
157             'stream': stream,
158         })
159 
160     def add_callback(self, method, url, callback, match_querystring=False,
161                      content_type='text/plain'):
162         # ensure the url has a default path set if the url is a string
163         # url = _ensure_url_default_path(url, match_querystring)
164 
165         self._urls.append({
166             'url': url,
167             'method': method,
168             'callback': callback,
169             'content_type': content_type,
170             'match_querystring': match_querystring,
171         })
172 
173     @property
174     def calls(self):
175         return self._calls
176 
177     def __enter__(self):
178         self.start()
179         return self
180 
181     def __exit__(self, type, value, traceback):
182         success = type is None
183         self.stop(allow_assert=success)
184         self.reset()
185         return success
186 
187     def activate(self, func):
188         evaldict = {'responses': self, 'func': func}
189         return get_wrapped(func, _wrapper_template, evaldict)
190 
191     def _find_match(self, request):
192         for match in self._urls:
193             if request.method != match['method']:
194                 continue
195 
196             if not self._has_url_match(match, request.url):
197                 continue
198 
199             break
200         else:
201             return None
202         if self.assert_all_requests_are_fired:
203             # for each found match remove the url from the stack
204             self._urls.remove(match)
205         return match
206 
207     def _has_url_match(self, match, request_url):
208         url = match['url']
209 
210         if not match['match_querystring']:
211             request_url = request_url.split('?', 1)[0]
212 
213         if _is_string(url):
214             if match['match_querystring']:
215                 return self._has_strict_url_match(url, request_url)
216             else:
217                 return url == request_url
218         elif isinstance(url, re._pattern_type) and url.match(request_url):
219             return True
220         else:
221             return False
222 
223     def _has_strict_url_match(self, url, other):
224         url_parsed = urlparse(url)
225         other_parsed = urlparse(other)
226 
227         if url_parsed[:3] != other_parsed[:3]:
228             return False
229 
230         url_qsl = sorted(parse_qsl(url_parsed.query))
231         other_qsl = sorted(parse_qsl(other_parsed.query))
232         return url_qsl == other_qsl
233 
234     def _on_request(self, adapter, request, **kwargs):
235         match = self._find_match(request)
236         # TODO(dcramer): find the correct class for this
237         if match is None:
238             error_msg = 'Connection refused: {0} {1}'.format(request.method,
239                                                              request.url)
240             response = ConnectionError(error_msg)
241             response.request = request
242 
243             self._calls.add(request, response)
244             raise response
245 
246         if 'body' in match and isinstance(match['body'], Exception):
247             self._calls.add(request, match['body'])
248             raise match['body']
249 
250         headers = {}
251         if match['content_type'] is not None:
252             headers['Content-Type'] = match['content_type']
253 
254         if 'callback' in match:  # use callback
255             status, r_headers, body = match['callback'](request)
256             if isinstance(body, six.text_type):
257                 body = body.encode('utf-8')
258             body = BufferIO(body)
259             headers.update(r_headers)
260 
261         elif 'body' in match:
262             if match['adding_headers']:
263                 headers.update(match['adding_headers'])
264             status = match['status']
265             body = BufferIO(match['body'])
266 
267         response = HTTPResponse(
268             status=status,
269             reason=six.moves.http_client.responses[status],
270             body=body,
271             headers=headers,
272             preload_content=False,
273             # Need to not decode_content to mimic requests
274             decode_content=False,
275         )
276 
277         response = adapter.build_response(request, response)
278         if not match.get('stream'):
279             response.content  # NOQA
280 
281         try:
282             resp_cookies = Cookies.from_request(response.headers['set-cookie'])
283             response.cookies = cookiejar_from_dict(dict(
284                 (v.name, v.value)
285                 for _, v
286                 in resp_cookies.items()
287             ))
288         except (KeyError, TypeError):
289             pass
290 
291         self._calls.add(request, response)
292 
293         return response
294 
295     def start(self):
296         try:
297             from unittest import mock
298         except ImportError:
299             import mock
300 
301         def unbound_on_send(adapter, request, *a, **kwargs):
302             return self._on_request(adapter, request, *a, **kwargs)
303         self._patcher1 = mock.patch('botocore.vendored.requests.adapters.HTTPAdapter.send',
304                                     unbound_on_send)
305         self._patcher1.start()
306         self._patcher2 = mock.patch('requests.adapters.HTTPAdapter.send',
307                                     unbound_on_send)
308         self._patcher2.start()
309 
310     def stop(self, allow_assert=True):
311         self._patcher1.stop()
312         self._patcher2.stop()
313         if allow_assert and self.assert_all_requests_are_fired and self._urls:
314             raise AssertionError(
315                 'Not all requests have been executed {0!r}'.format(
316                     [(url['method'], url['url']) for url in self._urls]))
317 
318 
319 # expose default mock namespace
320 mock = _default_mock = RequestsMock(assert_all_requests_are_fired=False)
321 __all__ = []
322 for __attr in (a for a in dir(_default_mock) if not a.startswith('_')):
323     __all__.append(__attr)
324     globals()[__attr] = getattr(_default_mock, __attr)
325
```
--- 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/moto/packages/responses/responses.py b/moto/packages/responses/responses.py
--- a/moto/packages/responses/responses.py
+++ b/moto/packages/responses/responses.py
@@ -10,6 +10,7 @@
 from collections import namedtuple, Sequence, Sized
 from functools import update_wrapper
 from cookies import Cookies
+from requests.adapters import HTTPAdapter
 from requests.utils import cookiejar_from_dict
 from requests.exceptions import ConnectionError
 from requests.sessions import REDIRECT_STATI
@@ -120,10 +121,12 @@
     POST = 'POST'
     PUT = 'PUT'
 
-    def __init__(self, assert_all_requests_are_fired=True):
+    def __init__(self, assert_all_requests_are_fired=True, pass_through=True):
         self._calls = CallList()
         self.reset()
         self.assert_all_requests_are_fired = assert_all_requests_are_fired
+        self.pass_through = pass_through
+        self.original_send = HTTPAdapter.send
 
     def reset(self):
         self._urls = []
@@ -235,6 +238,9 @@
         match = self._find_match(request)
         # TODO(dcramer): find the correct class for this
         if match is None:
+            if self.pass_through:
+                return self.original_send(adapter, request, **kwargs)
+
             error_msg = 'Connection refused: {0} {1}'.format(request.method,
                                                              request.url)
             response = ConnectionError(error_msg)
@@ -317,7 +323,7 @@
 
 
 # expose default mock namespace
-mock = _default_mock = RequestsMock(assert_all_requests_are_fired=False)
+mock = _default_mock = RequestsMock(assert_all_requests_are_fired=False, pass_through=False)
 __all__ = []
 for __attr in (a for a in dir(_default_mock) if not a.startswith('_')):
     __all__.append(__attr)

{"golden_diff": "diff --git a/moto/packages/responses/responses.py b/moto/packages/responses/responses.py\n--- a/moto/packages/responses/responses.py\n+++ b/moto/packages/responses/responses.py\n@@ -10,6 +10,7 @@\n from collections import namedtuple, Sequence, Sized\n from functools import update_wrapper\n from cookies import Cookies\n+from requests.adapters import HTTPAdapter\n from requests.utils import cookiejar_from_dict\n from requests.exceptions import ConnectionError\n from requests.sessions import REDIRECT_STATI\n@@ -120,10 +121,12 @@\n     POST = 'POST'\n     PUT = 'PUT'\n \n-    def __init__(self, assert_all_requests_are_fired=True):\n+    def __init__(self, assert_all_requests_are_fired=True, pass_through=True):\n         self._calls = CallList()\n         self.reset()\n         self.assert_all_requests_are_fired = assert_all_requests_are_fired\n+        self.pass_through = pass_through\n+        self.original_send = HTTPAdapter.send\n \n     def reset(self):\n         self._urls = []\n@@ -235,6 +238,9 @@\n         match = self._find_match(request)\n         # TODO(dcramer): find the correct class for this\n         if match is None:\n+            if self.pass_through:\n+                return self.original_send(adapter, request, **kwargs)\n+\n             error_msg = 'Connection refused: {0} {1}'.format(request.method,\n                                                              request.url)\n             response = ConnectionError(error_msg)\n@@ -317,7 +323,7 @@\n \n \n # expose default mock namespace\n-mock = _default_mock = RequestsMock(assert_all_requests_are_fired=False)\n+mock = _default_mock = RequestsMock(assert_all_requests_are_fired=False, pass_through=False)\n __all__ = []\n for __attr in (a for a in dir(_default_mock) if not a.startswith('_')):\n     __all__.append(__attr)\n", "issue": "can't use responses\nwith v1, since moto vendors in `responses`, it's impossible to use `responses` for mocking non-aws calls. example:\r\n\r\n```py\r\nwith _responses.RequestsMock() as rsps:\r\n    rsps.add(rsps.GET, 'http://foo')\r\n    with moto.mock_sns():\r\n       requests.get('http://foo')\r\n```\r\n\r\nthis used to work on < v1, on v1 it raises a connection refused error because basically requests is patched twice by two different modules\n", "before_files": [{"content": "from __future__ import (\n    absolute_import, print_function, division, unicode_literals\n)\n\nimport inspect\nimport json as json_module\nimport re\nimport six\n\nfrom collections import namedtuple, Sequence, Sized\nfrom functools import update_wrapper\nfrom cookies import Cookies\nfrom requests.utils import cookiejar_from_dict\nfrom requests.exceptions import ConnectionError\nfrom requests.sessions import REDIRECT_STATI\n\ntry:\n    from requests.packages.urllib3.response import HTTPResponse\nexcept ImportError:\n    from urllib3.response import HTTPResponse\n\nif six.PY2:\n    from urlparse import urlparse, parse_qsl\nelse:\n    from urllib.parse import urlparse, parse_qsl\n\nif six.PY2:\n    try:\n        from six import cStringIO as BufferIO\n    except ImportError:\n        from six import StringIO as BufferIO\nelse:\n    from io import BytesIO as BufferIO\n\n\nCall = namedtuple('Call', ['request', 'response'])\n\n_wrapper_template = \"\"\"\\\ndef wrapper%(signature)s:\n    with responses:\n        return func%(funcargs)s\n\"\"\"\n\n\ndef _is_string(s):\n    return isinstance(s, (six.string_types, six.text_type))\n\n\ndef _is_redirect(response):\n    try:\n        # 2.0.0 <= requests <= 2.2\n        return response.is_redirect\n    except AttributeError:\n        # requests > 2.2\n        return (\n            # use request.sessions conditional\n            response.status_code in REDIRECT_STATI and\n            'location' in response.headers\n        )\n\n\ndef get_wrapped(func, wrapper_template, evaldict):\n    # Preserve the argspec for the wrapped function so that testing\n    # tools such as pytest can continue to use their fixture injection.\n    args, a, kw, defaults = inspect.getargspec(func)\n\n    signature = inspect.formatargspec(args, a, kw, defaults)\n    is_bound_method = hasattr(func, '__self__')\n    if is_bound_method:\n        args = args[1:]     # Omit 'self'\n    callargs = inspect.formatargspec(args, a, kw, None)\n\n    ctx = {'signature': signature, 'funcargs': callargs}\n    six.exec_(wrapper_template % ctx, evaldict)\n\n    wrapper = evaldict['wrapper']\n\n    update_wrapper(wrapper, func)\n    if is_bound_method:\n        wrapper = wrapper.__get__(func.__self__, type(func.__self__))\n    return wrapper\n\n\nclass CallList(Sequence, Sized):\n\n    def __init__(self):\n        self._calls = []\n\n    def __iter__(self):\n        return iter(self._calls)\n\n    def __len__(self):\n        return len(self._calls)\n\n    def __getitem__(self, idx):\n        return self._calls[idx]\n\n    def add(self, request, response):\n        self._calls.append(Call(request, response))\n\n    def reset(self):\n        self._calls = []\n\n\ndef _ensure_url_default_path(url, match_querystring):\n    if _is_string(url) and url.count('/') == 2:\n        if match_querystring:\n            return url.replace('?', '/?', 1)\n        else:\n            return url + '/'\n    return url\n\n\nclass RequestsMock(object):\n    DELETE = 'DELETE'\n    GET = 'GET'\n    HEAD = 'HEAD'\n    OPTIONS = 'OPTIONS'\n    PATCH = 'PATCH'\n    POST = 'POST'\n    PUT = 'PUT'\n\n    def __init__(self, assert_all_requests_are_fired=True):\n        self._calls = CallList()\n        self.reset()\n        self.assert_all_requests_are_fired = assert_all_requests_are_fired\n\n    def reset(self):\n        self._urls = []\n        self._calls.reset()\n\n    def add(self, method, url, body='', match_querystring=False,\n            status=200, adding_headers=None, stream=False,\n            content_type='text/plain', json=None):\n\n        # if we were passed a `json` argument,\n        # override the body and content_type\n        if json is not None:\n            body = json_module.dumps(json)\n            content_type = 'application/json'\n\n        # ensure the url has a default path set if the url is a string\n        url = _ensure_url_default_path(url, match_querystring)\n\n        # body must be bytes\n        if isinstance(body, six.text_type):\n            body = body.encode('utf-8')\n\n        self._urls.append({\n            'url': url,\n            'method': method,\n            'body': body,\n            'content_type': content_type,\n            'match_querystring': match_querystring,\n            'status': status,\n            'adding_headers': adding_headers,\n            'stream': stream,\n        })\n\n    def add_callback(self, method, url, callback, match_querystring=False,\n                     content_type='text/plain'):\n        # ensure the url has a default path set if the url is a string\n        # url = _ensure_url_default_path(url, match_querystring)\n\n        self._urls.append({\n            'url': url,\n            'method': method,\n            'callback': callback,\n            'content_type': content_type,\n            'match_querystring': match_querystring,\n        })\n\n    @property\n    def calls(self):\n        return self._calls\n\n    def __enter__(self):\n        self.start()\n        return self\n\n    def __exit__(self, type, value, traceback):\n        success = type is None\n        self.stop(allow_assert=success)\n        self.reset()\n        return success\n\n    def activate(self, func):\n        evaldict = {'responses': self, 'func': func}\n        return get_wrapped(func, _wrapper_template, evaldict)\n\n    def _find_match(self, request):\n        for match in self._urls:\n            if request.method != match['method']:\n                continue\n\n            if not self._has_url_match(match, request.url):\n                continue\n\n            break\n        else:\n            return None\n        if self.assert_all_requests_are_fired:\n            # for each found match remove the url from the stack\n            self._urls.remove(match)\n        return match\n\n    def _has_url_match(self, match, request_url):\n        url = match['url']\n\n        if not match['match_querystring']:\n            request_url = request_url.split('?', 1)[0]\n\n        if _is_string(url):\n            if match['match_querystring']:\n                return self._has_strict_url_match(url, request_url)\n            else:\n                return url == request_url\n        elif isinstance(url, re._pattern_type) and url.match(request_url):\n            return True\n        else:\n            return False\n\n    def _has_strict_url_match(self, url, other):\n        url_parsed = urlparse(url)\n        other_parsed = urlparse(other)\n\n        if url_parsed[:3] != other_parsed[:3]:\n            return False\n\n        url_qsl = sorted(parse_qsl(url_parsed.query))\n        other_qsl = sorted(parse_qsl(other_parsed.query))\n        return url_qsl == other_qsl\n\n    def _on_request(self, adapter, request, **kwargs):\n        match = self._find_match(request)\n        # TODO(dcramer): find the correct class for this\n        if match is None:\n            error_msg = 'Connection refused: {0} {1}'.format(request.method,\n                                                             request.url)\n            response = ConnectionError(error_msg)\n            response.request = request\n\n            self._calls.add(request, response)\n            raise response\n\n        if 'body' in match and isinstance(match['body'], Exception):\n            self._calls.add(request, match['body'])\n            raise match['body']\n\n        headers = {}\n        if match['content_type'] is not None:\n            headers['Content-Type'] = match['content_type']\n\n        if 'callback' in match:  # use callback\n            status, r_headers, body = match['callback'](request)\n            if isinstance(body, six.text_type):\n                body = body.encode('utf-8')\n            body = BufferIO(body)\n            headers.update(r_headers)\n\n        elif 'body' in match:\n            if match['adding_headers']:\n                headers.update(match['adding_headers'])\n            status = match['status']\n            body = BufferIO(match['body'])\n\n        response = HTTPResponse(\n            status=status,\n            reason=six.moves.http_client.responses[status],\n            body=body,\n            headers=headers,\n            preload_content=False,\n            # Need to not decode_content to mimic requests\n            decode_content=False,\n        )\n\n        response = adapter.build_response(request, response)\n        if not match.get('stream'):\n            response.content  # NOQA\n\n        try:\n            resp_cookies = Cookies.from_request(response.headers['set-cookie'])\n            response.cookies = cookiejar_from_dict(dict(\n                (v.name, v.value)\n                for _, v\n                in resp_cookies.items()\n            ))\n        except (KeyError, TypeError):\n            pass\n\n        self._calls.add(request, response)\n\n        return response\n\n    def start(self):\n        try:\n            from unittest import mock\n        except ImportError:\n            import mock\n\n        def unbound_on_send(adapter, request, *a, **kwargs):\n            return self._on_request(adapter, request, *a, **kwargs)\n        self._patcher1 = mock.patch('botocore.vendored.requests.adapters.HTTPAdapter.send',\n                                    unbound_on_send)\n        self._patcher1.start()\n        self._patcher2 = mock.patch('requests.adapters.HTTPAdapter.send',\n                                    unbound_on_send)\n        self._patcher2.start()\n\n    def stop(self, allow_assert=True):\n        self._patcher1.stop()\n        self._patcher2.stop()\n        if allow_assert and self.assert_all_requests_are_fired and self._urls:\n            raise AssertionError(\n                'Not all requests have been executed {0!r}'.format(\n                    [(url['method'], url['url']) for url in self._urls]))\n\n\n# expose default mock namespace\nmock = _default_mock = RequestsMock(assert_all_requests_are_fired=False)\n__all__ = []\nfor __attr in (a for a in dir(_default_mock) if not a.startswith('_')):\n    __all__.append(__attr)\n    globals()[__attr] = getattr(_default_mock, __attr)\n", "path": "moto/packages/responses/responses.py"}], "after_files": [{"content": "from __future__ import (\n    absolute_import, print_function, division, unicode_literals\n)\n\nimport inspect\nimport json as json_module\nimport re\nimport six\n\nfrom collections import namedtuple, Sequence, Sized\nfrom functools import update_wrapper\nfrom cookies import Cookies\nfrom requests.adapters import HTTPAdapter\nfrom requests.utils import cookiejar_from_dict\nfrom requests.exceptions import ConnectionError\nfrom requests.sessions import REDIRECT_STATI\n\ntry:\n    from requests.packages.urllib3.response import HTTPResponse\nexcept ImportError:\n    from urllib3.response import HTTPResponse\n\nif six.PY2:\n    from urlparse import urlparse, parse_qsl\nelse:\n    from urllib.parse import urlparse, parse_qsl\n\nif six.PY2:\n    try:\n        from six import cStringIO as BufferIO\n    except ImportError:\n        from six import StringIO as BufferIO\nelse:\n    from io import BytesIO as BufferIO\n\n\nCall = namedtuple('Call', ['request', 'response'])\n\n_wrapper_template = \"\"\"\\\ndef wrapper%(signature)s:\n    with responses:\n        return func%(funcargs)s\n\"\"\"\n\n\ndef _is_string(s):\n    return isinstance(s, (six.string_types, six.text_type))\n\n\ndef _is_redirect(response):\n    try:\n        # 2.0.0 <= requests <= 2.2\n        return response.is_redirect\n    except AttributeError:\n        # requests > 2.2\n        return (\n            # use request.sessions conditional\n            response.status_code in REDIRECT_STATI and\n            'location' in response.headers\n        )\n\n\ndef get_wrapped(func, wrapper_template, evaldict):\n    # Preserve the argspec for the wrapped function so that testing\n    # tools such as pytest can continue to use their fixture injection.\n    args, a, kw, defaults = inspect.getargspec(func)\n\n    signature = inspect.formatargspec(args, a, kw, defaults)\n    is_bound_method = hasattr(func, '__self__')\n    if is_bound_method:\n        args = args[1:]     # Omit 'self'\n    callargs = inspect.formatargspec(args, a, kw, None)\n\n    ctx = {'signature': signature, 'funcargs': callargs}\n    six.exec_(wrapper_template % ctx, evaldict)\n\n    wrapper = evaldict['wrapper']\n\n    update_wrapper(wrapper, func)\n    if is_bound_method:\n        wrapper = wrapper.__get__(func.__self__, type(func.__self__))\n    return wrapper\n\n\nclass CallList(Sequence, Sized):\n\n    def __init__(self):\n        self._calls = []\n\n    def __iter__(self):\n        return iter(self._calls)\n\n    def __len__(self):\n        return len(self._calls)\n\n    def __getitem__(self, idx):\n        return self._calls[idx]\n\n    def add(self, request, response):\n        self._calls.append(Call(request, response))\n\n    def reset(self):\n        self._calls = []\n\n\ndef _ensure_url_default_path(url, match_querystring):\n    if _is_string(url) and url.count('/') == 2:\n        if match_querystring:\n            return url.replace('?', '/?', 1)\n        else:\n            return url + '/'\n    return url\n\n\nclass RequestsMock(object):\n    DELETE = 'DELETE'\n    GET = 'GET'\n    HEAD = 'HEAD'\n    OPTIONS = 'OPTIONS'\n    PATCH = 'PATCH'\n    POST = 'POST'\n    PUT = 'PUT'\n\n    def __init__(self, assert_all_requests_are_fired=True, pass_through=True):\n        self._calls = CallList()\n        self.reset()\n        self.assert_all_requests_are_fired = assert_all_requests_are_fired\n        self.pass_through = pass_through\n        self.original_send = HTTPAdapter.send\n\n    def reset(self):\n        self._urls = []\n        self._calls.reset()\n\n    def add(self, method, url, body='', match_querystring=False,\n            status=200, adding_headers=None, stream=False,\n            content_type='text/plain', json=None):\n\n        # if we were passed a `json` argument,\n        # override the body and content_type\n        if json is not None:\n            body = json_module.dumps(json)\n            content_type = 'application/json'\n\n        # ensure the url has a default path set if the url is a string\n        url = _ensure_url_default_path(url, match_querystring)\n\n        # body must be bytes\n        if isinstance(body, six.text_type):\n            body = body.encode('utf-8')\n\n        self._urls.append({\n            'url': url,\n            'method': method,\n            'body': body,\n            'content_type': content_type,\n            'match_querystring': match_querystring,\n            'status': status,\n            'adding_headers': adding_headers,\n            'stream': stream,\n        })\n\n    def add_callback(self, method, url, callback, match_querystring=False,\n                     content_type='text/plain'):\n        # ensure the url has a default path set if the url is a string\n        # url = _ensure_url_default_path(url, match_querystring)\n\n        self._urls.append({\n            'url': url,\n            'method': method,\n            'callback': callback,\n            'content_type': content_type,\n            'match_querystring': match_querystring,\n        })\n\n    @property\n    def calls(self):\n        return self._calls\n\n    def __enter__(self):\n        self.start()\n        return self\n\n    def __exit__(self, type, value, traceback):\n        success = type is None\n        self.stop(allow_assert=success)\n        self.reset()\n        return success\n\n    def activate(self, func):\n        evaldict = {'responses': self, 'func': func}\n        return get_wrapped(func, _wrapper_template, evaldict)\n\n    def _find_match(self, request):\n        for match in self._urls:\n            if request.method != match['method']:\n                continue\n\n            if not self._has_url_match(match, request.url):\n                continue\n\n            break\n        else:\n            return None\n        if self.assert_all_requests_are_fired:\n            # for each found match remove the url from the stack\n            self._urls.remove(match)\n        return match\n\n    def _has_url_match(self, match, request_url):\n        url = match['url']\n\n        if not match['match_querystring']:\n            request_url = request_url.split('?', 1)[0]\n\n        if _is_string(url):\n            if match['match_querystring']:\n                return self._has_strict_url_match(url, request_url)\n            else:\n                return url == request_url\n        elif isinstance(url, re._pattern_type) and url.match(request_url):\n            return True\n        else:\n            return False\n\n    def _has_strict_url_match(self, url, other):\n        url_parsed = urlparse(url)\n        other_parsed = urlparse(other)\n\n        if url_parsed[:3] != other_parsed[:3]:\n            return False\n\n        url_qsl = sorted(parse_qsl(url_parsed.query))\n        other_qsl = sorted(parse_qsl(other_parsed.query))\n        return url_qsl == other_qsl\n\n    def _on_request(self, adapter, request, **kwargs):\n        match = self._find_match(request)\n        # TODO(dcramer): find the correct class for this\n        if match is None:\n            if self.pass_through:\n                return self.original_send(adapter, request, **kwargs)\n\n            error_msg = 'Connection refused: {0} {1}'.format(request.method,\n                                                             request.url)\n            response = ConnectionError(error_msg)\n            response.request = request\n\n            self._calls.add(request, response)\n            raise response\n\n        if 'body' in match and isinstance(match['body'], Exception):\n            self._calls.add(request, match['body'])\n            raise match['body']\n\n        headers = {}\n        if match['content_type'] is not None:\n            headers['Content-Type'] = match['content_type']\n\n        if 'callback' in match:  # use callback\n            status, r_headers, body = match['callback'](request)\n            if isinstance(body, six.text_type):\n                body = body.encode('utf-8')\n            body = BufferIO(body)\n            headers.update(r_headers)\n\n        elif 'body' in match:\n            if match['adding_headers']:\n                headers.update(match['adding_headers'])\n            status = match['status']\n            body = BufferIO(match['body'])\n\n        response = HTTPResponse(\n            status=status,\n            reason=six.moves.http_client.responses[status],\n            body=body,\n            headers=headers,\n            preload_content=False,\n            # Need to not decode_content to mimic requests\n            decode_content=False,\n        )\n\n        response = adapter.build_response(request, response)\n        if not match.get('stream'):\n            response.content  # NOQA\n\n        try:\n            resp_cookies = Cookies.from_request(response.headers['set-cookie'])\n            response.cookies = cookiejar_from_dict(dict(\n                (v.name, v.value)\n                for _, v\n                in resp_cookies.items()\n            ))\n        except (KeyError, TypeError):\n            pass\n\n        self._calls.add(request, response)\n\n        return response\n\n    def start(self):\n        try:\n            from unittest import mock\n        except ImportError:\n            import mock\n\n        def unbound_on_send(adapter, request, *a, **kwargs):\n            return self._on_request(adapter, request, *a, **kwargs)\n        self._patcher1 = mock.patch('botocore.vendored.requests.adapters.HTTPAdapter.send',\n                                    unbound_on_send)\n        self._patcher1.start()\n        self._patcher2 = mock.patch('requests.adapters.HTTPAdapter.send',\n                                    unbound_on_send)\n        self._patcher2.start()\n\n    def stop(self, allow_assert=True):\n        self._patcher1.stop()\n        self._patcher2.stop()\n        if allow_assert and self.assert_all_requests_are_fired and self._urls:\n            raise AssertionError(\n                'Not all requests have been executed {0!r}'.format(\n                    [(url['method'], url['url']) for url in self._urls]))\n\n\n# expose default mock namespace\nmock = _default_mock = RequestsMock(assert_all_requests_are_fired=False, pass_through=False)\n__all__ = []\nfor __attr in (a for a in dir(_default_mock) if not a.startswith('_')):\n    __all__.append(__attr)\n    globals()[__attr] = getattr(_default_mock, __attr)\n", "path": "moto/packages/responses/responses.py"}]}