test_requests.py
This file
Path
tests/test_requests.py
956 lines · 30.5 KiB · Python
Last changed by
Merge pull request #690 from Lukasa/developKenneth Reitzbefore adoptionda35675
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 pickle15import tempfile1617import requests18from requests.compat import str, StringIO19# import envoy20from requests import HTTPError21from requests import get, post, head, put22from requests.auth import HTTPBasicAuth, HTTPDigestAuth2324if 'HTTPBIN_URL' not in os.environ:25 os.environ['HTTPBIN_URL'] = 'http://httpbin.org/'2627HTTPBIN_URL = os.environ.get('HTTPBIN_URL')282930def httpbin(*suffix):31 """Returns url for HTTPBIN resource."""32 return HTTPBIN_URL + '/'.join(suffix)333435SERVICES = (httpbin, )3637_httpbin = False383940class TestSetup(object):41 """Requests test cases."""4243 # It goes to eleven.44 _multiprocess_can_split_ = True4546 def setUp(self):4748 global _httpbin4950 if (not 'HTTPBIN_URL' in os.environ) and not _httpbin:51 # c = envoy.connect('httpbin %s' % (PORT))52 # time.sleep(1)53 _httpbin = True5455class TestBaseMixin(object):5657 def assertCookieHas(self, cookie, **kwargs):58 """Assert that a cookie has various specified properties."""59 for attr, expected_value in kwargs.items():60 cookie_attr = getattr(cookie, attr)61 message = 'Failed comparison for %s: %s != %s' % (attr, cookie_attr, expected_value)62 self.assertEqual(cookie_attr, expected_value, message)6364class RequestsTestSuite(TestSetup, TestBaseMixin, unittest.TestCase):65 """Requests test cases."""6667 def test_entry_points(self):6869 requests.session70 requests.session().get71 requests.session().head72 requests.get73 requests.head74 requests.put75 requests.patch76 requests.post7778 def test_invalid_url(self):79 self.assertRaises(ValueError, get, 'hiwpefhipowhefopw')8081 def test_path_is_not_double_encoded(self):82 request = requests.Request("http://0.0.0.0/get/test case")8384 self.assertEqual(request.path_url, "/get/test%20case")8586 def test_HTTP_200_OK_GET(self):87 r = get(httpbin('get'))88 self.assertEqual(r.status_code, 200)8990 def test_response_sent(self):91 r = get(httpbin('get'))9293 self.assertTrue(r.request.sent)9495 def test_HTTP_302_ALLOW_REDIRECT_GET(self):96 r = get(httpbin('redirect', '1'))97 self.assertEqual(r.status_code, 200)9899 def test_HTTP_302_GET(self):100 r = get(httpbin('redirect', '1'), allow_redirects=False)101 self.assertEqual(r.status_code, 302)102103 def test_HTTP_200_OK_GET_WITH_PARAMS(self):104 heads = {'User-agent': 'Mozilla/5.0'}105106 r = get(httpbin('user-agent'), headers=heads)107108 assert heads['User-agent'] in r.text109 self.assertEqual(r.status_code, 200)110111 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):112 heads = {'User-agent': 'Mozilla/5.0'}113114 r = get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)115 self.assertEqual(r.status_code, 200)116117 # def test_unicode_headers(self):118 # # Simply calling requests with a unicode instance should simply work119 # # when the characters are all representable using latin-1:120 # heads = { u'User-Agent': u'Requests Test Suite' }121 # requests.get(url=httpbin('get'), headers=heads)122123 # # Characters outside latin-1 should raise an exception:124 # heads = { u'User-Agent': u'\u30cd\u30c3\u30c8\u30ef\u30fc\u30af' }125 # self.assertRaises(UnicodeEncodeError, requests.get,126 # url=httpbin('get'), headers=heads)127128 # def test_session_with_escaped_url(self):129 # # Test a URL that contains percent-escaped characters130 # # This URL should not be modified (double-escaped)131 # # Tests:132 # # - Quoted illegal characters ("%20" (' '), "%3C" ('<'), "%3E" ('>'))133 # # - Quoted reserved characters ("%25" ('%'), "%23" ('#'), "%2F" ('/'))134 # # - Quoted non-ASCII characters ("%C3%98", "%C3%A5")135 # path_fully_escaped = '%3Ca%25b%23c%2Fd%3E/%C3%98%20%C3%A5'136 # url = httpbin('get/' + path_fully_escaped)137 # response = get(url)138 # self.assertEqual(response.url, httpbin('get/' + path_fully_escaped))139140 # # Test that illegal characters in a path get properly percent-escaped141 # # Tests:142 # # - Bare illegal characters (space, '<')143 # # - Bare non-ASCII characters ('\u00d8')144 # path = u'<a%25b%23c%2Fd%3E/\u00d8 %C3%A5'145 # url = httpbin('get/' + path)146 # response = get(url)147 # self.assertEqual(response.url, httpbin('get/' + path_fully_escaped))148149 # # Test that reserved characters in a path do not get percent-escaped150 # # Tests:151 # # - All reserved characters (RFC 3986), except '?', '#', '[' and ']',152 # # which are not allowed in the path, and ';' which delimits153 # # parameters.154 # # All such characters must be allowed bare in path, and must not be155 # # encoded.156 # # - Special unreserved characters (RFC 3986), which should not be157 # # encoded (even though it wouldn't hurt).158 # path_reserved = '!$&\'()*+,/:=@-._~'159 # url = httpbin('get/' + path_reserved)160 # response = get(url)161 # self.assertEqual(response.url, httpbin('get/' + path_reserved))162163 # # Test that percent-encoded unreserved characters in a path get164 # # normalised to their un-encoded forms.165 # path_unreserved = 'ABCDwxyz1234-._~'166 # path_unreserved_escaped = '%41%42%43%44%77%78%79%7A%31%32%33%34%2D%2E%5F%7E'167 # url = httpbin('get/' + path_unreserved_escaped)168 # response = get(url)169 # self.assertEqual(response.url, httpbin('get/' + path_unreserved))170171 # # Re-run all of the same tests on the query part of the URI172 # query_fully_escaped = '%3Ca%25b%23c%2Fd%3E=%C3%98%20%C3%A5'173 # url = httpbin('get/?' + query_fully_escaped)174 # response = get(url)175 # self.assertEqual(response.url, httpbin('get/?' + query_fully_escaped))176177 # query = u'<a%25b%23c%2Fd%3E=\u00d8 %C3%A5'178 # url = httpbin('get/?' + query)179 # response = get(url)180 # self.assertEqual(response.url, httpbin('get/?' + query_fully_escaped))181182 # # The legal characters in query happens to be the same as in path183 # query_reserved = '!$&\'()*+,/:=@-._~'184 # url = httpbin('get/?' + query_reserved)185 # response = get(url)186 # self.assertEqual(response.url, httpbin('get/?' + query_reserved))187188 # query_unreserved = 'ABCDwxyz=1234-._~'189 # query_unreserved_escaped = '%41%42%43%44%77%78%79%7A=%31%32%33%34%2D%2E%5F%7E'190 # url = httpbin('get/?' + query_unreserved_escaped)191 # response = get(url)192 # self.assertEqual(response.url, httpbin('get/?' + query_unreserved))193194 def test_user_agent_transfers(self):195 """Issue XX"""196197 heads = {198 'User-agent':199 'Mozilla/5.0 (github.com/kennethreitz/requests)'200 }201202 r = get(httpbin('user-agent'), headers=heads)203 self.assertTrue(heads['User-agent'] in r.text)204205 heads = {206 'user-agent':207 'Mozilla/5.0 (github.com/kennethreitz/requests)'208 }209210 r = get(httpbin('user-agent'), headers=heads)211 self.assertTrue(heads['user-agent'] in r.text)212213 def test_HTTP_200_OK_HEAD(self):214 r = head(httpbin('get'))215 self.assertEqual(r.status_code, 200)216217 def test_HTTP_200_OK_PUT(self):218 r = put(httpbin('put'))219 self.assertEqual(r.status_code, 200)220221 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):222223 for service in SERVICES:224225 auth = ('user', 'pass')226 url = service('basic-auth', 'user', 'pass')227228 r = get(url, auth=auth)229 self.assertEqual(r.status_code, 200)230231 r = get(url)232 self.assertEqual(r.status_code, 401)233234 s = requests.session(auth=auth)235 r = get(url, session=s)236 self.assertEqual(r.status_code, 200)237238 def test_BASICAUTH_HTTP_200_OK_GET(self):239240 for service in SERVICES:241242 auth = HTTPBasicAuth('user', 'pass')243 url = service('basic-auth', 'user', 'pass')244245 r = get(url, auth=auth)246 self.assertEqual(r.status_code, 200)247248 auth = ('user', 'pass')249 r = get(url, auth=auth)250 self.assertEqual(r.status_code, 200)251252 r = get(url)253 self.assertEqual(r.status_code, 401)254255 s = requests.session(auth=auth)256 r = get(url, session=s)257 self.assertEqual(r.status_code, 200)258259 def test_DIGESTAUTH_HTTP_200_OK_GET(self):260261 for service in SERVICES:262263 auth = HTTPDigestAuth('user', 'pass')264 url = service('digest-auth', 'auth', 'user', 'pass')265266 r = get(url, auth=auth)267 self.assertEqual(r.status_code, 200)268269 r = get(url)270 self.assertEqual(r.status_code, 401)271272 s = requests.session(auth=auth)273 r = get(url, session=s)274 self.assertEqual(r.status_code, 200)275276 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self):277278 for service in SERVICES:279280 auth = HTTPDigestAuth('user', 'wrongpass')281 url = service('digest-auth', 'auth', 'user', 'pass')282283 r = get(url, auth=auth)284 self.assertEqual(r.status_code, 401)285286 s = requests.session(auth=auth)287 r = get(url, session=s)288 self.assertEqual(r.status_code, 401)289290 def test_POSTBIN_GET_POST_FILES(self):291292 for service in SERVICES:293294 url = service('post')295 post1 = post(url).raise_for_status()296297 post1 = post(url, data={'some': 'data'})298 self.assertEqual(post1.status_code, 200)299300 with open(__file__) as f:301 post2 = post(url, files={'some': f})302 self.assertEqual(post2.status_code, 200)303304 post3 = post(url, data='[{"some": "json"}]')305 self.assertEqual(post3.status_code, 200)306307 def test_POSTBIN_GET_POST_FILES_WITH_PARAMS(self):308309 for service in SERVICES:310311 with open(__file__) as f:312 url = service('post')313 post1 = post(url,314 files={'some': f},315 data={'some': 'data'})316317 self.assertEqual(post1.status_code, 200)318319 def test_POSTBIN_GET_POST_FILES_WITH_HEADERS(self):320321 for service in SERVICES:322323 url = service('post')324325 with open(__file__) as f:326327 post2 = post(url,328 files={'some': f},329 headers={'User-Agent': 'requests-tests'})330331 self.assertEqual(post2.status_code, 200)332333 def test_POSTBIN_GET_POST_FILES_STRINGS(self):334335 for service in SERVICES:336337 url = service('post')338339 post1 = post(url, files={'fname.txt': 'fdata'})340 self.assertEqual(post1.status_code, 200)341342 post2 = post(url, files={'fname.txt': 'fdata', 'fname2.txt':'more fdata'})343 self.assertEqual(post2.status_code, 200)344345 post3 = post(url, files={'fname.txt': 'fdata', 'fname2.txt':open(__file__,'rb')})346 self.assertEqual(post3.status_code, 200)347348 post4 = post(url, files={'fname.txt': 'fdata'})349 self.assertEqual(post4.status_code, 200)350351 post5 = post(url, files={'file': ('file.txt', 'more fdata')})352 self.assertEqual(post5.status_code, 200)353354 # Dirty hack to tide us over until 3.3.355 # TODO: Remove this hack when Python 3.3 is released.356 if (sys.version_info[0] == 2):357 fdata = '\xc3\xa9'.decode('utf-8')358 else:359 fdata = '\xe9'360361 post6 = post(url, files={'fname.txt': fdata})362 self.assertEqual(post6.status_code, 200)363364 post7 = post(url, files={'fname.txt': 'fdata to verify'})365 rbody = json.loads(post7.text)366 self.assertTrue(rbody.get('files', None))367 self.assertTrue(rbody['files'].get('fname.txt'), None)368 self.assertEqual(rbody['files']['fname.txt'], 'fdata to verify')369370371 def test_nonzero_evaluation(self):372373 for service in SERVICES:374375 r = get(service('status', '500'))376 self.assertEqual(bool(r), False)377378 r = get(service('/get'))379 self.assertEqual(bool(r), True)380381 def test_request_ok_set(self):382383 for service in SERVICES:384385 r = get(service('status', '404'))386 # print r.status_code387 # r.raise_for_status()388 self.assertEqual(r.ok, False)389390 def test_status_raising(self):391 r = get(httpbin('status', '404'))392 self.assertRaises(HTTPError, r.raise_for_status)393394 r = get(httpbin('status', '200'))395 self.assertFalse(r.error)396 r.raise_for_status()397398 def test_default_status_raising(self):399 config = {'danger_mode': True}400 args = [httpbin('status', '404')]401 kwargs = dict(config=config)402 self.assertRaises(HTTPError, get, *args, **kwargs)403404 r = get(httpbin('status', '200'))405 self.assertEqual(r.status_code, 200)406407 def test_decompress_gzip(self):408409 r = get(httpbin('gzip'))410 r.content.decode('ascii')411412 def test_response_has_unicode_url(self):413414 for service in SERVICES:415416 url = service('get')417418 response = get(url)419420 assert isinstance(response.url, str)421422 def test_unicode_get(self):423424 for service in SERVICES:425426 url = service('/get')427428 get(url, params={'foo': 'føø'})429 get(url, params={'føø': 'føø'})430 get(url, params={'føø': 'føø'})431 get(url, params={'foo': 'foo'})432 get(service('ø'), params={'foo': 'foo'})433434 def test_httpauth_recursion(self):435436 http_auth = HTTPBasicAuth('user', 'BADpass')437438 for service in SERVICES:439 r = get(service('basic-auth', 'user', 'pass'), auth=http_auth)440 self.assertEqual(r.status_code, 401)441442 def test_urlencoded_post_data(self):443444 for service in SERVICES:445446 r = post(service('post'), data=dict(test='fooaowpeuf'))447448 self.assertEqual(r.status_code, 200)449 self.assertEqual(r.headers['content-type'], 'application/json')450 self.assertEqual(r.url, service('post'))451452 rbody = json.loads(r.text)453454 self.assertEqual(rbody.get('form'), dict(test='fooaowpeuf'))455 self.assertEqual(rbody.get('data'), '')456457 def test_nonurlencoded_post_data(self):458459 for service in SERVICES:460461 r = post(service('post'), data='fooaowpeuf')462463 self.assertEqual(r.status_code, 200)464 self.assertEqual(r.headers['content-type'], 'application/json')465 self.assertEqual(r.url, service('post'))466467 rbody = json.loads(r.text)468 # Body wasn't valid url encoded data, so the server returns None as469 # "form" and the raw body as "data".470471 assert rbody.get('form') in (None, {})472 self.assertEqual(rbody.get('data'), 'fooaowpeuf')473474 def test_file_post_data(self):475476 filecontent = b"fooaowpeufbarasjhf"477 testfile = tempfile.NamedTemporaryFile(delete=False)478 testfile.write(filecontent)479 testfile.flush()480 testfile.close()481482 for service in SERVICES:483484 data = open(testfile.name, "rb")485 r = post(service('post'), data=data,486 headers={"content-type": "application/octet-stream"})487488 data.close()489 self.assertEqual(r.status_code, 200)490 self.assertEqual(r.headers['content-type'], 'application/json')491 self.assertEqual(r.url, service('post'))492493 rbody = json.loads(r.text)494 assert rbody.get('form') in (None, {})495 self.assertEqual(rbody.get('data'), filecontent.decode('ascii'))496 os.remove(testfile.name)497498 def test_urlencoded_post_querystring(self):499500 for service in SERVICES:501502 r = post(service('post'), params=dict(test='fooaowpeuf'))503504 self.assertEqual(r.status_code, 200)505 self.assertEqual(r.headers['content-type'], 'application/json')506 self.assertEqual(r.url, service('post?test=fooaowpeuf'))507508 rbody = json.loads(r.text)509 self.assertEqual(rbody.get('form'), {}) # No form supplied510 self.assertEqual(rbody.get('data'), '')511512 def test_urlencoded_post_query_and_data(self):513514 for service in SERVICES:515516 r = post(517 service('post'),518 params=dict(test='fooaowpeuf'),519 data=dict(test2="foobar"))520521 self.assertEqual(r.status_code, 200)522 self.assertEqual(r.headers['content-type'], 'application/json')523 self.assertEqual(r.url, service('post?test=fooaowpeuf'))524525 rbody = json.loads(r.text)526 self.assertEqual(rbody.get('form'), dict(test2='foobar'))527 self.assertEqual(rbody.get('data'), '')528529 def test_nonurlencoded_postdata(self):530531 for service in SERVICES:532533 r = post(service('post'), data="foobar")534535 self.assertEqual(r.status_code, 200)536 self.assertEqual(r.headers['content-type'], 'application/json')537538 rbody = json.loads(r.text)539540 assert rbody.get('form') in (None, {})541 self.assertEqual(rbody.get('data'), 'foobar')542543 def test_urlencoded_get_query_multivalued_param(self):544545 for service in SERVICES:546547 r = get(service('get'), params=dict(test=['foo', 'baz']))548 self.assertEqual(r.status_code, 200)549 self.assertEqual(r.url, service('get?test=foo&test=baz'))550551 def test_urlencoded_post_querystring_multivalued(self):552553 for service in SERVICES:554555 r = post(service('post'), params=dict(test=['foo', 'baz']))556 self.assertEqual(r.status_code, 200)557 self.assertEqual(r.headers['content-type'], 'application/json')558 self.assertEqual(r.url, service('post?test=foo&test=baz'))559560 rbody = json.loads(r.text)561 self.assertEqual(rbody.get('form'), {}) # No form supplied562 self.assertEqual(rbody.get('data'), '')563564 def test_urlencoded_post_query_multivalued_and_data(self):565566 for service in SERVICES:567568 r = post(569 service('post'),570 params=dict(test=['foo', 'baz']),571 data=dict(test2="foobar", test3=['foo', 'baz']))572573 self.assertEqual(r.status_code, 200)574 self.assertEqual(r.headers['content-type'], 'application/json')575 self.assertEqual(r.url, service('post?test=foo&test=baz'))576577 # print(r.text)578 # print('-----------------------')579580 rbody = json.loads(r.text)581 self.assertEqual(rbody.get('form'), dict(test2='foobar', test3=['foo', 'baz']))582 self.assertEqual(rbody.get('data'), '')583584 def test_GET_no_redirect(self):585586 for service in SERVICES:587588 r = get(service('redirect', '3'), allow_redirects=False)589 self.assertEqual(r.status_code, 302)590 self.assertEqual(len(r.history), 0)591592 def test_HEAD_no_redirect(self):593594 for service in SERVICES:595596 r = head(service('redirect', '3'), allow_redirects=False)597 self.assertEqual(r.status_code, 302)598 self.assertEqual(len(r.history), 0)599600 def test_redirect_history(self):601602 for service in SERVICES:603604 r = get(service('redirect', '3'))605 self.assertEqual(r.status_code, 200)606 self.assertEqual(len(r.history), 3)607608 def test_relative_redirect_history(self):609610 for service in SERVICES:611612 r = get(service('relative-redirect', '3'))613 self.assertEqual(r.status_code, 200)614 self.assertEqual(len(r.history), 3)615616 def test_session_HTTP_200_OK_GET(self):617618 s = requests.session()619 r = get(httpbin('get'), session=s)620 self.assertEqual(r.status_code, 200)621622 def test_session_persistent_headers(self):623624 heads = {'User-agent': 'Mozilla/5.0'}625626 s = requests.session()627 s.headers = heads628629 # Make 2 requests from Session object, should send header both times630 r1 = get(httpbin('user-agent'), session=s)631 assert heads['User-agent'] in r1.text632633 r2 = get(httpbin('user-agent'), session=s)634 assert heads['User-agent'] in r2.text635636 new_heads = {'User-agent': 'blah'}637 r3 = get(httpbin('user-agent'), headers=new_heads, session=s)638 assert new_heads['User-agent'] in r3.text639640 self.assertEqual(r2.status_code, 200)641642 def test_single_hook(self):643644 def add_foo_header(args):645 if not args.get('headers'):646 args['headers'] = {}647648 args['headers'].update({649 'X-Foo': 'foo'650 })651652 return args653654 for service in SERVICES:655 url = service('headers')656 response = get(url=url, hooks={'args': add_foo_header})657658 assert 'foo' in response.text659660 def test_multiple_hooks(self):661662 def add_foo_header(args):663 if not args.get('headers'):664 args['headers'] = {}665666 args['headers'].update({667 'X-Foo': 'foo'668 })669670 return args671672 def add_bar_header(args):673 if not args.get('headers'):674 args['headers'] = {}675676 args['headers'].update({677 'X-Bar': 'bar'678 })679680 return args681682 for service in SERVICES:683 url = service('headers')684685 response = get(url=url,686 hooks={687 'args': [add_foo_header, add_bar_header]688 }689 )690691 assert 'foo' in response.text692 assert 'bar' in response.text693694 def test_session_persistent_cookies(self):695696 s = requests.session()697698 # Internally dispatched cookies are sent.699 _c = {'kenneth': 'reitz', 'bessie': 'monke'}700 r = get(httpbin('cookies'), cookies=_c, session=s)701 r = get(httpbin('cookies'), session=s)702703 # Those cookies persist transparently.704 c = json.loads(r.text).get('cookies')705 self.assertEqual(c, _c)706707 # Double check.708 r = get(httpbin('cookies'), cookies={}, session=s)709 c = json.loads(r.text).get('cookies')710 self.assertEqual(c, _c)711712 # Remove a cookie by setting it's value to None.713 r = get(httpbin('cookies'), cookies={'bessie': None}, session=s)714 c = json.loads(r.text).get('cookies')715 del _c['bessie']716 self.assertEqual(c, _c)717718 # Test session-level cookies.719 s = requests.session(cookies=_c)720 r = get(httpbin('cookies'), session=s)721 c = json.loads(r.text).get('cookies')722 self.assertEqual(c, _c)723724 # Have the server set a cookie.725 r = get(httpbin('cookies', 'set', 'k', 'v'), allow_redirects=True, session=s)726 c = json.loads(r.text).get('cookies')727728 assert 'k' in c729730 # And server-set cookie persistience.731 r = get(httpbin('cookies'), session=s)732 c = json.loads(r.text).get('cookies')733734 assert 'k' in c735736 def test_session_persistent_params(self):737738 params = {'a': 'a_test'}739740 s = requests.session()741 s.params = params742743 # Make 2 requests from Session object, should send header both times744 r1 = get(httpbin('get'), session=s)745 assert params['a'] in r1.text746747 params2 = {'b': 'b_test'}748749 r2 = get(httpbin('get'), params=params2, session=s)750 assert params['a'] in r2.text751 assert params2['b'] in r2.text752753 params3 = {'b': 'b_test', 'a': None, 'c': 'c_test'}754755 r3 = get(httpbin('get'), params=params3, session=s)756757 assert not params['a'] in r3.text758 assert params3['b'] in r3.text759 assert params3['c'] in r3.text760761 def test_session_cookies_with_return_response_false(self):762 s = requests.session()763 # return_response=False as it does requests.async.get764 rq = get(httpbin('cookies', 'set', 'k', 'v'), return_response=False,765 allow_redirects=True, session=s)766 rq.send(prefetch=True)767 c = rq.response.json.get('cookies')768 assert 'k' in c769 assert 'k' in s.cookies770771 def test_session_pickling(self):772773 s = requests.session(774 headers={'header': 'value'},775 cookies={'a-cookie': 'cookie-value'},776 auth=('username', 'password'))777778 ds = pickle.loads(pickle.dumps(s))779780 self.assertEqual(s.headers, ds.headers)781 self.assertEqual(s.auth, ds.auth)782783 # Cookie doesn't have a good __eq__, so verify manually:784 self.assertEqual(len(ds.cookies), 1)785 for cookie in ds.cookies:786 self.assertCookieHas(cookie, name='a-cookie', value='cookie-value')787788 def test_unpickled_session_requests(self):789 s = requests.session()790 r = get(httpbin('cookies', 'set', 'k', 'v'), allow_redirects=True, session=s)791 c = json.loads(r.text).get('cookies')792 assert 'k' in c793794 ds = pickle.loads(pickle.dumps(s))795 r = get(httpbin('cookies'), session=ds)796 c = json.loads(r.text).get('cookies')797 assert 'k' in c798799 ds1 = pickle.loads(pickle.dumps(requests.session()))800 ds2 = pickle.loads(pickle.dumps(requests.session(prefetch=True)))801 assert not ds1.prefetch802 assert ds2.prefetch803804 def test_invalid_content(self):805 # WARNING: if you're using a terrible DNS provider (comcast),806 # this will fail.807 try:808 hah = 'http://somedomainthatclearlydoesntexistg.com'809 r = get(hah, allow_redirects=False)810 except requests.ConnectionError:811 pass # \o/812 else:813 assert False814815 config = {'safe_mode': True}816 r = get(hah, allow_redirects=False, config=config)817 assert r.content == None818819 def test_cached_response(self):820821 r1 = get(httpbin('get'), prefetch=False)822 assert not r1._content823 assert r1.content824 assert r1.text825826 r2 = get(httpbin('get'), prefetch=True)827 assert r2._content828 assert r2.content829 assert r2.text830831 def test_iter_lines(self):832833 lines = (0, 2, 10, 100)834835 for i in lines:836 r = get(httpbin('stream', str(i)), prefetch=False)837 lines = list(r.iter_lines())838 len_lines = len(lines)839840 self.assertEqual(i, len_lines)841842 # Tests that trailing whitespaces within lines do not get stripped.843 # Tests that a trailing non-terminated line does not get stripped.844 quote = (845 '''Agamemnon \n'''846 '''\tWhy will he not upon our fair request\r\n'''847 '''\tUntent his person and share the air with us?'''848 )849850 # Make a request and monkey-patch its contents851 r = get(httpbin('get'))852 r.raw = StringIO(quote)853854 lines = list(r.iter_lines())855 len_lines = len(lines)856 self.assertEqual(len_lines, 3)857858 joined = lines[0] + '\n' + lines[1] + '\r\n' + lines[2]859 self.assertEqual(joined, quote)860861 def test_safe_mode(self):862863 safe = requests.session(config=dict(safe_mode=True))864865 # Safe mode creates empty responses for failed requests.866 # Iterating on these responses should produce empty sequences867 r = get('http://_/', session=safe)868 self.assertEqual(list(r.iter_lines()), [])869 assert isinstance(r.error, requests.exceptions.ConnectionError)870871 r = get('http://_/', session=safe)872 self.assertEqual(list(r.iter_content()), [])873 assert isinstance(r.error, requests.exceptions.ConnectionError)874875 # When not in safe mode, should raise Timeout exception876 self.assertRaises(877 requests.exceptions.Timeout,878 get,879 httpbin('stream', '1000'), timeout=0.0001)880881 # In safe mode, should return a blank response882 r = get(httpbin('stream', '1000'), timeout=0.0001,883 config=dict(safe_mode=True))884 assert r.content is None885 assert isinstance(r.error, requests.exceptions.Timeout)886887 def test_upload_binary_data(self):888889 requests.get(httpbin('post'), auth=('a', 'b'), data='\xff')890891 def test_useful_exception_for_invalid_port(self):892 # If we pass a legitimate URL with an invalid port, we should fail.893 self.assertRaises(894 ValueError,895 get,896 'http://google.com:banana')897898 def test_useful_exception_for_invalid_scheme(self):899900 # If we pass a legitimate URL with a scheme not supported901 # by requests, we should fail.902 self.assertRaises(903 ValueError,904 get,905 'ftp://ftp.kernel.org/pub/')906907 def test_can_have_none_in_header_values(self):908 try:909 # Don't choke on headers with none in the value.910 requests.get(httpbin('headers'), headers={'Foo': None})911 except TypeError:912 self.fail()913914 def test_danger_mode_redirects(self):915 s = requests.session()916 s.config['danger_mode'] = True917 s.get(httpbin('redirect', '4'))918919920 def test_empty_response(self):921 r = requests.get(httpbin('status', '404'))922 r.text923924 def test_max_redirects(self):925 """Test the max_redirects config variable, normally and under safe_mode."""926 def unsafe_callable():927 requests.get(httpbin('redirect', '3'), config=dict(max_redirects=2))928 self.assertRaises(requests.exceptions.TooManyRedirects, unsafe_callable)929930 # add safe mode931 response = requests.get(httpbin('redirect', '3'), config=dict(safe_mode=True, max_redirects=2))932 self.assertTrue(response.content is None)933 self.assertTrue(isinstance(response.error, requests.exceptions.TooManyRedirects))934935 def test_connection_keepalive_and_close(self):936 """Test that we send 'Connection: close' when keep_alive is disabled."""937 # keep-alive should be on by default938 r1 = requests.get(httpbin('get'))939 # XXX due to proxying issues, test the header sent back by httpbin, rather than940 # the header reported in its message body. See kennethreitz/httpbin#46941 self.assertEqual(r1.headers['Connection'].lower(), 'keep-alive')942943 # but when we disable it, we should send a 'Connection: close'944 # and get the same back:945 r2 = requests.get(httpbin('get'), config=dict(keep_alive=False))946 self.assertEqual(r2.headers['Connection'].lower(), 'close')947948 def test_head_content(self):949 """Test that empty bodies are properly supported."""950951 r = requests.head(httpbin('headers'))952 r.content953 r.text954955if __name__ == '__main__':956 unittest.main()