Skip to content
Myr

test_requests.py

This file

Path

tests/test_requests.py

1,234 lines · 41.7 KiB · Python

Last changed by

Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoption7fea9af

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_default_status_raising(self):466        config = {'danger_mode': True}467        args = [httpbin('status', '404')]468        kwargs = dict(config=config)469        self.assertRaises(HTTPError, get, *args, **kwargs)470471        r = get(httpbin('status', '200'))472        self.assertEqual(r.status_code, 200)473474    def test_decompress_gzip(self):475476        r = get(httpbin('gzip'))477        r.content.decode('ascii')478479    def test_response_has_unicode_url(self):480481        for service in SERVICES:482483            url = service('get')484485            response = get(url)486487            self.assertTrue(isinstance(response.url, str))488489    def test_unicode_get(self):490491        for service in SERVICES:492493            url = service('/get')494495            get(url, params={'foo': 'føø'})496            get(url, params={'føø': 'føø'})497            get(url, params={'føø': 'føø'})498            get(url, params={'foo': 'foo'})499            get(service('ø'), params={'foo': 'foo'})500501    def test_httpauth_recursion(self):502503        http_auth = HTTPBasicAuth('user', 'BADpass')504505        for service in SERVICES:506            r = get(service('basic-auth', 'user', 'pass'), auth=http_auth)507            self.assertEqual(r.status_code, 401)508509    def test_urlencoded_post_data(self):510511        for service in SERVICES:512513            r = post(service('post'), data=dict(test='fooaowpeuf'))514515            self.assertEqual(r.status_code, 200)516            self.assertEqual(r.headers['content-type'], 'application/json')517            self.assertEqual(r.url, service('post'))518519            rbody = json.loads(r.text)520521            self.assertEqual(rbody.get('form'), dict(test='fooaowpeuf'))522            self.assertEqual(rbody.get('data'), '')523524    def test_nonurlencoded_post_data(self):525526        for service in SERVICES:527528            r = post(service('post'), data='fooaowpeuf')529530            self.assertEqual(r.status_code, 200)531            self.assertEqual(r.headers['content-type'], 'application/json')532            self.assertEqual(r.url, service('post'))533534            rbody = json.loads(r.text)535            # Body wasn't valid url encoded data, so the server returns None as536            # "form" and the raw body as "data".537538            self.assertTrue(rbody.get('form') in (None, {}))539            self.assertEqual(rbody.get('data'), 'fooaowpeuf')540541    def test_file_post_data(self):542543        filecontent = b"fooaowpeufbarasjhf"544        testfile = tempfile.NamedTemporaryFile(delete=False)545        testfile.write(filecontent)546        testfile.flush()547        testfile.close()548549        for service in SERVICES:550551            data = open(testfile.name, "rb")552            r = post(service('post'), data=data,553                    headers={"content-type": "application/octet-stream"})554555            data.close()556            self.assertEqual(r.status_code, 200)557            self.assertEqual(r.headers['content-type'], 'application/json')558            self.assertEqual(r.url, service('post'))559560            rbody = json.loads(r.text)561            self.assertTrue(rbody.get('form') in (None, {}))562            self.assertEqual(rbody.get('data'), filecontent.decode('ascii'))563        os.remove(testfile.name)564565    def test_urlencoded_post_querystring(self):566567        for service in SERVICES:568569            r = post(service('post'), params=dict(test='fooaowpeuf'))570571            self.assertEqual(r.status_code, 200)572            self.assertEqual(r.headers['content-type'], 'application/json')573            self.assertEqual(r.url, service('post?test=fooaowpeuf'))574575            rbody = json.loads(r.text)576            self.assertEqual(rbody.get('form'), {})  # No form supplied577            self.assertEqual(rbody.get('data'), '')578579    def test_urlencoded_post_query_and_data(self):580581        for service in SERVICES:582583            r = post(584                service('post'),585                params=dict(test='fooaowpeuf'),586                data=dict(test2="foobar"))587588            self.assertEqual(r.status_code, 200)589            self.assertEqual(r.headers['content-type'], 'application/json')590            self.assertEqual(r.url, service('post?test=fooaowpeuf'))591592            rbody = json.loads(r.text)593            self.assertEqual(rbody.get('form'), dict(test2='foobar'))594            self.assertEqual(rbody.get('data'), '')595596    def test_nonurlencoded_postdata(self):597598        for service in SERVICES:599600            r = post(service('post'), data="foobar")601602            self.assertEqual(r.status_code, 200)603            self.assertEqual(r.headers['content-type'], 'application/json')604605            rbody = json.loads(r.text)606607            self.assertTrue(rbody.get('form') in (None, {}))608            self.assertEqual(rbody.get('data'), 'foobar')609610    def test_urlencoded_get_query_multivalued_param(self):611612        for service in SERVICES:613614            r = get(service('get'), params=dict(test=['foo', 'baz']))615            self.assertEqual(r.status_code, 200)616            self.assertEqual(r.url, service('get?test=foo&test=baz'))617618    def test_urlencoded_post_querystring_multivalued(self):619620        for service in SERVICES:621622            r = post(service('post'), params=dict(test=['foo', 'baz']))623            self.assertEqual(r.status_code, 200)624            self.assertEqual(r.headers['content-type'], 'application/json')625            self.assertEqual(r.url, service('post?test=foo&test=baz'))626627            rbody = json.loads(r.text)628            self.assertEqual(rbody.get('form'), {})  # No form supplied629            self.assertEqual(rbody.get('data'), '')630631    def test_urlencoded_post_query_multivalued_and_data(self):632633        for service in SERVICES:634635            r = post(636                service('post'),637                params=dict(test=['foo', 'baz']),638                data=dict(test2="foobar", test3=['foo', 'baz']))639640            self.assertEqual(r.status_code, 200)641            self.assertEqual(r.headers['content-type'], 'application/json')642            self.assertEqual(r.url, service('post?test=foo&test=baz'))643644            # print(r.text)645            # print('-----------------------')646647            rbody = json.loads(r.text)648            self.assertEqual(rbody.get('form'), dict(test2='foobar', test3=['foo', 'baz']))649            self.assertEqual(rbody.get('data'), '')650651    def test_multivalued_data_encoding(self):652        """653        Make sure data encoding works on a value that is an iterable but not654        a list655        """656        for service in SERVICES:657            # Can't have unicode literals in Python3, so avoid them.658            # TODO: fixup when moving to Python 3.3659            if (sys.version_info[0] == 2):660                nonascii = '\xc3\xa9'.decode('utf-8')661            else:662                nonascii = '\xe9'663664            r = post(665                service('post'),666                data=dict(test=('foo', nonascii)))667668            self.assertEqual(r.status_code, 200)669            self.assertEqual(r.headers['content-type'], 'application/json')670671            rbody = json.loads(r.text)672            self.assertEqual(rbody.get('form'),673                             dict(test=['foo', nonascii]))674675    def test_GET_no_redirect(self):676677        for service in SERVICES:678679            r = get(service('redirect', '3'), allow_redirects=False)680            self.assertEqual(r.status_code, 302)681            self.assertEqual(len(r.history), 0)682683    def test_HEAD_no_redirect(self):684685        for service in SERVICES:686687            r = head(service('redirect', '3'), allow_redirects=False)688            self.assertEqual(r.status_code, 302)689            self.assertEqual(len(r.history), 0)690691    def test_redirect_history(self):692693        for service in SERVICES:694695            r = get(service('redirect', '3'))696            self.assertEqual(r.status_code, 200)697            self.assertEqual(len(r.history), 3)698699    def test_relative_redirect_history(self):700701        for service in SERVICES:702703            r = get(service('relative-redirect', '3'))704            self.assertEqual(r.status_code, 200)705            self.assertEqual(len(r.history), 3)706707    def test_session_HTTP_200_OK_GET(self):708709        s = requests.session()710        r = get(httpbin('get'), session=s)711        self.assertEqual(r.status_code, 200)712713    def test_session_persistent_headers(self):714715        heads = {'User-agent': 'Mozilla/5.0'}716717        s = requests.session()718        s.headers = heads719720        # Make 2 requests from Session object, should send header both times721        r1 = get(httpbin('user-agent'), session=s)722        self.assertTrue(heads['User-agent'] in r1.text)723724        r2 = get(httpbin('user-agent'), session=s)725        self.assertTrue(heads['User-agent'] in r2.text)726727        new_heads = {'User-agent': 'blah'}728        r3 = get(httpbin('user-agent'), headers=new_heads, session=s)729        self.assertTrue(new_heads['User-agent'] in r3.text)730731        self.assertEqual(r2.status_code, 200)732733    def test_single_hook(self):734735        def add_foo_header(args):736            if not args.get('headers'):737                args['headers'] = {}738739            args['headers'].update({740                'X-Foo': 'foo'741            })742743            return args744745        for service in SERVICES:746            url = service('headers')747            response = get(url=url, hooks={'args': add_foo_header})748749            self.assertTrue('foo' in response.text)750751    def test_multiple_hooks(self):752753        def add_foo_header(args):754            if not args.get('headers'):755                args['headers'] = {}756757            args['headers'].update({758                'X-Foo': 'foo'759            })760761            return args762763        def add_bar_header(args):764            if not args.get('headers'):765                args['headers'] = {}766767            args['headers'].update({768                'X-Bar': 'bar'769            })770771            return args772773        for service in SERVICES:774            url = service('headers')775776            response = get(url=url,777                hooks={778                    'args': [add_foo_header, add_bar_header]779                }780            )781782            for text in ('foo', 'bar'):783                self.assertTrue(text in response.text)784785    def test_allow_list_of_hooks_to_register_hook(self):786        """Issue 785: https://github.com/kennethreitz/requests/issues/785"""787        def add_foo_header(args):788            if not args.get('headers'):789                args['headers'] = {}790791            args['headers'].update({792                'X-Foo': 'foo'793            })794795            return args796797        def add_bar_header(args):798            if not args.get('headers'):799                args['headers'] = {}800801            args['headers'].update({802                'X-Bar': 'bar'803            })804805            return args806807        def assert_hooks_are_callable(hooks):808            for h in hooks['args']:809                self.assertTrue(isinstance(h, collections.Callable))810811        hooks = [add_foo_header, add_bar_header]812        r = requests.models.Request()813        r.register_hook('args', hooks)814        assert_hooks_are_callable(r.hooks)815816        r = requests.models.Request(hooks={'args': hooks})817        assert_hooks_are_callable(r.hooks)818819        hooks.append('string that should not be registered')820        r = requests.models.Request(hooks={'args': hooks})821        assert_hooks_are_callable(r.hooks)822823    def test_session_persistent_cookies(self):824825        s = requests.session()826827        # Internally dispatched cookies are sent.828        _c = {'kenneth': 'reitz', 'bessie': 'monke'}829        r = get(httpbin('cookies'), cookies=_c, session=s)830        r = get(httpbin('cookies'), session=s)831832        # Those cookies persist transparently.833        c = json.loads(r.text).get('cookies')834        self.assertEqual(c, _c)835836        # Double check.837        r = get(httpbin('cookies'), cookies={}, session=s)838        c = json.loads(r.text).get('cookies')839        self.assertEqual(c, _c)840841        # Remove a cookie by setting it's value to None.842        r = get(httpbin('cookies'), cookies={'bessie': None}, session=s)843        c = json.loads(r.text).get('cookies')844        del _c['bessie']845        self.assertEqual(c, _c)846847        # Test session-level cookies.848        s = requests.session(cookies=_c)849        r = get(httpbin('cookies'), session=s)850        c = json.loads(r.text).get('cookies')851        self.assertEqual(c, _c)852853        # Have the server set a cookie.854        r = get(httpbin('cookies', 'set', 'k', 'v'), allow_redirects=True, session=s)855        c = json.loads(r.text).get('cookies')856857        self.assertTrue('k' in c)858859        # And server-set cookie persistience.860        r = get(httpbin('cookies'), session=s)861        c = json.loads(r.text).get('cookies')862863        self.assertTrue('k' in c)864865    def test_session_persistent_params(self):866867        params = {'a': 'a_test'}868869        s = requests.session()870        s.params = params871872        # Make 2 requests from Session object, should send header both times873        r1 = get(httpbin('get'), session=s)874        self.assertTrue(params['a'] in r1.text)875876        params2 = {'b': 'b_test'}877878        r2 = get(httpbin('get'), params=params2, session=s)879        for param in (params['a'], params2['b']):880            self.assertTrue(param in r2.text)881882        params3 = {'b': 'b_test', 'a': None, 'c': 'c_test'}883884        r3 = get(httpbin('get'), params=params3, session=s)885886        self.assertFalse(params['a'] in r3.text)887888        for param in (params3['b'], params3['c']):889            self.assertTrue(param in r3.text)890891    def test_session_cookies_with_return_response_false(self):892        s = requests.session()893        # return_response=False as it does requests.async.get894        rq = get(httpbin('cookies', 'set', 'k', 'v'), return_response=False,895                 allow_redirects=True, session=s)896        rq.send(prefetch=True)897        c = rq.response.json.get('cookies')898        self.assertTrue('k' in c)899        self.assertTrue('k' in s.cookies)900901    def test_session_pickling(self):902903        s = requests.session(904                headers={'header': 'value'},905                cookies={'a-cookie': 'cookie-value'},906                auth=('username', 'password'))907908        ds = pickle.loads(pickle.dumps(s))909910        self.assertEqual(s.headers, ds.headers)911        self.assertEqual(s.auth, ds.auth)912913        # Cookie doesn't have a good __eq__, so verify manually:914        self.assertEqual(len(ds.cookies), 1)915        for cookie in ds.cookies:916            self.assertCookieHas(cookie, name='a-cookie', value='cookie-value')917918    def test_unpickled_session_requests(self):919        s = requests.session()920        r = get(httpbin('cookies', 'set', 'k', 'v'), allow_redirects=True, session=s)921        c = json.loads(r.text).get('cookies')922        self.assertTrue('k' in c)923924        ds = pickle.loads(pickle.dumps(s))925        r = get(httpbin('cookies'), session=ds)926        c = json.loads(r.text).get('cookies')927        self.assertTrue('k' in c)928929        ds1 = pickle.loads(pickle.dumps(requests.session()))930        ds2 = pickle.loads(pickle.dumps(requests.session(prefetch=False)))931        self.assertTrue(ds1.prefetch)932        self.assertFalse(ds2.prefetch)933    934    def test_session_connection_error_with_safe_mode(self):935        config = {"safe_mode":True}936937        s = requests.session()938        r = s.get("http://localhost:1/nope", timeout=0.1, config=config)939        self.assertFalse(r.ok)940        self.assertTrue(r.content is None)941942        s2 = requests.session(config=config)943        r2 = s2.get("http://localhost:1/nope", timeout=0.1)944        self.assertFalse(r2.ok)945        self.assertTrue(r2.content is None)946947    def test_connection_error(self):948        try:949            get('http://localhost:1/nope')950        except requests.ConnectionError:951            pass952        else:953            self.fail()954955    def test_connection_error_with_safe_mode(self):956        config = {'safe_mode': True}957        r = get('http://localhost:1/nope', allow_redirects=False, config=config)958        self.assertTrue(r.content is None)959960    # def test_invalid_content(self):961    #     # WARNING: if you're using a terrible DNS provider (comcast),962    #     # this will fail.963    #     try:964    #         hah = 'http://somedomainthatclearlydoesntexistg.com'965    #         r = get(hah, allow_redirects=False)966    #     except requests.ConnectionError:967    #         pass   # \o/968    #     else:969    #         assert False970971    #     config = {'safe_mode': True}972    #     r = get(hah, allow_redirects=False, config=config)973    #     assert r.content == None974975    def test_cached_response(self):976977        r1 = get(httpbin('get'), prefetch=False)978        self.assertFalse(r1._content)979        self.assertTrue(r1.content)980        self.assertTrue(r1.text)981982        r2 = get(httpbin('get'), prefetch=True)983        self.assertTrue(r2._content)984        self.assertTrue(r2.content)985        self.assertTrue(r2.text)986987    def test_iter_lines(self):988989        lines = (0, 2, 10, 100)990991        for i in lines:992            r = get(httpbin('stream', str(i)), prefetch=False)993            lines = list(r.iter_lines())994            len_lines = len(lines)995996            self.assertEqual(i, len_lines)997998        # Tests that trailing whitespaces within lines do not get stripped.999        # Tests that a trailing non-terminated line does not get stripped.1000        quote = (1001            '''Agamemnon  \n'''1002            '''\tWhy will he not upon our fair request\r\n'''1003            '''\tUntent his person and share the air with us?'''1004        )10051006        # Make a request and monkey-patch its contents1007        r = get(httpbin('get'), prefetch=False)1008        r.raw = StringIO(quote)10091010        lines = list(r.iter_lines())1011        len_lines = len(lines)1012        self.assertEqual(len_lines, 3)10131014        joined = lines[0] + '\n' + lines[1] + '\r\n' + lines[2]1015        self.assertEqual(joined, quote)10161017    def test_permissive_iter_content(self):1018        """Test that iter_content and iter_lines work even after the body has been fetched."""1019        r = get(httpbin('stream', '10'), prefetch=True)1020        self.assertTrue(r._content_consumed)1021        # iter_lines should still work without crashing1022        self.assertEqual(len(list(r.iter_lines())), 10)10231024        # iter_content should return a one-item iterator over the whole content1025        iter_content_list = list(r.iter_content(chunk_size=1))1026        self.assertTrue(all(len(item) == 1 for item in iter_content_list))1027        # when joined, it should be exactly the original content1028        self.assertEqual(bytes().join(iter_content_list), r.content)10291030        # test different chunk sizes:1031        for chunk_size in range(2, 20):1032            self.assertEqual(bytes().join(r.iter_content(chunk_size=chunk_size)), r.content)103310341035    # def test_safe_mode(self):10361037    #     safe = requests.session(config=dict(safe_mode=True))10381039    #     # Safe mode creates empty responses for failed requests.1040    #     # Iterating on these responses should produce empty sequences1041    #     r = get('http://0.0.0.0:700/', session=safe)1042    #     self.assertEqual(list(r.iter_lines()), [])1043    #     assert isinstance(r.error, requests.exceptions.ConnectionError)10441045    #     r = get('http://0.0.0.0:789/', session=safe)1046    #     self.assertEqual(list(r.iter_content()), [])1047    #     assert isinstance(r.error, requests.exceptions.ConnectionError)10481049    #     # When not in safe mode, should raise Timeout exception1050    #     self.assertRaises(1051    #         requests.exceptions.Timeout,1052    #         get,1053    #         httpbin('stream', '1000'), timeout=0.0001)10541055    #     # In safe mode, should return a blank response1056    #     r = get(httpbin('stream', '1000'), timeout=0.0001,1057    #             config=dict(safe_mode=True))1058    #     assert r.content is None1059    #     assert isinstance(r.error, requests.exceptions.Timeout)10601061    def test_upload_binary_data(self):10621063        requests.get(httpbin('post'), auth=('a', 'b'), data='\xff')10641065    def test_useful_exception_for_invalid_port(self):1066        # If we pass a legitimate URL with an invalid port, we should fail.1067        self.assertRaises(1068              ValueError,1069              get,1070              'http://google.com:banana')10711072    def test_useful_exception_for_invalid_scheme(self):10731074        # If we pass a legitimate URL with a scheme not supported1075        # by requests, we should fail.1076        self.assertRaises(1077              ValueError,1078              get,1079              'ftp://ftp.kernel.org/pub/')10801081    def test_can_have_none_in_header_values(self):1082        try:1083            # Don't choke on headers with none in the value.1084            requests.get(httpbin('headers'), headers={'Foo': None})1085        except TypeError:1086            self.fail('Not able to have none in header values')10871088    def test_danger_mode_redirects(self):1089        s = requests.session()1090        s.config['danger_mode'] = True1091        s.get(httpbin('redirect', '4'))10921093    def test_empty_response(self):1094        r = requests.get(httpbin('status', '404'))1095        r.text10961097    def test_max_redirects(self):1098        """Test the max_redirects config variable, normally and under safe_mode."""1099        def unsafe_callable():1100            requests.get(httpbin('redirect', '3'), config=dict(max_redirects=2))1101        self.assertRaises(requests.exceptions.TooManyRedirects, unsafe_callable)11021103        # add safe mode1104        response = requests.get(httpbin('redirect', '3'), config=dict(safe_mode=True, max_redirects=2))1105        self.assertTrue(response.content is None)1106        self.assertTrue(isinstance(response.error, requests.exceptions.TooManyRedirects))11071108    def test_connection_keepalive_and_close(self):1109        """Test that we send 'Connection: close' when keep_alive is disabled."""1110        # keep-alive should be on by default1111        r1 = requests.get(httpbin('get'))1112        # XXX due to proxying issues, test the header sent back by httpbin, rather than1113        # the header reported in its message body. See kennethreitz/httpbin#461114        self.assertEqual(r1.headers['Connection'].lower(), 'keep-alive')11151116        # but when we disable it, we should send a 'Connection: close'1117        # and get the same back:1118        r2 = requests.get(httpbin('get'), config=dict(keep_alive=False))1119        self.assertEqual(r2.headers['Connection'].lower(), 'close')11201121    def test_head_content(self):1122        """Test that empty bodies are properly supported."""11231124        r = requests.head(httpbin('headers'))1125        r.content1126        r.text11271128    def test_post_fields_with_multiple_values_and_files(self):1129        """Test that it is possible to POST using the files argument and a1130        list for a value in the data argument."""11311132        data = {'field': ['a', 'b']}1133        files = {'field': 'Garbled data'}1134        r = post(httpbin('post'), data=data, files=files)1135        t = json.loads(r.text)1136        self.assertEqual(t.get('form'), {'field': ['a', 'b']})1137        self.assertEqual(t.get('files'), files)1138        r = post(httpbin('post'), data=data, files=files.items())1139        self.assertEqual(t.get('files'), files)11401141    def test_str_data_content_type(self):1142        data = 'test string data'1143        r = post(httpbin('post'), data=data)1144        t = json.loads(r.text)1145        self.assertEqual(t.get('headers').get('Content-Type'), '')11461147    def test_prefetch_redirect_bug(self):1148        """Test that prefetch persists across redirections."""1149        res = get(httpbin('redirect/2'), prefetch=False)1150        # prefetch should persist across the redirect;1151        # the content should not have been consumed1152        self.assertFalse(res._content_consumed)1153        first_line = next(res.iter_lines())1154        self.assertTrue(first_line.strip().decode('utf-8').startswith('{'))11551156    def test_prefetch_return_response_interaction(self):1157        """Test that prefetch can be overridden as a kwarg to `send`."""1158        req = requests.get(httpbin('get'), return_response=False)1159        req.send(prefetch=False)1160        # content should not have been prefetched1161        self.assertFalse(req.response._content_consumed)1162        first_line = next(req.response.iter_lines())1163        self.assertTrue(first_line.strip().decode('utf-8').startswith('{'))11641165    def test_accept_objects_with_string_representations_as_urls(self):1166        """Test that URLs can be set to objects with string representations,1167        e.g. for use with furl."""1168        class URL():1169            def __unicode__(self):1170                # Can't have unicode literals in Python3, so avoid them.1171                # TODO: fixup when moving to Python 3.31172                if (sys.version_info[0] == 2):1173                    return 'http://httpbin.org/get'.decode('utf-8')1174                else:1175                    return 'http://httpbin.org/get'11761177            def __str__(self):1178                return 'http://httpbin.org/get'11791180        r = get(URL())1181        self.assertEqual(r.status_code, 200)11821183    def test_post_fields_with_multiple_values_and_files_as_tuples(self):1184        """Test that it is possible to POST multiple data and file fields1185        with the same name.1186        https://github.com/kennethreitz/requests/pull/7461187        """11881189        fields = [1190            ('__field__', '__value__'),1191            ('__field__', '__value__'),1192        ]11931194        r = post(httpbin('post'), data=fields, files=fields)1195        t = json.loads(r.text)11961197        self.assertEqual(t.get('form'), {1198            '__field__': [1199                '__value__',1200                '__value__',1201            ]1202        })12031204        # It's not currently possible to test for multiple file fields with1205        # the same name against httpbin so we need to inspect the encoded1206        # body manually.1207        request = r.request1208        body, content_type = request._encode_files(request.files)1209        file_field = (b'Content-Disposition: form-data;'1210                      b' name="__field__"; filename="__field__"')1211        self.assertEqual(body.count(b'__value__'), 4)1212        self.assertEqual(body.count(file_field), 2)12131214    def test_bytes_files(self):1215        """Test that `bytes` can be used as the values of `files`."""1216        post(httpbin('post'), files={'test': b'test'})12171218    def test_invalid_urls_throw_requests_exception(self):1219        """Test that URLs with invalid labels throw1220        Requests.exceptions.InvalidURL instead of UnicodeError."""1221        self.assertRaises(InvalidURL, get, 'http://.google.com/')12221223    def test_none_vals_in_data_are_deleted(self):1224        """Test that keys with None as the value are removed instead of1225        being posted."""1226        data = {'key1': 'value1', 'key2': None}1227        r = post(httpbin('post'), data=data)1228        vals = r.json['form']1229        self.assertEqual(vals['key1'], 'value1')1230        # The 'key2' key should not have been sent.1231        self.assertTrue(vals.get('key2') is None)12321233if __name__ == '__main__':1234    unittest.main()