forked from getsentry/responses
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_responses.py
415 lines (318 loc) · 12.3 KB
/
test_responses.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
from __future__ import (
absolute_import, print_function, division, unicode_literals
)
import re
import requests
import responses
import pytest
from inspect import getargspec
from requests.exceptions import ConnectionError, HTTPError
def assert_reset():
assert len(responses._default_mock._urls) == 0
assert len(responses.calls) == 0
def assert_response(resp, body=None, content_type='text/plain'):
assert resp.status_code == 200
assert resp.headers['Content-Type'] == content_type
assert resp.text == body
def test_response():
@responses.activate
def run():
responses.add(responses.GET, 'http://example.com', body=b'test')
resp = requests.get('http://example.com')
assert_response(resp, 'test')
assert len(responses.calls) == 1
assert responses.calls[0].request.url == 'http://example.com/'
assert responses.calls[0].response.content == b'test'
resp = requests.get('http://example.com?foo=bar')
assert_response(resp, 'test')
assert len(responses.calls) == 2
assert responses.calls[1].request.url == 'http://example.com/?foo=bar'
assert responses.calls[1].response.content == b'test'
run()
assert_reset()
def test_connection_error():
@responses.activate
def run():
responses.add(responses.GET, 'http://example.com')
with pytest.raises(ConnectionError):
requests.get('http://example.com/foo')
assert len(responses.calls) == 1
assert responses.calls[0].request.url == 'http://example.com/foo'
assert type(responses.calls[0].response) is ConnectionError
assert responses.calls[0].response.request
run()
assert_reset()
def test_match_querystring():
@responses.activate
def run():
url = 'http://example.com?test=1&foo=bar'
responses.add(
responses.GET, url,
match_querystring=True, body=b'test')
resp = requests.get('http://example.com?test=1&foo=bar')
assert_response(resp, 'test')
resp = requests.get('http://example.com?foo=bar&test=1')
assert_response(resp, 'test')
run()
assert_reset()
def test_match_querystring_with_params():
@responses.activate
def run():
url = 'http://example.com'
query_params = {
"test": 2, "foo": "baz",
"name": ["boaty", "mcboatface"]
}
responses.add(
responses.GET, url,
match_querystring=True, query_params=query_params,
body=b'test')
resp = requests.get(
'http://example.com?test=2&foo=baz&name=boaty&name=mcboatface')
assert_response(resp, 'test')
resp = requests.get(
'http://example.com?foo=baz&test=2&name=mcboatface&name=boaty')
assert_response(resp, 'test')
run()
assert_reset()
def test_match_querystring_error():
@responses.activate
def run():
responses.add(
responses.GET, 'http://example.com/?test=1',
match_querystring=True)
with pytest.raises(ConnectionError):
requests.get('http://example.com/foo/?test=2')
run()
assert_reset()
def test_match_querystring_regex():
@responses.activate
def run():
"""Note that `match_querystring` value shouldn't matter when passing a
regular expression"""
responses.add(
responses.GET, re.compile(r'http://example\.com/foo/\?test=1'),
body='test1', match_querystring=True)
resp = requests.get('http://example.com/foo/?test=1')
assert_response(resp, 'test1')
responses.add(
responses.GET, re.compile(r'http://example\.com/foo/\?test=2'),
body='test2', match_querystring=False)
resp = requests.get('http://example.com/foo/?test=2')
assert_response(resp, 'test2')
run()
assert_reset()
def test_match_querystring_error_regex():
@responses.activate
def run():
"""Note that `match_querystring` value shouldn't matter when passing a
regular expression"""
responses.add(
responses.GET, re.compile(r'http://example\.com/foo/\?test=1'),
match_querystring=True)
with pytest.raises(ConnectionError):
requests.get('http://example.com/foo/?test=3')
responses.add(
responses.GET, re.compile(r'http://example\.com/foo/\?test=2'),
match_querystring=False)
with pytest.raises(ConnectionError):
requests.get('http://example.com/foo/?test=4')
run()
assert_reset()
def test_accept_string_body():
@responses.activate
def run():
url = 'http://example.com/'
responses.add(
responses.GET, url, body='test')
resp = requests.get(url)
assert_response(resp, 'test')
run()
assert_reset()
def test_accept_json_body():
@responses.activate
def run():
content_type = 'application/json'
url = 'http://example.com/'
responses.add(
responses.GET, url, json={"message": "success"})
resp = requests.get(url)
assert_response(resp, '{"message": "success"}', content_type)
url = 'http://example.com/1/'
responses.add(responses.GET, url, json=[])
resp = requests.get(url)
assert_response(resp, '[]', content_type)
run()
assert_reset()
def test_throw_connection_error_explicit():
@responses.activate
def run():
url = 'http://example.com'
exception = HTTPError('HTTP Error')
responses.add(
responses.GET, url, exception)
with pytest.raises(HTTPError) as HE:
requests.get(url)
assert str(HE.value) == 'HTTP Error'
run()
assert_reset()
def test_callback():
body = b'test callback'
status = 400
headers = {'foo': 'bar'}
url = 'http://example.com/'
def request_callback(request):
return (status, headers, body)
@responses.activate
def run():
responses.add_callback(responses.GET, url, request_callback)
resp = requests.get(url)
assert resp.text == "test callback"
assert resp.status_code == status
assert 'foo' in resp.headers
assert resp.headers['foo'] == 'bar'
run()
assert_reset()
def test_regular_expression_url():
@responses.activate
def run():
url = re.compile(r'https?://(.*\.)?example.com')
responses.add(responses.GET, url, body=b'test')
resp = requests.get('http://example.com')
assert_response(resp, 'test')
resp = requests.get('https://example.com')
assert_response(resp, 'test')
resp = requests.get('https://uk.example.com')
assert_response(resp, 'test')
with pytest.raises(ConnectionError):
requests.get('https://uk.exaaample.com')
run()
assert_reset()
def test_custom_adapter():
@responses.activate
def run():
url = "http://example.com"
responses.add(responses.GET, url, body=b'test')
calls = [0]
class DummyAdapter(requests.adapters.HTTPAdapter):
def send(self, *a, **k):
calls[0] += 1
return super(DummyAdapter, self).send(*a, **k)
# Test that the adapter is actually used
session = requests.Session()
session.mount("http://", DummyAdapter())
resp = session.get(url, allow_redirects=False)
assert calls[0] == 1
# Test that the response is still correctly emulated
session = requests.Session()
session.mount("http://", DummyAdapter())
resp = session.get(url)
assert_response(resp, 'test')
run()
def test_responses_as_context_manager():
def run():
with responses.mock:
responses.add(responses.GET, 'http://example.com', body=b'test')
resp = requests.get('http://example.com')
assert_response(resp, 'test')
assert len(responses.calls) == 1
assert responses.calls[0].request.url == 'http://example.com/'
assert responses.calls[0].response.content == b'test'
resp = requests.get('http://example.com?foo=bar')
assert_response(resp, 'test')
assert len(responses.calls) == 2
assert (responses.calls[1].request.url ==
'http://example.com/?foo=bar')
assert responses.calls[1].response.content == b'test'
run()
assert_reset()
def test_activate_doesnt_change_signature():
def test_function(a, b=None):
return (a, b)
decorated_test_function = responses.activate(test_function)
assert getargspec(test_function) == getargspec(decorated_test_function)
assert decorated_test_function(1, 2) == test_function(1, 2)
assert decorated_test_function(3) == test_function(3)
def test_activate_doesnt_change_signature_for_method():
class TestCase(object):
def test_function(self, a, b=None):
return (self, a, b)
test_case = TestCase()
argspec = getargspec(test_case.test_function)
decorated_test_function = responses.activate(test_case.test_function)
assert argspec == getargspec(decorated_test_function)
assert decorated_test_function(1, 2) == test_case.test_function(1, 2)
assert decorated_test_function(3) == test_case.test_function(3)
def test_response_cookies():
body = b'test callback'
status = 200
headers = {'set-cookie': 'session_id=12345; a=b; c=d'}
url = 'http://example.com/'
def request_callback(request):
return (status, headers, body)
@responses.activate
def run():
responses.add_callback(responses.GET, url, request_callback)
resp = requests.get(url)
assert resp.text == "test callback"
assert resp.status_code == status
assert 'session_id' in resp.cookies
assert resp.cookies['session_id'] == '12345'
assert resp.cookies['a'] == 'b'
assert resp.cookies['c'] == 'd'
run()
assert_reset()
def test_assert_all_requests_are_fired():
def run():
with pytest.raises(AssertionError) as excinfo:
with responses.RequestsMock(
assert_all_requests_are_fired=True) as m:
m.add(responses.GET, 'http://example.com', body=b'test')
assert 'http://example.com' in str(excinfo.value)
assert responses.GET in str(excinfo)
# check that assert_all_requests_are_fired default to True
with pytest.raises(AssertionError):
with responses.RequestsMock() as m:
m.add(responses.GET, 'http://example.com', body=b'test')
run()
assert_reset()
def test_allow_redirects_samehost():
redirecting_url = 'http://example.com'
final_url_path = '/1'
final_url = '{0}{1}'.format(redirecting_url, final_url_path)
url_re = re.compile(r'^http://example.com(/)?(\d+)?$')
def request_callback(request):
# endpoint of chained redirect
if request.url.endswith(final_url_path):
return 200, (), b'test'
# otherwise redirect to an integer path
else:
if request.url.endswith('/0'):
n = 1
else:
n = 0
redirect_headers = {'location': '/{0!s}'.format(n)}
return 301, redirect_headers, None
def run():
# setup redirect
with responses.mock:
responses.add_callback(responses.GET, url_re, request_callback)
resp_no_redirects = requests.get(redirecting_url,
allow_redirects=False)
assert resp_no_redirects.status_code == 301
assert len(responses.calls) == 1 # 1x300
assert responses.calls[0][1].status_code == 301
assert_reset()
with responses.mock:
responses.add_callback(responses.GET, url_re, request_callback)
resp_yes_redirects = requests.get(redirecting_url,
allow_redirects=True)
assert len(responses.calls) == 3 # 2x300 + 1x200
assert len(resp_yes_redirects.history) == 2
assert resp_yes_redirects.status_code == 200
assert final_url == resp_yes_redirects.url
status_codes = [call[1].status_code for call in responses.calls]
assert status_codes == [301, 301, 200]
assert_reset()
run()
assert_reset()