13
14
from requests.auth import HTTPDigestAuth
14
15
from requests.adapters import HTTPAdapter
15
from requests.compat import str, cookielib
16
from requests.compat import str, cookielib, getproxies, urljoin, urlparse
16
17
from requests.cookies import cookiejar_from_dict
17
18
from requests.exceptions import InvalidURL, MissingSchema
18
19
from requests.structures import CaseInsensitiveDict
23
24
import io as StringIO
25
26
HTTPBIN = os.environ.get('HTTPBIN_URL', 'http://httpbin.org/')
27
# Issue #1483: Make sure the URL always has a trailing slash
28
HTTPBIN = HTTPBIN.rstrip('/') + '/'
28
31
def httpbin(*suffix):
29
32
"""Returns url for HTTPBIN resource."""
30
return HTTPBIN + '/'.join(suffix)
33
return urljoin(HTTPBIN, '/'.join(suffix))
33
36
class RequestsTestCase(unittest.TestCase):
87
90
self.assertEqual(request.url,
88
91
"http://example.com/path?key=value&a=b#fragment")
93
def test_mixed_case_scheme_acceptable(self):
94
s = requests.Session()
95
s.proxies = getproxies()
96
parts = urlparse(httpbin('get'))
97
schemes = ['http://', 'HTTP://', 'hTTp://', 'HttP://',
98
'https://', 'HTTPS://', 'hTTps://', 'HttPs://']
99
for scheme in schemes:
100
url = scheme + parts.netloc + parts.path
101
r = requests.Request('GET', url)
102
r = s.send(r.prepare())
103
self.assertEqual(r.status_code, 200,
104
"failed for scheme %s" % scheme)
90
106
def test_HTTP_200_OK_GET_ALTERNATIVE(self):
91
107
r = requests.Request('GET', httpbin('get'))
92
108
s = requests.Session()
109
s.proxies = getproxies()
94
111
r = s.send(r.prepare())
161
183
# Make sure the session cj is still the custom one
162
184
assert s.cookies is cj
186
def test_requests_in_history_are_not_overridden(self):
187
resp = requests.get(httpbin('redirect/3'))
188
urls = [r.url for r in resp.history]
189
req_urls = [r.request.url for r in resp.history]
190
self.assertEquals(urls, req_urls)
164
192
def test_user_agent_transfers(self):
201
229
self.assertEqual(r.status_code, 200)
231
def test_basicauth_with_netrc(self):
232
auth = ('user', 'pass')
233
wrong_auth = ('wronguser', 'wrongpass')
234
url = httpbin('basic-auth', 'user', 'pass')
236
def get_netrc_auth_mock(url):
238
requests.sessions.get_netrc_auth = get_netrc_auth_mock
240
# Should use netrc and work.
241
r = requests.get(url)
242
self.assertEqual(r.status_code, 200)
244
# Given auth should override and fail.
245
r = requests.get(url, auth=wrong_auth)
246
self.assertEqual(r.status_code, 401)
248
s = requests.session()
250
# Should use netrc and work.
252
self.assertEqual(r.status_code, 200)
254
# Given auth should override and fail.
257
self.assertEqual(r.status_code, 401)
203
259
def test_DIGEST_HTTP_200_OK_GET(self):
205
261
auth = HTTPDigestAuth('user', 'pass')
212
268
self.assertEqual(r.status_code, 401)
214
270
s = requests.session()
271
s.auth = HTTPDigestAuth('user', 'pass')
217
273
self.assertEqual(r.status_code, 200)
275
def test_DIGEST_AUTH_RETURNS_COOKIE(self):
276
url = httpbin('digest-auth', 'auth', 'user', 'pass')
277
auth = HTTPDigestAuth('user', 'pass')
278
r = requests.get(url)
279
assert r.cookies['fake'] == 'fake_value'
281
r = requests.get(url, auth=auth)
282
assert r.status_code == 200
284
def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self):
285
url = httpbin('digest-auth', 'auth', 'user', 'pass')
286
auth = HTTPDigestAuth('user', 'pass')
287
s = requests.Session()
288
s.get(url, auth=auth)
289
assert s.cookies['fake'] == 'fake_value'
219
291
def test_DIGEST_STREAM(self):
221
293
auth = HTTPDigestAuth('user', 'pass')
284
356
except ValueError:
359
def test_conflicting_post_params(self):
360
url = httpbin('post')
361
with open('requirements.txt') as f:
362
pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")
363
pytest.raises(ValueError, "requests.post(url, data=u'[{\"some\": \"data\"}]', files={'some': f})")
287
365
def test_request_ok_set(self):
288
366
r = requests.get(httpbin('status', '404'))
289
367
self.assertEqual(r.ok, False)
380
458
prep = req.prepare()
382
460
s = requests.Session()
461
s.proxies = getproxies()
383
462
resp = s.send(prep)
385
464
self.assertTrue(hasattr(resp, 'hook_working'))
466
def test_prepared_from_session(self):
467
class DummyAuth(requests.auth.AuthBase):
468
def __call__(self, r):
469
r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'
472
req = requests.Request('GET', httpbin('headers'))
473
self.assertEqual(req.auth, None)
475
s = requests.Session()
478
prep = s.prepare_request(req)
481
self.assertTrue(resp.json()['headers']['Dummy-Auth-Test'], 'dummy-auth-test-ok')
387
483
def test_links(self):
388
484
r = requests.Response()
482
579
s.headers.update({'accept': 'application/json'})
483
580
r = s.get(httpbin('get'))
484
581
headers = r.request.headers
485
# ASCII encode because of key comparison changes in py3
487
headers['accept'.encode('ascii')],
491
headers['Accept'.encode('ascii')],
495
headers['ACCEPT'.encode('ascii')],
595
def test_uppercase_scheme_redirect(self):
596
parts = urlparse(httpbin('html'))
597
url = "HTTP://" + parts.netloc + parts.path
598
r = requests.get(httpbin('redirect-to'), params={'url': url})
599
self.assertEqual(r.status_code, 200)
600
self.assertEqual(r.url.lower(), url.lower())
499
602
def test_transport_adapter_ordering(self):
500
603
s = requests.Session()
557
660
r = requests.Request('GET', url).prepare()
558
661
self.assertEqual(r.url, url)
663
def test_header_keys_are_native(self):
664
headers = {u'unicode': 'blah', 'byte'.encode('ascii'): 'blah'}
665
r = requests.Request('GET', httpbin('get'), headers=headers)
668
# This is testing that they are builtin strings. A bit weird, but there
670
self.assertTrue('unicode' in p.headers.keys())
671
self.assertTrue('byte' in p.headers.keys())
673
def test_can_send_nonstring_objects_with_files(self):
676
r = requests.Request('POST', httpbin('post'), data=data, files=files)
679
self.assertTrue('multipart/form-data' in p.headers['Content-Type'])
682
class TestContentEncodingDetection(unittest.TestCase):
685
encodings = requests.utils.get_encodings_from_content('')
686
self.assertEqual(len(encodings), 0)
688
def test_html_charset(self):
689
"""HTML5 meta charset attribute"""
690
content = '<meta charset="UTF-8">'
691
encodings = requests.utils.get_encodings_from_content(content)
692
self.assertEqual(len(encodings), 1)
693
self.assertEqual(encodings[0], 'UTF-8')
695
def test_html4_pragma(self):
696
"""HTML4 pragma directive"""
697
content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">'
698
encodings = requests.utils.get_encodings_from_content(content)
699
self.assertEqual(len(encodings), 1)
700
self.assertEqual(encodings[0], 'UTF-8')
702
def test_xhtml_pragma(self):
703
"""XHTML 1.x served with text/html MIME type"""
704
content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />'
705
encodings = requests.utils.get_encodings_from_content(content)
706
self.assertEqual(len(encodings), 1)
707
self.assertEqual(encodings[0], 'UTF-8')
710
"""XHTML 1.x served as XML"""
711
content = '<?xml version="1.0" encoding="UTF-8"?>'
712
encodings = requests.utils.get_encodings_from_content(content)
713
self.assertEqual(len(encodings), 1)
714
self.assertEqual(encodings[0], 'UTF-8')
716
def test_precedence(self):
718
<?xml version="1.0" encoding="XML"?>
719
<meta charset="HTML5">
720
<meta http-equiv="Content-type" content="text/html;charset=HTML4" />
722
encodings = requests.utils.get_encodings_from_content(content)
723
self.assertEqual(encodings, ['HTML5', 'HTML4', 'XML'])
561
726
class TestCaseInsensitiveDict(unittest.TestCase):