Skip to content
Myr

test_requests.py

This file

Path

tests/test_requests.py

1,151 lines · 38.5 KiB · Python

Last changed by

remove danger_mode testsKenneth Reitzbefore adoption7999257

History of this file

Take 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('..'))10import json11import unittest12import pickle13import tempfile14import collections1516import requests17from requests.compat import str, StringIO18# import envoy19from requests import HTTPError20from requests import get, post, head, put21from requests.auth import HTTPBasicAuth, HTTPDigestAuth22from requests.exceptions import InvalidURL2324if '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 = True545556class TestBaseMixin(object):5758    def assertCookieHas(self, cookie, **kwargs):59        """Assert that a cookie has various specified properties."""60        for attr, expected_value in kwargs.items():61            cookie_attr = getattr(cookie, attr)62            message = 'Failed comparison for %s: %s != %s' % (attr, cookie_attr, expected_value)63            self.assertEqual(cookie_attr, expected_value, message)646566class RequestsTestSuite(TestSetup, TestBaseMixin, unittest.TestCase):67    """Requests test cases."""6869    def test_entry_points(self):7071        requests.session72        requests.session().get73        requests.session().head74        requests.get75        requests.head76        requests.put77        requests.patch78        requests.post7980    def test_invalid_url(self):81        self.assertRaises(ValueError, get, 'hiwpefhipowhefopw')8283    def test_path_is_not_double_encoded(self):84        request = requests.Request("http://0.0.0.0/get/test case")8586        self.assertEqual(request.path_url, "/get/test%20case")8788    def test_params_are_added_before_fragment(self):89        request = requests.Request(90            "http://example.com/path#fragment", params={"a": "b"})91        self.assertEqual(request.full_url,92            "http://example.com/path?a=b#fragment")93        request = requests.Request(94            "http://example.com/path?key=value#fragment", params={"a": "b"})95        self.assertEqual(request.full_url,96            "http://example.com/path?key=value&a=b#fragment")9798    def test_params_accepts_kv_list(self):99        request = requests.Request('http://example.com/path',100                params=[('a', 'b')])101        self.assertEqual(request.full_url, 'http://example.com/path?a=b')102103    def test_HTTP_200_OK_GET(self):104        r = get(httpbin('get'))105        self.assertEqual(r.status_code, 200)106107    def test_response_sent(self):108        r = get(httpbin('get'))109110        self.assertTrue(r.request.sent)111112    def test_HTTP_302_ALLOW_REDIRECT_GET(self):113        r = get(httpbin('redirect', '1'))114        self.assertEqual(r.status_code, 200)115116    def test_HTTP_302_GET(self):117        r = get(httpbin('redirect', '1'), allow_redirects=False)118        self.assertEqual(r.status_code, 302)119120    def test_HTTP_200_OK_GET_WITH_PARAMS(self):121        heads = {'User-agent': 'Mozilla/5.0'}122123        r = get(httpbin('user-agent'), headers=heads)124125        self.assertTrue(heads['User-agent'] in r.text)126        self.assertEqual(r.status_code, 200)127128    def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):129        heads = {'User-agent': 'Mozilla/5.0'}130131        r = get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)132        self.assertEqual(r.status_code, 200)133134    # def test_unicode_headers(self):135    #     # Simply calling requests with a unicode instance should simply work136    #     # when the characters are all representable using latin-1:137    #     heads = { u'User-Agent': u'Requests Test Suite' }138    #     requests.get(url=httpbin('get'), headers=heads)139140    #     # Characters outside latin-1 should raise an exception:141    #     heads = { u'User-Agent': u'\u30cd\u30c3\u30c8\u30ef\u30fc\u30af' }142    #     self.assertRaises(UnicodeEncodeError, requests.get,143    #                       url=httpbin('get'), headers=heads)144145    # def test_session_with_escaped_url(self):146    #     # Test a URL that contains percent-escaped characters147    #     # This URL should not be modified (double-escaped)148    #     # Tests:149    #     # - Quoted illegal characters ("%20" (' '), "%3C" ('<'), "%3E" ('>'))150    #     # - Quoted reserved characters ("%25" ('%'), "%23" ('#'), "%2F" ('/'))151    #     # - Quoted non-ASCII characters ("%C3%98", "%C3%A5")152    #     path_fully_escaped = '%3Ca%25b%23c%2Fd%3E/%C3%98%20%C3%A5'153    #     url = httpbin('get/' + path_fully_escaped)154    #     response = get(url)155    #     self.assertEqual(response.url, httpbin('get/' + path_fully_escaped))156157    #     # Test that illegal characters in a path get properly percent-escaped158    #     # Tests:159    #     # - Bare illegal characters (space, '<')160    #     # - Bare non-ASCII characters ('\u00d8')161    #     path = u'<a%25b%23c%2Fd%3E/\u00d8 %C3%A5'162    #     url = httpbin('get/' + path)163    #     response = get(url)164    #     self.assertEqual(response.url, httpbin('get/' + path_fully_escaped))165166    #     # Test that reserved characters in a path do not get percent-escaped167    #     # Tests:168    #     # - All reserved characters (RFC 3986), except '?', '#', '[' and ']',169    #     #   which are not allowed in the path, and ';' which delimits170    #     #   parameters.171    #     #   All such characters must be allowed bare in path, and must not be172    #     #   encoded.173    #     # - Special unreserved characters (RFC 3986), which should not be174    #     #   encoded (even though it wouldn't hurt).175    #     path_reserved = '!$&\'()*+,/:=@-._~'176    #     url = httpbin('get/' + path_reserved)177    #     response = get(url)178    #     self.assertEqual(response.url, httpbin('get/' + path_reserved))179180    #     # Test that percent-encoded unreserved characters in a path get181    #     # normalised to their un-encoded forms.182    #     path_unreserved = 'ABCDwxyz1234-._~'183    #     path_unreserved_escaped = '%41%42%43%44%77%78%79%7A%31%32%33%34%2D%2E%5F%7E'184    #     url = httpbin('get/' + path_unreserved_escaped)185    #     response = get(url)186    #     self.assertEqual(response.url, httpbin('get/' + path_unreserved))187188    #     # Re-run all of the same tests on the query part of the URI189    #     query_fully_escaped = '%3Ca%25b%23c%2Fd%3E=%C3%98%20%C3%A5'190    #     url = httpbin('get/?' + query_fully_escaped)191    #     response = get(url)192    #     self.assertEqual(response.url, httpbin('get/?' + query_fully_escaped))193194    #     query = u'<a%25b%23c%2Fd%3E=\u00d8 %C3%A5'195    #     url = httpbin('get/?' + query)196    #     response = get(url)197    #     self.assertEqual(response.url, httpbin('get/?' + query_fully_escaped))198199    #     # The legal characters in query happens to be the same as in path200    #     query_reserved = '!$&\'()*+,/:=@-._~'201    #     url = httpbin('get/?' + query_reserved)202    #     response = get(url)203    #     self.assertEqual(response.url, httpbin('get/?' + query_reserved))204205    #     query_unreserved = 'ABCDwxyz=1234-._~'206    #     query_unreserved_escaped = '%41%42%43%44%77%78%79%7A=%31%32%33%34%2D%2E%5F%7E'207    #     url = httpbin('get/?' + query_unreserved_escaped)208    #     response = get(url)209    #     self.assertEqual(response.url, httpbin('get/?' + query_unreserved))210211    def test_user_agent_transfers(self):212        """Issue XX"""213214        heads = {215            'User-agent':216                'Mozilla/5.0 (github.com/kennethreitz/requests)'217        }218219        r = get(httpbin('user-agent'), headers=heads)220        self.assertTrue(heads['User-agent'] in r.text)221222        heads = {223            'user-agent':224                'Mozilla/5.0 (github.com/kennethreitz/requests)'225        }226227        r = get(httpbin('user-agent'), headers=heads)228        self.assertTrue(heads['user-agent'] in r.text)229230    def test_HTTP_200_OK_HEAD(self):231        r = head(httpbin('get'))232        self.assertEqual(r.status_code, 200)233234    def test_HTTP_200_OK_PUT(self):235        r = put(httpbin('put'))236        self.assertEqual(r.status_code, 200)237238    def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):239240        for service in SERVICES:241242            auth = ('user', 'pass')243            url = service('basic-auth', 'user', 'pass')244245            r = get(url, auth=auth)246            self.assertEqual(r.status_code, 200)247248            r = get(url)249            self.assertEqual(r.status_code, 401)250251            s = requests.session(auth=auth)252            r = get(url, session=s)253            self.assertEqual(r.status_code, 200)254255    def test_BASICAUTH_HTTP_200_OK_GET(self):256257        for service in SERVICES:258259            auth = HTTPBasicAuth('user', 'pass')260            url = service('basic-auth', 'user', 'pass')261262            r = get(url, auth=auth)263            self.assertEqual(r.status_code, 200)264265            auth = ('user', 'pass')266            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_HTTP_200_OK_GET(self):277278        for service in SERVICES:279280            auth = HTTPDigestAuth('user', 'pass')281            url = service('digest-auth', 'auth', 'user', 'pass')282283            r = get(url, auth=auth)284            self.assertEqual(r.status_code, 200)285            self.assertEqual(len(r.history), 1)286287            r = get(url, auth=auth)288            self.assertEqual(r.status_code, 200)289            self.assertEqual(len(r.history), 0)290291            r = get(url)292            self.assertEqual(r.status_code, 401)293294            s = requests.session(auth=auth)295            r = get(url, session=s)296            self.assertEqual(r.status_code, 200)297298    def test_DIGESTAUTH_WRONG_HTTP_401_GET(self):299300        for service in SERVICES:301302            auth = HTTPDigestAuth('user', 'wrongpass')303            url = service('digest-auth', 'auth', 'user', 'pass')304305            r = get(url, auth=auth)306            self.assertEqual(r.status_code, 401)307308            s = requests.session(auth=auth)309            r = get(url, session=s)310            self.assertEqual(r.status_code, 401)311312    def test_POSTBIN_GET_POST_FILES(self):313314        for service in SERVICES:315316            url = service('post')317            post1 = post(url).raise_for_status()318319            post1 = post(url, data={'some': 'data'})320            self.assertEqual(post1.status_code, 200)321322            with open(__file__) as f:323                post2 = post(url, files={'some': f})324                post3 = post(url, files=[('some', f)])325            self.assertEqual(post2.status_code, 200)326            self.assertEqual(post3.status_code, 200)327328            post4 = post(url, data='[{"some": "json"}]')329            self.assertEqual(post4.status_code, 200)330331            try:332                post(url, files=['bad file data'])333            except ValueError:334                pass335336    def test_POSTBIN_GET_POST_FILES_WITH_PARAMS(self):337338        for service in SERVICES:339340            with open(__file__) as f:341                url = service('post')342                post1 = post(url, data={'some': 'data'}, files={'some': f})343                post2 = post(url, data={'some': 'data'}, files=[('some', f)])344                post3 = post(url, data=[('some', 'data')], files=[('some', f)])345346            self.assertEqual(post1.status_code, 200)347            self.assertEqual(post2.status_code, 200)348            self.assertEqual(post3.status_code, 200)349350    def test_POSTBIN_GET_POST_FILES_WITH_CJK_PARAMS(self):351352        for service in SERVICES:353354            with open(__file__) as f:355                url = service('post')356                post1 = post(url, data={'some': '中文'}, files={'some': f})357                post2 = post(url, data={'some': '日本語'}, files=[('some', f)])358                post3 = post(url, data=[('some', '한국의')], files=[('some', f)])359360            self.assertEqual(post1.status_code, 200)361            self.assertEqual(post2.status_code, 200)362            self.assertEqual(post3.status_code, 200)363364    def test_POSTBIN_GET_POST_FILES_WITH_HEADERS(self):365366        for service in SERVICES:367368            url = service('post')369370            with open(__file__) as f:371372                post2 = post(url,373                    files={'some': f},374                    headers={'User-Agent': 'requests-tests'})375376            self.assertEqual(post2.status_code, 200)377378    def test_POSTBIN_GET_POST_FILES_STRINGS(self):379380        for service in SERVICES:381382            url = service('post')383384            post1 = post(url, files={'fname.txt': 'fdata'})385            self.assertEqual(post1.status_code, 200)386387            post2 = post(url, files={'fname.txt': 'fdata',388                    'fname2.txt': 'more fdata'})389            self.assertEqual(post2.status_code, 200)390391            post3 = post(url, files={'fname.txt': 'fdata',392                    'fname2.txt': open(__file__, 'rb')})393            self.assertEqual(post3.status_code, 200)394395            post4 = post(url, files={'fname.txt': 'fdata'})396            self.assertEqual(post4.status_code, 200)397398            post5 = post(url, files={'file': ('file.txt', 'more fdata')})399            self.assertEqual(post5.status_code, 200)400401            # Dirty hack to tide us over until 3.3.402            # TODO: Remove this hack when Python 3.3 is released.403            if (sys.version_info[0] == 2):404                fdata = '\xc3\xa9'.decode('utf-8')405            else:406                fdata = '\xe9'407408            post6 = post(url, files={'fname.txt': fdata})409            self.assertEqual(post6.status_code, 200)410411            post7 = post(url, files={'fname.txt': 'fdata to verify'})412            rbody = json.loads(post7.text)413            self.assertTrue(rbody.get('files', None))414            self.assertTrue(rbody['files'].get('fname.txt', None))415            self.assertEqual(rbody['files']['fname.txt'], 'fdata to verify')416417            post8 = post(url, files=[('fname.txt', 'fdata')])418            self.assertEqual(post8.status_code, 200)419            resp_body = post8.json420            self.assertTrue(resp_body.get('files', None))421            self.assertTrue(resp_body['files'].get('fname.txt', None))422            self.assertEqual(resp_body['files']['fname.txt'], 'fdata')423424            post9 = post(url, files=[('fname.txt', fdata)])425            self.assertEqual(post9.status_code, 200)426427            post10 = post(url, files=[('file',428                        ('file.txt', 'more file data'))])429            self.assertEqual(post10.status_code, 200)430431            post11 = post(url, files=[('fname.txt', 'fdata'),432                    ('fname2.txt', 'more fdata')])433            post12 = post(url, files=[('fname.txt', 'fdata'),434                    ('fname2.txt', open(__file__, 'rb'))])435            self.assertEqual(post11.status_code, 200)436            self.assertEqual(post12.status_code, 200)437438    def test_nonzero_evaluation(self):439440        for service in SERVICES:441442            r = get(service('status', '500'))443            self.assertEqual(bool(r), False)444445            r = get(service('/get'))446            self.assertEqual(bool(r), True)447448    def test_request_ok_set(self):449450        for service in SERVICES:451452            r = get(service('status', '404'))453            # print r.status_code454            # r.raise_for_status()455            self.assertEqual(r.ok, False)456457    def test_status_raising(self):458        r = get(httpbin('status', '404'))459        self.assertRaises(HTTPError, r.raise_for_status)460461        r = get(httpbin('status', '200'))462        self.assertFalse(r.error)463        r.raise_for_status()464465    def test_decompress_gzip(self):466467        r = get(httpbin('gzip'))468        r.content.decode('ascii')469470    def test_response_has_unicode_url(self):471472        for service in SERVICES:473474            url = service('get')475476            response = get(url)477478            self.assertTrue(isinstance(response.url, str))479480    def test_unicode_get(self):481482        for service in SERVICES:483484            url = service('/get')485486            get(url, params={'foo': 'føø'})487            get(url, params={'føø': 'føø'})488            get(url, params={'føø': 'føø'})489            get(url, params={'foo': 'foo'})490            get(service('ø'), params={'foo': 'foo'})491492    def test_httpauth_recursion(self):493494        http_auth = HTTPBasicAuth('user', 'BADpass')495496        for service in SERVICES:497            r = get(service('basic-auth', 'user', 'pass'), auth=http_auth)498            self.assertEqual(r.status_code, 401)499500    def test_urlencoded_post_data(self):501502        for service in SERVICES:503504            r = post(service('post'), data=dict(test='fooaowpeuf'))505506            self.assertEqual(r.status_code, 200)507            self.assertEqual(r.headers['content-type'], 'application/json')508            self.assertEqual(r.url, service('post'))509510            rbody = json.loads(r.text)511512            self.assertEqual(rbody.get('form'), dict(test='fooaowpeuf'))513            self.assertEqual(rbody.get('data'), '')514515    def test_nonurlencoded_post_data(self):516517        for service in SERVICES:518519            r = post(service('post'), data='fooaowpeuf')520521            self.assertEqual(r.status_code, 200)522            self.assertEqual(r.headers['content-type'], 'application/json')523            self.assertEqual(r.url, service('post'))524525            rbody = json.loads(r.text)526            # Body wasn't valid url encoded data, so the server returns None as527            # "form" and the raw body as "data".528529            self.assertTrue(rbody.get('form') in (None, {}))530            self.assertEqual(rbody.get('data'), 'fooaowpeuf')531532    def test_file_post_data(self):533534        filecontent = b"fooaowpeufbarasjhf"535        testfile = tempfile.NamedTemporaryFile(delete=False)536        testfile.write(filecontent)537        testfile.flush()538        testfile.close()539540        for service in SERVICES:541542            data = open(testfile.name, "rb")543            r = post(service('post'), data=data,544                    headers={"content-type": "application/octet-stream"})545546            data.close()547            self.assertEqual(r.status_code, 200)548            self.assertEqual(r.headers['content-type'], 'application/json')549            self.assertEqual(r.url, service('post'))550551            rbody = json.loads(r.text)552            self.assertTrue(rbody.get('form') in (None, {}))553            self.assertEqual(rbody.get('data'), filecontent.decode('ascii'))554        os.remove(testfile.name)555556    def test_urlencoded_post_querystring(self):557558        for service in SERVICES:559560            r = post(service('post'), params=dict(test='fooaowpeuf'))561562            self.assertEqual(r.status_code, 200)563            self.assertEqual(r.headers['content-type'], 'application/json')564            self.assertEqual(r.url, service('post?test=fooaowpeuf'))565566            rbody = json.loads(r.text)567            self.assertEqual(rbody.get('form'), {})  # No form supplied568            self.assertEqual(rbody.get('data'), '')569570    def test_urlencoded_post_query_and_data(self):571572        for service in SERVICES:573574            r = post(575                service('post'),576                params=dict(test='fooaowpeuf'),577                data=dict(test2="foobar"))578579            self.assertEqual(r.status_code, 200)580            self.assertEqual(r.headers['content-type'], 'application/json')581            self.assertEqual(r.url, service('post?test=fooaowpeuf'))582583            rbody = json.loads(r.text)584            self.assertEqual(rbody.get('form'), dict(test2='foobar'))585            self.assertEqual(rbody.get('data'), '')586587    def test_nonurlencoded_postdata(self):588589        for service in SERVICES:590591            r = post(service('post'), data="foobar")592593            self.assertEqual(r.status_code, 200)594            self.assertEqual(r.headers['content-type'], 'application/json')595596            rbody = json.loads(r.text)597598            self.assertTrue(rbody.get('form') in (None, {}))599            self.assertEqual(rbody.get('data'), 'foobar')600601    def test_urlencoded_get_query_multivalued_param(self):602603        for service in SERVICES:604605            r = get(service('get'), params=dict(test=['foo', 'baz']))606            self.assertEqual(r.status_code, 200)607            self.assertEqual(r.url, service('get?test=foo&test=baz'))608609    def test_urlencoded_post_querystring_multivalued(self):610611        for service in SERVICES:612613            r = post(service('post'), params=dict(test=['foo', 'baz']))614            self.assertEqual(r.status_code, 200)615            self.assertEqual(r.headers['content-type'], 'application/json')616            self.assertEqual(r.url, service('post?test=foo&test=baz'))617618            rbody = json.loads(r.text)619            self.assertEqual(rbody.get('form'), {})  # No form supplied620            self.assertEqual(rbody.get('data'), '')621622    def test_urlencoded_post_query_multivalued_and_data(self):623624        for service in SERVICES:625626            r = post(627                service('post'),628                params=dict(test=['foo', 'baz']),629                data=dict(test2="foobar", test3=['foo', 'baz']))630631            self.assertEqual(r.status_code, 200)632            self.assertEqual(r.headers['content-type'], 'application/json')633            self.assertEqual(r.url, service('post?test=foo&test=baz'))634635            # print(r.text)636            # print('-----------------------')637638            rbody = json.loads(r.text)639            self.assertEqual(rbody.get('form'), dict(test2='foobar', test3=['foo', 'baz']))640            self.assertEqual(rbody.get('data'), '')641642    def test_multivalued_data_encoding(self):643        """644        Make sure data encoding works on a value that is an iterable but not645        a list646        """647        for service in SERVICES:648            # Can't have unicode literals in Python3, so avoid them.649            # TODO: fixup when moving to Python 3.3650            if (sys.version_info[0] == 2):651                nonascii = '\xc3\xa9'.decode('utf-8')652            else:653                nonascii = '\xe9'654655            r = post(656                service('post'),657                data=dict(test=('foo', nonascii)))658659            self.assertEqual(r.status_code, 200)660            self.assertEqual(r.headers['content-type'], 'application/json')661662            rbody = json.loads(r.text)663            self.assertEqual(rbody.get('form'),664                             dict(test=['foo', nonascii]))665666    def test_GET_no_redirect(self):667668        for service in SERVICES:669670            r = get(service('redirect', '3'), allow_redirects=False)671            self.assertEqual(r.status_code, 302)672            self.assertEqual(len(r.history), 0)673674    def test_HEAD_no_redirect(self):675676        for service in SERVICES:677678            r = head(service('redirect', '3'), allow_redirects=False)679            self.assertEqual(r.status_code, 302)680            self.assertEqual(len(r.history), 0)681682    def test_redirect_history(self):683684        for service in SERVICES:685686            r = get(service('redirect', '3'))687            self.assertEqual(r.status_code, 200)688            self.assertEqual(len(r.history), 3)689690    def test_relative_redirect_history(self):691692        for service in SERVICES:693694            r = get(service('relative-redirect', '3'))695            self.assertEqual(r.status_code, 200)696            self.assertEqual(len(r.history), 3)697698    def test_session_HTTP_200_OK_GET(self):699700        s = requests.session()701        r = get(httpbin('get'), session=s)702        self.assertEqual(r.status_code, 200)703704    def test_session_persistent_headers(self):705706        heads = {'User-agent': 'Mozilla/5.0'}707708        s = requests.session()709        s.headers = heads710711        # Make 2 requests from Session object, should send header both times712        r1 = get(httpbin('user-agent'), session=s)713        self.assertTrue(heads['User-agent'] in r1.text)714715        r2 = get(httpbin('user-agent'), session=s)716        self.assertTrue(heads['User-agent'] in r2.text)717718        new_heads = {'User-agent': 'blah'}719        r3 = get(httpbin('user-agent'), headers=new_heads, session=s)720        self.assertTrue(new_heads['User-agent'] in r3.text)721722        self.assertEqual(r2.status_code, 200)723724    def test_single_hook(self):725726        def add_foo_header(args):727            if not args.get('headers'):728                args['headers'] = {}729730            args['headers'].update({731                'X-Foo': 'foo'732            })733734            return args735736        for service in SERVICES:737            url = service('headers')738            response = get(url=url, hooks={'args': add_foo_header})739740            self.assertTrue('foo' in response.text)741742    def test_multiple_hooks(self):743744        def add_foo_header(args):745            if not args.get('headers'):746                args['headers'] = {}747748            args['headers'].update({749                'X-Foo': 'foo'750            })751752            return args753754        def add_bar_header(args):755            if not args.get('headers'):756                args['headers'] = {}757758            args['headers'].update({759                'X-Bar': 'bar'760            })761762            return args763764        for service in SERVICES:765            url = service('headers')766767            response = get(url=url,768                hooks={769                    'args': [add_foo_header, add_bar_header]770                }771            )772773            for text in ('foo', 'bar'):774                self.assertTrue(text in response.text)775776    def test_allow_list_of_hooks_to_register_hook(self):777        """Issue 785: https://github.com/kennethreitz/requests/issues/785"""778        def add_foo_header(args):779            if not args.get('headers'):780                args['headers'] = {}781782            args['headers'].update({783                'X-Foo': 'foo'784            })785786            return args787788        def add_bar_header(args):789            if not args.get('headers'):790                args['headers'] = {}791792            args['headers'].update({793                'X-Bar': 'bar'794            })795796            return args797798        def assert_hooks_are_callable(hooks):799            for h in hooks['args']:800                self.assertTrue(isinstance(h, collections.Callable))801802        hooks = [add_foo_header, add_bar_header]803        r = requests.models.Request()804        r.register_hook('args', hooks)805        assert_hooks_are_callable(r.hooks)806807        r = requests.models.Request(hooks={'args': hooks})808        assert_hooks_are_callable(r.hooks)809810        hooks.append('string that should not be registered')811        r = requests.models.Request(hooks={'args': hooks})812        assert_hooks_are_callable(r.hooks)813814    def test_session_persistent_cookies(self):815816        s = requests.session()817818        # Internally dispatched cookies are sent.819        _c = {'kenneth': 'reitz', 'bessie': 'monke'}820        r = get(httpbin('cookies'), cookies=_c, session=s)821        r = get(httpbin('cookies'), session=s)822823        # Those cookies persist transparently.824        c = json.loads(r.text).get('cookies')825        self.assertEqual(c, _c)826827        # Double check.828        r = get(httpbin('cookies'), cookies={}, session=s)829        c = json.loads(r.text).get('cookies')830        self.assertEqual(c, _c)831832        # Remove a cookie by setting it's value to None.833        r = get(httpbin('cookies'), cookies={'bessie': None}, session=s)834        c = json.loads(r.text).get('cookies')835        del _c['bessie']836        self.assertEqual(c, _c)837838        # Test session-level cookies.839        s = requests.session(cookies=_c)840        r = get(httpbin('cookies'), session=s)841        c = json.loads(r.text).get('cookies')842        self.assertEqual(c, _c)843844        # Have the server set a cookie.845        r = get(httpbin('cookies', 'set', 'k', 'v'), allow_redirects=True, session=s)846        c = json.loads(r.text).get('cookies')847848        self.assertTrue('k' in c)849850        # And server-set cookie persistience.851        r = get(httpbin('cookies'), session=s)852        c = json.loads(r.text).get('cookies')853854        self.assertTrue('k' in c)855856    def test_session_persistent_params(self):857858        params = {'a': 'a_test'}859860        s = requests.session()861        s.params = params862863        # Make 2 requests from Session object, should send header both times864        r1 = get(httpbin('get'), session=s)865        self.assertTrue(params['a'] in r1.text)866867        params2 = {'b': 'b_test'}868869        r2 = get(httpbin('get'), params=params2, session=s)870        for param in (params['a'], params2['b']):871            self.assertTrue(param in r2.text)872873        params3 = {'b': 'b_test', 'a': None, 'c': 'c_test'}874875        r3 = get(httpbin('get'), params=params3, session=s)876877        self.assertFalse(params['a'] in r3.text)878879        for param in (params3['b'], params3['c']):880            self.assertTrue(param in r3.text)881882    def test_session_cookies_with_return_response_false(self):883        s = requests.session()884        # return_response=False as it does requests.async.get885        rq = get(httpbin('cookies', 'set', 'k', 'v'), return_response=False,886                 allow_redirects=True, session=s)887        rq.send(prefetch=True)888        c = rq.response.json.get('cookies')889        self.assertTrue('k' in c)890        self.assertTrue('k' in s.cookies)891892    def test_session_pickling(self):893894        s = requests.session(895                headers={'header': 'value'},896                cookies={'a-cookie': 'cookie-value'},897                auth=('username', 'password'))898899        ds = pickle.loads(pickle.dumps(s))900901        self.assertEqual(s.headers, ds.headers)902        self.assertEqual(s.auth, ds.auth)903904        # Cookie doesn't have a good __eq__, so verify manually:905        self.assertEqual(len(ds.cookies), 1)906        for cookie in ds.cookies:907            self.assertCookieHas(cookie, name='a-cookie', value='cookie-value')908909    def test_unpickled_session_requests(self):910        s = requests.session()911        r = get(httpbin('cookies', 'set', 'k', 'v'), allow_redirects=True, session=s)912        c = json.loads(r.text).get('cookies')913        self.assertTrue('k' in c)914915        ds = pickle.loads(pickle.dumps(s))916        r = get(httpbin('cookies'), session=ds)917        c = json.loads(r.text).get('cookies')918        self.assertTrue('k' in c)919920        ds1 = pickle.loads(pickle.dumps(requests.session()))921        ds2 = pickle.loads(pickle.dumps(requests.session(prefetch=False)))922        self.assertTrue(ds1.prefetch)923        self.assertFalse(ds2.prefetch)924925    def test_connection_error(self):926        try:927            get('http://localhost:1/nope')928        except requests.ConnectionError:929            pass930        else:931            self.fail()932933    def test_cached_response(self):934935        r1 = get(httpbin('get'), prefetch=False)936        self.assertFalse(r1._content)937        self.assertTrue(r1.content)938        self.assertTrue(r1.text)939940        r2 = get(httpbin('get'), prefetch=True)941        self.assertTrue(r2._content)942        self.assertTrue(r2.content)943        self.assertTrue(r2.text)944945    def test_iter_lines(self):946947        lines = (0, 2, 10, 100)948949        for i in lines:950            r = get(httpbin('stream', str(i)), prefetch=False)951            lines = list(r.iter_lines())952            len_lines = len(lines)953954            self.assertEqual(i, len_lines)955956        # Tests that trailing whitespaces within lines do not get stripped.957        # Tests that a trailing non-terminated line does not get stripped.958        quote = (959            '''Agamemnon  \n'''960            '''\tWhy will he not upon our fair request\r\n'''961            '''\tUntent his person and share the air with us?'''962        )963964        # Make a request and monkey-patch its contents965        r = get(httpbin('get'), prefetch=False)966        r.raw = StringIO(quote)967968        lines = list(r.iter_lines())969        len_lines = len(lines)970        self.assertEqual(len_lines, 3)971972        joined = lines[0] + '\n' + lines[1] + '\r\n' + lines[2]973        self.assertEqual(joined, quote)974975    def test_permissive_iter_content(self):976        """Test that iter_content and iter_lines work even after the body has been fetched."""977        r = get(httpbin('stream', '10'), prefetch=True)978        self.assertTrue(r._content_consumed)979        # iter_lines should still work without crashing980        self.assertEqual(len(list(r.iter_lines())), 10)981982        # iter_content should return a one-item iterator over the whole content983        iter_content_list = list(r.iter_content(chunk_size=1))984        self.assertTrue(all(len(item) == 1 for item in iter_content_list))985        # when joined, it should be exactly the original content986        self.assertEqual(bytes().join(iter_content_list), r.content)987988        # test different chunk sizes:989        for chunk_size in range(2, 20):990            self.assertEqual(bytes().join(r.iter_content(chunk_size=chunk_size)), r.content)991992993    def test_upload_binary_data(self):994995        requests.get(httpbin('post'), auth=('a', 'b'), data='\xff')996997    def test_useful_exception_for_invalid_port(self):998        # If we pass a legitimate URL with an invalid port, we should fail.999        self.assertRaises(1000              ValueError,1001              get,1002              'http://google.com:banana')10031004    def test_useful_exception_for_invalid_scheme(self):10051006        # If we pass a legitimate URL with a scheme not supported1007        # by requests, we should fail.1008        self.assertRaises(1009              ValueError,1010              get,1011              'ftp://ftp.kernel.org/pub/')10121013    def test_can_have_none_in_header_values(self):1014        try:1015            # Don't choke on headers with none in the value.1016            requests.get(httpbin('headers'), headers={'Foo': None})1017        except TypeError:1018            self.fail('Not able to have none in header values')101910201021    def test_empty_response(self):1022        r = requests.get(httpbin('status', '404'))1023        r.text10241025    def test_connection_keepalive_and_close(self):1026        """Test that we send 'Connection: close' when keep_alive is disabled."""1027        # keep-alive should be on by default1028        r1 = requests.get(httpbin('get'))1029        # XXX due to proxying issues, test the header sent back by httpbin, rather than1030        # the header reported in its message body. See kennethreitz/httpbin#461031        self.assertEqual(r1.headers['Connection'].lower(), 'keep-alive')10321033        # but when we disable it, we should send a 'Connection: close'1034        # and get the same back:1035        r2 = requests.get(httpbin('get'), config=dict(keep_alive=False))1036        self.assertEqual(r2.headers['Connection'].lower(), 'close')10371038    def test_head_content(self):1039        """Test that empty bodies are properly supported."""10401041        r = requests.head(httpbin('headers'))1042        r.content1043        r.text10441045    def test_post_fields_with_multiple_values_and_files(self):1046        """Test that it is possible to POST using the files argument and a1047        list for a value in the data argument."""10481049        data = {'field': ['a', 'b']}1050        files = {'field': 'Garbled data'}1051        r = post(httpbin('post'), data=data, files=files)1052        t = json.loads(r.text)1053        self.assertEqual(t.get('form'), {'field': ['a', 'b']})1054        self.assertEqual(t.get('files'), files)1055        r = post(httpbin('post'), data=data, files=files.items())1056        self.assertEqual(t.get('files'), files)10571058    def test_str_data_content_type(self):1059        data = 'test string data'1060        r = post(httpbin('post'), data=data)1061        t = json.loads(r.text)1062        self.assertEqual(t.get('headers').get('Content-Type'), '')10631064    def test_prefetch_redirect_bug(self):1065        """Test that prefetch persists across redirections."""1066        res = get(httpbin('redirect/2'), prefetch=False)1067        # prefetch should persist across the redirect;1068        # the content should not have been consumed1069        self.assertFalse(res._content_consumed)1070        first_line = next(res.iter_lines())1071        self.assertTrue(first_line.strip().decode('utf-8').startswith('{'))10721073    def test_prefetch_return_response_interaction(self):1074        """Test that prefetch can be overridden as a kwarg to `send`."""1075        req = requests.get(httpbin('get'), return_response=False)1076        req.send(prefetch=False)1077        # content should not have been prefetched1078        self.assertFalse(req.response._content_consumed)1079        first_line = next(req.response.iter_lines())1080        self.assertTrue(first_line.strip().decode('utf-8').startswith('{'))10811082    def test_accept_objects_with_string_representations_as_urls(self):1083        """Test that URLs can be set to objects with string representations,1084        e.g. for use with furl."""1085        class URL():1086            def __unicode__(self):1087                # Can't have unicode literals in Python3, so avoid them.1088                # TODO: fixup when moving to Python 3.31089                if (sys.version_info[0] == 2):1090                    return 'http://httpbin.org/get'.decode('utf-8')1091                else:1092                    return 'http://httpbin.org/get'10931094            def __str__(self):1095                return 'http://httpbin.org/get'10961097        r = get(URL())1098        self.assertEqual(r.status_code, 200)10991100    def test_post_fields_with_multiple_values_and_files_as_tuples(self):1101        """Test that it is possible to POST multiple data and file fields1102        with the same name.1103        https://github.com/kennethreitz/requests/pull/7461104        """11051106        fields = [1107            ('__field__', '__value__'),1108            ('__field__', '__value__'),1109        ]11101111        r = post(httpbin('post'), data=fields, files=fields)1112        t = json.loads(r.text)11131114        self.assertEqual(t.get('form'), {1115            '__field__': [1116                '__value__',1117                '__value__',1118            ]1119        })11201121        # It's not currently possible to test for multiple file fields with1122        # the same name against httpbin so we need to inspect the encoded1123        # body manually.1124        request = r.request1125        body, content_type = request._encode_files(request.files)1126        file_field = (b'Content-Disposition: form-data;'1127                      b' name="__field__"; filename="__field__"')1128        self.assertEqual(body.count(b'__value__'), 4)1129        self.assertEqual(body.count(file_field), 2)11301131    def test_bytes_files(self):1132        """Test that `bytes` can be used as the values of `files`."""1133        post(httpbin('post'), files={'test': b'test'})11341135    def test_invalid_urls_throw_requests_exception(self):1136        """Test that URLs with invalid labels throw1137        Requests.exceptions.InvalidURL instead of UnicodeError."""1138        self.assertRaises(InvalidURL, get, 'http://.google.com/')11391140    def test_none_vals_in_data_are_deleted(self):1141        """Test that keys with None as the value are removed instead of1142        being posted."""1143        data = {'key1': 'value1', 'key2': None}1144        r = post(httpbin('post'), data=data)1145        vals = r.json['form']1146        self.assertEqual(vals['key1'], 'value1')1147        # The 'key2' key should not have been sent.1148        self.assertTrue(vals.get('key2') is None)11491150if __name__ == '__main__':1151    unittest.main()