Skip to content
Myr

test_requests.py

This file

Path

tests/test_requests.py

1,454 lines · 48.8 KiB · Python

Last changed by

syntax changesKenneth Reitzbefore adoptionbbadf47

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 contextlib1213import io14import requests15import pytest16from requests.adapters import HTTPAdapter17from requests.auth import HTTPDigestAuth, _basic_auth_str18from requests.compat import (19    Morsel, cookielib, getproxies, str, urlparse,20    builtin_str, OrderedDict)21from requests.cookies import cookiejar_from_dict, morsel_to_cookie22from requests.exceptions import (23    ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,24    MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects)25from requests.models import PreparedRequest26from requests.structures import CaseInsensitiveDict27from requests.sessions import SessionRedirectMixin28from requests.models import urlencode29from requests.hooks import default_hooks3031from .compat import StringIO, u3233# Requests to this URL should always fail with a connection timeout (nothing34# listening on that port)35TARPIT = 'http://10.255.255.1'363738class TestRequests:3940    def test_entry_points(self):4142        requests.session43        requests.session().get44        requests.session().head45        requests.get46        requests.head47        requests.put48        requests.patch49        requests.post5051    @pytest.mark.parametrize(52        'exception, url', (53            (MissingSchema, 'hiwpefhipowhefopw'),54            (InvalidSchema, 'localhost:3128'),55            (InvalidSchema, 'localhost.localdomain:3128/'),56            (InvalidSchema, '10.122.1.1:3128/'),57            (InvalidURL, 'http://'),58        ))59    def test_invalid_url(self, exception, url):60        with pytest.raises(exception):61            requests.get(url)6263    def test_basic_building(self):64        req = requests.Request()65        req.url = 'http://kennethreitz.org/'66        req.data = {'life': '42'}6768        pr = req.prepare()69        assert pr.url == req.url70        assert pr.body == 'life=42'7172    @pytest.mark.parametrize('method', ('GET', 'HEAD'))73    def test_no_content_length(self, httpbin, method):74        req = requests.Request(method, httpbin(method.lower())).prepare()75        assert 'Content-Length' not in req.headers7677    def test_override_content_length(self, httpbin):78        headers = {79            'Content-Length': 'not zero'80        }81        r = requests.Request('POST', httpbin('post'), headers=headers).prepare()82        assert 'Content-Length' in r.headers83        assert r.headers['Content-Length'] == 'not zero'8485    def test_path_is_not_double_encoded(self):86        request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()8788        assert request.path_url == '/get/test%20case'8990    @pytest.mark.parametrize(91        'url, expected', (92            ('http://example.com/path#fragment', 'http://example.com/path?a=b#fragment'),93            ('http://example.com/path?key=value#fragment', 'http://example.com/path?key=value&a=b#fragment')94        ))95    def test_params_are_added_before_fragment(self, url, expected):96        request = requests.Request('GET', url, params={"a": "b"}).prepare()97        assert request.url == expected9899    def test_params_original_order_is_preserved_by_default(self):100        param_ordered_dict = OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))101        session = requests.Session()102        request = requests.Request('GET', 'http://example.com/', params=param_ordered_dict)103        prep = session.prepare_request(request)104        assert prep.url == 'http://example.com/?z=1&a=1&k=1&d=1'105106    def test_params_bytes_are_encoded(self):107        request = requests.Request('GET', 'http://example.com',108                                   params=b'test=foo').prepare()109        assert request.url == 'http://example.com/?test=foo'110111    def test_binary_put(self):112        request = requests.Request('PUT', 'http://example.com',113                                   data=u"ööö".encode("utf-8")).prepare()114        assert isinstance(request.body, bytes)115116    @pytest.mark.parametrize('scheme', ('http://', 'HTTP://', 'hTTp://', 'HttP://'))117    def test_mixed_case_scheme_acceptable(self, httpbin, scheme):118        s = requests.Session()119        s.proxies = getproxies()120        parts = urlparse(httpbin('get'))121        url = scheme + parts.netloc + parts.path122        r = requests.Request('GET', url)123        r = s.send(r.prepare())124        assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)125126    def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):127        r = requests.Request('GET', httpbin('get'))128        s = requests.Session()129        s.proxies = getproxies()130131        r = s.send(r.prepare())132133        assert r.status_code == 200134135    def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):136        r = requests.get(httpbin('redirect', '1'))137        assert r.status_code == 200138        assert r.history[0].status_code == 302139        assert r.history[0].is_redirect140141    def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):142        try:143            requests.get(httpbin('relative-redirect', '50'))144        except TooManyRedirects as e:145            url = httpbin('relative-redirect', '20')146            assert e.request.url == url147            assert e.response.url == url148            assert len(e.response.history) == 30149        else:150            pytest.fail('Expected redirect to raise TooManyRedirects but it did not')151152    def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):153        s = requests.session()154        s.max_redirects = 5155        try:156            s.get(httpbin('relative-redirect', '50'))157        except TooManyRedirects as e:158            url = httpbin('relative-redirect', '45')159            assert e.request.url == url160            assert e.response.url == url161            assert len(e.response.history) == 5162        else:163            pytest.fail('Expected custom max number of redirects to be respected but was not')164165    # def test_HTTP_302_ALLOW_REDIRECT_POST(self):166    #     r = requests.post(httpbin('status', '302'), data={'some': 'data'})167    #     self.assertEqual(r.status_code, 200)168169    def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):170        heads = {'User-agent': 'Mozilla/5.0'}171172        r = requests.get(httpbin('user-agent'), headers=heads)173174        assert heads['User-agent'] in r.text175        assert r.status_code == 200176177    def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):178        heads = {'User-agent': 'Mozilla/5.0'}179180        r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)181        assert r.status_code == 200182183    def test_set_cookie_on_301(self, httpbin):184        s = requests.session()185        url = httpbin('cookies/set?foo=bar')186        s.get(url)187        assert s.cookies['foo'] == 'bar'188189    def test_cookie_sent_on_redirect(self, httpbin):190        s = requests.session()191        s.get(httpbin('cookies/set?foo=bar'))192        r = s.get(httpbin('redirect/1'))  # redirects to httpbin('get')193        assert 'Cookie' in r.json()['headers']194195    def test_cookie_removed_on_expire(self, httpbin):196        s = requests.session()197        s.get(httpbin('cookies/set?foo=bar'))198        assert s.cookies['foo'] == 'bar'199        s.get(200            httpbin('response-headers'),201            params={202                'Set-Cookie':203                    'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'204            }205        )206        assert 'foo' not in s.cookies207208    def test_cookie_quote_wrapped(self, httpbin):209        s = requests.session()210        s.get(httpbin('cookies/set?foo="bar:baz"'))211        assert s.cookies['foo'] == '"bar:baz"'212213    def test_cookie_persists_via_api(self, httpbin):214        s = requests.session()215        r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})216        assert 'foo' in r.request.headers['Cookie']217        assert 'foo' in r.history[0].request.headers['Cookie']218219    def test_request_cookie_overrides_session_cookie(self, httpbin):220        s = requests.session()221        s.cookies['foo'] = 'bar'222        r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})223        assert r.json()['cookies']['foo'] == 'baz'224        # Session cookie should not be modified225        assert s.cookies['foo'] == 'bar'226227    def test_request_cookies_not_persisted(self, httpbin):228        s = requests.session()229        s.get(httpbin('cookies'), cookies={'foo': 'baz'})230        # Sending a request with cookies should not add cookies to the session231        assert not s.cookies232233    def test_generic_cookiejar_works(self, httpbin):234        cj = cookielib.CookieJar()235        cookiejar_from_dict({'foo': 'bar'}, cj)236        s = requests.session()237        s.cookies = cj238        r = s.get(httpbin('cookies'))239        # Make sure the cookie was sent240        assert r.json()['cookies']['foo'] == 'bar'241        # Make sure the session cj is still the custom one242        assert s.cookies is cj243244    def test_param_cookiejar_works(self, httpbin):245        cj = cookielib.CookieJar()246        cookiejar_from_dict({'foo': 'bar'}, cj)247        s = requests.session()248        r = s.get(httpbin('cookies'), cookies=cj)249        # Make sure the cookie was sent250        assert r.json()['cookies']['foo'] == 'bar'251252    def test_requests_in_history_are_not_overridden(self, httpbin):253        resp = requests.get(httpbin('redirect/3'))254        urls = [r.url for r in resp.history]255        req_urls = [r.request.url for r in resp.history]256        assert urls == req_urls257258    def test_history_is_always_a_list(self, httpbin):259        """Show that even with redirects, Response.history is always a list."""260        resp = requests.get(httpbin('get'))261        assert isinstance(resp.history, list)262        resp = requests.get(httpbin('redirect/1'))263        assert isinstance(resp.history, list)264        assert not isinstance(resp.history, tuple)265266    def test_headers_on_session_with_None_are_not_sent(self, httpbin):267        """Do not send headers in Session.headers with None values."""268        ses = requests.Session()269        ses.headers['Accept-Encoding'] = None270        req = requests.Request('GET', httpbin('get'))271        prep = ses.prepare_request(req)272        assert 'Accept-Encoding' not in prep.headers273274    @pytest.mark.parametrize('key', ('User-agent', 'user-agent'))275    def test_user_agent_transfers(self, httpbin, key):276277        heads = {key: 'Mozilla/5.0 (github.com/kennethreitz/requests)'}278279        r = requests.get(httpbin('user-agent'), headers=heads)280        assert heads[key] in r.text281282    def test_HTTP_200_OK_HEAD(self, httpbin):283        r = requests.head(httpbin('get'))284        assert r.status_code == 200285286    def test_HTTP_200_OK_PUT(self, httpbin):287        r = requests.put(httpbin('put'))288        assert r.status_code == 200289290    def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):291        auth = ('user', 'pass')292        url = httpbin('basic-auth', 'user', 'pass')293294        r = requests.get(url, auth=auth)295        assert r.status_code == 200296297        r = requests.get(url)298        assert r.status_code == 401299300        s = requests.session()301        s.auth = auth302        r = s.get(url)303        assert r.status_code == 200304305    @pytest.mark.parametrize(306        'url, exception', (307            # Connecting to an unknown domain should raise a ConnectionError308            ('http://doesnotexist.google.com', ConnectionError),309            # Connecting to an invalid port should raise a ConnectionError310            ('http://localhost:1', ConnectionError),311            # Inputing a URL that cannot be parsed should raise an InvalidURL error312            ('http://fe80::5054:ff:fe5a:fc0', InvalidURL)313        ))314    def test_errors(self, url, exception):315        with pytest.raises(exception):316            requests.get(url, timeout=1)317318    def test_basicauth_with_netrc(self, httpbin):319        auth = ('user', 'pass')320        wrong_auth = ('wronguser', 'wrongpass')321        url = httpbin('basic-auth', 'user', 'pass')322323        old_auth = requests.sessions.get_netrc_auth324325        try:326            def get_netrc_auth_mock(url):327                return auth328            requests.sessions.get_netrc_auth = get_netrc_auth_mock329330            # Should use netrc and work.331            r = requests.get(url)332            assert r.status_code == 200333334            # Given auth should override and fail.335            r = requests.get(url, auth=wrong_auth)336            assert r.status_code == 401337338            s = requests.session()339340            # Should use netrc and work.341            r = s.get(url)342            assert r.status_code == 200343344            # Given auth should override and fail.345            s.auth = wrong_auth346            r = s.get(url)347            assert r.status_code == 401348        finally:349            requests.sessions.get_netrc_auth = old_auth350351    def test_DIGEST_HTTP_200_OK_GET(self, httpbin):352353        auth = HTTPDigestAuth('user', 'pass')354        url = httpbin('digest-auth', 'auth', 'user', 'pass')355356        r = requests.get(url, auth=auth)357        assert r.status_code == 200358359        r = requests.get(url)360        assert r.status_code == 401361362        s = requests.session()363        s.auth = HTTPDigestAuth('user', 'pass')364        r = s.get(url)365        assert r.status_code == 200366367    def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):368        url = httpbin('digest-auth', 'auth', 'user', 'pass')369        auth = HTTPDigestAuth('user', 'pass')370        r = requests.get(url)371        assert r.cookies['fake'] == 'fake_value'372373        r = requests.get(url, auth=auth)374        assert r.status_code == 200375376    def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):377        url = httpbin('digest-auth', 'auth', 'user', 'pass')378        auth = HTTPDigestAuth('user', 'pass')379        s = requests.Session()380        s.get(url, auth=auth)381        assert s.cookies['fake'] == 'fake_value'382383    def test_DIGEST_STREAM(self, httpbin):384385        auth = HTTPDigestAuth('user', 'pass')386        url = httpbin('digest-auth', 'auth', 'user', 'pass')387388        r = requests.get(url, auth=auth, stream=True)389        assert r.raw.read() != b''390391        r = requests.get(url, auth=auth, stream=False)392        assert r.raw.read() == b''393394    def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):395396        auth = HTTPDigestAuth('user', 'wrongpass')397        url = httpbin('digest-auth', 'auth', 'user', 'pass')398399        r = requests.get(url, auth=auth)400        assert r.status_code == 401401402        r = requests.get(url)403        assert r.status_code == 401404405        s = requests.session()406        s.auth = auth407        r = s.get(url)408        assert r.status_code == 401409410    def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):411412        auth = HTTPDigestAuth('user', 'pass')413        url = httpbin('digest-auth', 'auth', 'user', 'pass')414415        r = requests.get(url, auth=auth)416        assert '"auth"' in r.request.headers['Authorization']417418    def test_POSTBIN_GET_POST_FILES(self, httpbin):419420        url = httpbin('post')421        requests.post(url).raise_for_status()422423        post1 = requests.post(url, data={'some': 'data'})424        assert post1.status_code == 200425426        with open('requirements.txt') as f:427            post2 = requests.post(url, files={'some': f})428        assert post2.status_code == 200429430        post4 = requests.post(url, data='[{"some": "json"}]')431        assert post4.status_code == 200432433        with pytest.raises(ValueError):434            requests.post(url, files=['bad file data'])435436    def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):437438        url = httpbin('post')439        requests.post(url).raise_for_status()440441        post1 = requests.post(url, data={'some': 'data'})442        assert post1.status_code == 200443444        with open('requirements.txt') as f:445            post2 = requests.post(url,446                data={'some': 'data'}, files={'some': f})447        assert post2.status_code == 200448449        post4 = requests.post(url, data='[{"some": "json"}]')450        assert post4.status_code == 200451452        with pytest.raises(ValueError):453            requests.post(url, files=['bad file data'])454455    def test_conflicting_post_params(self, httpbin):456        url = httpbin('post')457        with open('requirements.txt') as f:458            pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")459            pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")460461    def test_request_ok_set(self, httpbin):462        r = requests.get(httpbin('status', '404'))463        assert not r.ok464465    def test_status_raising(self, httpbin):466        r = requests.get(httpbin('status', '404'))467        with pytest.raises(requests.exceptions.HTTPError):468            r.raise_for_status()469470        r = requests.get(httpbin('status', '500'))471        assert not r.ok472473    def test_decompress_gzip(self, httpbin):474        r = requests.get(httpbin('gzip'))475        r.content.decode('ascii')476477    @pytest.mark.parametrize(478        'url, params', (479            ('/get', {'foo': 'føø'}),480            ('/get', {'føø': 'føø'}),481            ('/get', {'føø': 'føø'}),482            ('/get', {'foo': 'foo'}),483            ('ø', {'foo': 'foo'}),484        ))485    def test_unicode_get(self, httpbin, url, params):486        requests.get(httpbin(url), params=params)487488    def test_unicode_header_name(self, httpbin):489        requests.put(490            httpbin('put'),491            headers={str('Content-Type'): 'application/octet-stream'},492            data='\xff')  # compat.str is unicode.493494    def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):495        requests.get(httpbin_secure('status', '301'), verify=httpbin_ca_bundle)496497    def test_urlencoded_get_query_multivalued_param(self, httpbin):498499        r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))500        assert r.status_code == 200501        assert r.url == httpbin('get?test=foo&test=baz')502503    def test_different_encodings_dont_break_post(self, httpbin):504        r = requests.post(httpbin('post'),505            data={'stuff': json.dumps({'a': 123})},506            params={'blah': 'asdf1234'},507            files={'file': ('test_requests.py', open(__file__, 'rb'))})508        assert r.status_code == 200509510    @pytest.mark.parametrize(511        'data', (512            {'stuff': u('ëlïxr')},513            {'stuff': u('ëlïxr').encode('utf-8')},514            {'stuff': 'elixr'},515            {'stuff': 'elixr'.encode('utf-8')},516        ))517    def test_unicode_multipart_post(self, httpbin, data):518        r = requests.post(httpbin('post'),519            data=data,520            files={'file': ('test_requests.py', open(__file__, 'rb'))})521        assert r.status_code == 200522523    def test_unicode_multipart_post_fieldnames(self, httpbin):524        filename = os.path.splitext(__file__)[0] + '.py'525        r = requests.Request(526            method='POST', url=httpbin('post'),527            data={'stuff'.encode('utf-8'): 'elixr'},528            files={'file': ('test_requests.py', open(filename, 'rb'))})529        prep = r.prepare()530        assert b'name="stuff"' in prep.body531        assert b'name="b\'stuff\'"' not in prep.body532533    def test_unicode_method_name(self, httpbin):534        files = {'file': open(__file__, 'rb')}535        r = requests.request(536            method=u('POST'), url=httpbin('post'), files=files)537        assert r.status_code == 200538539    def test_unicode_method_name_with_request_object(self, httpbin):540        files = {'file': open(__file__, 'rb')}541        s = requests.Session()542        req = requests.Request(u('POST'), httpbin('post'), files=files)543        prep = s.prepare_request(req)544        assert isinstance(prep.method, builtin_str)545        assert prep.method == 'POST'546547        resp = s.send(prep)548        assert resp.status_code == 200549550    def test_custom_content_type(self, httpbin):551        r = requests.post(552            httpbin('post'),553            data={'stuff': json.dumps({'a': 123})},554            files={555                'file1': ('test_requests.py', open(__file__, 'rb')),556                'file2': ('test_requests', open(__file__, 'rb'),557                    'text/py-content-type')})558        assert r.status_code == 200559        assert b"text/py-content-type" in r.request.body560561    def test_hook_receives_request_arguments(self, httpbin):562        def hook(resp, **kwargs):563            assert resp is not None564            assert kwargs != {}565566        s = requests.Session()567        r = requests.Request('GET', httpbin(), hooks={'response': hook})568        prep = s.prepare_request(r)569        s.send(prep)570571    def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):572        hook = lambda x, *args, **kwargs: x573        s = requests.Session()574        s.hooks['response'].append(hook)575        r = requests.Request('GET', httpbin())576        prep = s.prepare_request(r)577        assert prep.hooks['response'] != []578        assert prep.hooks['response'] == [hook]579580    def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):581        hook1 = lambda x, *args, **kwargs: x582        hook2 = lambda x, *args, **kwargs: x583        assert hook1 is not hook2584        s = requests.Session()585        s.hooks['response'].append(hook2)586        r = requests.Request('GET', httpbin(), hooks={'response': [hook1]})587        prep = s.prepare_request(r)588        assert prep.hooks['response'] == [hook1]589590    def test_prepared_request_hook(self, httpbin):591        def hook(resp, **kwargs):592            resp.hook_working = True593            return resp594595        req = requests.Request('GET', httpbin(), hooks={'response': hook})596        prep = req.prepare()597598        s = requests.Session()599        s.proxies = getproxies()600        resp = s.send(prep)601602        assert hasattr(resp, 'hook_working')603604    def test_prepared_from_session(self, httpbin):605        class DummyAuth(requests.auth.AuthBase):606            def __call__(self, r):607                r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'608                return r609610        req = requests.Request('GET', httpbin('headers'))611        assert not req.auth612613        s = requests.Session()614        s.auth = DummyAuth()615616        prep = s.prepare_request(req)617        resp = s.send(prep)618619        assert resp.json()['headers'][620            'Dummy-Auth-Test'] == 'dummy-auth-test-ok'621622    def test_prepare_request_with_bytestring_url(self):623        req = requests.Request('GET', b'https://httpbin.org/')624        s = requests.Session()625        prep = s.prepare_request(req)626        assert prep.url == "https://httpbin.org/"627628    def test_links(self):629        r = requests.Response()630        r.headers = {631            'cache-control': 'public, max-age=60, s-maxage=60',632            'connection': 'keep-alive',633            'content-encoding': 'gzip',634            'content-type': 'application/json; charset=utf-8',635            'date': 'Sat, 26 Jan 2013 16:47:56 GMT',636            'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',637            'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',638            'link': ('<https://api.github.com/users/kennethreitz/repos?'639                     'page=2&per_page=10>; rel="next", <https://api.github.'640                     'com/users/kennethreitz/repos?page=7&per_page=10>; '641                     ' rel="last"'),642            'server': 'GitHub.com',643            'status': '200 OK',644            'vary': 'Accept',645            'x-content-type-options': 'nosniff',646            'x-github-media-type': 'github.beta',647            'x-ratelimit-limit': '60',648            'x-ratelimit-remaining': '57'649        }650        assert r.links['next']['rel'] == 'next'651652    def test_cookie_parameters(self):653        key = 'some_cookie'654        value = 'some_value'655        secure = True656        domain = 'test.com'657        rest = {'HttpOnly': True}658659        jar = requests.cookies.RequestsCookieJar()660        jar.set(key, value, secure=secure, domain=domain, rest=rest)661662        assert len(jar) == 1663        assert 'some_cookie' in jar664665        cookie = list(jar)[0]666        assert cookie.secure == secure667        assert cookie.domain == domain668        assert cookie._rest['HttpOnly'] == rest['HttpOnly']669670    def test_cookie_as_dict_keeps_len(self):671        key = 'some_cookie'672        value = 'some_value'673674        key1 = 'some_cookie1'675        value1 = 'some_value1'676677        jar = requests.cookies.RequestsCookieJar()678        jar.set(key, value)679        jar.set(key1, value1)680681        d1 = dict(jar)682        d2 = dict(jar.iteritems())683        d3 = dict(jar.items())684685        assert len(jar) == 2686        assert len(d1) == 2687        assert len(d2) == 2688        assert len(d3) == 2689690    def test_cookie_as_dict_keeps_items(self):691        key = 'some_cookie'692        value = 'some_value'693694        key1 = 'some_cookie1'695        value1 = 'some_value1'696697        jar = requests.cookies.RequestsCookieJar()698        jar.set(key, value)699        jar.set(key1, value1)700701        d1 = dict(jar)702        d2 = dict(jar.iteritems())703        d3 = dict(jar.items())704705        assert d1['some_cookie'] == 'some_value'706        assert d2['some_cookie'] == 'some_value'707        assert d3['some_cookie1'] == 'some_value1'708709    def test_cookie_as_dict_keys(self):710        key = 'some_cookie'711        value = 'some_value'712713        key1 = 'some_cookie1'714        value1 = 'some_value1'715716        jar = requests.cookies.RequestsCookieJar()717        jar.set(key, value)718        jar.set(key1, value1)719720        keys = jar.keys()721        assert keys == list(keys)722        # make sure one can use keys multiple times723        assert list(keys) == list(keys)724725    def test_cookie_as_dict_values(self):726        key = 'some_cookie'727        value = 'some_value'728729        key1 = 'some_cookie1'730        value1 = 'some_value1'731732        jar = requests.cookies.RequestsCookieJar()733        jar.set(key, value)734        jar.set(key1, value1)735736        values = jar.values()737        assert values == list(values)738        # make sure one can use values multiple times739        assert list(values) == list(values)740741    def test_cookie_as_dict_items(self):742        key = 'some_cookie'743        value = 'some_value'744745        key1 = 'some_cookie1'746        value1 = 'some_value1'747748        jar = requests.cookies.RequestsCookieJar()749        jar.set(key, value)750        jar.set(key1, value1)751752        items = jar.items()753        assert items == list(items)754        # make sure one can use items multiple times755        assert list(items) == list(items)756757    def test_time_elapsed_blank(self, httpbin):758        r = requests.get(httpbin('get'))759        td = r.elapsed760        total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)761                         * 10**6) / 10**6)762        assert total_seconds > 0.0763764    def test_response_is_iterable(self):765        r = requests.Response()766        io = StringIO.StringIO('abc')767        read_ = io.read768769        def read_mock(amt, decode_content=None):770            return read_(amt)771        setattr(io, 'read', read_mock)772        r.raw = io773        assert next(iter(r))774        io.close()775776    def test_response_decode_unicode(self):777        """778        When called with decode_unicode, Response.iter_content should always779        return unicode.780        """781        r = requests.Response()782        r._content_consumed = True783        r._content = b'the content'784        r.encoding = 'ascii'785786        chunks = r.iter_content(decode_unicode=True)787        assert all(isinstance(chunk, str) for chunk in chunks)788789        # also for streaming790        r = requests.Response()791        r.raw = io.BytesIO(b'the content')792        r.encoding = 'ascii'793        chunks = r.iter_content(decode_unicode=True)794        assert all(isinstance(chunk, str) for chunk in chunks)795796    def test_request_and_response_are_pickleable(self, httpbin):797        r = requests.get(httpbin('get'))798799        # verify we can pickle the original request800        assert pickle.loads(pickle.dumps(r.request))801802        # verify we can pickle the response and that we have access to803        # the original request.804        pr = pickle.loads(pickle.dumps(r))805        assert r.request.url == pr.request.url806        assert r.request.headers == pr.request.headers807808    def test_cannot_send_unprepared_requests(self, httpbin):809        r = requests.Request(url=httpbin())810        with pytest.raises(ValueError):811            requests.Session().send(r)812813    def test_http_error(self):814        error = requests.exceptions.HTTPError()815        assert not error.response816        response = requests.Response()817        error = requests.exceptions.HTTPError(response=response)818        assert error.response == response819        error = requests.exceptions.HTTPError('message', response=response)820        assert str(error) == 'message'821        assert error.response == response822823    def test_session_pickling(self, httpbin):824        r = requests.Request('GET', httpbin('get'))825        s = requests.Session()826827        s = pickle.loads(pickle.dumps(s))828        s.proxies = getproxies()829830        r = s.send(r.prepare())831        assert r.status_code == 200832833    def test_fixes_1329(self, httpbin):834        """835        Ensure that header updates are done case-insensitively.836        """837        s = requests.Session()838        s.headers.update({'ACCEPT': 'BOGUS'})839        s.headers.update({'accept': 'application/json'})840        r = s.get(httpbin('get'))841        headers = r.request.headers842        assert headers['accept'] == 'application/json'843        assert headers['Accept'] == 'application/json'844        assert headers['ACCEPT'] == 'application/json'845846    def test_uppercase_scheme_redirect(self, httpbin):847        parts = urlparse(httpbin('html'))848        url = "HTTP://" + parts.netloc + parts.path849        r = requests.get(httpbin('redirect-to'), params={'url': url})850        assert r.status_code == 200851        assert r.url.lower() == url.lower()852853    def test_transport_adapter_ordering(self):854        s = requests.Session()855        order = ['https://', 'http://']856        assert order == list(s.adapters)857        s.mount('http://git', HTTPAdapter())858        s.mount('http://github', HTTPAdapter())859        s.mount('http://github.com', HTTPAdapter())860        s.mount('http://github.com/about/', HTTPAdapter())861        order = [862            'http://github.com/about/',863            'http://github.com',864            'http://github',865            'http://git',866            'https://',867            'http://',868        ]869        assert order == list(s.adapters)870        s.mount('http://gittip', HTTPAdapter())871        s.mount('http://gittip.com', HTTPAdapter())872        s.mount('http://gittip.com/about/', HTTPAdapter())873        order = [874            'http://github.com/about/',875            'http://gittip.com/about/',876            'http://github.com',877            'http://gittip.com',878            'http://github',879            'http://gittip',880            'http://git',881            'https://',882            'http://',883        ]884        assert order == list(s.adapters)885        s2 = requests.Session()886        s2.adapters = {'http://': HTTPAdapter()}887        s2.mount('https://', HTTPAdapter())888        assert 'http://' in s2.adapters889        assert 'https://' in s2.adapters890891    def test_header_remove_is_case_insensitive(self, httpbin):892        # From issue #1321893        s = requests.Session()894        s.headers['foo'] = 'bar'895        r = s.get(httpbin('get'), headers={'FOO': None})896        assert 'foo' not in r.request.headers897898    def test_params_are_merged_case_sensitive(self, httpbin):899        s = requests.Session()900        s.params['foo'] = 'bar'901        r = s.get(httpbin('get'), params={'FOO': 'bar'})902        assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}903904    def test_long_authinfo_in_url(self):905        url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(906            'E8A3BE87-9E3F-4620-8858-95478E385B5B',907            'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',908            'exactly-------------sixty-----------three------------characters',909        )910        r = requests.Request('GET', url).prepare()911        assert r.url == url912913    def test_header_keys_are_native(self, httpbin):914        headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}915        r = requests.Request('GET', httpbin('get'), headers=headers)916        p = r.prepare()917918        # This is testing that they are builtin strings. A bit weird, but there919        # we go.920        assert 'unicode' in p.headers.keys()921        assert 'byte' in p.headers.keys()922923    @pytest.mark.parametrize('files', ('foo', b'foo', bytearray(b'foo')))924    def test_can_send_objects_with_files(self, httpbin, files):925        data = {'a': 'this is a string'}926        files = {'b': files}927        r = requests.Request('POST', httpbin('post'), data=data, files=files)928        p = r.prepare()929        assert 'multipart/form-data' in p.headers['Content-Type']930931    def test_can_send_file_object_with_non_string_filename(self, httpbin):932        f = io.BytesIO()933        f.name = 2934        r = requests.Request('POST', httpbin('post'), files={'f': f})935        p = r.prepare()936937        assert 'multipart/form-data' in p.headers['Content-Type']938939    def test_autoset_header_values_are_native(self, httpbin):940        data = 'this is a string'941        length = '16'942        req = requests.Request('POST', httpbin('post'), data=data)943        p = req.prepare()944945        assert p.headers['Content-Length'] == length946947    def test_nonhttp_schemes_dont_check_URLs(self):948        test_urls = (949            'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',950            'file:///etc/passwd',951            'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',952        )953        for test_url in test_urls:954            req = requests.Request('GET', test_url)955            preq = req.prepare()956            assert test_url == preq.url957958    def test_auth_is_stripped_on_redirect_off_host(self, httpbin):959        r = requests.get(960            httpbin('redirect-to'),961            params={'url': 'http://www.google.co.uk'},962            auth=('user', 'pass'),963        )964        assert r.history[0].request.headers['Authorization']965        assert not r.request.headers.get('Authorization', '')966967    def test_auth_is_retained_for_redirect_on_host(self, httpbin):968        r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))969        h1 = r.history[0].request.headers['Authorization']970        h2 = r.request.headers['Authorization']971972        assert h1 == h2973974    def test_manual_redirect_with_partial_body_read(self, httpbin):975        s = requests.Session()976        r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)977        assert r1.is_redirect978        rg = s.resolve_redirects(r1, r1.request, stream=True)979980        # read only the first eight bytes of the response body,981        # then follow the redirect982        r1.iter_content(8)983        r2 = next(rg)984        assert r2.is_redirect985986        # read all of the response via iter_content,987        # then follow the redirect988        for _ in r2.iter_content():989            pass990        r3 = next(rg)991        assert not r3.is_redirect992993    def _patch_adapter_gzipped_redirect(self, session, url):994        adapter = session.get_adapter(url=url)995        org_build_response = adapter.build_response996        self._patched_response = False997998        def build_response(*args, **kwargs):999            resp = org_build_response(*args, **kwargs)1000            if not self._patched_response:1001                resp.raw.headers['content-encoding'] = 'gzip'1002                self._patched_response = True1003            return resp10041005        adapter.build_response = build_response10061007    def test_redirect_with_wrong_gzipped_header(self, httpbin):1008        s = requests.Session()1009        url = httpbin('redirect/1')1010        self._patch_adapter_gzipped_redirect(s, url)1011        s.get(url)10121013    def test_basic_auth_str_is_always_native(self):1014        s = _basic_auth_str("test", "test")1015        assert isinstance(s, builtin_str)1016        assert s == "Basic dGVzdDp0ZXN0"10171018    def test_requests_history_is_saved(self, httpbin):1019        r = requests.get(httpbin('redirect/5'))1020        total = r.history[-1].history1021        i = 01022        for item in r.history:1023            assert item.history == total[0:i]1024            i += 110251026    def test_json_param_post_content_type_works(self, httpbin):1027        r = requests.post(1028            httpbin('post'),1029            json={'life': 42}1030        )1031        assert r.status_code == 2001032        assert 'application/json' in r.request.headers['Content-Type']1033        assert {'life': 42} == r.json()['json']10341035    def test_json_param_post_should_not_override_data_param(self, httpbin):1036        r = requests.Request(method='POST', url=httpbin('post'),1037                             data={'stuff': 'elixr'},1038                             json={'music': 'flute'})1039        prep = r.prepare()1040        assert 'stuff=elixr' == prep.body10411042    def test_response_iter_lines(self, httpbin):1043        r = requests.get(httpbin('stream/4'), stream=True)1044        assert r.status_code == 20010451046        it = r.iter_lines()1047        next(it)1048        assert len(list(it)) == 310491050    def test_unconsumed_session_response_closes_connection(self, httpbin):1051        s = requests.session()10521053        with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1054            pass10551056        assert response._content_consumed is False1057        assert response.raw.closed10581059    @pytest.mark.xfail1060    def test_response_iter_lines_reentrant(self, httpbin):1061        """Response.iter_lines() is not reentrant safe"""1062        r = requests.get(httpbin('stream/4'), stream=True)1063        assert r.status_code == 20010641065        next(r.iter_lines())1066        assert len(list(r.iter_lines())) == 3106710681069class TestCaseInsensitiveDict:10701071    @pytest.mark.parametrize(1072        'cid', (1073            CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}),1074            CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')]),1075            CaseInsensitiveDict(FOO='foo', BAr='bar'),1076        ))1077    def test_init(self, cid):1078        assert len(cid) == 21079        assert 'foo' in cid1080        assert 'bar' in cid10811082    def test_docstring_example(self):1083        cid = CaseInsensitiveDict()1084        cid['Accept'] = 'application/json'1085        assert cid['aCCEPT'] == 'application/json'1086        assert list(cid) == ['Accept']10871088    def test_len(self):1089        cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1090        cid['A'] = 'a'1091        assert len(cid) == 210921093    def test_getitem(self):1094        cid = CaseInsensitiveDict({'Spam': 'blueval'})1095        assert cid['spam'] == 'blueval'1096        assert cid['SPAM'] == 'blueval'10971098    def test_fixes_649(self):1099        """__setitem__ should behave case-insensitively."""1100        cid = CaseInsensitiveDict()1101        cid['spam'] = 'oneval'1102        cid['Spam'] = 'twoval'1103        cid['sPAM'] = 'redval'1104        cid['SPAM'] = 'blueval'1105        assert cid['spam'] == 'blueval'1106        assert cid['SPAM'] == 'blueval'1107        assert list(cid.keys()) == ['SPAM']11081109    def test_delitem(self):1110        cid = CaseInsensitiveDict()1111        cid['Spam'] = 'someval'1112        del cid['sPam']1113        assert 'spam' not in cid1114        assert len(cid) == 011151116    def test_contains(self):1117        cid = CaseInsensitiveDict()1118        cid['Spam'] = 'someval'1119        assert 'Spam' in cid1120        assert 'spam' in cid1121        assert 'SPAM' in cid1122        assert 'sPam' in cid1123        assert 'notspam' not in cid11241125    def test_get(self):1126        cid = CaseInsensitiveDict()1127        cid['spam'] = 'oneval'1128        cid['SPAM'] = 'blueval'1129        assert cid.get('spam') == 'blueval'1130        assert cid.get('SPAM') == 'blueval'1131        assert cid.get('sPam') == 'blueval'1132        assert cid.get('notspam', 'default') == 'default'11331134    def test_update(self):1135        cid = CaseInsensitiveDict()1136        cid['spam'] = 'blueval'1137        cid.update({'sPam': 'notblueval'})1138        assert cid['spam'] == 'notblueval'1139        cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1140        cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1141        assert len(cid) == 21142        assert cid['foo'] == 'anotherfoo'1143        assert cid['bar'] == 'anotherbar'11441145    def test_update_retains_unchanged(self):1146        cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1147        cid.update({'foo': 'newfoo'})1148        assert cid['bar'] == 'bar'11491150    def test_iter(self):1151        cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1152        keys = frozenset(['Spam', 'Eggs'])1153        assert frozenset(iter(cid)) == keys11541155    def test_equality(self):1156        cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1157        othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1158        assert cid == othercid1159        del othercid['spam']1160        assert cid != othercid1161        assert cid == {'spam': 'blueval', 'eggs': 'redval'}1162        assert cid != object()11631164    def test_setdefault(self):1165        cid = CaseInsensitiveDict({'Spam': 'blueval'})1166        assert cid.setdefault('spam', 'notblueval') == 'blueval'1167        assert cid.setdefault('notspam', 'notblueval') == 'notblueval'11681169    def test_lower_items(self):1170        cid = CaseInsensitiveDict({1171            'Accept': 'application/json',1172            'user-Agent': 'requests',1173        })1174        keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1175        lowerkeyset = frozenset(['accept', 'user-agent'])1176        assert keyset == lowerkeyset11771178    def test_preserve_key_case(self):1179        cid = CaseInsensitiveDict({1180            'Accept': 'application/json',1181            'user-Agent': 'requests',1182        })1183        keyset = frozenset(['Accept', 'user-Agent'])1184        assert frozenset(i[0] for i in cid.items()) == keyset1185        assert frozenset(cid.keys()) == keyset1186        assert frozenset(cid) == keyset11871188    def test_preserve_last_key_case(self):1189        cid = CaseInsensitiveDict({1190            'Accept': 'application/json',1191            'user-Agent': 'requests',1192        })1193        cid.update({'ACCEPT': 'application/json'})1194        cid['USER-AGENT'] = 'requests'1195        keyset = frozenset(['ACCEPT', 'USER-AGENT'])1196        assert frozenset(i[0] for i in cid.items()) == keyset1197        assert frozenset(cid.keys()) == keyset1198        assert frozenset(cid) == keyset11991200    def test_copy(self):1201        cid = CaseInsensitiveDict({1202            'Accept': 'application/json',1203            'user-Agent': 'requests',1204        })1205        cid_copy = cid.copy()1206        assert cid == cid_copy1207        cid['changed'] = True1208        assert cid != cid_copy120912101211class TestMorselToCookieExpires:1212    """Tests for morsel_to_cookie when morsel contains expires."""12131214    def test_expires_valid_str(self):1215        """Test case where we convert expires from string time."""12161217        morsel = Morsel()1218        morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1219        cookie = morsel_to_cookie(morsel)1220        assert cookie.expires == 112211222    @pytest.mark.parametrize(1223        'value, exception', (1224            (100, TypeError),1225            ('woops', ValueError),1226        ))1227    def test_expires_invalid_int(self, value, exception):1228        """Test case where an invalid type is passed for expires."""1229        morsel = Morsel()1230        morsel['expires'] = value1231        with pytest.raises(exception):1232            morsel_to_cookie(morsel)12331234    def test_expires_none(self):1235        """Test case where expires is None."""12361237        morsel = Morsel()1238        morsel['expires'] = None1239        cookie = morsel_to_cookie(morsel)1240        assert cookie.expires is None124112421243class TestMorselToCookieMaxAge:12441245    """Tests for morsel_to_cookie when morsel contains max-age."""12461247    def test_max_age_valid_int(self):1248        """Test case where a valid max age in seconds is passed."""12491250        morsel = Morsel()1251        morsel['max-age'] = 601252        cookie = morsel_to_cookie(morsel)1253        assert isinstance(cookie.expires, int)12541255    def test_max_age_invalid_str(self):1256        """Test case where a invalid max age is passed."""12571258        morsel = Morsel()1259        morsel['max-age'] = 'woops'1260        with pytest.raises(TypeError):1261            morsel_to_cookie(morsel)126212631264class TestTimeout:12651266    def test_stream_timeout(self, httpbin):1267        try:1268            requests.get(httpbin('delay/10'), timeout=2.0)1269        except requests.exceptions.Timeout as e:1270            assert 'Read timed out' in e.args[0].args[0]12711272    @pytest.mark.parametrize(1273        'timeout, error_text', (1274            ((3, 4, 5), '(connect, read)'),1275            ('foo', 'must be an int or float'),1276        ))1277    def test_invalid_timeout(self, httpbin, timeout, error_text):1278        with pytest.raises(ValueError) as e:1279            requests.get(httpbin('get'), timeout=timeout)1280        assert error_text in str(e)12811282    def test_none_timeout(self, httpbin):1283        """ Check that you can set None as a valid timeout value.12841285        To actually test this behavior, we'd want to check that setting the1286        timeout to None actually lets the request block past the system default1287        timeout. However, this would make the test suite unbearably slow.1288        Instead we verify that setting the timeout to None does not prevent the1289        request from succeeding.1290        """1291        r = requests.get(httpbin('get'), timeout=None)1292        assert r.status_code == 20012931294    def test_read_timeout(self, httpbin):1295        try:1296            requests.get(httpbin('delay/10'), timeout=(None, 0.1))1297            pytest.fail('The recv() request should time out.')1298        except ReadTimeout:1299            pass13001301    def test_connect_timeout(self):1302        try:1303            requests.get(TARPIT, timeout=(0.1, None))1304            pytest.fail('The connect() request should time out.')1305        except ConnectTimeout as e:1306            assert isinstance(e, ConnectionError)1307            assert isinstance(e, Timeout)13081309    def test_total_timeout_connect(self):1310        try:1311            requests.get(TARPIT, timeout=(0.1, 0.1))1312            pytest.fail('The connect() request should time out.')1313        except ConnectTimeout:1314            pass13151316    def test_encoded_methods(self, httpbin):1317        """See: https://github.com/kennethreitz/requests/issues/2316"""1318        r = requests.request(b'GET', httpbin('get'))1319        assert r.ok132013211322SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))132313241325class RedirectSession(SessionRedirectMixin):1326    def __init__(self, order_of_redirects):1327        self.redirects = order_of_redirects1328        self.calls = []1329        self.max_redirects = 301330        self.cookies = {}1331        self.trust_env = False13321333    def send(self, *args, **kwargs):1334        self.calls.append(SendCall(args, kwargs))1335        return self.build_response()13361337    def build_response(self):1338        request = self.calls[-1].args[0]1339        r = requests.Response()13401341        try:1342            r.status_code = int(self.redirects.pop(0))1343        except IndexError:1344            r.status_code = 20013451346        r.headers = CaseInsensitiveDict({'Location': '/'})1347        r.raw = self._build_raw()1348        r.request = request1349        return r13501351    def _build_raw(self):1352        string = StringIO.StringIO('')1353        setattr(string, 'release_conn', lambda *args: args)1354        return string135513561357def test_requests_are_updated_each_time(httpbin):1358    session = RedirectSession([303, 307])1359    prep = requests.Request('POST', httpbin('post')).prepare()1360    r0 = session.send(prep)1361    assert r0.request.method == 'POST'1362    assert session.calls[-1] == SendCall((r0.request,), {})1363    redirect_generator = session.resolve_redirects(r0, prep)1364    default_keyword_args = {1365        'stream': False,1366        'verify': True,1367        'cert': None,1368        'timeout': None,1369        'allow_redirects': False,1370        'proxies': {},1371    }1372    for response in redirect_generator:1373        assert response.request.method == 'GET'1374        send_call = SendCall((response.request,), default_keyword_args)1375        assert session.calls[-1] == send_call137613771378@pytest.mark.parametrize(1379    'data', (1380        (('a', 'b'), ('c', 'd')),1381        (('c', 'd'), ('a', 'b')),1382        (('a', 'b'), ('c', 'd'), ('e', 'f')),1383    ))1384def test_data_argument_accepts_tuples(data):1385    """Ensure that the data argument will accept tuples of strings1386    and properly encode them.1387    """1388    p = PreparedRequest()1389    p.prepare(1390        method='GET',1391        url='http://www.example.com',1392        data=data,1393        hooks=default_hooks()1394    )1395    assert p.body == urlencode(data)139613971398@pytest.mark.parametrize(1399    'kwargs', (1400        None,1401        {1402            'method': 'GET',1403            'url': 'http://www.example.com',1404            'data': 'foo=bar',1405            'hooks': default_hooks()1406        },1407        {1408            'method': 'GET',1409            'url': 'http://www.example.com',1410            'data': 'foo=bar',1411            'hooks': default_hooks(),1412            'cookies': {'foo': 'bar'}1413        },1414        {1415            'method': 'GET',1416            'url': u('http://www.example.com/üniçø∂é')1417        },1418    ))1419def test_prepared_copy(kwargs):1420    p = PreparedRequest()1421    if kwargs:1422        p.prepare(**kwargs)1423    copy = p.copy()1424    for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):1425        assert getattr(p, attr) == getattr(copy, attr)142614271428def test_urllib3_retries(httpbin):1429    from requests.packages.urllib3.util import Retry1430    s = requests.Session()1431    s.mount('http://', HTTPAdapter(max_retries=Retry(1432        total=2, status_forcelist=[500]1433    )))14341435    with pytest.raises(RetryError):1436        s.get(httpbin('status/500'))143714381439def test_urllib3_pool_connection_closed(httpbin):1440    s = requests.Session()1441    s.mount('http://', HTTPAdapter(pool_connections=0, pool_maxsize=0))14421443    try:1444        s.get(httpbin('status/200'))1445    except ConnectionError as e:1446        assert u"Pool is closed." in str(e)144714481449def test_vendor_aliases():1450    from requests.packages import urllib31451    from requests.packages import chardet14521453    with pytest.raises(ImportError):1454        from requests.packages import webbrowser