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
move tests overKenneth Reitzbefore adoption0b9a2a1
lines 1–6why, one step back1#!/usr/bin/env python2# -*- coding: utf-8 -*-34# from __future__ import unicode_literals56# Path hack.test cleanupsKenneth Reitzbefore adoptiond806ffc
lines 7–8why, one step back7import sys8import osmove tests overKenneth Reitzbefore adoption0b9a2a1
lines 9–13why, one step back9sys.path.insert(0, os.path.abspath('..'))1011import json12import os13import unittestImplemented #439. Added supporting test.Shrikant Sharatbefore adoption590ce29
line 14why, one step back14import picklemove tests overKenneth Reitzbefore adoption0b9a2a1
lines 15–16why, one step back1516import requeststest cleanupsKenneth Reitzbefore adoptiond806ffc
line 17why, one step back17from requests.compat import str, StringIOmove tests overKenneth Reitzbefore adoption0b9a2a1
lines 18–22why, one step back18# import envoy19from requests import HTTPError20from requests import get, post, head, put21from requests.auth import HTTPBasicAuth, HTTPDigestAuth22simplify httpbin stuffKenneth Reitzbefore adoptiond974b46
line 23why, one step back23if 'HTTPBIN_URL' not in os.environ:move tests overKenneth Reitzbefore adoption0b9a2a1
lines 24–25why, one step back24 os.environ['HTTPBIN_URL'] = 'http://httpbin.org/'25simplify httpbin stuffKenneth Reitzbefore adoptiond974b46
line 26why, one step back26HTTPBIN_URL = os.environ.get('HTTPBIN_URL')move tests overKenneth Reitzbefore adoption0b9a2a1
lines 27–37why, one step back272829def httpbin(*suffix):30 """Returns url for HTTPBIN resource."""31 return HTTPBIN_URL + '/'.join(suffix)323334SERVICES = (httpbin, )3536_httpbin = False37test cleanupsKenneth Reitzbefore adoptiond806ffc
line 38why, one step back38move tests overKenneth Reitzbefore adoption0b9a2a1
lines 39–53why, one step back39class 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 = True53Merge pull request #565 from slingamn/cookiejarKenneth Reitzbefore adoption45be14e
line 54why, one step back54class TestBaseMixin(object):move tests overKenneth Reitzbefore adoption0b9a2a1
line 55why, one step back55Merge pull request #565 from slingamn/cookiejarKenneth Reitzbefore adoption45be14e
lines 56–62why, one step back56 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):move tests overKenneth Reitzbefore adoption0b9a2a1
lines 63–81why, one step back63 """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")81default encode_uri to TrueKenneth Reitzbefore adoption658d609
line 82why, one step back82 self.assertEqual(request.path_url, "/get/test%20case")move tests overKenneth Reitzbefore adoption0b9a2a1
lines 83–84why, one step back8384 def test_HTTP_200_OK_GET(self):Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoptionccd19c5
line 85why, one step back85 r = get(httpbin('get'))move tests overKenneth Reitzbefore adoption0b9a2a1
lines 86–88why, one step back86 self.assertEqual(r.status_code, 200)8788 def test_response_sent(self):Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoptionccd19c5
line 89why, one step back89 r = get(httpbin('get'))move tests overKenneth Reitzbefore adoption0b9a2a1
lines 90–125why, one step back9091 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)125Revert "Reenable test_session_with_escaped_url test"Kenneth Reitzbefore adoption3843a40
lines 126–136why, one step back126 # 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))move tests overKenneth Reitzbefore adoption0b9a2a1
line 137why, one step back137Revert "Reenable test_session_with_escaped_url test"Kenneth Reitzbefore adoption3843a40
lines 138–145why, one step back138 # # 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))move tests overKenneth Reitzbefore adoption0b9a2a1
line 146why, one step back146Revert "Reenable test_session_with_escaped_url test"Kenneth Reitzbefore adoption3843a40
lines 147–159why, one step back147 # # 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))move tests overKenneth Reitzbefore adoption0b9a2a1
line 160why, one step back160Revert "Reenable test_session_with_escaped_url test"Kenneth Reitzbefore adoption3843a40
lines 161–167why, one step back161 # # 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))move tests overKenneth Reitzbefore adoption0b9a2a1
line 168why, one step back168Revert "Reenable test_session_with_escaped_url test"Kenneth Reitzbefore adoption3843a40
lines 169–173why, one step back169 # # 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))move tests overKenneth Reitzbefore adoption0b9a2a1
line 174why, one step back174Revert "Reenable test_session_with_escaped_url test"Kenneth Reitzbefore adoption3843a40
lines 175–178why, one step back175 # 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))move tests overKenneth Reitzbefore adoption0b9a2a1
line 179why, one step back179Revert "Reenable test_session_with_escaped_url test"Kenneth Reitzbefore adoption3843a40
lines 180–184why, one step back180 # # 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))move tests overKenneth Reitzbefore adoption0b9a2a1
line 185why, one step back185Revert "Reenable test_session_with_escaped_url test"Kenneth Reitzbefore adoption3843a40
lines 186–190why, one step back186 # 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))Merge pull request #535 from Jonty/developKenneth Reitzbefore adoption8a055c5
line 191why, one step back191move tests overKenneth Reitzbefore adoption0b9a2a1
lines 192–199why, one step back192 def test_user_agent_transfers(self):193 """Issue XX"""194195 heads = {196 'User-agent':197 'Mozilla/5.0 (github.com/kennethreitz/requests)'198 }199test cleanupsKenneth Reitzbefore adoptiond806ffc
line 200why, one step back200 r = get(httpbin('user-agent'), headers=heads)move tests overKenneth Reitzbefore adoption0b9a2a1
lines 201–207why, one step back201 self.assertTrue(heads['User-agent'] in r.text)202203 heads = {204 'user-agent':205 'Mozilla/5.0 (github.com/kennethreitz/requests)'206 }207test cleanupsKenneth Reitzbefore adoptiond806ffc
line 208why, one step back208 r = get(httpbin('user-agent'), headers=heads)move tests overKenneth Reitzbefore adoption0b9a2a1
lines 209–211why, one step back209 self.assertTrue(heads['user-agent'] in r.text)210211 def test_HTTP_200_OK_HEAD(self):Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoptionccd19c5
line 212why, one step back212 r = head(httpbin('get'))move tests overKenneth Reitzbefore adoption0b9a2a1
lines 213–273why, one step back213 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)273Merge branch 'develop' of https://github.com/catwell/requests into developKenneth Reitzbefore adoptione3ba495
lines 274–287why, one step back274 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)287move tests overKenneth Reitzbefore adoption0b9a2a1
lines 288–297why, one step back288 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)297__file__Kenneth Reitzbefore adoptionfdbb53d
line 298why, one step back298 with open(__file__) as f:move tests overKenneth Reitzbefore adoption0b9a2a1
lines 299–308why, one step back299 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:308__file__Kenneth Reitzbefore adoptionfdbb53d
line 309why, one step back309 with open(__file__) as f:move tests overKenneth Reitzbefore adoption0b9a2a1
lines 310–322why, one step back310 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')322__file__Kenneth Reitzbefore adoptionfdbb53d
line 323why, one step back323 with open(__file__) as f:move tests overKenneth Reitzbefore adoption0b9a2a1
lines 324–326why, one step back324325 post2 = post(url,326 files={'some': f},__file__Kenneth Reitzbefore adoptionfdbb53d
line 327why, one step back327 headers={'User-Agent': 'requests-tests'})move tests overKenneth Reitzbefore adoption0b9a2a1
lines 328–444why, one step back328329 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)test cleanupsKenneth Reitzbefore adoptiond806ffc
line 445why, one step back445 self.assertEqual(rbody.get('form'), {}) # No form suppliedmove tests overKenneth Reitzbefore adoption0b9a2a1
lines 446–482why, one step back446 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:482test cleanupsKenneth Reitzbefore adoptiond806ffc
line 483why, one step back483 r = get(service('get'), params=dict(test=['foo', 'baz']))move tests overKenneth Reitzbefore adoption0b9a2a1
lines 484–490why, one step back484 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:490test cleanupsKenneth Reitzbefore adoptiond806ffc
line 491why, one step back491 r = post(service('post'), params=dict(test=['foo', 'baz']))move tests overKenneth Reitzbefore adoption0b9a2a1
lines 492–496why, one step back492 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)test cleanupsKenneth Reitzbefore adoptiond806ffc
line 497why, one step back497 self.assertEqual(rbody.get('form'), {}) # No form suppliedmove tests overKenneth Reitzbefore adoption0b9a2a1
lines 498–505why, one step back498 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'),test cleanupsKenneth Reitzbefore adoptiond806ffc
lines 506–507why, one step back506 params=dict(test=['foo', 'baz']),507 data=dict(test2="foobar", test3=['foo', 'baz']))move tests overKenneth Reitzbefore adoption0b9a2a1
lines 508–516why, one step back508509 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)test cleanupsKenneth Reitzbefore adoptiond806ffc
line 517why, one step back517 self.assertEqual(rbody.get('form'), dict(test2='foobar', test3=['foo', 'baz']))move tests overKenneth Reitzbefore adoption0b9a2a1
lines 518–554why, one step back518 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()Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoptionccd19c5
line 555why, one step back555 r = get(httpbin('get'), session=s)move tests overKenneth Reitzbefore adoption0b9a2a1
lines 556–591why, one step back556 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')test cleanupsKenneth Reitzbefore adoptiond806ffc
line 592why, one step back592 response = get(url=url, hooks={'args': add_foo_header})move tests overKenneth Reitzbefore adoption0b9a2a1
lines 593–620why, one step back593594 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')620test cleanupsKenneth Reitzbefore adoptiond806ffc
lines 621–622why, one step back621 response = get(url=url,622 hooks={move tests overKenneth Reitzbefore adoption0b9a2a1
lines 623–640why, one step back623 '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')Merge pull request #565 from slingamn/cookiejarKenneth Reitzbefore adoption45be14e
line 641why, one step back641 self.assertEqual(c, _c)move tests overKenneth Reitzbefore adoption0b9a2a1
lines 642–645why, one step back642643 # Double check.644 r = get(httpbin('cookies'), cookies={}, session=s)645 c = json.loads(r.text).get('cookies')Merge pull request #565 from slingamn/cookiejarKenneth Reitzbefore adoption45be14e
line 646why, one step back646 self.assertEqual(c, _c)move tests overKenneth Reitzbefore adoption0b9a2a1
lines 647–651why, one step back647648 # 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']Merge pull request #565 from slingamn/cookiejarKenneth Reitzbefore adoption45be14e
line 652why, one step back652 self.assertEqual(c, _c)move tests overKenneth Reitzbefore adoption0b9a2a1
lines 653–657why, one step back653654 # 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')Merge pull request #565 from slingamn/cookiejarKenneth Reitzbefore adoption45be14e
line 658why, one step back658 self.assertEqual(c, _c)move tests overKenneth Reitzbefore adoption0b9a2a1
lines 659–695why, one step back659660 # 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.textImplemented #439. Added supporting test.Shrikant Sharatbefore adoption590ce29
lines 696–707why, one step back696697 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)Merge pull request #565 from slingamn/cookiejarKenneth Reitzbefore adoption45be14e
lines 708–712why, one step back708709 # 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')move tests overKenneth Reitzbefore adoption0b9a2a1
line 713why, one step back713Merge pull request #550 from reclosedev/developKenneth Reitzbefore adoption2f6b5fe
lines 714–729why, one step back714 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.prefetch729move tests overKenneth Reitzbefore adoption0b9a2a1
lines 730–767why, one step back730 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)767Merge branch 'iter_lines-fix' of https://github.com/fawek/requests into developKenneth Reitzbefore adoptionc7f165a
lines 768–769why, one step back768 # Tests that trailing whitespaces within lines do not get stripped.769 # Tests that a trailing non-terminated line does not get stripped.move tests overKenneth Reitzbefore adoption0b9a2a1
line 770why, one step back770 quote = (Merge branch 'iter_lines-fix' of https://github.com/fawek/requests into developKenneth Reitzbefore adoptionc7f165a
lines 771–773why, one step back771 '''Agamemnon \n'''772 '''\tWhy will he not upon our fair request\r\n'''773 '''\tUntent his person and share the air with us?'''move tests overKenneth Reitzbefore adoption0b9a2a1
lines 774–779why, one step back774 )775776 # Make a request and monkey-patch its contents777 r = get(httpbin('get'))778 r.raw = StringIO(quote)779Merge branch 'iter_lines-fix' of https://github.com/fawek/requests into developKenneth Reitzbefore adoptionc7f165a
lines 780–785why, one step back780 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)move tests overKenneth Reitzbefore adoption0b9a2a1
lines 786–814why, one step back786787 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):814test cleanupsKenneth Reitzbefore adoptiond806ffc
line 815why, one step back815 requests.get(httpbin('post'), auth=('a', 'b'), data='\xff')move tests overKenneth Reitzbefore adoption0b9a2a1
line 816why, one step back816Merge pull request #548 from umbrae/httperror_fixKenneth Reitzbefore adoptiond4a77cf
lines 817–823why, one step back817 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')823Merge branch 'issue_380' of https://github.com/Lukasa/requests into developKenneth Reitzbefore adoption5f83471
line 824why, one step back824 def test_useful_exception_for_invalid_scheme(self):test cleanupsKenneth Reitzbefore adoptiond806ffc
lines 825–826why, one step back825826 # If we pass a legitimate URL with a scheme not supportedMerge branch 'issue_380' of https://github.com/Lukasa/requests into developKenneth Reitzbefore adoption5f83471
lines 827–831why, one step back827 # by requests, we should fail.828 self.assertRaises(829 ValueError,830 get,831 'ftp://ftp.kernel.org/pub/')move tests overKenneth Reitzbefore adoption0b9a2a1
line 832why, one step back832none headers testKenneth Reitzbefore adoption80fe5dc
lines 833–839why, one step back833 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()839danger_mode redirect testKenneth Reitzbefore adoptionb355b67
lines 840–845why, one step back840 def test_danger_mode_redirects(self):841 s = requests.session()842 s.config['danger_mode'] = True843 s.get(httpbin('redirect', '4'))844845Fix content-length: 0Kenneth Reitzbefore adoptionea1d5f3
lines 846–849why, one step back846 def test_empty_response(self):847 r = requests.get(httpbin('status', '404'))848 r.text849Merge pull request #577 from slingamn/redirects_537Kenneth Reitzbefore adoption317f64a
line 850why, one step back850 def test_max_redirects(self):test for #458Shivaram Lingamnenibefore adoption3d4d5ab
line 851why, one step back851 """Test the max_redirects config variable, normally and under safe_mode."""Merge pull request #577 from slingamn/redirects_537Kenneth Reitzbefore adoption317f64a
line 852why, one step back852 def unsafe_callable():test for #458Shivaram Lingamnenibefore adoption3d4d5ab
line 853why, one step back853 requests.get(httpbin('redirect', '3'), config=dict(max_redirects=2))Merge pull request #577 from slingamn/redirects_537Kenneth Reitzbefore adoption317f64a
lines 854–856why, one step back854 self.assertRaises(requests.exceptions.TooManyRedirects, unsafe_callable)855856 # add safe modetest for #458Shivaram Lingamnenibefore adoption3d4d5ab
line 857why, one step back857 response = requests.get(httpbin('redirect', '3'), config=dict(safe_mode=True, max_redirects=2))Merge pull request #577 from slingamn/redirects_537Kenneth Reitzbefore adoption317f64a
lines 858–859why, one step back858 self.assertTrue(response.content is None)859 self.assertTrue(isinstance(response.error, requests.exceptions.TooManyRedirects))test for #458Shivaram Lingamnenibefore adoption3d4d5ab
lines 860–872why, one step back860861 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')Merge pull request #577 from slingamn/redirects_537Kenneth Reitzbefore adoption317f64a
line 873why, one step back873move tests overKenneth Reitzbefore adoption0b9a2a1
lines 874–875why, one step back874if __name__ == '__main__':875 unittest.main()