test_requests.py
This file
Path
tests/test_requests.py
875 lines · 27.6 KiB · Python
Last changed by
test for #458Shivaram Lingamnenibefore adoption3d4d5ab
History of this fileTake it
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34# from __future__ import unicode_literals56# Path hack.7import sys8import os9sys.path.insert(0, os.path.abspath('..'))1011import json12import os13import unittest14import pickle1516import requests17from requests.compat import str, StringIO18# import envoy19from requests import HTTPError20from requests import get, post, head, put21from requests.auth import HTTPBasicAuth, HTTPDigestAuth2223if 'HTTPBIN_URL' not in os.environ:24 os.environ['HTTPBIN_URL'] = 'http://httpbin.org/'2526HTTPBIN_URL = os.environ.get('HTTPBIN_URL')272829def httpbin(*suffix):30 """Returns url for HTTPBIN resource."""31 return HTTPBIN_URL + '/'.join(suffix)323334SERVICES = (httpbin, )3536_httpbin = False373839class TestSetup(object):40 """Requests test cases."""4142 # It goes to eleven.43 _multiprocess_can_split_ = True4445 def setUp(self):4647 global _httpbin4849 if (not 'HTTPBIN_URL' in os.environ) and not _httpbin:50 # c = envoy.connect('httpbin %s' % (PORT))51 # time.sleep(1)52 _httpbin = True5354class TestBaseMixin(object):5556 def assertCookieHas(self, cookie, **kwargs):57 """Assert that a cookie has various specified properties."""58 for attr, expected_value in kwargs.items():59 message = 'Failed comparison for %s' % (attr,)60 self.assertEqual(getattr(cookie, attr), expected_value, message)6162class RequestsTestSuite(TestSetup, TestBaseMixin, unittest.TestCase):63 """Requests test cases."""6465 def test_entry_points(self):6667 requests.session68 requests.session().get69 requests.session().head70 requests.get71 requests.head72 requests.put73 requests.patch74 requests.post7576 def test_invalid_url(self):77 self.assertRaises(ValueError, get, 'hiwpefhipowhefopw')7879 def test_path_is_not_double_encoded(self):80 request = requests.Request("http://0.0.0.0/get/test case")8182 self.assertEqual(request.path_url, "/get/test%20case")8384 def test_HTTP_200_OK_GET(self):85 r = get(httpbin('get'))86 self.assertEqual(r.status_code, 200)8788 def test_response_sent(self):89 r = get(httpbin('get'))9091 self.assertTrue(r.request.sent)9293 def test_HTTP_302_ALLOW_REDIRECT_GET(self):94 r = get(httpbin('redirect', '1'))95 self.assertEqual(r.status_code, 200)9697 def test_HTTP_302_GET(self):98 r = get(httpbin('redirect', '1'), allow_redirects=False)99 self.assertEqual(r.status_code, 302)100101 def test_HTTP_200_OK_GET_WITH_PARAMS(self):102 heads = {'User-agent': 'Mozilla/5.0'}103104 r = get(httpbin('user-agent'), headers=heads)105106 assert heads['User-agent'] in r.text107 self.assertEqual(r.status_code, 200)108109 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):110 heads = {'User-agent': 'Mozilla/5.0'}111112 r = get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)113 self.assertEqual(r.status_code, 200)114115 # def test_unicode_headers(self):116 # # Simply calling requests with a unicode instance should simply work117 # # when the characters are all representable using latin-1:118 # heads = { u'User-Agent': u'Requests Test Suite' }119 # requests.get(url=httpbin('get'), headers=heads)120121 # # Characters outside latin-1 should raise an exception:122 # heads = { u'User-Agent': u'\u30cd\u30c3\u30c8\u30ef\u30fc\u30af' }123 # self.assertRaises(UnicodeEncodeError, requests.get,124 # url=httpbin('get'), headers=heads)125126 # def test_session_with_escaped_url(self):127 # # Test a URL that contains percent-escaped characters128 # # This URL should not be modified (double-escaped)129 # # Tests:130 # # - Quoted illegal characters ("%20" (' '), "%3C" ('<'), "%3E" ('>'))131 # # - Quoted reserved characters ("%25" ('%'), "%23" ('#'), "%2F" ('/'))132 # # - Quoted non-ASCII characters ("%C3%98", "%C3%A5")133 # path_fully_escaped = '%3Ca%25b%23c%2Fd%3E/%C3%98%20%C3%A5'134 # url = httpbin('get/' + path_fully_escaped)135 # response = get(url)136 # self.assertEqual(response.url, httpbin('get/' + path_fully_escaped))137138 # # Test that illegal characters in a path get properly percent-escaped139 # # Tests:140 # # - Bare illegal characters (space, '<')141 # # - Bare non-ASCII characters ('\u00d8')142 # path = u'<a%25b%23c%2Fd%3E/\u00d8 %C3%A5'143 # url = httpbin('get/' + path)144 # response = get(url)145 # self.assertEqual(response.url, httpbin('get/' + path_fully_escaped))146147 # # Test that reserved characters in a path do not get percent-escaped148 # # Tests:149 # # - All reserved characters (RFC 3986), except '?', '#', '[' and ']',150 # # which are not allowed in the path, and ';' which delimits151 # # parameters.152 # # All such characters must be allowed bare in path, and must not be153 # # encoded.154 # # - Special unreserved characters (RFC 3986), which should not be155 # # encoded (even though it wouldn't hurt).156 # path_reserved = '!$&\'()*+,/:=@-._~'157 # url = httpbin('get/' + path_reserved)158 # response = get(url)159 # self.assertEqual(response.url, httpbin('get/' + path_reserved))160161 # # Test that percent-encoded unreserved characters in a path get162 # # normalised to their un-encoded forms.163 # path_unreserved = 'ABCDwxyz1234-._~'164 # path_unreserved_escaped = '%41%42%43%44%77%78%79%7A%31%32%33%34%2D%2E%5F%7E'165 # url = httpbin('get/' + path_unreserved_escaped)166 # response = get(url)167 # self.assertEqual(response.url, httpbin('get/' + path_unreserved))168169 # # Re-run all of the same tests on the query part of the URI170 # query_fully_escaped = '%3Ca%25b%23c%2Fd%3E=%C3%98%20%C3%A5'171 # url = httpbin('get/?' + query_fully_escaped)172 # response = get(url)173 # self.assertEqual(response.url, httpbin('get/?' + query_fully_escaped))174175 # query = u'<a%25b%23c%2Fd%3E=\u00d8 %C3%A5'176 # url = httpbin('get/?' + query)177 # response = get(url)178 # self.assertEqual(response.url, httpbin('get/?' + query_fully_escaped))179180 # # The legal characters in query happens to be the same as in path181 # query_reserved = '!$&\'()*+,/:=@-._~'182 # url = httpbin('get/?' + query_reserved)183 # response = get(url)184 # self.assertEqual(response.url, httpbin('get/?' + query_reserved))185186 # query_unreserved = 'ABCDwxyz=1234-._~'187 # query_unreserved_escaped = '%41%42%43%44%77%78%79%7A=%31%32%33%34%2D%2E%5F%7E'188 # url = httpbin('get/?' + query_unreserved_escaped)189 # response = get(url)190 # self.assertEqual(response.url, httpbin('get/?' + query_unreserved))191192 def test_user_agent_transfers(self):193 """Issue XX"""194195 heads = {196 'User-agent':197 'Mozilla/5.0 (github.com/kennethreitz/requests)'198 }199200 r = get(httpbin('user-agent'), headers=heads)201 self.assertTrue(heads['User-agent'] in r.text)202203 heads = {204 'user-agent':205 'Mozilla/5.0 (github.com/kennethreitz/requests)'206 }207208 r = get(httpbin('user-agent'), headers=heads)209 self.assertTrue(heads['user-agent'] in r.text)210211 def test_HTTP_200_OK_HEAD(self):212 r = head(httpbin('get'))213 self.assertEqual(r.status_code, 200)214215 def test_HTTP_200_OK_PUT(self):216 r = put(httpbin('put'))217 self.assertEqual(r.status_code, 200)218219 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):220221 for service in SERVICES:222223 auth = ('user', 'pass')224 url = service('basic-auth', 'user', 'pass')225226 r = get(url, auth=auth)227 self.assertEqual(r.status_code, 200)228229 r = get(url)230 self.assertEqual(r.status_code, 401)231232 s = requests.session(auth=auth)233 r = get(url, session=s)234 self.assertEqual(r.status_code, 200)235236 def test_BASICAUTH_HTTP_200_OK_GET(self):237238 for service in SERVICES:239240 auth = HTTPBasicAuth('user', 'pass')241 url = service('basic-auth', 'user', 'pass')242243 r = get(url, auth=auth)244 self.assertEqual(r.status_code, 200)245246 auth = ('user', 'pass')247 r = get(url, auth=auth)248 self.assertEqual(r.status_code, 200)249250 r = get(url)251 self.assertEqual(r.status_code, 401)252253 s = requests.session(auth=auth)254 r = get(url, session=s)255 self.assertEqual(r.status_code, 200)256257 def test_DIGESTAUTH_HTTP_200_OK_GET(self):258259 for service in SERVICES:260261 auth = HTTPDigestAuth('user', 'pass')262 url = service('digest-auth', 'auth', 'user', 'pass')263264 r = get(url, auth=auth)265 self.assertEqual(r.status_code, 200)266267 r = get(url)268 self.assertEqual(r.status_code, 401)269270 s = requests.session(auth=auth)271 r = get(url, session=s)272 self.assertEqual(r.status_code, 200)273274 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self):275276 for service in SERVICES:277278 auth = HTTPDigestAuth('user', 'wrongpass')279 url = service('digest-auth', 'auth', 'user', 'pass')280281 r = get(url, auth=auth)282 self.assertEqual(r.status_code, 401)283284 s = requests.session(auth=auth)285 r = get(url, session=s)286 self.assertEqual(r.status_code, 401)287288 def test_POSTBIN_GET_POST_FILES(self):289290 for service in SERVICES:291292 url = service('post')293 post1 = post(url).raise_for_status()294295 post1 = post(url, data={'some': 'data'})296 self.assertEqual(post1.status_code, 200)297298 with open(__file__) as f:299 post2 = post(url, files={'some': f})300 self.assertEqual(post2.status_code, 200)301302 post3 = post(url, data='[{"some": "json"}]')303 self.assertEqual(post3.status_code, 200)304305 def test_POSTBIN_GET_POST_FILES_WITH_PARAMS(self):306307 for service in SERVICES:308309 with open(__file__) as f:310 url = service('post')311 post1 = post(url,312 files={'some': f},313 data={'some': 'data'})314315 self.assertEqual(post1.status_code, 200)316317 def test_POSTBIN_GET_POST_FILES_WITH_HEADERS(self):318319 for service in SERVICES:320321 url = service('post')322323 with open(__file__) as f:324325 post2 = post(url,326 files={'some': f},327 headers={'User-Agent': 'requests-tests'})328329 self.assertEqual(post2.status_code, 200)330331 def test_nonzero_evaluation(self):332333 for service in SERVICES:334335 r = get(service('status', '500'))336 self.assertEqual(bool(r), False)337338 r = get(service('/get'))339 self.assertEqual(bool(r), True)340341 def test_request_ok_set(self):342343 for service in SERVICES:344345 r = get(service('status', '404'))346 # print r.status_code347 # r.raise_for_status()348 self.assertEqual(r.ok, False)349350 def test_status_raising(self):351 r = get(httpbin('status', '404'))352 self.assertRaises(HTTPError, r.raise_for_status)353354 r = get(httpbin('status', '200'))355 self.assertFalse(r.error)356 r.raise_for_status()357358 def test_default_status_raising(self):359 config = {'danger_mode': True}360 args = [httpbin('status', '404')]361 kwargs = dict(config=config)362 self.assertRaises(HTTPError, get, *args, **kwargs)363364 r = get(httpbin('status', '200'))365 self.assertEqual(r.status_code, 200)366367 def test_decompress_gzip(self):368369 r = get(httpbin('gzip'))370 r.content.decode('ascii')371372 def test_response_has_unicode_url(self):373374 for service in SERVICES:375376 url = service('get')377378 response = get(url)379380 assert isinstance(response.url, str)381382 def test_unicode_get(self):383384 for service in SERVICES:385386 url = service('/get')387388 get(url, params={'foo': 'føø'})389 get(url, params={'føø': 'føø'})390 get(url, params={'føø': 'føø'})391 get(url, params={'foo': 'foo'})392 get(service('ø'), params={'foo': 'foo'})393394 def test_httpauth_recursion(self):395396 http_auth = HTTPBasicAuth('user', 'BADpass')397398 for service in SERVICES:399 r = get(service('basic-auth', 'user', 'pass'), auth=http_auth)400 self.assertEqual(r.status_code, 401)401402 def test_urlencoded_post_data(self):403404 for service in SERVICES:405406 r = post(service('post'), data=dict(test='fooaowpeuf'))407408 self.assertEqual(r.status_code, 200)409 self.assertEqual(r.headers['content-type'], 'application/json')410 self.assertEqual(r.url, service('post'))411412 rbody = json.loads(r.text)413414 self.assertEqual(rbody.get('form'), dict(test='fooaowpeuf'))415 self.assertEqual(rbody.get('data'), '')416417 def test_nonurlencoded_post_data(self):418419 for service in SERVICES:420421 r = post(service('post'), data='fooaowpeuf')422423 self.assertEqual(r.status_code, 200)424 self.assertEqual(r.headers['content-type'], 'application/json')425 self.assertEqual(r.url, service('post'))426427 rbody = json.loads(r.text)428 # Body wasn't valid url encoded data, so the server returns None as429 # "form" and the raw body as "data".430431 assert rbody.get('form') in (None, {})432 self.assertEqual(rbody.get('data'), 'fooaowpeuf')433434 def test_urlencoded_post_querystring(self):435436 for service in SERVICES:437438 r = post(service('post'), params=dict(test='fooaowpeuf'))439440 self.assertEqual(r.status_code, 200)441 self.assertEqual(r.headers['content-type'], 'application/json')442 self.assertEqual(r.url, service('post?test=fooaowpeuf'))443444 rbody = json.loads(r.text)445 self.assertEqual(rbody.get('form'), {}) # No form supplied446 self.assertEqual(rbody.get('data'), '')447448 def test_urlencoded_post_query_and_data(self):449450 for service in SERVICES:451452 r = post(453 service('post'),454 params=dict(test='fooaowpeuf'),455 data=dict(test2="foobar"))456457 self.assertEqual(r.status_code, 200)458 self.assertEqual(r.headers['content-type'], 'application/json')459 self.assertEqual(r.url, service('post?test=fooaowpeuf'))460461 rbody = json.loads(r.text)462 self.assertEqual(rbody.get('form'), dict(test2='foobar'))463 self.assertEqual(rbody.get('data'), '')464465 def test_nonurlencoded_postdata(self):466467 for service in SERVICES:468469 r = post(service('post'), data="foobar")470471 self.assertEqual(r.status_code, 200)472 self.assertEqual(r.headers['content-type'], 'application/json')473474 rbody = json.loads(r.text)475476 assert rbody.get('form') in (None, {})477 self.assertEqual(rbody.get('data'), 'foobar')478479 def test_urlencoded_get_query_multivalued_param(self):480481 for service in SERVICES:482483 r = get(service('get'), params=dict(test=['foo', 'baz']))484 self.assertEqual(r.status_code, 200)485 self.assertEqual(r.url, service('get?test=foo&test=baz'))486487 def test_urlencoded_post_querystring_multivalued(self):488489 for service in SERVICES:490491 r = post(service('post'), params=dict(test=['foo', 'baz']))492 self.assertEqual(r.status_code, 200)493 self.assertEqual(r.headers['content-type'], 'application/json')494 self.assertEqual(r.url, service('post?test=foo&test=baz'))495496 rbody = json.loads(r.text)497 self.assertEqual(rbody.get('form'), {}) # No form supplied498 self.assertEqual(rbody.get('data'), '')499500 def test_urlencoded_post_query_multivalued_and_data(self):501502 for service in SERVICES:503504 r = post(505 service('post'),506 params=dict(test=['foo', 'baz']),507 data=dict(test2="foobar", test3=['foo', 'baz']))508509 self.assertEqual(r.status_code, 200)510 self.assertEqual(r.headers['content-type'], 'application/json')511 self.assertEqual(r.url, service('post?test=foo&test=baz'))512513 # print(r.text)514 # print('-----------------------')515516 rbody = json.loads(r.text)517 self.assertEqual(rbody.get('form'), dict(test2='foobar', test3=['foo', 'baz']))518 self.assertEqual(rbody.get('data'), '')519520 def test_GET_no_redirect(self):521522 for service in SERVICES:523524 r = get(service('redirect', '3'), allow_redirects=False)525 self.assertEqual(r.status_code, 302)526 self.assertEqual(len(r.history), 0)527528 def test_HEAD_no_redirect(self):529530 for service in SERVICES:531532 r = head(service('redirect', '3'), allow_redirects=False)533 self.assertEqual(r.status_code, 302)534 self.assertEqual(len(r.history), 0)535536 def test_redirect_history(self):537538 for service in SERVICES:539540 r = get(service('redirect', '3'))541 self.assertEqual(r.status_code, 200)542 self.assertEqual(len(r.history), 3)543544 def test_relative_redirect_history(self):545546 for service in SERVICES:547548 r = get(service('relative-redirect', '3'))549 self.assertEqual(r.status_code, 200)550 self.assertEqual(len(r.history), 3)551552 def test_session_HTTP_200_OK_GET(self):553554 s = requests.session()555 r = get(httpbin('get'), session=s)556 self.assertEqual(r.status_code, 200)557558 def test_session_persistent_headers(self):559560 heads = {'User-agent': 'Mozilla/5.0'}561562 s = requests.session()563 s.headers = heads564565 # Make 2 requests from Session object, should send header both times566 r1 = get(httpbin('user-agent'), session=s)567 assert heads['User-agent'] in r1.text568569 r2 = get(httpbin('user-agent'), session=s)570 assert heads['User-agent'] in r2.text571572 new_heads = {'User-agent': 'blah'}573 r3 = get(httpbin('user-agent'), headers=new_heads, session=s)574 assert new_heads['User-agent'] in r3.text575576 self.assertEqual(r2.status_code, 200)577578 def test_single_hook(self):579580 def add_foo_header(args):581 if not args.get('headers'):582 args['headers'] = {}583584 args['headers'].update({585 'X-Foo': 'foo'586 })587588 return args589590 for service in SERVICES:591 url = service('headers')592 response = get(url=url, hooks={'args': add_foo_header})593594 assert 'foo' in response.text595596 def test_multiple_hooks(self):597598 def add_foo_header(args):599 if not args.get('headers'):600 args['headers'] = {}601602 args['headers'].update({603 'X-Foo': 'foo'604 })605606 return args607608 def add_bar_header(args):609 if not args.get('headers'):610 args['headers'] = {}611612 args['headers'].update({613 'X-Bar': 'bar'614 })615616 return args617618 for service in SERVICES:619 url = service('headers')620621 response = get(url=url,622 hooks={623 'args': [add_foo_header, add_bar_header]624 }625 )626627 assert 'foo' in response.text628 assert 'bar' in response.text629630 def test_session_persistent_cookies(self):631632 s = requests.session()633634 # Internally dispatched cookies are sent.635 _c = {'kenneth': 'reitz', 'bessie': 'monke'}636 r = get(httpbin('cookies'), cookies=_c, session=s)637 r = get(httpbin('cookies'), session=s)638639 # Those cookies persist transparently.640 c = json.loads(r.text).get('cookies')641 self.assertEqual(c, _c)642643 # Double check.644 r = get(httpbin('cookies'), cookies={}, session=s)645 c = json.loads(r.text).get('cookies')646 self.assertEqual(c, _c)647648 # Remove a cookie by setting it's value to None.649 r = get(httpbin('cookies'), cookies={'bessie': None}, session=s)650 c = json.loads(r.text).get('cookies')651 del _c['bessie']652 self.assertEqual(c, _c)653654 # Test session-level cookies.655 s = requests.session(cookies=_c)656 r = get(httpbin('cookies'), session=s)657 c = json.loads(r.text).get('cookies')658 self.assertEqual(c, _c)659660 # Have the server set a cookie.661 r = get(httpbin('cookies', 'set', 'k', 'v'), allow_redirects=True, session=s)662 c = json.loads(r.text).get('cookies')663664 assert 'k' in c665666 # And server-set cookie persistience.667 r = get(httpbin('cookies'), session=s)668 c = json.loads(r.text).get('cookies')669670 assert 'k' in c671672 def test_session_persistent_params(self):673674 params = {'a': 'a_test'}675676 s = requests.session()677 s.params = params678679 # Make 2 requests from Session object, should send header both times680 r1 = get(httpbin('get'), session=s)681 assert params['a'] in r1.text682683 params2 = {'b': 'b_test'}684685 r2 = get(httpbin('get'), params=params2, session=s)686 assert params['a'] in r2.text687 assert params2['b'] in r2.text688689 params3 = {'b': 'b_test', 'a': None, 'c': 'c_test'}690691 r3 = get(httpbin('get'), params=params3, session=s)692693 assert not params['a'] in r3.text694 assert params3['b'] in r3.text695 assert params3['c'] in r3.text696697 def test_session_pickling(self):698699 s = requests.session(700 headers={'header': 'value'},701 cookies={'a-cookie': 'cookie-value'},702 auth=('username', 'password'))703704 ds = pickle.loads(pickle.dumps(s))705706 self.assertEqual(s.headers, ds.headers)707 self.assertEqual(s.auth, ds.auth)708709 # Cookie doesn't have a good __eq__, so verify manually:710 self.assertEqual(len(ds.cookies), 1)711 for cookie in ds.cookies:712 self.assertCookieHas(cookie, name='a-cookie', value='cookie-value')713714 def test_unpickled_session_requests(self):715 s = requests.session()716 r = get(httpbin('cookies', 'set', 'k', 'v'), allow_redirects=True, session=s)717 c = json.loads(r.text).get('cookies')718 assert 'k' in c719720 ds = pickle.loads(pickle.dumps(s))721 r = get(httpbin('cookies'), session=ds)722 c = json.loads(r.text).get('cookies')723 assert 'k' in c724725 ds1 = pickle.loads(pickle.dumps(requests.session()))726 ds2 = pickle.loads(pickle.dumps(requests.session(prefetch=True)))727 assert not ds1.prefetch728 assert ds2.prefetch729730 def test_invalid_content(self):731 # WARNING: if you're using a terrible DNS provider (comcast),732 # this will fail.733 try:734 hah = 'http://somedomainthatclearlydoesntexistg.com'735 r = get(hah, allow_redirects=False)736 except requests.ConnectionError:737 pass # \o/738 else:739 assert False740741 config = {'safe_mode': True}742 r = get(hah, allow_redirects=False, config=config)743 assert r.content == None744745 def test_cached_response(self):746747 r1 = get(httpbin('get'), prefetch=False)748 assert not r1._content749 assert r1.content750 assert r1.text751752 r2 = get(httpbin('get'), prefetch=True)753 assert r2._content754 assert r2.content755 assert r2.text756757 def test_iter_lines(self):758759 lines = (0, 2, 10, 100)760761 for i in lines:762 r = get(httpbin('stream', str(i)), prefetch=False)763 lines = list(r.iter_lines())764 len_lines = len(lines)765766 self.assertEqual(i, len_lines)767768 # Tests that trailing whitespaces within lines do not get stripped.769 # Tests that a trailing non-terminated line does not get stripped.770 quote = (771 '''Agamemnon \n'''772 '''\tWhy will he not upon our fair request\r\n'''773 '''\tUntent his person and share the air with us?'''774 )775776 # Make a request and monkey-patch its contents777 r = get(httpbin('get'))778 r.raw = StringIO(quote)779780 lines = list(r.iter_lines())781 len_lines = len(lines)782 self.assertEqual(len_lines, 3)783784 joined = lines[0] + '\n' + lines[1] + '\r\n' + lines[2]785 self.assertEqual(joined, quote)786787 def test_safe_mode(self):788789 safe = requests.session(config=dict(safe_mode=True))790791 # Safe mode creates empty responses for failed requests.792 # Iterating on these responses should produce empty sequences793 r = get('http://_/', session=safe)794 self.assertEqual(list(r.iter_lines()), [])795 assert isinstance(r.error, requests.exceptions.ConnectionError)796797 r = get('http://_/', session=safe)798 self.assertEqual(list(r.iter_content()), [])799 assert isinstance(r.error, requests.exceptions.ConnectionError)800801 # When not in safe mode, should raise Timeout exception802 self.assertRaises(803 requests.exceptions.Timeout,804 get,805 httpbin('stream', '1000'), timeout=0.0001)806807 # In safe mode, should return a blank response808 r = get(httpbin('stream', '1000'), timeout=0.0001,809 config=dict(safe_mode=True))810 assert r.content is None811 assert isinstance(r.error, requests.exceptions.Timeout)812813 def test_upload_binary_data(self):814815 requests.get(httpbin('post'), auth=('a', 'b'), data='\xff')816817 def test_useful_exception_for_invalid_port(self):818 # If we pass a legitimate URL with an invalid port, we should fail.819 self.assertRaises(820 ValueError,821 get,822 'http://google.com:banana')823824 def test_useful_exception_for_invalid_scheme(self):825826 # If we pass a legitimate URL with a scheme not supported827 # by requests, we should fail.828 self.assertRaises(829 ValueError,830 get,831 'ftp://ftp.kernel.org/pub/')832833 def test_can_have_none_in_header_values(self):834 try:835 # Don't choke on headers with none in the value.836 requests.get(httpbin('headers'), headers={'Foo': None})837 except TypeError:838 self.fail()839840 def test_danger_mode_redirects(self):841 s = requests.session()842 s.config['danger_mode'] = True843 s.get(httpbin('redirect', '4'))844845846 def test_empty_response(self):847 r = requests.get(httpbin('status', '404'))848 r.text849850 def test_max_redirects(self):851 """Test the max_redirects config variable, normally and under safe_mode."""852 def unsafe_callable():853 requests.get(httpbin('redirect', '3'), config=dict(max_redirects=2))854 self.assertRaises(requests.exceptions.TooManyRedirects, unsafe_callable)855856 # add safe mode857 response = requests.get(httpbin('redirect', '3'), config=dict(safe_mode=True, max_redirects=2))858 self.assertTrue(response.content is None)859 self.assertTrue(isinstance(response.error, requests.exceptions.TooManyRedirects))860861 def test_connection_keepalive_and_close(self):862 """Test that we send 'Connection: close' when keep_alive is disabled."""863 # keep-alive should be on by default864 r1 = requests.get(httpbin('get'))865 # XXX due to proxying issues, test the header sent back by httpbin, rather than866 # the header reported in its message body. See kennethreitz/httpbin#46867 self.assertEqual(r1.headers['Connection'].lower(), 'keep-alive')868869 # but when we disable it, we should send a 'Connection: close'870 # and get the same back:871 r2 = requests.get(httpbin('get'), config=dict(keep_alive=False))872 self.assertEqual(r2.headers['Connection'].lower(), 'close')873874if __name__ == '__main__':875 unittest.main()