Skip to content
Myr

test_requests.py

This file

Path

tests/test_requests.py

1,782 lines · 60.5 KiB · Python

Last changed by

Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456

History of this file

Take it

1#!/usr/bin/env python2# -*- coding: utf-8 -*-34"""Tests for Requests."""56from __future__ import division7import json8import os9import pickle10import collections11import contextlib12import warnings1314import io15import requests16import pytest17from requests.adapters import HTTPAdapter18from requests.auth import HTTPDigestAuth, _basic_auth_str19from requests.compat import (20    Morsel, cookielib, getproxies, str, urlparse,21    builtin_str, OrderedDict)22from requests.cookies import cookiejar_from_dict, morsel_to_cookie23from requests.exceptions import (24    ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,25    MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects,26    ProxyError, InvalidHeader)27from requests.models import PreparedRequest28from requests.structures import CaseInsensitiveDict29from requests.sessions import SessionRedirectMixin30from requests.models import urlencode31from requests.hooks import default_hooks3233from .compat import StringIO, u34from .utils import override_environ3536# Requests to this URL should always fail with a connection timeout (nothing37# listening on that port)38TARPIT = 'http://10.255.255.1'3940try:41    from ssl import SSLContext42    del SSLContext43    HAS_MODERN_SSL = True44except ImportError:45    HAS_MODERN_SSL = False4647try:48    requests.pyopenssl49    HAS_PYOPENSSL = True50except AttributeError:51    HAS_PYOPENSSL = False525354class TestRequests:5556    def test_entry_points(self):5758        requests.session59        requests.session().get60        requests.session().head61        requests.get62        requests.head63        requests.put64        requests.patch65        requests.post6667    @pytest.mark.parametrize(68        'exception, url', (69            (MissingSchema, 'hiwpefhipowhefopw'),70            (InvalidSchema, 'localhost:3128'),71            (InvalidSchema, 'localhost.localdomain:3128/'),72            (InvalidSchema, '10.122.1.1:3128/'),73            (InvalidURL, 'http://'),74        ))75    def test_invalid_url(self, exception, url):76        with pytest.raises(exception):77            requests.get(url)7879    def test_basic_building(self):80        req = requests.Request()81        req.url = 'http://kennethreitz.org/'82        req.data = {'life': '42'}8384        pr = req.prepare()85        assert pr.url == req.url86        assert pr.body == 'life=42'8788    @pytest.mark.parametrize('method', ('GET', 'HEAD'))89    def test_no_content_length(self, httpbin, method):90        req = requests.Request(method, httpbin(method.lower())).prepare()91        assert 'Content-Length' not in req.headers9293    def test_override_content_length(self, httpbin):94        headers = {95            'Content-Length': 'not zero'96        }97        r = requests.Request('POST', httpbin('post'), headers=headers).prepare()98        assert 'Content-Length' in r.headers99        assert r.headers['Content-Length'] == 'not zero'100101    def test_path_is_not_double_encoded(self):102        request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()103104        assert request.path_url == '/get/test%20case'105106    @pytest.mark.parametrize(107        'url, expected', (108            ('http://example.com/path#fragment', 'http://example.com/path?a=b#fragment'),109            ('http://example.com/path?key=value#fragment', 'http://example.com/path?key=value&a=b#fragment')110        ))111    def test_params_are_added_before_fragment(self, url, expected):112        request = requests.Request('GET', url, params={"a": "b"}).prepare()113        assert request.url == expected114115    def test_params_original_order_is_preserved_by_default(self):116        param_ordered_dict = OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))117        session = requests.Session()118        request = requests.Request('GET', 'http://example.com/', params=param_ordered_dict)119        prep = session.prepare_request(request)120        assert prep.url == 'http://example.com/?z=1&a=1&k=1&d=1'121122    def test_params_bytes_are_encoded(self):123        request = requests.Request('GET', 'http://example.com',124                                   params=b'test=foo').prepare()125        assert request.url == 'http://example.com/?test=foo'126127    def test_binary_put(self):128        request = requests.Request('PUT', 'http://example.com',129                                   data=u"ööö".encode("utf-8")).prepare()130        assert isinstance(request.body, bytes)131132    @pytest.mark.parametrize('scheme', ('http://', 'HTTP://', 'hTTp://', 'HttP://'))133    def test_mixed_case_scheme_acceptable(self, httpbin, scheme):134        s = requests.Session()135        s.proxies = getproxies()136        parts = urlparse(httpbin('get'))137        url = scheme + parts.netloc + parts.path138        r = requests.Request('GET', url)139        r = s.send(r.prepare())140        assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)141142    def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):143        r = requests.Request('GET', httpbin('get'))144        s = requests.Session()145        s.proxies = getproxies()146147        r = s.send(r.prepare())148149        assert r.status_code == 200150151    def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):152        r = requests.get(httpbin('redirect', '1'))153        assert r.status_code == 200154        assert r.history[0].status_code == 302155        assert r.history[0].is_redirect156157    def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):158        try:159            requests.get(httpbin('relative-redirect', '50'))160        except TooManyRedirects as e:161            url = httpbin('relative-redirect', '20')162            assert e.request.url == url163            assert e.response.url == url164            assert len(e.response.history) == 30165        else:166            pytest.fail('Expected redirect to raise TooManyRedirects but it did not')167168    def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):169        s = requests.session()170        s.max_redirects = 5171        try:172            s.get(httpbin('relative-redirect', '50'))173        except TooManyRedirects as e:174            url = httpbin('relative-redirect', '45')175            assert e.request.url == url176            assert e.response.url == url177            assert len(e.response.history) == 5178        else:179            pytest.fail('Expected custom max number of redirects to be respected but was not')180181    def test_http_301_changes_post_to_get(self, httpbin):182        r = requests.post(httpbin('status', '301'))183        assert r.status_code == 200184        assert r.request.method == 'GET'185        assert r.history[0].status_code == 301186        assert r.history[0].is_redirect187188    def test_http_301_doesnt_change_head_to_get(self, httpbin):189        r = requests.head(httpbin('status', '301'), allow_redirects=True)190        print(r.content)191        assert r.status_code == 200192        assert r.request.method == 'HEAD'193        assert r.history[0].status_code == 301194        assert r.history[0].is_redirect195196    def test_http_302_changes_post_to_get(self, httpbin):197        r = requests.post(httpbin('status', '302'))198        assert r.status_code == 200199        assert r.request.method == 'GET'200        assert r.history[0].status_code == 302201        assert r.history[0].is_redirect202203    def test_http_302_doesnt_change_head_to_get(self, httpbin):204        r = requests.head(httpbin('status', '302'), allow_redirects=True)205        assert r.status_code == 200206        assert r.request.method == 'HEAD'207        assert r.history[0].status_code == 302208        assert r.history[0].is_redirect209210    def test_http_303_changes_post_to_get(self, httpbin):211        r = requests.post(httpbin('status', '303'))212        assert r.status_code == 200213        assert r.request.method == 'GET'214        assert r.history[0].status_code == 303215        assert r.history[0].is_redirect216217    def test_http_303_doesnt_change_head_to_get(self, httpbin):218        r = requests.head(httpbin('status', '303'), allow_redirects=True)219        assert r.status_code == 200220        assert r.request.method == 'HEAD'221        assert r.history[0].status_code == 303222        assert r.history[0].is_redirect223224    def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):225        heads = {'User-agent': 'Mozilla/5.0'}226227        r = requests.get(httpbin('user-agent'), headers=heads)228229        assert heads['User-agent'] in r.text230        assert r.status_code == 200231232    def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):233        heads = {'User-agent': 'Mozilla/5.0'}234235        r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)236        assert r.status_code == 200237238    def test_set_cookie_on_301(self, httpbin):239        s = requests.session()240        url = httpbin('cookies/set?foo=bar')241        s.get(url)242        assert s.cookies['foo'] == 'bar'243244    def test_cookie_sent_on_redirect(self, httpbin):245        s = requests.session()246        s.get(httpbin('cookies/set?foo=bar'))247        r = s.get(httpbin('redirect/1'))  # redirects to httpbin('get')248        assert 'Cookie' in r.json()['headers']249250    def test_cookie_removed_on_expire(self, httpbin):251        s = requests.session()252        s.get(httpbin('cookies/set?foo=bar'))253        assert s.cookies['foo'] == 'bar'254        s.get(255            httpbin('response-headers'),256            params={257                'Set-Cookie':258                    'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'259            }260        )261        assert 'foo' not in s.cookies262263    def test_cookie_quote_wrapped(self, httpbin):264        s = requests.session()265        s.get(httpbin('cookies/set?foo="bar:baz"'))266        assert s.cookies['foo'] == '"bar:baz"'267268    def test_cookie_persists_via_api(self, httpbin):269        s = requests.session()270        r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})271        assert 'foo' in r.request.headers['Cookie']272        assert 'foo' in r.history[0].request.headers['Cookie']273274    def test_request_cookie_overrides_session_cookie(self, httpbin):275        s = requests.session()276        s.cookies['foo'] = 'bar'277        r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})278        assert r.json()['cookies']['foo'] == 'baz'279        # Session cookie should not be modified280        assert s.cookies['foo'] == 'bar'281282    def test_request_cookies_not_persisted(self, httpbin):283        s = requests.session()284        s.get(httpbin('cookies'), cookies={'foo': 'baz'})285        # Sending a request with cookies should not add cookies to the session286        assert not s.cookies287288    def test_generic_cookiejar_works(self, httpbin):289        cj = cookielib.CookieJar()290        cookiejar_from_dict({'foo': 'bar'}, cj)291        s = requests.session()292        s.cookies = cj293        r = s.get(httpbin('cookies'))294        # Make sure the cookie was sent295        assert r.json()['cookies']['foo'] == 'bar'296        # Make sure the session cj is still the custom one297        assert s.cookies is cj298299    def test_param_cookiejar_works(self, httpbin):300        cj = cookielib.CookieJar()301        cookiejar_from_dict({'foo': 'bar'}, cj)302        s = requests.session()303        r = s.get(httpbin('cookies'), cookies=cj)304        # Make sure the cookie was sent305        assert r.json()['cookies']['foo'] == 'bar'306307    def test_requests_in_history_are_not_overridden(self, httpbin):308        resp = requests.get(httpbin('redirect/3'))309        urls = [r.url for r in resp.history]310        req_urls = [r.request.url for r in resp.history]311        assert urls == req_urls312313    def test_history_is_always_a_list(self, httpbin):314        """Show that even with redirects, Response.history is always a list."""315        resp = requests.get(httpbin('get'))316        assert isinstance(resp.history, list)317        resp = requests.get(httpbin('redirect/1'))318        assert isinstance(resp.history, list)319        assert not isinstance(resp.history, tuple)320321    def test_headers_on_session_with_None_are_not_sent(self, httpbin):322        """Do not send headers in Session.headers with None values."""323        ses = requests.Session()324        ses.headers['Accept-Encoding'] = None325        req = requests.Request('GET', httpbin('get'))326        prep = ses.prepare_request(req)327        assert 'Accept-Encoding' not in prep.headers328329    def test_headers_preserve_order(self, httpbin):330        """Preserve order when headers provided as OrderedDict."""331        ses = requests.Session()332        ses.headers = OrderedDict()333        ses.headers['Accept-Encoding'] = 'identity'334        ses.headers['First'] = '1'335        ses.headers['Second'] = '2'336        headers = OrderedDict([('Third', '3'), ('Fourth', '4')])337        headers['Fifth'] = '5'338        headers['Second'] = '222'339        req = requests.Request('GET', httpbin('get'), headers=headers)340        prep = ses.prepare_request(req)341        items = list(prep.headers.items())342        assert items[0] == ('Accept-Encoding', 'identity')343        assert items[1] == ('First', '1')344        assert items[2] == ('Second', '222')345        assert items[3] == ('Third', '3')346        assert items[4] == ('Fourth', '4')347        assert items[5] == ('Fifth', '5')348349    @pytest.mark.parametrize('key', ('User-agent', 'user-agent'))350    def test_user_agent_transfers(self, httpbin, key):351352        heads = {key: 'Mozilla/5.0 (github.com/kennethreitz/requests)'}353354        r = requests.get(httpbin('user-agent'), headers=heads)355        assert heads[key] in r.text356357    def test_HTTP_200_OK_HEAD(self, httpbin):358        r = requests.head(httpbin('get'))359        assert r.status_code == 200360361    def test_HTTP_200_OK_PUT(self, httpbin):362        r = requests.put(httpbin('put'))363        assert r.status_code == 200364365    def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):366        auth = ('user', 'pass')367        url = httpbin('basic-auth', 'user', 'pass')368369        r = requests.get(url, auth=auth)370        assert r.status_code == 200371372        r = requests.get(url)373        assert r.status_code == 401374375        s = requests.session()376        s.auth = auth377        r = s.get(url)378        assert r.status_code == 200379380    @pytest.mark.parametrize(381        'url, exception', (382            # Connecting to an unknown domain should raise a ConnectionError383            ('http://doesnotexist.google.com', ConnectionError),384            # Connecting to an invalid port should raise a ConnectionError385            ('http://localhost:1', ConnectionError),386            # Inputing a URL that cannot be parsed should raise an InvalidURL error387            ('http://fe80::5054:ff:fe5a:fc0', InvalidURL)388        ))389    def test_errors(self, url, exception):390        with pytest.raises(exception):391            requests.get(url, timeout=1)392393    def test_proxy_error(self):394        # any proxy related error (address resolution, no route to host, etc) should result in a ProxyError395        with pytest.raises(ProxyError):396            requests.get('http://localhost:1', proxies={'http': 'non-resolvable-address'})397398    def test_basicauth_with_netrc(self, httpbin):399        auth = ('user', 'pass')400        wrong_auth = ('wronguser', 'wrongpass')401        url = httpbin('basic-auth', 'user', 'pass')402403        old_auth = requests.sessions.get_netrc_auth404405        try:406            def get_netrc_auth_mock(url):407                return auth408            requests.sessions.get_netrc_auth = get_netrc_auth_mock409410            # Should use netrc and work.411            r = requests.get(url)412            assert r.status_code == 200413414            # Given auth should override and fail.415            r = requests.get(url, auth=wrong_auth)416            assert r.status_code == 401417418            s = requests.session()419420            # Should use netrc and work.421            r = s.get(url)422            assert r.status_code == 200423424            # Given auth should override and fail.425            s.auth = wrong_auth426            r = s.get(url)427            assert r.status_code == 401428        finally:429            requests.sessions.get_netrc_auth = old_auth430431    def test_DIGEST_HTTP_200_OK_GET(self, httpbin):432433        auth = HTTPDigestAuth('user', 'pass')434        url = httpbin('digest-auth', 'auth', 'user', 'pass')435436        r = requests.get(url, auth=auth)437        assert r.status_code == 200438439        r = requests.get(url)440        assert r.status_code == 401441442        s = requests.session()443        s.auth = HTTPDigestAuth('user', 'pass')444        r = s.get(url)445        assert r.status_code == 200446447    def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):448        url = httpbin('digest-auth', 'auth', 'user', 'pass')449        auth = HTTPDigestAuth('user', 'pass')450        r = requests.get(url)451        assert r.cookies['fake'] == 'fake_value'452453        r = requests.get(url, auth=auth)454        assert r.status_code == 200455456    def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):457        url = httpbin('digest-auth', 'auth', 'user', 'pass')458        auth = HTTPDigestAuth('user', 'pass')459        s = requests.Session()460        s.get(url, auth=auth)461        assert s.cookies['fake'] == 'fake_value'462463    def test_DIGEST_STREAM(self, httpbin):464465        auth = HTTPDigestAuth('user', 'pass')466        url = httpbin('digest-auth', 'auth', 'user', 'pass')467468        r = requests.get(url, auth=auth, stream=True)469        assert r.raw.read() != b''470471        r = requests.get(url, auth=auth, stream=False)472        assert r.raw.read() == b''473474    def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):475476        auth = HTTPDigestAuth('user', 'wrongpass')477        url = httpbin('digest-auth', 'auth', 'user', 'pass')478479        r = requests.get(url, auth=auth)480        assert r.status_code == 401481482        r = requests.get(url)483        assert r.status_code == 401484485        s = requests.session()486        s.auth = auth487        r = s.get(url)488        assert r.status_code == 401489490    def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):491492        auth = HTTPDigestAuth('user', 'pass')493        url = httpbin('digest-auth', 'auth', 'user', 'pass')494495        r = requests.get(url, auth=auth)496        assert '"auth"' in r.request.headers['Authorization']497498    def test_POSTBIN_GET_POST_FILES(self, httpbin):499500        url = httpbin('post')501        requests.post(url).raise_for_status()502503        post1 = requests.post(url, data={'some': 'data'})504        assert post1.status_code == 200505506        with open('requirements.txt') as f:507            post2 = requests.post(url, files={'some': f})508        assert post2.status_code == 200509510        post4 = requests.post(url, data='[{"some": "json"}]')511        assert post4.status_code == 200512513        with pytest.raises(ValueError):514            requests.post(url, files=['bad file data'])515516    def test_POSTBIN_SEEKED_OBJECT_WITH_NO_ITER(self, httpbin):517518        class TestStream(object):519            def __init__(self, data):520                self.data = data.encode()521                self.length = len(self.data)522                self.index = 0523524            def __len__(self):525                return self.length526527            def read(self, size=None):528                if size:529                    ret = self.data[self.index:self.index + size]530                    self.index += size531                else:532                    ret = self.data[self.index:]533                    self.index = self.length534                return ret535536            def tell(self):537                return self.index538539            def seek(self, offset, where=0):540                if where == 0:541                    self.index = offset542                elif where == 1:543                    self.index += offset544                elif where == 2:545                    self.index = self.length + offset546547        test = TestStream('test')548        post1 = requests.post(httpbin('post'), data=test)549        assert post1.status_code == 200550        assert post1.json()['data'] == 'test'551552        test = TestStream('test')553        test.seek(2)554        post2 = requests.post(httpbin('post'), data=test)555        assert post2.status_code == 200556        assert post2.json()['data'] == 'st'557558    def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):559560        url = httpbin('post')561        requests.post(url).raise_for_status()562563        post1 = requests.post(url, data={'some': 'data'})564        assert post1.status_code == 200565566        with open('requirements.txt') as f:567            post2 = requests.post(url, data={'some': 'data'}, files={'some': f})568        assert post2.status_code == 200569570        post4 = requests.post(url, data='[{"some": "json"}]')571        assert post4.status_code == 200572573        with pytest.raises(ValueError):574            requests.post(url, files=['bad file data'])575576    def test_conflicting_post_params(self, httpbin):577        url = httpbin('post')578        with open('requirements.txt') as f:579            pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")580            pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")581582    def test_request_ok_set(self, httpbin):583        r = requests.get(httpbin('status', '404'))584        assert not r.ok585586    def test_status_raising(self, httpbin):587        r = requests.get(httpbin('status', '404'))588        with pytest.raises(requests.exceptions.HTTPError):589            r.raise_for_status()590591        r = requests.get(httpbin('status', '500'))592        assert not r.ok593594    def test_decompress_gzip(self, httpbin):595        r = requests.get(httpbin('gzip'))596        r.content.decode('ascii')597598    @pytest.mark.parametrize(599        'url, params', (600            ('/get', {'foo': 'føø'}),601            ('/get', {'føø': 'føø'}),602            ('/get', {'føø': 'føø'}),603            ('/get', {'foo': 'foo'}),604            ('ø', {'foo': 'foo'}),605        ))606    def test_unicode_get(self, httpbin, url, params):607        requests.get(httpbin(url), params=params)608609    def test_unicode_header_name(self, httpbin):610        requests.put(611            httpbin('put'),612            headers={str('Content-Type'): 'application/octet-stream'},613            data='\xff')  # compat.str is unicode.614615    def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):616        requests.get(httpbin_secure('status', '301'), verify=httpbin_ca_bundle)617618    def test_https_warnings(self, httpbin_secure, httpbin_ca_bundle):619        """warnings are emitted with requests.get"""620        if HAS_MODERN_SSL or HAS_PYOPENSSL:621            warnings_expected = ('SubjectAltNameWarning', )622        else:623            warnings_expected = ('SNIMissingWarning',624                                 'InsecurePlatformWarning',625                                 'SubjectAltNameWarning', )626627        with pytest.warns(None) as warning_records:628            warnings.simplefilter('always')629            requests.get(httpbin_secure('status', '200'),630                         verify=httpbin_ca_bundle)631632        warning_records = [item for item in warning_records633                           if item.category.__name__ != 'ResourceWarning']634635        warnings_category = tuple(636            item.category.__name__ for item in warning_records)637        assert warnings_category == warnings_expected638639    def test_urlencoded_get_query_multivalued_param(self, httpbin):640641        r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))642        assert r.status_code == 200643        assert r.url == httpbin('get?test=foo&test=baz')644645    def test_different_encodings_dont_break_post(self, httpbin):646        r = requests.post(httpbin('post'),647            data={'stuff': json.dumps({'a': 123})},648            params={'blah': 'asdf1234'},649            files={'file': ('test_requests.py', open(__file__, 'rb'))})650        assert r.status_code == 200651652    @pytest.mark.parametrize(653        'data', (654            {'stuff': u('ëlïxr')},655            {'stuff': u('ëlïxr').encode('utf-8')},656            {'stuff': 'elixr'},657            {'stuff': 'elixr'.encode('utf-8')},658        ))659    def test_unicode_multipart_post(self, httpbin, data):660        r = requests.post(httpbin('post'),661            data=data,662            files={'file': ('test_requests.py', open(__file__, 'rb'))})663        assert r.status_code == 200664665    def test_unicode_multipart_post_fieldnames(self, httpbin):666        filename = os.path.splitext(__file__)[0] + '.py'667        r = requests.Request(668            method='POST', url=httpbin('post'),669            data={'stuff'.encode('utf-8'): 'elixr'},670            files={'file': ('test_requests.py', open(filename, 'rb'))})671        prep = r.prepare()672        assert b'name="stuff"' in prep.body673        assert b'name="b\'stuff\'"' not in prep.body674675    def test_unicode_method_name(self, httpbin):676        files = {'file': open(__file__, 'rb')}677        r = requests.request(678            method=u('POST'), url=httpbin('post'), files=files)679        assert r.status_code == 200680681    def test_unicode_method_name_with_request_object(self, httpbin):682        files = {'file': open(__file__, 'rb')}683        s = requests.Session()684        req = requests.Request(u('POST'), httpbin('post'), files=files)685        prep = s.prepare_request(req)686        assert isinstance(prep.method, builtin_str)687        assert prep.method == 'POST'688689        resp = s.send(prep)690        assert resp.status_code == 200691692    def test_non_prepared_request_error(self):693        s = requests.Session()694        req = requests.Request(u('POST'), '/')695696        with pytest.raises(ValueError) as e:697            s.send(req)698        assert str(e.value) == 'You can only send PreparedRequests.'699700    def test_custom_content_type(self, httpbin):701        r = requests.post(702            httpbin('post'),703            data={'stuff': json.dumps({'a': 123})},704            files={705                'file1': ('test_requests.py', open(__file__, 'rb')),706                'file2': ('test_requests', open(__file__, 'rb'),707                    'text/py-content-type')})708        assert r.status_code == 200709        assert b"text/py-content-type" in r.request.body710711    def test_hook_receives_request_arguments(self, httpbin):712        def hook(resp, **kwargs):713            assert resp is not None714            assert kwargs != {}715716        s = requests.Session()717        r = requests.Request('GET', httpbin(), hooks={'response': hook})718        prep = s.prepare_request(r)719        s.send(prep)720721    def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):722        hook = lambda x, *args, **kwargs: x723        s = requests.Session()724        s.hooks['response'].append(hook)725        r = requests.Request('GET', httpbin())726        prep = s.prepare_request(r)727        assert prep.hooks['response'] != []728        assert prep.hooks['response'] == [hook]729730    def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):731        hook1 = lambda x, *args, **kwargs: x732        hook2 = lambda x, *args, **kwargs: x733        assert hook1 is not hook2734        s = requests.Session()735        s.hooks['response'].append(hook2)736        r = requests.Request('GET', httpbin(), hooks={'response': [hook1]})737        prep = s.prepare_request(r)738        assert prep.hooks['response'] == [hook1]739740    def test_prepared_request_hook(self, httpbin):741        def hook(resp, **kwargs):742            resp.hook_working = True743            return resp744745        req = requests.Request('GET', httpbin(), hooks={'response': hook})746        prep = req.prepare()747748        s = requests.Session()749        s.proxies = getproxies()750        resp = s.send(prep)751752        assert hasattr(resp, 'hook_working')753754    def test_prepared_from_session(self, httpbin):755        class DummyAuth(requests.auth.AuthBase):756            def __call__(self, r):757                r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'758                return r759760        req = requests.Request('GET', httpbin('headers'))761        assert not req.auth762763        s = requests.Session()764        s.auth = DummyAuth()765766        prep = s.prepare_request(req)767        resp = s.send(prep)768769        assert resp.json()['headers'][770            'Dummy-Auth-Test'] == 'dummy-auth-test-ok'771772    def test_prepare_request_with_bytestring_url(self):773        req = requests.Request('GET', b'https://httpbin.org/')774        s = requests.Session()775        prep = s.prepare_request(req)776        assert prep.url == "https://httpbin.org/"777778    def test_links(self):779        r = requests.Response()780        r.headers = {781            'cache-control': 'public, max-age=60, s-maxage=60',782            'connection': 'keep-alive',783            'content-encoding': 'gzip',784            'content-type': 'application/json; charset=utf-8',785            'date': 'Sat, 26 Jan 2013 16:47:56 GMT',786            'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',787            'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',788            'link': ('<https://api.github.com/users/kennethreitz/repos?'789                     'page=2&per_page=10>; rel="next", <https://api.github.'790                     'com/users/kennethreitz/repos?page=7&per_page=10>; '791                     ' rel="last"'),792            'server': 'GitHub.com',793            'status': '200 OK',794            'vary': 'Accept',795            'x-content-type-options': 'nosniff',796            'x-github-media-type': 'github.beta',797            'x-ratelimit-limit': '60',798            'x-ratelimit-remaining': '57'799        }800        assert r.links['next']['rel'] == 'next'801802    def test_cookie_parameters(self):803        key = 'some_cookie'804        value = 'some_value'805        secure = True806        domain = 'test.com'807        rest = {'HttpOnly': True}808809        jar = requests.cookies.RequestsCookieJar()810        jar.set(key, value, secure=secure, domain=domain, rest=rest)811812        assert len(jar) == 1813        assert 'some_cookie' in jar814815        cookie = list(jar)[0]816        assert cookie.secure == secure817        assert cookie.domain == domain818        assert cookie._rest['HttpOnly'] == rest['HttpOnly']819820    def test_cookie_as_dict_keeps_len(self):821        key = 'some_cookie'822        value = 'some_value'823824        key1 = 'some_cookie1'825        value1 = 'some_value1'826827        jar = requests.cookies.RequestsCookieJar()828        jar.set(key, value)829        jar.set(key1, value1)830831        d1 = dict(jar)832        d2 = dict(jar.iteritems())833        d3 = dict(jar.items())834835        assert len(jar) == 2836        assert len(d1) == 2837        assert len(d2) == 2838        assert len(d3) == 2839840    def test_cookie_as_dict_keeps_items(self):841        key = 'some_cookie'842        value = 'some_value'843844        key1 = 'some_cookie1'845        value1 = 'some_value1'846847        jar = requests.cookies.RequestsCookieJar()848        jar.set(key, value)849        jar.set(key1, value1)850851        d1 = dict(jar)852        d2 = dict(jar.iteritems())853        d3 = dict(jar.items())854855        assert d1['some_cookie'] == 'some_value'856        assert d2['some_cookie'] == 'some_value'857        assert d3['some_cookie1'] == 'some_value1'858859    def test_cookie_as_dict_keys(self):860        key = 'some_cookie'861        value = 'some_value'862863        key1 = 'some_cookie1'864        value1 = 'some_value1'865866        jar = requests.cookies.RequestsCookieJar()867        jar.set(key, value)868        jar.set(key1, value1)869870        keys = jar.keys()871        assert keys == list(keys)872        # make sure one can use keys multiple times873        assert list(keys) == list(keys)874875    def test_cookie_as_dict_values(self):876        key = 'some_cookie'877        value = 'some_value'878879        key1 = 'some_cookie1'880        value1 = 'some_value1'881882        jar = requests.cookies.RequestsCookieJar()883        jar.set(key, value)884        jar.set(key1, value1)885886        values = jar.values()887        assert values == list(values)888        # make sure one can use values multiple times889        assert list(values) == list(values)890891    def test_cookie_as_dict_items(self):892        key = 'some_cookie'893        value = 'some_value'894895        key1 = 'some_cookie1'896        value1 = 'some_value1'897898        jar = requests.cookies.RequestsCookieJar()899        jar.set(key, value)900        jar.set(key1, value1)901902        items = jar.items()903        assert items == list(items)904        # make sure one can use items multiple times905        assert list(items) == list(items)906907    def test_cookie_duplicate_names_different_domains(self):908        key = 'some_cookie'909        value = 'some_value'910        domain1 = 'test1.com'911        domain2 = 'test2.com'912913        jar = requests.cookies.RequestsCookieJar()914        jar.set(key, value, domain=domain1)915        jar.set(key, value, domain=domain2)916        assert key in jar917        items = jar.items()918        assert len(items) == 2919920        # Verify that CookieConflictError is raised if domain is not specified921        with pytest.raises(requests.cookies.CookieConflictError):922            jar.get(key)923924        # Verify that CookieConflictError is not raised if domain is specified925        cookie = jar.get(key, domain=domain1)926        assert cookie == value927928    def test_cookie_duplicate_names_raises_cookie_conflict_error(self):929        key = 'some_cookie'930        value = 'some_value'931        path = 'some_path'932933        jar = requests.cookies.RequestsCookieJar()934        jar.set(key, value, path=path)935        jar.set(key, value)936        with pytest.raises(requests.cookies.CookieConflictError):937            jar.get(key)938939    def test_time_elapsed_blank(self, httpbin):940        r = requests.get(httpbin('get'))941        td = r.elapsed942        total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6)943        assert total_seconds > 0.0944945    def test_response_is_iterable(self):946        r = requests.Response()947        io = StringIO.StringIO('abc')948        read_ = io.read949950        def read_mock(amt, decode_content=None):951            return read_(amt)952        setattr(io, 'read', read_mock)953        r.raw = io954        assert next(iter(r))955        io.close()956957    def test_response_decode_unicode(self):958        """When called with decode_unicode, Response.iter_content should always959        return unicode.960        """961        r = requests.Response()962        r._content_consumed = True963        r._content = b'the content'964        r.encoding = 'ascii'965966        chunks = r.iter_content(decode_unicode=True)967        assert all(isinstance(chunk, str) for chunk in chunks)968969        # also for streaming970        r = requests.Response()971        r.raw = io.BytesIO(b'the content')972        r.encoding = 'ascii'973        chunks = r.iter_content(decode_unicode=True)974        assert all(isinstance(chunk, str) for chunk in chunks)975976        # check for encoding value of None977        r = requests.Response()978        r.raw = io.BytesIO(b'the content')979        r.encoding = None980        chunks = r.iter_content(decode_unicode=True)981        assert all(isinstance(chunk, str) for chunk in chunks)982983    def test_response_reason_unicode(self):984        # check for unicode HTTP status985        r = requests.Response()986        r.url = u'unicode URL'987        r.reason = u'Komponenttia ei löydy'.encode('utf-8')988        r.status_code = 404989        r.encoding = None990        assert not r.ok  # old behaviour - crashes here991992    def test_response_chunk_size_type(self):993        """Ensure that chunk_size is passed as None or an integer, otherwise994        raise a TypeError.995        """996        r = requests.Response()997        r.raw = io.BytesIO(b'the content')998        chunks = r.iter_content(1)999        assert all(len(chunk) == 1 for chunk in chunks)10001001        r = requests.Response()1002        r.raw = io.BytesIO(b'the content')1003        chunks = r.iter_content(None)1004        assert list(chunks) == [b'the content']10051006        r = requests.Response()1007        r.raw = io.BytesIO(b'the content')1008        with pytest.raises(TypeError):1009            chunks = r.iter_content("1024")10101011    def test_request_and_response_are_pickleable(self, httpbin):1012        r = requests.get(httpbin('get'))10131014        # verify we can pickle the original request1015        assert pickle.loads(pickle.dumps(r.request))10161017        # verify we can pickle the response and that we have access to1018        # the original request.1019        pr = pickle.loads(pickle.dumps(r))1020        assert r.request.url == pr.request.url1021        assert r.request.headers == pr.request.headers10221023    def test_cannot_send_unprepared_requests(self, httpbin):1024        r = requests.Request(url=httpbin())1025        with pytest.raises(ValueError):1026            requests.Session().send(r)10271028    def test_http_error(self):1029        error = requests.exceptions.HTTPError()1030        assert not error.response1031        response = requests.Response()1032        error = requests.exceptions.HTTPError(response=response)1033        assert error.response == response1034        error = requests.exceptions.HTTPError('message', response=response)1035        assert str(error) == 'message'1036        assert error.response == response10371038    def test_session_pickling(self, httpbin):1039        r = requests.Request('GET', httpbin('get'))1040        s = requests.Session()10411042        s = pickle.loads(pickle.dumps(s))1043        s.proxies = getproxies()10441045        r = s.send(r.prepare())1046        assert r.status_code == 20010471048    def test_fixes_1329(self, httpbin):1049        """Ensure that header updates are done case-insensitively."""1050        s = requests.Session()1051        s.headers.update({'ACCEPT': 'BOGUS'})1052        s.headers.update({'accept': 'application/json'})1053        r = s.get(httpbin('get'))1054        headers = r.request.headers1055        assert headers['accept'] == 'application/json'1056        assert headers['Accept'] == 'application/json'1057        assert headers['ACCEPT'] == 'application/json'10581059    def test_uppercase_scheme_redirect(self, httpbin):1060        parts = urlparse(httpbin('html'))1061        url = "HTTP://" + parts.netloc + parts.path1062        r = requests.get(httpbin('redirect-to'), params={'url': url})1063        assert r.status_code == 2001064        assert r.url.lower() == url.lower()10651066    def test_transport_adapter_ordering(self):1067        s = requests.Session()1068        order = ['https://', 'http://']1069        assert order == list(s.adapters)1070        s.mount('http://git', HTTPAdapter())1071        s.mount('http://github', HTTPAdapter())1072        s.mount('http://github.com', HTTPAdapter())1073        s.mount('http://github.com/about/', HTTPAdapter())1074        order = [1075            'http://github.com/about/',1076            'http://github.com',1077            'http://github',1078            'http://git',1079            'https://',1080            'http://',1081        ]1082        assert order == list(s.adapters)1083        s.mount('http://gittip', HTTPAdapter())1084        s.mount('http://gittip.com', HTTPAdapter())1085        s.mount('http://gittip.com/about/', HTTPAdapter())1086        order = [1087            'http://github.com/about/',1088            'http://gittip.com/about/',1089            'http://github.com',1090            'http://gittip.com',1091            'http://github',1092            'http://gittip',1093            'http://git',1094            'https://',1095            'http://',1096        ]1097        assert order == list(s.adapters)1098        s2 = requests.Session()1099        s2.adapters = {'http://': HTTPAdapter()}1100        s2.mount('https://', HTTPAdapter())1101        assert 'http://' in s2.adapters1102        assert 'https://' in s2.adapters11031104    def test_header_remove_is_case_insensitive(self, httpbin):1105        # From issue #13211106        s = requests.Session()1107        s.headers['foo'] = 'bar'1108        r = s.get(httpbin('get'), headers={'FOO': None})1109        assert 'foo' not in r.request.headers11101111    def test_params_are_merged_case_sensitive(self, httpbin):1112        s = requests.Session()1113        s.params['foo'] = 'bar'1114        r = s.get(httpbin('get'), params={'FOO': 'bar'})1115        assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}11161117    def test_long_authinfo_in_url(self):1118        url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(1119            'E8A3BE87-9E3F-4620-8858-95478E385B5B',1120            'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',1121            'exactly-------------sixty-----------three------------characters',1122        )1123        r = requests.Request('GET', url).prepare()1124        assert r.url == url11251126    def test_header_keys_are_native(self, httpbin):1127        headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}1128        r = requests.Request('GET', httpbin('get'), headers=headers)1129        p = r.prepare()11301131        # This is testing that they are builtin strings. A bit weird, but there1132        # we go.1133        assert 'unicode' in p.headers.keys()1134        assert 'byte' in p.headers.keys()11351136    def test_header_validation(self, httpbin):1137        """Ensure prepare_headers regex isn't flagging valid header contents."""1138        headers_ok = {'foo': 'bar baz qux',1139                      'bar': u'fbbq'.encode('utf8'),1140                      'baz': '',1141                      'qux': '1'}1142        r = requests.get(httpbin('get'), headers=headers_ok)1143        assert r.request.headers['foo'] == headers_ok['foo']11441145    def test_header_value_not_str(self, httpbin):1146        """Ensure the header value is of type string or bytes as1147        per discussion in GH issue #33861148        """1149        headers_int = {'foo': 3}1150        headers_dict = {'bar': {'foo': 'bar'}}1151        headers_list = {'baz': ['foo', 'bar']}11521153        # Test for int1154        with pytest.raises(InvalidHeader):1155            r = requests.get(httpbin('get'), headers=headers_int)1156        # Test for dict1157        with pytest.raises(InvalidHeader):1158            r = requests.get(httpbin('get'), headers=headers_dict)1159        # Test for list1160        with pytest.raises(InvalidHeader):1161            r = requests.get(httpbin('get'), headers=headers_list)11621163    def test_header_no_return_chars(self, httpbin):1164        """Ensure that a header containing return character sequences raise an1165        exception. Otherwise, multiple headers are created from single string.1166        """1167        headers_ret = {'foo': 'bar\r\nbaz: qux'}1168        headers_lf = {'foo': 'bar\nbaz: qux'}1169        headers_cr = {'foo': 'bar\rbaz: qux'}11701171        # Test for newline1172        with pytest.raises(InvalidHeader):1173            r = requests.get(httpbin('get'), headers=headers_ret)1174        # Test for line feed1175        with pytest.raises(InvalidHeader):1176            r = requests.get(httpbin('get'), headers=headers_lf)1177        # Test for carriage return1178        with pytest.raises(InvalidHeader):1179            r = requests.get(httpbin('get'), headers=headers_cr)11801181    def test_header_no_leading_space(self, httpbin):1182        """Ensure headers containing leading whitespace raise1183        InvalidHeader Error before sending.1184        """1185        headers_space = {'foo': ' bar'}1186        headers_tab = {'foo': '   bar'}11871188        # Test for whitespace1189        with pytest.raises(InvalidHeader):1190            r = requests.get(httpbin('get'), headers=headers_space)1191        # Test for tab1192        with pytest.raises(InvalidHeader):1193            r = requests.get(httpbin('get'), headers=headers_tab)11941195    @pytest.mark.parametrize('files', ('foo', b'foo', bytearray(b'foo')))1196    def test_can_send_objects_with_files(self, httpbin, files):1197        data = {'a': 'this is a string'}1198        files = {'b': files}1199        r = requests.Request('POST', httpbin('post'), data=data, files=files)1200        p = r.prepare()1201        assert 'multipart/form-data' in p.headers['Content-Type']12021203    def test_can_send_file_object_with_non_string_filename(self, httpbin):1204        f = io.BytesIO()1205        f.name = 21206        r = requests.Request('POST', httpbin('post'), files={'f': f})1207        p = r.prepare()12081209        assert 'multipart/form-data' in p.headers['Content-Type']12101211    def test_autoset_header_values_are_native(self, httpbin):1212        data = 'this is a string'1213        length = '16'1214        req = requests.Request('POST', httpbin('post'), data=data)1215        p = req.prepare()12161217        assert p.headers['Content-Length'] == length12181219    def test_nonhttp_schemes_dont_check_URLs(self):1220        test_urls = (1221            'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',1222            'file:///etc/passwd',1223            'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',1224        )1225        for test_url in test_urls:1226            req = requests.Request('GET', test_url)1227            preq = req.prepare()1228            assert test_url == preq.url12291230    @pytest.mark.xfail(raises=ConnectionError)1231    def test_auth_is_stripped_on_redirect_off_host(self, httpbin):1232        r = requests.get(1233            httpbin('redirect-to'),1234            params={'url': 'http://www.google.co.uk'},1235            auth=('user', 'pass'),1236        )1237        assert r.history[0].request.headers['Authorization']1238        assert not r.request.headers.get('Authorization', '')12391240    def test_auth_is_retained_for_redirect_on_host(self, httpbin):1241        r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))1242        h1 = r.history[0].request.headers['Authorization']1243        h2 = r.request.headers['Authorization']12441245        assert h1 == h212461247    def test_manual_redirect_with_partial_body_read(self, httpbin):1248        s = requests.Session()1249        r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)1250        assert r1.is_redirect1251        rg = s.resolve_redirects(r1, r1.request, stream=True)12521253        # read only the first eight bytes of the response body,1254        # then follow the redirect1255        r1.iter_content(8)1256        r2 = next(rg)1257        assert r2.is_redirect12581259        # read all of the response via iter_content,1260        # then follow the redirect1261        for _ in r2.iter_content():1262            pass1263        r3 = next(rg)1264        assert not r3.is_redirect12651266    def _patch_adapter_gzipped_redirect(self, session, url):1267        adapter = session.get_adapter(url=url)1268        org_build_response = adapter.build_response1269        self._patched_response = False12701271        def build_response(*args, **kwargs):1272            resp = org_build_response(*args, **kwargs)1273            if not self._patched_response:1274                resp.raw.headers['content-encoding'] = 'gzip'1275                self._patched_response = True1276            return resp12771278        adapter.build_response = build_response12791280    def test_redirect_with_wrong_gzipped_header(self, httpbin):1281        s = requests.Session()1282        url = httpbin('redirect/1')1283        self._patch_adapter_gzipped_redirect(s, url)1284        s.get(url)12851286    def test_basic_auth_str_is_always_native(self):1287        s = _basic_auth_str("test", "test")1288        assert isinstance(s, builtin_str)1289        assert s == "Basic dGVzdDp0ZXN0"12901291    def test_requests_history_is_saved(self, httpbin):1292        r = requests.get(httpbin('redirect/5'))1293        total = r.history[-1].history1294        i = 01295        for item in r.history:1296            assert item.history == total[0:i]1297            i += 112981299    def test_json_param_post_content_type_works(self, httpbin):1300        r = requests.post(1301            httpbin('post'),1302            json={'life': 42}1303        )1304        assert r.status_code == 2001305        assert 'application/json' in r.request.headers['Content-Type']1306        assert {'life': 42} == r.json()['json']13071308    def test_json_param_post_should_not_override_data_param(self, httpbin):1309        r = requests.Request(method='POST', url=httpbin('post'),1310                             data={'stuff': 'elixr'},1311                             json={'music': 'flute'})1312        prep = r.prepare()1313        assert 'stuff=elixr' == prep.body13141315    def test_response_iter_lines(self, httpbin):1316        r = requests.get(httpbin('stream/4'), stream=True)1317        assert r.status_code == 20013181319        it = r.iter_lines()1320        next(it)1321        assert len(list(it)) == 313221323    def test_unconsumed_session_response_closes_connection(self, httpbin):1324        s = requests.session()13251326        with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1327            pass13281329        assert response._content_consumed is False1330        assert response.raw.closed13311332    @pytest.mark.xfail1333    def test_response_iter_lines_reentrant(self, httpbin):1334        """Response.iter_lines() is not reentrant safe"""1335        r = requests.get(httpbin('stream/4'), stream=True)1336        assert r.status_code == 20013371338        next(r.iter_lines())1339        assert len(list(r.iter_lines())) == 313401341    def test_session_close_proxy_clear(self, mocker):1342        proxies = {1343          'one': mocker.Mock(),1344          'two': mocker.Mock(),1345        }1346        session = requests.Session()1347        mocker.patch.dict(session.adapters['http://'].proxy_manager, proxies)1348        session.close()1349        proxies['one'].clear.assert_called_once_with()1350        proxies['two'].clear.assert_called_once_with()13511352    def test_response_json_when_content_is_None(self, httpbin):1353        r = requests.get(httpbin('/status/204'))1354        # Make sure r.content is None1355        r.status_code = 01356        r._content = False1357        r._content_consumed = False13581359        assert r.content is None1360        with pytest.raises(ValueError):1361            r.json()136213631364class TestCaseInsensitiveDict:13651366    @pytest.mark.parametrize(1367        'cid', (1368            CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}),1369            CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')]),1370            CaseInsensitiveDict(FOO='foo', BAr='bar'),1371        ))1372    def test_init(self, cid):1373        assert len(cid) == 21374        assert 'foo' in cid1375        assert 'bar' in cid13761377    def test_docstring_example(self):1378        cid = CaseInsensitiveDict()1379        cid['Accept'] = 'application/json'1380        assert cid['aCCEPT'] == 'application/json'1381        assert list(cid) == ['Accept']13821383    def test_len(self):1384        cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1385        cid['A'] = 'a'1386        assert len(cid) == 213871388    def test_getitem(self):1389        cid = CaseInsensitiveDict({'Spam': 'blueval'})1390        assert cid['spam'] == 'blueval'1391        assert cid['SPAM'] == 'blueval'13921393    def test_fixes_649(self):1394        """__setitem__ should behave case-insensitively."""1395        cid = CaseInsensitiveDict()1396        cid['spam'] = 'oneval'1397        cid['Spam'] = 'twoval'1398        cid['sPAM'] = 'redval'1399        cid['SPAM'] = 'blueval'1400        assert cid['spam'] == 'blueval'1401        assert cid['SPAM'] == 'blueval'1402        assert list(cid.keys()) == ['SPAM']14031404    def test_delitem(self):1405        cid = CaseInsensitiveDict()1406        cid['Spam'] = 'someval'1407        del cid['sPam']1408        assert 'spam' not in cid1409        assert len(cid) == 014101411    def test_contains(self):1412        cid = CaseInsensitiveDict()1413        cid['Spam'] = 'someval'1414        assert 'Spam' in cid1415        assert 'spam' in cid1416        assert 'SPAM' in cid1417        assert 'sPam' in cid1418        assert 'notspam' not in cid14191420    def test_get(self):1421        cid = CaseInsensitiveDict()1422        cid['spam'] = 'oneval'1423        cid['SPAM'] = 'blueval'1424        assert cid.get('spam') == 'blueval'1425        assert cid.get('SPAM') == 'blueval'1426        assert cid.get('sPam') == 'blueval'1427        assert cid.get('notspam', 'default') == 'default'14281429    def test_update(self):1430        cid = CaseInsensitiveDict()1431        cid['spam'] = 'blueval'1432        cid.update({'sPam': 'notblueval'})1433        assert cid['spam'] == 'notblueval'1434        cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1435        cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1436        assert len(cid) == 21437        assert cid['foo'] == 'anotherfoo'1438        assert cid['bar'] == 'anotherbar'14391440    def test_update_retains_unchanged(self):1441        cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1442        cid.update({'foo': 'newfoo'})1443        assert cid['bar'] == 'bar'14441445    def test_iter(self):1446        cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1447        keys = frozenset(['Spam', 'Eggs'])1448        assert frozenset(iter(cid)) == keys14491450    def test_equality(self):1451        cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1452        othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1453        assert cid == othercid1454        del othercid['spam']1455        assert cid != othercid1456        assert cid == {'spam': 'blueval', 'eggs': 'redval'}1457        assert cid != object()14581459    def test_setdefault(self):1460        cid = CaseInsensitiveDict({'Spam': 'blueval'})1461        assert cid.setdefault('spam', 'notblueval') == 'blueval'1462        assert cid.setdefault('notspam', 'notblueval') == 'notblueval'14631464    def test_lower_items(self):1465        cid = CaseInsensitiveDict({1466            'Accept': 'application/json',1467            'user-Agent': 'requests',1468        })1469        keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1470        lowerkeyset = frozenset(['accept', 'user-agent'])1471        assert keyset == lowerkeyset14721473    def test_preserve_key_case(self):1474        cid = CaseInsensitiveDict({1475            'Accept': 'application/json',1476            'user-Agent': 'requests',1477        })1478        keyset = frozenset(['Accept', 'user-Agent'])1479        assert frozenset(i[0] for i in cid.items()) == keyset1480        assert frozenset(cid.keys()) == keyset1481        assert frozenset(cid) == keyset14821483    def test_preserve_last_key_case(self):1484        cid = CaseInsensitiveDict({1485            'Accept': 'application/json',1486            'user-Agent': 'requests',1487        })1488        cid.update({'ACCEPT': 'application/json'})1489        cid['USER-AGENT'] = 'requests'1490        keyset = frozenset(['ACCEPT', 'USER-AGENT'])1491        assert frozenset(i[0] for i in cid.items()) == keyset1492        assert frozenset(cid.keys()) == keyset1493        assert frozenset(cid) == keyset14941495    def test_copy(self):1496        cid = CaseInsensitiveDict({1497            'Accept': 'application/json',1498            'user-Agent': 'requests',1499        })1500        cid_copy = cid.copy()1501        assert cid == cid_copy1502        cid['changed'] = True1503        assert cid != cid_copy150415051506class TestMorselToCookieExpires:1507    """Tests for morsel_to_cookie when morsel contains expires."""15081509    def test_expires_valid_str(self):1510        """Test case where we convert expires from string time."""15111512        morsel = Morsel()1513        morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1514        cookie = morsel_to_cookie(morsel)1515        assert cookie.expires == 115161517    @pytest.mark.parametrize(1518        'value, exception', (1519            (100, TypeError),1520            ('woops', ValueError),1521        ))1522    def test_expires_invalid_int(self, value, exception):1523        """Test case where an invalid type is passed for expires."""1524        morsel = Morsel()1525        morsel['expires'] = value1526        with pytest.raises(exception):1527            morsel_to_cookie(morsel)15281529    def test_expires_none(self):1530        """Test case where expires is None."""15311532        morsel = Morsel()1533        morsel['expires'] = None1534        cookie = morsel_to_cookie(morsel)1535        assert cookie.expires is None153615371538class TestMorselToCookieMaxAge:15391540    """Tests for morsel_to_cookie when morsel contains max-age."""15411542    def test_max_age_valid_int(self):1543        """Test case where a valid max age in seconds is passed."""15441545        morsel = Morsel()1546        morsel['max-age'] = 601547        cookie = morsel_to_cookie(morsel)1548        assert isinstance(cookie.expires, int)15491550    def test_max_age_invalid_str(self):1551        """Test case where a invalid max age is passed."""15521553        morsel = Morsel()1554        morsel['max-age'] = 'woops'1555        with pytest.raises(TypeError):1556            morsel_to_cookie(morsel)155715581559class TestTimeout:15601561    def test_stream_timeout(self, httpbin):1562        try:1563            requests.get(httpbin('delay/10'), timeout=2.0)1564        except requests.exceptions.Timeout as e:1565            assert 'Read timed out' in e.args[0].args[0]15661567    @pytest.mark.parametrize(1568        'timeout, error_text', (1569            ((3, 4, 5), '(connect, read)'),1570            ('foo', 'must be an int or float'),1571        ))1572    def test_invalid_timeout(self, httpbin, timeout, error_text):1573        with pytest.raises(ValueError) as e:1574            requests.get(httpbin('get'), timeout=timeout)1575        assert error_text in str(e)15761577    def test_none_timeout(self, httpbin):1578        """Check that you can set None as a valid timeout value.15791580        To actually test this behavior, we'd want to check that setting the1581        timeout to None actually lets the request block past the system default1582        timeout. However, this would make the test suite unbearably slow.1583        Instead we verify that setting the timeout to None does not prevent the1584        request from succeeding.1585        """1586        r = requests.get(httpbin('get'), timeout=None)1587        assert r.status_code == 20015881589    def test_read_timeout(self, httpbin):1590        try:1591            requests.get(httpbin('delay/10'), timeout=(None, 0.1))1592            pytest.fail('The recv() request should time out.')1593        except ReadTimeout:1594            pass15951596    def test_connect_timeout(self):1597        try:1598            requests.get(TARPIT, timeout=(0.1, None))1599            pytest.fail('The connect() request should time out.')1600        except ConnectTimeout as e:1601            assert isinstance(e, ConnectionError)1602            assert isinstance(e, Timeout)16031604    def test_total_timeout_connect(self):1605        try:1606            requests.get(TARPIT, timeout=(0.1, 0.1))1607            pytest.fail('The connect() request should time out.')1608        except ConnectTimeout:1609            pass16101611    def test_encoded_methods(self, httpbin):1612        """See: https://github.com/kennethreitz/requests/issues/2316"""1613        r = requests.request(b'GET', httpbin('get'))1614        assert r.ok161516161617SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))161816191620class RedirectSession(SessionRedirectMixin):1621    def __init__(self, order_of_redirects):1622        self.redirects = order_of_redirects1623        self.calls = []1624        self.max_redirects = 301625        self.cookies = {}1626        self.trust_env = False16271628    def send(self, *args, **kwargs):1629        self.calls.append(SendCall(args, kwargs))1630        return self.build_response()16311632    def build_response(self):1633        request = self.calls[-1].args[0]1634        r = requests.Response()16351636        try:1637            r.status_code = int(self.redirects.pop(0))1638        except IndexError:1639            r.status_code = 20016401641        r.headers = CaseInsensitiveDict({'Location': '/'})1642        r.raw = self._build_raw()1643        r.request = request1644        return r16451646    def _build_raw(self):1647        string = StringIO.StringIO('')1648        setattr(string, 'release_conn', lambda *args: args)1649        return string165016511652def test_json_encodes_as_bytes():1653    # urllib3 expects bodies as bytes-like objects1654    body = {"key": "value"}1655    p = PreparedRequest()1656    p.prepare(1657        method='GET',1658        url='https://www.example.com/',1659        json=body1660    )1661    assert isinstance(p.body, bytes)166216631664def test_requests_are_updated_each_time(httpbin):1665    session = RedirectSession([303, 307])1666    prep = requests.Request('POST', httpbin('post')).prepare()1667    r0 = session.send(prep)1668    assert r0.request.method == 'POST'1669    assert session.calls[-1] == SendCall((r0.request,), {})1670    redirect_generator = session.resolve_redirects(r0, prep)1671    default_keyword_args = {1672        'stream': False,1673        'verify': True,1674        'cert': None,1675        'timeout': None,1676        'allow_redirects': False,1677        'proxies': {},1678    }1679    for response in redirect_generator:1680        assert response.request.method == 'GET'1681        send_call = SendCall((response.request,), default_keyword_args)1682        assert session.calls[-1] == send_call168316841685@pytest.mark.parametrize("var,url,proxy", [1686    ('http_proxy', 'http://example.com', 'socks5://proxy.com:9876'),1687    ('https_proxy', 'https://example.com', 'socks5://proxy.com:9876'),1688    ('all_proxy', 'http://example.com', 'socks5://proxy.com:9876'),1689    ('all_proxy', 'https://example.com', 'socks5://proxy.com:9876'),1690])1691def test_proxy_env_vars_override_default(var, url, proxy):1692    session = requests.Session()1693    prep = PreparedRequest()1694    prep.prepare(method='GET', url=url)16951696    kwargs = {1697        var: proxy1698    }1699    scheme = urlparse(url).scheme1700    with override_environ(**kwargs):1701        proxies = session.rebuild_proxies(prep, {})1702        assert scheme in proxies1703        assert proxies[scheme] == proxy170417051706@pytest.mark.parametrize(1707    'data', (1708        (('a', 'b'), ('c', 'd')),1709        (('c', 'd'), ('a', 'b')),1710        (('a', 'b'), ('c', 'd'), ('e', 'f')),1711    ))1712def test_data_argument_accepts_tuples(data):1713    """Ensure that the data argument will accept tuples of strings1714    and properly encode them.1715    """1716    p = PreparedRequest()1717    p.prepare(1718        method='GET',1719        url='http://www.example.com',1720        data=data,1721        hooks=default_hooks()1722    )1723    assert p.body == urlencode(data)172417251726@pytest.mark.parametrize(1727    'kwargs', (1728        None,1729        {1730            'method': 'GET',1731            'url': 'http://www.example.com',1732            'data': 'foo=bar',1733            'hooks': default_hooks()1734        },1735        {1736            'method': 'GET',1737            'url': 'http://www.example.com',1738            'data': 'foo=bar',1739            'hooks': default_hooks(),1740            'cookies': {'foo': 'bar'}1741        },1742        {1743            'method': 'GET',1744            'url': u('http://www.example.com/üniçø∂é')1745        },1746    ))1747def test_prepared_copy(kwargs):1748    p = PreparedRequest()1749    if kwargs:1750        p.prepare(**kwargs)1751    copy = p.copy()1752    for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):1753        assert getattr(p, attr) == getattr(copy, attr)175417551756def test_urllib3_retries(httpbin):1757    from requests.packages.urllib3.util import Retry1758    s = requests.Session()1759    s.mount('http://', HTTPAdapter(max_retries=Retry(1760        total=2, status_forcelist=[500]1761    )))17621763    with pytest.raises(RetryError):1764        s.get(httpbin('status/500'))176517661767def test_urllib3_pool_connection_closed(httpbin):1768    s = requests.Session()1769    s.mount('http://', HTTPAdapter(pool_connections=0, pool_maxsize=0))17701771    try:1772        s.get(httpbin('status/200'))1773    except ConnectionError as e:1774        assert u"Pool is closed." in str(e)177517761777def test_vendor_aliases():1778    from requests.packages import urllib31779    from requests.packages import chardet17801781    with pytest.raises(ImportError):1782        from requests.packages import webbrowser