Debian Codegraph @

third_party/python/responses/responses-0.10.6.dist-info/METADATA

raw
1 Metadata-Version: 2.1
2 Name: responses
3 Version: 0.10.6
4 Summary: A utility library for mocking out the `requests` Python library.
5 Home-page: https://github.com/getsentry/responses
6 Author: David Cramer
7 License: Apache 2.0
8 Platform: UNKNOWN
9 Classifier: Intended Audience :: Developers
10 Classifier: Intended Audience :: System Administrators
11 Classifier: Operating System :: OS Independent
12 Classifier: Programming Language :: Python
13 Classifier: Programming Language :: Python :: 2
14 Classifier: Programming Language :: Python :: 2.7
15 Classifier: Programming Language :: Python :: 3
16 Classifier: Programming Language :: Python :: 3.4
17 Classifier: Programming Language :: Python :: 3.5
18 Classifier: Programming Language :: Python :: 3.6
19 Classifier: Programming Language :: Python :: 3.7
20 Classifier: Topic :: Software Development
21 Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*
22 Requires-Dist: requests (>=2.0)
23 Requires-Dist: six
24 Requires-Dist: mock ; python_version < "3.3"
25 Requires-Dist: cookies ; python_version < "3.4"
26 Provides-Extra: tests
27 Requires-Dist: pytest ; extra == 'tests'
28 Requires-Dist: coverage (<5.0.0,>=3.7.1) ; extra == 'tests'
29 Requires-Dist: pytest-cov ; extra == 'tests'
30 Requires-Dist: pytest-localserver ; extra == 'tests'
31 Requires-Dist: flake8 ; extra == 'tests'
32
33 Responses
34 =========
35
36 .. image:: https://travis-ci.org/getsentry/responses.svg?branch=master
37 :target: https://travis-ci.org/getsentry/responses
38
39 A utility library for mocking out the `requests` Python library.
40
41 .. note::
42
43 Responses requires Python 2.7 or newer, and requests >= 2.0
44
45
46 Installing
47 ----------
48
49 ``pip install responses``
50
51
52 Basics
53 ------
54
55 The core of ``responses`` comes from registering mock responses:
56
57 .. code-block:: python
58
59 import responses
60 import requests
61
62 @responses.activate
63 def test_simple():
64 responses.add(responses.GET, 'http://twitter.com/api/1/foobar',
65 json={'error': 'not found'}, status=404)
66
67 resp = requests.get('http://twitter.com/api/1/foobar')
68
69 assert resp.json() == {"error": "not found"}
70
71 assert len(responses.calls) == 1
72 assert responses.calls[0].request.url == 'http://twitter.com/api/1/foobar'
73 assert responses.calls[0].response.text == '{"error": "not found"}'
74
75 If you attempt to fetch a url which doesn't hit a match, ``responses`` will raise
76 a ``ConnectionError``:
77
78 .. code-block:: python
79
80 import responses
81 import requests
82
83 from requests.exceptions import ConnectionError
84
85 @responses.activate
86 def test_simple():
87 with pytest.raises(ConnectionError):
88 requests.get('http://twitter.com/api/1/foobar')
89
90 Lastly, you can pass an ``Exception`` as the body to trigger an error on the request:
91
92 .. code-block:: python
93
94 import responses
95 import requests
96
97 @responses.activate
98 def test_simple():
99 responses.add(responses.GET, 'http://twitter.com/api/1/foobar',
100 body=Exception('...'))
101 with pytest.raises(Exception):
102 requests.get('http://twitter.com/api/1/foobar')
103
104
105 Response Parameters
106 -------------------
107
108 Responses are automatically registered via params on ``add``, but can also be
109 passed directly:
110
111 .. code-block:: python
112
113 import responses
114
115 responses.add(
116 responses.Response(
117 method='GET',
118 url='http://example.com',
119 )
120 )
121
122 The following attributes can be passed to a Response mock:
123
124 method (``str``)
125 The HTTP method (GET, POST, etc).
126
127 url (``str`` or compiled regular expression)
128 The full resource URL.
129
130 match_querystring (``bool``)
131 Include the query string when matching requests.
132 Enabled by default if the response URL contains a query string,
133 disabled if it doesn't or the URL is a regular expression.
134
135 body (``str`` or ``BufferedReader``)
136 The response body.
137
138 json
139 A Python object representing the JSON response body. Automatically configures
140 the appropriate Content-Type.
141
142 status (``int``)
143 The HTTP status code.
144
145 content_type (``content_type``)
146 Defaults to ``text/plain``.
147
148 headers (``dict``)
149 Response headers.
150
151 stream (``bool``)
152 Disabled by default. Indicates the response should use the streaming API.
153
154
155 Dynamic Responses
156 -----------------
157
158 You can utilize callbacks to provide dynamic responses. The callback must return
159 a tuple of (``status``, ``headers``, ``body``).
160
161 .. code-block:: python
162
163 import json
164
165 import responses
166 import requests
167
168 @responses.activate
169 def test_calc_api():
170
171 def request_callback(request):
172 payload = json.loads(request.body)
173 resp_body = {'value': sum(payload['numbers'])}
174 headers = {'request-id': '728d329e-0e86-11e4-a748-0c84dc037c13'}
175 return (200, headers, json.dumps(resp_body))
176
177 responses.add_callback(
178 responses.POST, 'http://calc.com/sum',
179 callback=request_callback,
180 content_type='application/json',
181 )
182
183 resp = requests.post(
184 'http://calc.com/sum',
185 json.dumps({'numbers': [1, 2, 3]}),
186 headers={'content-type': 'application/json'},
187 )
188
189 assert resp.json() == {'value': 6}
190
191 assert len(responses.calls) == 1
192 assert responses.calls[0].request.url == 'http://calc.com/sum'
193 assert responses.calls[0].response.text == '{"value": 6}'
194 assert (
195 responses.calls[0].response.headers['request-id'] ==
196 '728d329e-0e86-11e4-a748-0c84dc037c13'
197 )
198
199 You can also pass a compiled regex to `add_callback` to match multiple urls:
200
201 .. code-block:: python
202
203 import re, json
204
205 from functools import reduce
206
207 import responses
208 import requests
209
210 operators = {
211 'sum': lambda x, y: x+y,
212 'prod': lambda x, y: x*y,
213 'pow': lambda x, y: x**y
214 }
215
216 @responses.activate
217 def test_regex_url():
218
219 def request_callback(request):
220 payload = json.loads(request.body)
221 operator_name = request.path_url[1:]
222
223 operator = operators[operator_name]
224
225 resp_body = {'value': reduce(operator, payload['numbers'])}
226 headers = {'request-id': '728d329e-0e86-11e4-a748-0c84dc037c13'}
227 return (200, headers, json.dumps(resp_body))
228
229 responses.add_callback(
230 responses.POST,
231 re.compile('http://calc.com/(sum|prod|pow|unsupported)'),
232 callback=request_callback,
233 content_type='application/json',
234 )
235
236 resp = requests.post(
237 'http://calc.com/prod',
238 json.dumps({'numbers': [2, 3, 4]}),
239 headers={'content-type': 'application/json'},
240 )
241 assert resp.json() == {'value': 24}
242
243 test_regex_url()
244
245
246 If you want to pass extra keyword arguments to the callback function, for example when reusing
247 a callback function to give a slightly different result, you can use ``functools.partial``:
248
249 .. code-block:: python
250
251 from functools import partial
252
253 ...
254
255 def request_callback(request, id=None):
256 payload = json.loads(request.body)
257 resp_body = {'value': sum(payload['numbers'])}
258 headers = {'request-id': id}
259 return (200, headers, json.dumps(resp_body))
260
261 responses.add_callback(
262 responses.POST, 'http://calc.com/sum',
263 callback=partial(request_callback, id='728d329e-0e86-11e4-a748-0c84dc037c13'),
264 content_type='application/json',
265 )
266
267
268 Responses as a context manager
269 ------------------------------
270
271 .. code-block:: python
272
273 import responses
274 import requests
275
276 def test_my_api():
277 with responses.RequestsMock() as rsps:
278 rsps.add(responses.GET, 'http://twitter.com/api/1/foobar',
279 body='{}', status=200,
280 content_type='application/json')
281 resp = requests.get('http://twitter.com/api/1/foobar')
282
283 assert resp.status_code == 200
284
285 # outside the context manager requests will hit the remote server
286 resp = requests.get('http://twitter.com/api/1/foobar')
287 resp.status_code == 404
288
289 Responses as a pytest fixture
290 -----------------------------
291
292 .. code-block:: python
293
294 @pytest.fixture
295 def mocked_responses():
296 with responses.RequestsMock() as rsps:
297 yield rsps
298
299 def test_api(mocked_responses):
300 mocked_responses.add(
301 responses.GET, 'http://twitter.com/api/1/foobar',
302 body='{}', status=200,
303 content_type='application/json')
304 resp = requests.get('http://twitter.com/api/1/foobar')
305 assert resp.status_code == 200
306
307 Assertions on declared responses
308 --------------------------------
309
310 When used as a context manager, Responses will, by default, raise an assertion
311 error if a url was registered but not accessed. This can be disabled by passing
312 the ``assert_all_requests_are_fired`` value:
313
314 .. code-block:: python
315
316 import responses
317 import requests
318
319 def test_my_api():
320 with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
321 rsps.add(responses.GET, 'http://twitter.com/api/1/foobar',
322 body='{}', status=200,
323 content_type='application/json')
324
325
326 Multiple Responses
327 ------------------
328
329 You can also add multiple responses for the same url:
330
331 .. code-block:: python
332
333 import responses
334 import requests
335
336 @responses.activate
337 def test_my_api():
338 responses.add(responses.GET, 'http://twitter.com/api/1/foobar', status=500)
339 responses.add(responses.GET, 'http://twitter.com/api/1/foobar',
340 body='{}', status=200,
341 content_type='application/json')
342
343 resp = requests.get('http://twitter.com/api/1/foobar')
344 assert resp.status_code == 500
345 resp = requests.get('http://twitter.com/api/1/foobar')
346 assert resp.status_code == 200
347
348
349 Using a callback to modify the response
350 ---------------------------------------
351
352 If you use customized processing in `requests` via subclassing/mixins, or if you
353 have library tools that interact with `requests` at a low level, you may need
354 to add extended processing to the mocked Response object to fully simulate the
355 environment for your tests. A `response_callback` can be used, which will be
356 wrapped by the library before being returned to the caller. The callback
357 accepts a `response` as it's single argument, and is expected to return a
358 single `response` object.
359
360 .. code-block:: python
361
362 import responses
363 import requests
364
365 def response_callback(resp):
366 resp.callback_processed = True
367 return resp
368
369 with responses.RequestsMock(response_callback=response_callback) as m:
370 m.add(responses.GET, 'http://example.com', body=b'test')
371 resp = requests.get('http://example.com')
372 assert resp.text == "test"
373 assert hasattr(resp, 'callback_processed')
374 assert resp.callback_processed is True
375
376
377 Passing thru real requests
378 --------------------------
379
380 In some cases you may wish to allow for certain requests to pass thru responses
381 and hit a real server. This can be done with the 'passthru' methods:
382
383 .. code-block:: python
384
385 import responses
386
387 @responses.activate
388 def test_my_api():
389 responses.add_passthru('https://percy.io')
390
391 This will allow any requests matching that prefix, that is otherwise not registered
392 as a mock response, to passthru using the standard behavior.
393
394
395 Viewing/Modifying registered responses
396 --------------------------------------
397
398 Registered responses are available as a private attribute of the RequestMock
399 instance. It is sometimes useful for debugging purposes to view the stack of
400 registered responses which can be accessed via ``responses.mock._matches``.
401
402 The ``replace`` function allows a previously registered ``response`` to be
403 changed. The method signature is identical to ``add``. ``response``s are
404 identified using ``method`` and ``url``. Only the first matched ``response`` is
405 replaced.
406
407 .. code-block:: python
408
409 import responses
410 import requests
411
412 @responses.activate
413 def test_replace():
414
415 responses.add(responses.GET, 'http://example.org', json={'data': 1})
416 responses.replace(responses.GET, 'http://example.org', json={'data': 2})
417
418 resp = requests.get('http://example.org')
419
420 assert resp.json() == {'data': 2}
421
422
423 ``remove`` takes a ``method`` and ``url`` argument and will remove *all*
424 matched ``response``s from the registered list.
425
426 Finally, ``clear`` will reset all registered ``response``s
427
428
429
430 Contributing
431 ------------
432
433 Responses uses several linting and autoformatting utilities, so it's important that when
434 submitting patches you use the appropriate toolchain:
435
436 Clone the repository:
437
438 .. code-block:: shell
439
440 git clone https://github.com/getsentry/responses.git
441
442 Create an environment (e.g. with ``virtualenv``):
443
444 .. code-block:: shell
445
446 virtualenv .env && source .env/bin/activate
447
448 Configure development requirements:
449
450 .. code-block:: shell
451
452 make develop
453
454