Skip to content
Myr

test_requests.py

This file

Path

tests/test_requests.py

2,467 lines · 86.2 KiB · Python

Last changed by

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

History of this file

Take it

1# -*- coding: utf-8 -*-23"""Tests for Requests."""45from __future__ import division6import json7import os8import pickle9import collections10import contextlib11import warnings1213import 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 (22    cookiejar_from_dict, morsel_to_cookie)23from requests.exceptions import (24    ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,25    MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects,26    ProxyError, InvalidHeader, UnrewindableBodyError, SSLError, InvalidProxyURL)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_environ35from urllib3.util import Timeout as Urllib3Timeout3637# Requests to this URL should always fail with a connection timeout (nothing38# listening on that port)39TARPIT = 'http://10.255.255.1'4041try:42    from ssl import SSLContext43    del SSLContext44    HAS_MODERN_SSL = True45except ImportError:46    HAS_MODERN_SSL = False4748try:49    requests.pyopenssl50    HAS_PYOPENSSL = True51except AttributeError:52    HAS_PYOPENSSL = False535455class TestRequests:5657    digest_auth_algo = ('MD5', 'SHA-256', 'SHA-512')5859    def test_entry_points(self):6061        requests.session62        requests.session().get63        requests.session().head64        requests.get65        requests.head66        requests.put67        requests.patch68        requests.post69        # Not really an entry point, but people rely on it.70        from requests.packages.urllib3.poolmanager import PoolManager7172    @pytest.mark.parametrize(73        'exception, url', (74            (MissingSchema, 'hiwpefhipowhefopw'),75            (InvalidSchema, 'localhost:3128'),76            (InvalidSchema, 'localhost.localdomain:3128/'),77            (InvalidSchema, '10.122.1.1:3128/'),78            (InvalidURL, 'http://'),79        ))80    def test_invalid_url(self, exception, url):81        with pytest.raises(exception):82            requests.get(url)8384    def test_basic_building(self):85        req = requests.Request()86        req.url = 'http://kennethreitz.org/'87        req.data = {'life': '42'}8889        pr = req.prepare()90        assert pr.url == req.url91        assert pr.body == 'life=42'9293    @pytest.mark.parametrize('method', ('GET', 'HEAD'))94    def test_no_content_length(self, httpbin, method):95        req = requests.Request(method, httpbin(method.lower())).prepare()96        assert 'Content-Length' not in req.headers9798    @pytest.mark.parametrize('method', ('POST', 'PUT', 'PATCH', 'OPTIONS'))99    def test_no_body_content_length(self, httpbin, method):100        req = requests.Request(method, httpbin(method.lower())).prepare()101        assert req.headers['Content-Length'] == '0'102103    @pytest.mark.parametrize('method', ('POST', 'PUT', 'PATCH', 'OPTIONS'))104    def test_empty_content_length(self, httpbin, method):105        req = requests.Request(method, httpbin(method.lower()), data='').prepare()106        assert req.headers['Content-Length'] == '0'107108    def test_override_content_length(self, httpbin):109        headers = {110            'Content-Length': 'not zero'111        }112        r = requests.Request('POST', httpbin('post'), headers=headers).prepare()113        assert 'Content-Length' in r.headers114        assert r.headers['Content-Length'] == 'not zero'115116    def test_path_is_not_double_encoded(self):117        request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()118119        assert request.path_url == '/get/test%20case'120121    @pytest.mark.parametrize(122        'url, expected', (123            ('http://example.com/path#fragment', 'http://example.com/path?a=b#fragment'),124            ('http://example.com/path?key=value#fragment', 'http://example.com/path?key=value&a=b#fragment')125        ))126    def test_params_are_added_before_fragment(self, url, expected):127        request = requests.Request('GET', url, params={"a": "b"}).prepare()128        assert request.url == expected129130    def test_params_original_order_is_preserved_by_default(self):131        param_ordered_dict = OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))132        session = requests.Session()133        request = requests.Request('GET', 'http://example.com/', params=param_ordered_dict)134        prep = session.prepare_request(request)135        assert prep.url == 'http://example.com/?z=1&a=1&k=1&d=1'136137    def test_params_bytes_are_encoded(self):138        request = requests.Request('GET', 'http://example.com',139                                   params=b'test=foo').prepare()140        assert request.url == 'http://example.com/?test=foo'141142    def test_binary_put(self):143        request = requests.Request('PUT', 'http://example.com',144                                   data=u"ööö".encode("utf-8")).prepare()145        assert isinstance(request.body, bytes)146147    def test_whitespaces_are_removed_from_url(self):148        # Test for issue #3696149        request = requests.Request('GET', ' http://example.com').prepare()150        assert request.url == 'http://example.com/'151152    @pytest.mark.parametrize('scheme', ('http://', 'HTTP://', 'hTTp://', 'HttP://'))153    def test_mixed_case_scheme_acceptable(self, httpbin, scheme):154        s = requests.Session()155        s.proxies = getproxies()156        parts = urlparse(httpbin('get'))157        url = scheme + parts.netloc + parts.path158        r = requests.Request('GET', url)159        r = s.send(r.prepare())160        assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)161162    def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):163        r = requests.Request('GET', httpbin('get'))164        s = requests.Session()165        s.proxies = getproxies()166167        r = s.send(r.prepare())168169        assert r.status_code == 200170171    def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):172        r = requests.get(httpbin('redirect', '1'))173        assert r.status_code == 200174        assert r.history[0].status_code == 302175        assert r.history[0].is_redirect176177    def test_HTTP_307_ALLOW_REDIRECT_POST(self, httpbin):178        r = requests.post(httpbin('redirect-to'), data='test', params={'url': 'post', 'status_code': 307})179        assert r.status_code == 200180        assert r.history[0].status_code == 307181        assert r.history[0].is_redirect182        assert r.json()['data'] == 'test'183184    def test_HTTP_307_ALLOW_REDIRECT_POST_WITH_SEEKABLE(self, httpbin):185        byte_str = b'test'186        r = requests.post(httpbin('redirect-to'), data=io.BytesIO(byte_str), params={'url': 'post', 'status_code': 307})187        assert r.status_code == 200188        assert r.history[0].status_code == 307189        assert r.history[0].is_redirect190        assert r.json()['data'] == byte_str.decode('utf-8')191192    def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):193        try:194            requests.get(httpbin('relative-redirect', '50'))195        except TooManyRedirects as e:196            url = httpbin('relative-redirect', '20')197            assert e.request.url == url198            assert e.response.url == url199            assert len(e.response.history) == 30200        else:201            pytest.fail('Expected redirect to raise TooManyRedirects but it did not')202203    def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):204        s = requests.session()205        s.max_redirects = 5206        try:207            s.get(httpbin('relative-redirect', '50'))208        except TooManyRedirects as e:209            url = httpbin('relative-redirect', '45')210            assert e.request.url == url211            assert e.response.url == url212            assert len(e.response.history) == 5213        else:214            pytest.fail('Expected custom max number of redirects to be respected but was not')215216    def test_http_301_changes_post_to_get(self, httpbin):217        r = requests.post(httpbin('status', '301'))218        assert r.status_code == 200219        assert r.request.method == 'GET'220        assert r.history[0].status_code == 301221        assert r.history[0].is_redirect222223    def test_http_301_doesnt_change_head_to_get(self, httpbin):224        r = requests.head(httpbin('status', '301'), allow_redirects=True)225        print(r.content)226        assert r.status_code == 200227        assert r.request.method == 'HEAD'228        assert r.history[0].status_code == 301229        assert r.history[0].is_redirect230231    def test_http_302_changes_post_to_get(self, httpbin):232        r = requests.post(httpbin('status', '302'))233        assert r.status_code == 200234        assert r.request.method == 'GET'235        assert r.history[0].status_code == 302236        assert r.history[0].is_redirect237238    def test_http_302_doesnt_change_head_to_get(self, httpbin):239        r = requests.head(httpbin('status', '302'), allow_redirects=True)240        assert r.status_code == 200241        assert r.request.method == 'HEAD'242        assert r.history[0].status_code == 302243        assert r.history[0].is_redirect244245    def test_http_303_changes_post_to_get(self, httpbin):246        r = requests.post(httpbin('status', '303'))247        assert r.status_code == 200248        assert r.request.method == 'GET'249        assert r.history[0].status_code == 303250        assert r.history[0].is_redirect251252    def test_http_303_doesnt_change_head_to_get(self, httpbin):253        r = requests.head(httpbin('status', '303'), allow_redirects=True)254        assert r.status_code == 200255        assert r.request.method == 'HEAD'256        assert r.history[0].status_code == 303257        assert r.history[0].is_redirect258259    def test_header_and_body_removal_on_redirect(self, httpbin):260        purged_headers = ('Content-Length', 'Content-Type')261        ses = requests.Session()262        req = requests.Request('POST', httpbin('post'), data={'test': 'data'})263        prep = ses.prepare_request(req)264        resp = ses.send(prep)265266        # Mimic a redirect response267        resp.status_code = 302268        resp.headers['location'] = 'get'269270        # Run request through resolve_redirects271        next_resp = next(ses.resolve_redirects(resp, prep))272        assert next_resp.request.body is None273        for header in purged_headers:274            assert header not in next_resp.request.headers275276    def test_transfer_enc_removal_on_redirect(self, httpbin):277        purged_headers = ('Transfer-Encoding', 'Content-Type')278        ses = requests.Session()279        req = requests.Request('POST', httpbin('post'), data=(b'x' for x in range(1)))280        prep = ses.prepare_request(req)281        assert 'Transfer-Encoding' in prep.headers282283        # Create Response to avoid https://github.com/kevin1024/pytest-httpbin/issues/33284        resp = requests.Response()285        resp.raw = io.BytesIO(b'the content')286        resp.request = prep287        setattr(resp.raw, 'release_conn', lambda *args: args)288289        # Mimic a redirect response290        resp.status_code = 302291        resp.headers['location'] = httpbin('get')292293        # Run request through resolve_redirect294        next_resp = next(ses.resolve_redirects(resp, prep))295        assert next_resp.request.body is None296        for header in purged_headers:297            assert header not in next_resp.request.headers298299    def test_fragment_maintained_on_redirect(self, httpbin):300        fragment = "#view=edit&token=hunter2"301        r = requests.get(httpbin('redirect-to?url=get')+fragment)302303        assert len(r.history) > 0304        assert r.history[0].request.url == httpbin('redirect-to?url=get')+fragment305        assert r.url == httpbin('get')+fragment306307    def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):308        heads = {'User-agent': 'Mozilla/5.0'}309310        r = requests.get(httpbin('user-agent'), headers=heads)311312        assert heads['User-agent'] in r.text313        assert r.status_code == 200314315    def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):316        heads = {'User-agent': 'Mozilla/5.0'}317318        r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)319        assert r.status_code == 200320321    def test_set_cookie_on_301(self, httpbin):322        s = requests.session()323        url = httpbin('cookies/set?foo=bar')324        s.get(url)325        assert s.cookies['foo'] == 'bar'326327    def test_cookie_sent_on_redirect(self, httpbin):328        s = requests.session()329        s.get(httpbin('cookies/set?foo=bar'))330        r = s.get(httpbin('redirect/1'))  # redirects to httpbin('get')331        assert 'Cookie' in r.json()['headers']332333    def test_cookie_removed_on_expire(self, httpbin):334        s = requests.session()335        s.get(httpbin('cookies/set?foo=bar'))336        assert s.cookies['foo'] == 'bar'337        s.get(338            httpbin('response-headers'),339            params={340                'Set-Cookie':341                    'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'342            }343        )344        assert 'foo' not in s.cookies345346    def test_cookie_quote_wrapped(self, httpbin):347        s = requests.session()348        s.get(httpbin('cookies/set?foo="bar:baz"'))349        assert s.cookies['foo'] == '"bar:baz"'350351    def test_cookie_persists_via_api(self, httpbin):352        s = requests.session()353        r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})354        assert 'foo' in r.request.headers['Cookie']355        assert 'foo' in r.history[0].request.headers['Cookie']356357    def test_request_cookie_overrides_session_cookie(self, httpbin):358        s = requests.session()359        s.cookies['foo'] = 'bar'360        r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})361        assert r.json()['cookies']['foo'] == 'baz'362        # Session cookie should not be modified363        assert s.cookies['foo'] == 'bar'364365    def test_request_cookies_not_persisted(self, httpbin):366        s = requests.session()367        s.get(httpbin('cookies'), cookies={'foo': 'baz'})368        # Sending a request with cookies should not add cookies to the session369        assert not s.cookies370371    def test_generic_cookiejar_works(self, httpbin):372        cj = cookielib.CookieJar()373        cookiejar_from_dict({'foo': 'bar'}, cj)374        s = requests.session()375        s.cookies = cj376        r = s.get(httpbin('cookies'))377        # Make sure the cookie was sent378        assert r.json()['cookies']['foo'] == 'bar'379        # Make sure the session cj is still the custom one380        assert s.cookies is cj381382    def test_param_cookiejar_works(self, httpbin):383        cj = cookielib.CookieJar()384        cookiejar_from_dict({'foo': 'bar'}, cj)385        s = requests.session()386        r = s.get(httpbin('cookies'), cookies=cj)387        # Make sure the cookie was sent388        assert r.json()['cookies']['foo'] == 'bar'389390    def test_cookielib_cookiejar_on_redirect(self, httpbin):391        """Tests resolve_redirect doesn't fail when merging cookies392        with non-RequestsCookieJar cookiejar.393394        See GH #3579395        """396        cj = cookiejar_from_dict({'foo': 'bar'}, cookielib.CookieJar())397        s = requests.Session()398        s.cookies = cookiejar_from_dict({'cookie': 'tasty'})399400        # Prepare request without using Session401        req = requests.Request('GET', httpbin('headers'), cookies=cj)402        prep_req = req.prepare()403404        # Send request and simulate redirect405        resp = s.send(prep_req)406        resp.status_code = 302407        resp.headers['location'] = httpbin('get')408        redirects = s.resolve_redirects(resp, prep_req)409        resp = next(redirects)410411        # Verify CookieJar isn't being converted to RequestsCookieJar412        assert isinstance(prep_req._cookies, cookielib.CookieJar)413        assert isinstance(resp.request._cookies, cookielib.CookieJar)414        assert not isinstance(resp.request._cookies, requests.cookies.RequestsCookieJar)415416        cookies = {}417        for c in resp.request._cookies:418            cookies[c.name] = c.value419        assert cookies['foo'] == 'bar'420        assert cookies['cookie'] == 'tasty'421422    def test_requests_in_history_are_not_overridden(self, httpbin):423        resp = requests.get(httpbin('redirect/3'))424        urls = [r.url for r in resp.history]425        req_urls = [r.request.url for r in resp.history]426        assert urls == req_urls427428    def test_history_is_always_a_list(self, httpbin):429        """Show that even with redirects, Response.history is always a list."""430        resp = requests.get(httpbin('get'))431        assert isinstance(resp.history, list)432        resp = requests.get(httpbin('redirect/1'))433        assert isinstance(resp.history, list)434        assert not isinstance(resp.history, tuple)435436    def test_headers_on_session_with_None_are_not_sent(self, httpbin):437        """Do not send headers in Session.headers with None values."""438        ses = requests.Session()439        ses.headers['Accept-Encoding'] = None440        req = requests.Request('GET', httpbin('get'))441        prep = ses.prepare_request(req)442        assert 'Accept-Encoding' not in prep.headers443444    def test_headers_preserve_order(self, httpbin):445        """Preserve order when headers provided as OrderedDict."""446        ses = requests.Session()447        ses.headers = OrderedDict()448        ses.headers['Accept-Encoding'] = 'identity'449        ses.headers['First'] = '1'450        ses.headers['Second'] = '2'451        headers = OrderedDict([('Third', '3'), ('Fourth', '4')])452        headers['Fifth'] = '5'453        headers['Second'] = '222'454        req = requests.Request('GET', httpbin('get'), headers=headers)455        prep = ses.prepare_request(req)456        items = list(prep.headers.items())457        assert items[0] == ('Accept-Encoding', 'identity')458        assert items[1] == ('First', '1')459        assert items[2] == ('Second', '222')460        assert items[3] == ('Third', '3')461        assert items[4] == ('Fourth', '4')462        assert items[5] == ('Fifth', '5')463464    @pytest.mark.parametrize('key', ('User-agent', 'user-agent'))465    def test_user_agent_transfers(self, httpbin, key):466467        heads = {key: 'Mozilla/5.0 (github.com/requests/requests)'}468469        r = requests.get(httpbin('user-agent'), headers=heads)470        assert heads[key] in r.text471472    def test_HTTP_200_OK_HEAD(self, httpbin):473        r = requests.head(httpbin('get'))474        assert r.status_code == 200475476    def test_HTTP_200_OK_PUT(self, httpbin):477        r = requests.put(httpbin('put'))478        assert r.status_code == 200479480    def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):481        auth = ('user', 'pass')482        url = httpbin('basic-auth', 'user', 'pass')483484        r = requests.get(url, auth=auth)485        assert r.status_code == 200486487        r = requests.get(url)488        assert r.status_code == 401489490        s = requests.session()491        s.auth = auth492        r = s.get(url)493        assert r.status_code == 200494495    @pytest.mark.parametrize(496        'username, password', (497            ('user', 'pass'),498            (u'имя'.encode('utf-8'), u'пароль'.encode('utf-8')),499            (42, 42),500            (None, None),501        ))502    def test_set_basicauth(self, httpbin, username, password):503        auth = (username, password)504        url = httpbin('get')505506        r = requests.Request('GET', url, auth=auth)507        p = r.prepare()508509        assert p.headers['Authorization'] == _basic_auth_str(username, password)510511    def test_basicauth_encodes_byte_strings(self):512        """Ensure b'test' formats as the byte string "test" rather513        than the unicode string "b'test'" in Python 3.514        """515        auth = (b'\xc5\xafsername', b'test\xc6\xb6')516        r = requests.Request('GET', 'http://localhost', auth=auth)517        p = r.prepare()518519        assert p.headers['Authorization'] == 'Basic xa9zZXJuYW1lOnRlc3TGtg=='520521    @pytest.mark.parametrize(522        'url, exception', (523            # Connecting to an unknown domain should raise a ConnectionError524            ('http://doesnotexist.google.com', ConnectionError),525            # Connecting to an invalid port should raise a ConnectionError526            ('http://localhost:1', ConnectionError),527            # Inputing a URL that cannot be parsed should raise an InvalidURL error528            ('http://fe80::5054:ff:fe5a:fc0', InvalidURL)529        ))530    def test_errors(self, url, exception):531        with pytest.raises(exception):532            requests.get(url, timeout=1)533534    def test_proxy_error(self):535        # any proxy related error (address resolution, no route to host, etc) should result in a ProxyError536        with pytest.raises(ProxyError):537            requests.get('http://localhost:1', proxies={'http': 'non-resolvable-address'})538539    def test_proxy_error_on_bad_url(self, httpbin, httpbin_secure):540        with pytest.raises(InvalidProxyURL):541            requests.get(httpbin_secure(), proxies={'https': 'http:/badproxyurl:3128'})542543        with pytest.raises(InvalidProxyURL):544            requests.get(httpbin(), proxies={'http': 'http://:8080'})545546        with pytest.raises(InvalidProxyURL):547            requests.get(httpbin_secure(), proxies={'https': 'https://'})548549        with pytest.raises(InvalidProxyURL):550            requests.get(httpbin(), proxies={'http': 'http:///example.com:8080'})551552    def test_basicauth_with_netrc(self, httpbin):553        auth = ('user', 'pass')554        wrong_auth = ('wronguser', 'wrongpass')555        url = httpbin('basic-auth', 'user', 'pass')556557        old_auth = requests.sessions.get_netrc_auth558559        try:560            def get_netrc_auth_mock(url):561                return auth562            requests.sessions.get_netrc_auth = get_netrc_auth_mock563564            # Should use netrc and work.565            r = requests.get(url)566            assert r.status_code == 200567568            # Given auth should override and fail.569            r = requests.get(url, auth=wrong_auth)570            assert r.status_code == 401571572            s = requests.session()573574            # Should use netrc and work.575            r = s.get(url)576            assert r.status_code == 200577578            # Given auth should override and fail.579            s.auth = wrong_auth580            r = s.get(url)581            assert r.status_code == 401582        finally:583            requests.sessions.get_netrc_auth = old_auth584585    def test_DIGEST_HTTP_200_OK_GET(self, httpbin):586587        for authtype in self.digest_auth_algo:588            auth = HTTPDigestAuth('user', 'pass')589            url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype, 'never')590591            r = requests.get(url, auth=auth)592            assert r.status_code == 200593594            r = requests.get(url)595            assert r.status_code == 401596            print(r.headers['WWW-Authenticate'])597598            s = requests.session()599            s.auth = HTTPDigestAuth('user', 'pass')600            r = s.get(url)601            assert r.status_code == 200602603    def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):604605        for authtype in self.digest_auth_algo:606            url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype)607            auth = HTTPDigestAuth('user', 'pass')608            r = requests.get(url)609            assert r.cookies['fake'] == 'fake_value'610611            r = requests.get(url, auth=auth)612            assert r.status_code == 200613614    def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):615616        for authtype in self.digest_auth_algo:617            url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype)618            auth = HTTPDigestAuth('user', 'pass')619            s = requests.Session()620            s.get(url, auth=auth)621            assert s.cookies['fake'] == 'fake_value'622623    def test_DIGEST_STREAM(self, httpbin):624625        for authtype in self.digest_auth_algo:626            auth = HTTPDigestAuth('user', 'pass')627            url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype)628629            r = requests.get(url, auth=auth, stream=True)630            assert r.raw.read() != b''631632            r = requests.get(url, auth=auth, stream=False)633            assert r.raw.read() == b''634635    def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):636637        for authtype in self.digest_auth_algo:638            auth = HTTPDigestAuth('user', 'wrongpass')639            url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype)640641            r = requests.get(url, auth=auth)642            assert r.status_code == 401643644            r = requests.get(url)645            assert r.status_code == 401646647            s = requests.session()648            s.auth = auth649            r = s.get(url)650            assert r.status_code == 401651652    def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):653654        for authtype in self.digest_auth_algo:655            auth = HTTPDigestAuth('user', 'pass')656            url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype)657658            r = requests.get(url, auth=auth)659            assert '"auth"' in r.request.headers['Authorization']660661    def test_POSTBIN_GET_POST_FILES(self, httpbin):662663        url = httpbin('post')664        requests.post(url).raise_for_status()665666        post1 = requests.post(url, data={'some': 'data'})667        assert post1.status_code == 200668669        with open('Pipfile') as f:670            post2 = requests.post(url, files={'some': f})671        assert post2.status_code == 200672673        post4 = requests.post(url, data='[{"some": "json"}]')674        assert post4.status_code == 200675676        with pytest.raises(ValueError):677            requests.post(url, files=['bad file data'])678679    def test_invalid_files_input(self, httpbin):680681        url = httpbin('post')682        post = requests.post(url,683                             files={"random-file-1": None, "random-file-2": 1})684        assert b'name="random-file-1"' not in post.request.body685        assert b'name="random-file-2"' in post.request.body686687    def test_POSTBIN_SEEKED_OBJECT_WITH_NO_ITER(self, httpbin):688689        class TestStream(object):690            def __init__(self, data):691                self.data = data.encode()692                self.length = len(self.data)693                self.index = 0694695            def __len__(self):696                return self.length697698            def read(self, size=None):699                if size:700                    ret = self.data[self.index:self.index + size]701                    self.index += size702                else:703                    ret = self.data[self.index:]704                    self.index = self.length705                return ret706707            def tell(self):708                return self.index709710            def seek(self, offset, where=0):711                if where == 0:712                    self.index = offset713                elif where == 1:714                    self.index += offset715                elif where == 2:716                    self.index = self.length + offset717718        test = TestStream('test')719        post1 = requests.post(httpbin('post'), data=test)720        assert post1.status_code == 200721        assert post1.json()['data'] == 'test'722723        test = TestStream('test')724        test.seek(2)725        post2 = requests.post(httpbin('post'), data=test)726        assert post2.status_code == 200727        assert post2.json()['data'] == 'st'728729    def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):730731        url = httpbin('post')732        requests.post(url).raise_for_status()733734        post1 = requests.post(url, data={'some': 'data'})735        assert post1.status_code == 200736737        with open('Pipfile') as f:738            post2 = requests.post(url, data={'some': 'data'}, files={'some': f})739        assert post2.status_code == 200740741        post4 = requests.post(url, data='[{"some": "json"}]')742        assert post4.status_code == 200743744        with pytest.raises(ValueError):745            requests.post(url, files=['bad file data'])746747    def test_post_with_custom_mapping(self, httpbin):748        class CustomMapping(collections.MutableMapping):749            def __init__(self, *args, **kwargs):750                self.data = dict(*args, **kwargs)751752            def __delitem__(self, key):753                del self.data[key]754755            def __getitem__(self, key):756                return self.data[key]757758            def __setitem__(self, key, value):759                self.data[key] = value760761            def __iter__(self):762                return iter(self.data)763764            def __len__(self):765                return len(self.data)766767        data = CustomMapping({'some': 'data'})768        url = httpbin('post')769        found_json = requests.post(url, data=data).json().get('form')770        assert found_json == {'some': 'data'}771772    def test_conflicting_post_params(self, httpbin):773        url = httpbin('post')774        with open('Pipfile') as f:775            pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")776            pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")777778    def test_request_ok_set(self, httpbin):779        r = requests.get(httpbin('status', '404'))780        assert not r.ok781782    def test_status_raising(self, httpbin):783        r = requests.get(httpbin('status', '404'))784        with pytest.raises(requests.exceptions.HTTPError):785            r.raise_for_status()786787        r = requests.get(httpbin('status', '500'))788        assert not r.ok789790    def test_decompress_gzip(self, httpbin):791        r = requests.get(httpbin('gzip'))792        r.content.decode('ascii')793794    @pytest.mark.parametrize(795        'url, params', (796            ('/get', {'foo': 'føø'}),797            ('/get', {'føø': 'føø'}),798            ('/get', {'føø': 'føø'}),799            ('/get', {'foo': 'foo'}),800            ('ø', {'foo': 'foo'}),801        ))802    def test_unicode_get(self, httpbin, url, params):803        requests.get(httpbin(url), params=params)804805    def test_unicode_header_name(self, httpbin):806        requests.put(807            httpbin('put'),808            headers={str('Content-Type'): 'application/octet-stream'},809            data='\xff')  # compat.str is unicode.810811    def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):812        requests.get(httpbin_secure('status', '301'), verify=httpbin_ca_bundle)813814    def test_invalid_ca_certificate_path(self, httpbin_secure):815        INVALID_PATH = '/garbage'816        with pytest.raises(IOError) as e:817            requests.get(httpbin_secure(), verify=INVALID_PATH)818        assert str(e.value) == 'Could not find a suitable TLS CA certificate bundle, invalid path: {0}'.format(INVALID_PATH)819820    def test_invalid_ssl_certificate_files(self, httpbin_secure):821        INVALID_PATH = '/garbage'822        with pytest.raises(IOError) as e:823            requests.get(httpbin_secure(), cert=INVALID_PATH)824        assert str(e.value) == 'Could not find the TLS certificate file, invalid path: {0}'.format(INVALID_PATH)825826        with pytest.raises(IOError) as e:827            requests.get(httpbin_secure(), cert=('.', INVALID_PATH))828        assert str(e.value) == 'Could not find the TLS key file, invalid path: {0}'.format(INVALID_PATH)829830    def test_http_with_certificate(self, httpbin):831        r = requests.get(httpbin(), cert='.')832        assert r.status_code == 200833834    def test_https_warnings(self, httpbin_secure, httpbin_ca_bundle):835        """warnings are emitted with requests.get"""836        if HAS_MODERN_SSL or HAS_PYOPENSSL:837            warnings_expected = ('SubjectAltNameWarning', )838        else:839            warnings_expected = ('SNIMissingWarning',840                                 'InsecurePlatformWarning',841                                 'SubjectAltNameWarning', )842843        with pytest.warns(None) as warning_records:844            warnings.simplefilter('always')845            requests.get(httpbin_secure('status', '200'),846                         verify=httpbin_ca_bundle)847848        warning_records = [item for item in warning_records849                           if item.category.__name__ != 'ResourceWarning']850851        warnings_category = tuple(852            item.category.__name__ for item in warning_records)853        assert warnings_category == warnings_expected854855    def test_certificate_failure(self, httpbin_secure):856        """857        When underlying SSL problems occur, an SSLError is raised.858        """859        with pytest.raises(SSLError):860            # Our local httpbin does not have a trusted CA, so this call will861            # fail if we use our default trust bundle.862            requests.get(httpbin_secure('status', '200'))863864    def test_urlencoded_get_query_multivalued_param(self, httpbin):865866        r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))867        assert r.status_code == 200868        assert r.url == httpbin('get?test=foo&test=baz')869870    def test_different_encodings_dont_break_post(self, httpbin):871        r = requests.post(httpbin('post'),872            data={'stuff': json.dumps({'a': 123})},873            params={'blah': 'asdf1234'},874            files={'file': ('test_requests.py', open(__file__, 'rb'))})875        assert r.status_code == 200876877    @pytest.mark.parametrize(878        'data', (879            {'stuff': u('ëlïxr')},880            {'stuff': u('ëlïxr').encode('utf-8')},881            {'stuff': 'elixr'},882            {'stuff': 'elixr'.encode('utf-8')},883        ))884    def test_unicode_multipart_post(self, httpbin, data):885        r = requests.post(httpbin('post'),886            data=data,887            files={'file': ('test_requests.py', open(__file__, 'rb'))})888        assert r.status_code == 200889890    def test_unicode_multipart_post_fieldnames(self, httpbin):891        filename = os.path.splitext(__file__)[0] + '.py'892        r = requests.Request(893            method='POST', url=httpbin('post'),894            data={'stuff'.encode('utf-8'): 'elixr'},895            files={'file': ('test_requests.py', open(filename, 'rb'))})896        prep = r.prepare()897        assert b'name="stuff"' in prep.body898        assert b'name="b\'stuff\'"' not in prep.body899900    def test_unicode_method_name(self, httpbin):901        files = {'file': open(__file__, 'rb')}902        r = requests.request(903            method=u('POST'), url=httpbin('post'), files=files)904        assert r.status_code == 200905906    def test_unicode_method_name_with_request_object(self, httpbin):907        files = {'file': open(__file__, 'rb')}908        s = requests.Session()909        req = requests.Request(u('POST'), httpbin('post'), files=files)910        prep = s.prepare_request(req)911        assert isinstance(prep.method, builtin_str)912        assert prep.method == 'POST'913914        resp = s.send(prep)915        assert resp.status_code == 200916917    def test_non_prepared_request_error(self):918        s = requests.Session()919        req = requests.Request(u('POST'), '/')920921        with pytest.raises(ValueError) as e:922            s.send(req)923        assert str(e.value) == 'You can only send PreparedRequests.'924925    def test_custom_content_type(self, httpbin):926        r = requests.post(927            httpbin('post'),928            data={'stuff': json.dumps({'a': 123})},929            files={930                'file1': ('test_requests.py', open(__file__, 'rb')),931                'file2': ('test_requests', open(__file__, 'rb'),932                    'text/py-content-type')})933        assert r.status_code == 200934        assert b"text/py-content-type" in r.request.body935936    def test_hook_receives_request_arguments(self, httpbin):937        def hook(resp, **kwargs):938            assert resp is not None939            assert kwargs != {}940941        s = requests.Session()942        r = requests.Request('GET', httpbin(), hooks={'response': hook})943        prep = s.prepare_request(r)944        s.send(prep)945946    def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):947        hook = lambda x, *args, **kwargs: x948        s = requests.Session()949        s.hooks['response'].append(hook)950        r = requests.Request('GET', httpbin())951        prep = s.prepare_request(r)952        assert prep.hooks['response'] != []953        assert prep.hooks['response'] == [hook]954955    def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):956        hook1 = lambda x, *args, **kwargs: x957        hook2 = lambda x, *args, **kwargs: x958        assert hook1 is not hook2959        s = requests.Session()960        s.hooks['response'].append(hook2)961        r = requests.Request('GET', httpbin(), hooks={'response': [hook1]})962        prep = s.prepare_request(r)963        assert prep.hooks['response'] == [hook1]964965    def test_prepared_request_hook(self, httpbin):966        def hook(resp, **kwargs):967            resp.hook_working = True968            return resp969970        req = requests.Request('GET', httpbin(), hooks={'response': hook})971        prep = req.prepare()972973        s = requests.Session()974        s.proxies = getproxies()975        resp = s.send(prep)976977        assert hasattr(resp, 'hook_working')978979    def test_prepared_from_session(self, httpbin):980        class DummyAuth(requests.auth.AuthBase):981            def __call__(self, r):982                r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'983                return r984985        req = requests.Request('GET', httpbin('headers'))986        assert not req.auth987988        s = requests.Session()989        s.auth = DummyAuth()990991        prep = s.prepare_request(req)992        resp = s.send(prep)993994        assert resp.json()['headers'][995            'Dummy-Auth-Test'] == 'dummy-auth-test-ok'996997    def test_prepare_request_with_bytestring_url(self):998        req = requests.Request('GET', b'https://httpbin.org/')999        s = requests.Session()1000        prep = s.prepare_request(req)1001        assert prep.url == "https://httpbin.org/"10021003    def test_request_with_bytestring_host(self, httpbin):1004        s = requests.Session()1005        resp = s.request(1006            'GET',1007            httpbin('cookies/set?cookie=value'),1008            allow_redirects=False,1009            headers={'Host': b'httpbin.org'}1010        )1011        assert resp.cookies.get('cookie') == 'value'10121013    def test_links(self):1014        r = requests.Response()1015        r.headers = {1016            'cache-control': 'public, max-age=60, s-maxage=60',1017            'connection': 'keep-alive',1018            'content-encoding': 'gzip',1019            'content-type': 'application/json; charset=utf-8',1020            'date': 'Sat, 26 Jan 2013 16:47:56 GMT',1021            'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',1022            'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',1023            'link': ('<https://api.github.com/users/kennethreitz/repos?'1024                     'page=2&per_page=10>; rel="next", <https://api.github.'1025                     'com/users/kennethreitz/repos?page=7&per_page=10>; '1026                     ' rel="last"'),1027            'server': 'GitHub.com',1028            'status': '200 OK',1029            'vary': 'Accept',1030            'x-content-type-options': 'nosniff',1031            'x-github-media-type': 'github.beta',1032            'x-ratelimit-limit': '60',1033            'x-ratelimit-remaining': '57'1034        }1035        assert r.links['next']['rel'] == 'next'10361037    def test_cookie_parameters(self):1038        key = 'some_cookie'1039        value = 'some_value'1040        secure = True1041        domain = 'test.com'1042        rest = {'HttpOnly': True}10431044        jar = requests.cookies.RequestsCookieJar()1045        jar.set(key, value, secure=secure, domain=domain, rest=rest)10461047        assert len(jar) == 11048        assert 'some_cookie' in jar10491050        cookie = list(jar)[0]1051        assert cookie.secure == secure1052        assert cookie.domain == domain1053        assert cookie._rest['HttpOnly'] == rest['HttpOnly']10541055    def test_cookie_as_dict_keeps_len(self):1056        key = 'some_cookie'1057        value = 'some_value'10581059        key1 = 'some_cookie1'1060        value1 = 'some_value1'10611062        jar = requests.cookies.RequestsCookieJar()1063        jar.set(key, value)1064        jar.set(key1, value1)10651066        d1 = dict(jar)1067        d2 = dict(jar.iteritems())1068        d3 = dict(jar.items())10691070        assert len(jar) == 21071        assert len(d1) == 21072        assert len(d2) == 21073        assert len(d3) == 210741075    def test_cookie_as_dict_keeps_items(self):1076        key = 'some_cookie'1077        value = 'some_value'10781079        key1 = 'some_cookie1'1080        value1 = 'some_value1'10811082        jar = requests.cookies.RequestsCookieJar()1083        jar.set(key, value)1084        jar.set(key1, value1)10851086        d1 = dict(jar)1087        d2 = dict(jar.iteritems())1088        d3 = dict(jar.items())10891090        assert d1['some_cookie'] == 'some_value'1091        assert d2['some_cookie'] == 'some_value'1092        assert d3['some_cookie1'] == 'some_value1'10931094    def test_cookie_as_dict_keys(self):1095        key = 'some_cookie'1096        value = 'some_value'10971098        key1 = 'some_cookie1'1099        value1 = 'some_value1'11001101        jar = requests.cookies.RequestsCookieJar()1102        jar.set(key, value)1103        jar.set(key1, value1)11041105        keys = jar.keys()1106        assert keys == list(keys)1107        # make sure one can use keys multiple times1108        assert list(keys) == list(keys)11091110    def test_cookie_as_dict_values(self):1111        key = 'some_cookie'1112        value = 'some_value'11131114        key1 = 'some_cookie1'1115        value1 = 'some_value1'11161117        jar = requests.cookies.RequestsCookieJar()1118        jar.set(key, value)1119        jar.set(key1, value1)11201121        values = jar.values()1122        assert values == list(values)1123        # make sure one can use values multiple times1124        assert list(values) == list(values)11251126    def test_cookie_as_dict_items(self):1127        key = 'some_cookie'1128        value = 'some_value'11291130        key1 = 'some_cookie1'1131        value1 = 'some_value1'11321133        jar = requests.cookies.RequestsCookieJar()1134        jar.set(key, value)1135        jar.set(key1, value1)11361137        items = jar.items()1138        assert items == list(items)1139        # make sure one can use items multiple times1140        assert list(items) == list(items)11411142    def test_cookie_duplicate_names_different_domains(self):1143        key = 'some_cookie'1144        value = 'some_value'1145        domain1 = 'test1.com'1146        domain2 = 'test2.com'11471148        jar = requests.cookies.RequestsCookieJar()1149        jar.set(key, value, domain=domain1)1150        jar.set(key, value, domain=domain2)1151        assert key in jar1152        items = jar.items()1153        assert len(items) == 211541155        # Verify that CookieConflictError is raised if domain is not specified1156        with pytest.raises(requests.cookies.CookieConflictError):1157            jar.get(key)11581159        # Verify that CookieConflictError is not raised if domain is specified1160        cookie = jar.get(key, domain=domain1)1161        assert cookie == value11621163    def test_cookie_duplicate_names_raises_cookie_conflict_error(self):1164        key = 'some_cookie'1165        value = 'some_value'1166        path = 'some_path'11671168        jar = requests.cookies.RequestsCookieJar()1169        jar.set(key, value, path=path)1170        jar.set(key, value)1171        with pytest.raises(requests.cookies.CookieConflictError):1172            jar.get(key)11731174    def test_time_elapsed_blank(self, httpbin):1175        r = requests.get(httpbin('get'))1176        td = r.elapsed1177        total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6)1178        assert total_seconds > 0.011791180    def test_empty_response_has_content_none(self):1181        r = requests.Response()1182        assert r.content is None11831184    def test_response_is_iterable(self):1185        r = requests.Response()1186        io = StringIO.StringIO('abc')1187        read_ = io.read11881189        def read_mock(amt, decode_content=None):1190            return read_(amt)1191        setattr(io, 'read', read_mock)1192        r.raw = io1193        assert next(iter(r))1194        io.close()11951196    def test_response_decode_unicode(self):1197        """When called with decode_unicode, Response.iter_content should always1198        return unicode.1199        """1200        r = requests.Response()1201        r._content_consumed = True1202        r._content = b'the content'1203        r.encoding = 'ascii'12041205        chunks = r.iter_content(decode_unicode=True)1206        assert all(isinstance(chunk, str) for chunk in chunks)12071208        # also for streaming1209        r = requests.Response()1210        r.raw = io.BytesIO(b'the content')1211        r.encoding = 'ascii'1212        chunks = r.iter_content(decode_unicode=True)1213        assert all(isinstance(chunk, str) for chunk in chunks)12141215    def test_response_reason_unicode(self):1216        # check for unicode HTTP status1217        r = requests.Response()1218        r.url = u'unicode URL'1219        r.reason = u'Komponenttia ei löydy'.encode('utf-8')1220        r.status_code = 4041221        r.encoding = None1222        assert not r.ok  # old behaviour - crashes here12231224    def test_response_reason_unicode_fallback(self):1225        # check raise_status falls back to ISO-8859-11226        r = requests.Response()1227        r.url = 'some url'1228        reason = u'Komponenttia ei löydy'1229        r.reason = reason.encode('latin-1')1230        r.status_code = 5001231        r.encoding = None1232        with pytest.raises(requests.exceptions.HTTPError) as e:1233            r.raise_for_status()1234        assert reason in e.value.args[0]12351236    def test_response_chunk_size_type(self):1237        """Ensure that chunk_size is passed as None or an integer, otherwise1238        raise a TypeError.1239        """1240        r = requests.Response()1241        r.raw = io.BytesIO(b'the content')1242        chunks = r.iter_content(1)1243        assert all(len(chunk) == 1 for chunk in chunks)12441245        r = requests.Response()1246        r.raw = io.BytesIO(b'the content')1247        chunks = r.iter_content(None)1248        assert list(chunks) == [b'the content']12491250        r = requests.Response()1251        r.raw = io.BytesIO(b'the content')1252        with pytest.raises(TypeError):1253            chunks = r.iter_content("1024")12541255    def test_request_and_response_are_pickleable(self, httpbin):1256        r = requests.get(httpbin('get'))12571258        # verify we can pickle the original request1259        assert pickle.loads(pickle.dumps(r.request))12601261        # verify we can pickle the response and that we have access to1262        # the original request.1263        pr = pickle.loads(pickle.dumps(r))1264        assert r.request.url == pr.request.url1265        assert r.request.headers == pr.request.headers12661267    def test_prepared_request_is_pickleable(self, httpbin):1268        p = requests.Request('GET', httpbin('get')).prepare()12691270        # Verify PreparedRequest can be pickled and unpickled1271        r = pickle.loads(pickle.dumps(p))1272        assert r.url == p.url1273        assert r.headers == p.headers1274        assert r.body == p.body12751276        # Verify unpickled PreparedRequest sends properly1277        s = requests.Session()1278        resp = s.send(r)1279        assert resp.status_code == 20012801281    def test_prepared_request_with_file_is_pickleable(self, httpbin):1282        files = {'file': open(__file__, 'rb')}1283        r = requests.Request('POST', httpbin('post'), files=files)1284        p = r.prepare()12851286        # Verify PreparedRequest can be pickled and unpickled1287        r = pickle.loads(pickle.dumps(p))1288        assert r.url == p.url1289        assert r.headers == p.headers1290        assert r.body == p.body12911292        # Verify unpickled PreparedRequest sends properly1293        s = requests.Session()1294        resp = s.send(r)1295        assert resp.status_code == 20012961297    def test_prepared_request_with_hook_is_pickleable(self, httpbin):1298        r = requests.Request('GET', httpbin('get'), hooks=default_hooks())1299        p = r.prepare()13001301        # Verify PreparedRequest can be pickled1302        r = pickle.loads(pickle.dumps(p))1303        assert r.url == p.url1304        assert r.headers == p.headers1305        assert r.body == p.body1306        assert r.hooks == p.hooks13071308        # Verify unpickled PreparedRequest sends properly1309        s = requests.Session()1310        resp = s.send(r)1311        assert resp.status_code == 20013121313    def test_cannot_send_unprepared_requests(self, httpbin):1314        r = requests.Request(url=httpbin())1315        with pytest.raises(ValueError):1316            requests.Session().send(r)13171318    def test_http_error(self):1319        error = requests.exceptions.HTTPError()1320        assert not error.response1321        response = requests.Response()1322        error = requests.exceptions.HTTPError(response=response)1323        assert error.response == response1324        error = requests.exceptions.HTTPError('message', response=response)1325        assert str(error) == 'message'1326        assert error.response == response13271328    def test_session_pickling(self, httpbin):1329        r = requests.Request('GET', httpbin('get'))1330        s = requests.Session()13311332        s = pickle.loads(pickle.dumps(s))1333        s.proxies = getproxies()13341335        r = s.send(r.prepare())1336        assert r.status_code == 20013371338    def test_fixes_1329(self, httpbin):1339        """Ensure that header updates are done case-insensitively."""1340        s = requests.Session()1341        s.headers.update({'ACCEPT': 'BOGUS'})1342        s.headers.update({'accept': 'application/json'})1343        r = s.get(httpbin('get'))1344        headers = r.request.headers1345        assert headers['accept'] == 'application/json'1346        assert headers['Accept'] == 'application/json'1347        assert headers['ACCEPT'] == 'application/json'13481349    def test_uppercase_scheme_redirect(self, httpbin):1350        parts = urlparse(httpbin('html'))1351        url = "HTTP://" + parts.netloc + parts.path1352        r = requests.get(httpbin('redirect-to'), params={'url': url})1353        assert r.status_code == 2001354        assert r.url.lower() == url.lower()13551356    def test_transport_adapter_ordering(self):1357        s = requests.Session()1358        order = ['https://', 'http://']1359        assert order == list(s.adapters)1360        s.mount('http://git', HTTPAdapter())1361        s.mount('http://github', HTTPAdapter())1362        s.mount('http://github.com', HTTPAdapter())1363        s.mount('http://github.com/about/', HTTPAdapter())1364        order = [1365            'http://github.com/about/',1366            'http://github.com',1367            'http://github',1368            'http://git',1369            'https://',1370            'http://',1371        ]1372        assert order == list(s.adapters)1373        s.mount('http://gittip', HTTPAdapter())1374        s.mount('http://gittip.com', HTTPAdapter())1375        s.mount('http://gittip.com/about/', HTTPAdapter())1376        order = [1377            'http://github.com/about/',1378            'http://gittip.com/about/',1379            'http://github.com',1380            'http://gittip.com',1381            'http://github',1382            'http://gittip',1383            'http://git',1384            'https://',1385            'http://',1386        ]1387        assert order == list(s.adapters)1388        s2 = requests.Session()1389        s2.adapters = {'http://': HTTPAdapter()}1390        s2.mount('https://', HTTPAdapter())1391        assert 'http://' in s2.adapters1392        assert 'https://' in s2.adapters13931394    def test_session_get_adapter_prefix_matching(self, httpbin):1395        prefix = 'https://example.com'1396        more_specific_prefix = prefix + '/some/path'13971398        url_matching_only_prefix = prefix + '/another/path'1399        url_matching_more_specific_prefix = more_specific_prefix + '/longer/path'1400        url_not_matching_prefix = 'https://another.example.com/'14011402        s = requests.Session()1403        prefix_adapter = HTTPAdapter()1404        more_specific_prefix_adapter = HTTPAdapter()1405        s.mount(prefix, prefix_adapter)1406        s.mount(more_specific_prefix, more_specific_prefix_adapter)14071408        assert s.get_adapter(url_matching_only_prefix) is prefix_adapter1409        assert s.get_adapter(url_matching_more_specific_prefix) is more_specific_prefix_adapter1410        assert s.get_adapter(url_not_matching_prefix) not in (prefix_adapter, more_specific_prefix_adapter)14111412    def test_session_get_adapter_prefix_matching_mixed_case(self, httpbin):1413        mixed_case_prefix = 'hTtPs://eXamPle.CoM/MixEd_CAse_PREfix'1414        url_matching_prefix = mixed_case_prefix + '/full_url'14151416        s = requests.Session()1417        my_adapter = HTTPAdapter()1418        s.mount(mixed_case_prefix, my_adapter)14191420        assert s.get_adapter(url_matching_prefix) is my_adapter14211422    def test_session_get_adapter_prefix_matching_is_case_insensitive(self, httpbin):1423        mixed_case_prefix = 'hTtPs://eXamPle.CoM/MixEd_CAse_PREfix'1424        url_matching_prefix_with_different_case = 'HtTpS://exaMPLe.cOm/MiXeD_caSE_preFIX/another_url'14251426        s = requests.Session()1427        my_adapter = HTTPAdapter()1428        s.mount(mixed_case_prefix, my_adapter)14291430        assert s.get_adapter(url_matching_prefix_with_different_case) is my_adapter14311432    def test_header_remove_is_case_insensitive(self, httpbin):1433        # From issue #13211434        s = requests.Session()1435        s.headers['foo'] = 'bar'1436        r = s.get(httpbin('get'), headers={'FOO': None})1437        assert 'foo' not in r.request.headers14381439    def test_params_are_merged_case_sensitive(self, httpbin):1440        s = requests.Session()1441        s.params['foo'] = 'bar'1442        r = s.get(httpbin('get'), params={'FOO': 'bar'})1443        assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}14441445    def test_long_authinfo_in_url(self):1446        url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(1447            'E8A3BE87-9E3F-4620-8858-95478E385B5B',1448            'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',1449            'exactly-------------sixty-----------three------------characters',1450        )1451        r = requests.Request('GET', url).prepare()1452        assert r.url == url14531454    def test_header_keys_are_native(self, httpbin):1455        headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}1456        r = requests.Request('GET', httpbin('get'), headers=headers)1457        p = r.prepare()14581459        # This is testing that they are builtin strings. A bit weird, but there1460        # we go.1461        assert 'unicode' in p.headers.keys()1462        assert 'byte' in p.headers.keys()14631464    def test_header_validation(self, httpbin):1465        """Ensure prepare_headers regex isn't flagging valid header contents."""1466        headers_ok = {'foo': 'bar baz qux',1467                      'bar': u'fbbq'.encode('utf8'),1468                      'baz': '',1469                      'qux': '1'}1470        r = requests.get(httpbin('get'), headers=headers_ok)1471        assert r.request.headers['foo'] == headers_ok['foo']14721473    def test_header_value_not_str(self, httpbin):1474        """Ensure the header value is of type string or bytes as1475        per discussion in GH issue #33861476        """1477        headers_int = {'foo': 3}1478        headers_dict = {'bar': {'foo': 'bar'}}1479        headers_list = {'baz': ['foo', 'bar']}14801481        # Test for int1482        with pytest.raises(InvalidHeader) as excinfo:1483            r = requests.get(httpbin('get'), headers=headers_int)1484        assert 'foo' in str(excinfo.value)1485        # Test for dict1486        with pytest.raises(InvalidHeader) as excinfo:1487            r = requests.get(httpbin('get'), headers=headers_dict)1488        assert 'bar' in str(excinfo.value)1489        # Test for list1490        with pytest.raises(InvalidHeader) as excinfo:1491            r = requests.get(httpbin('get'), headers=headers_list)1492        assert 'baz' in str(excinfo.value)14931494    def test_header_no_return_chars(self, httpbin):1495        """Ensure that a header containing return character sequences raise an1496        exception. Otherwise, multiple headers are created from single string.1497        """1498        headers_ret = {'foo': 'bar\r\nbaz: qux'}1499        headers_lf = {'foo': 'bar\nbaz: qux'}1500        headers_cr = {'foo': 'bar\rbaz: qux'}15011502        # Test for newline1503        with pytest.raises(InvalidHeader):1504            r = requests.get(httpbin('get'), headers=headers_ret)1505        # Test for line feed1506        with pytest.raises(InvalidHeader):1507            r = requests.get(httpbin('get'), headers=headers_lf)1508        # Test for carriage return1509        with pytest.raises(InvalidHeader):1510            r = requests.get(httpbin('get'), headers=headers_cr)15111512    def test_header_no_leading_space(self, httpbin):1513        """Ensure headers containing leading whitespace raise1514        InvalidHeader Error before sending.1515        """1516        headers_space = {'foo': ' bar'}1517        headers_tab = {'foo': '   bar'}15181519        # Test for whitespace1520        with pytest.raises(InvalidHeader):1521            r = requests.get(httpbin('get'), headers=headers_space)1522        # Test for tab1523        with pytest.raises(InvalidHeader):1524            r = requests.get(httpbin('get'), headers=headers_tab)15251526    @pytest.mark.parametrize('files', ('foo', b'foo', bytearray(b'foo')))1527    def test_can_send_objects_with_files(self, httpbin, files):1528        data = {'a': 'this is a string'}1529        files = {'b': files}1530        r = requests.Request('POST', httpbin('post'), data=data, files=files)1531        p = r.prepare()1532        assert 'multipart/form-data' in p.headers['Content-Type']15331534    def test_can_send_file_object_with_non_string_filename(self, httpbin):1535        f = io.BytesIO()1536        f.name = 21537        r = requests.Request('POST', httpbin('post'), files={'f': f})1538        p = r.prepare()15391540        assert 'multipart/form-data' in p.headers['Content-Type']15411542    def test_autoset_header_values_are_native(self, httpbin):1543        data = 'this is a string'1544        length = '16'1545        req = requests.Request('POST', httpbin('post'), data=data)1546        p = req.prepare()15471548        assert p.headers['Content-Length'] == length15491550    def test_nonhttp_schemes_dont_check_URLs(self):1551        test_urls = (1552            'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',1553            'file:///etc/passwd',1554            'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',1555        )1556        for test_url in test_urls:1557            req = requests.Request('GET', test_url)1558            preq = req.prepare()1559            assert test_url == preq.url15601561    @pytest.mark.xfail(raises=ConnectionError)1562    def test_auth_is_stripped_on_redirect_off_host(self, httpbin):1563        r = requests.get(1564            httpbin('redirect-to'),1565            params={'url': 'http://www.google.co.uk'},1566            auth=('user', 'pass'),1567        )1568        assert r.history[0].request.headers['Authorization']1569        assert not r.request.headers.get('Authorization', '')15701571    def test_auth_is_retained_for_redirect_on_host(self, httpbin):1572        r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))1573        h1 = r.history[0].request.headers['Authorization']1574        h2 = r.request.headers['Authorization']15751576        assert h1 == h215771578    def test_manual_redirect_with_partial_body_read(self, httpbin):1579        s = requests.Session()1580        r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)1581        assert r1.is_redirect1582        rg = s.resolve_redirects(r1, r1.request, stream=True)15831584        # read only the first eight bytes of the response body,1585        # then follow the redirect1586        r1.iter_content(8)1587        r2 = next(rg)1588        assert r2.is_redirect15891590        # read all of the response via iter_content,1591        # then follow the redirect1592        for _ in r2.iter_content():1593            pass1594        r3 = next(rg)1595        assert not r3.is_redirect15961597    def test_prepare_body_position_non_stream(self):1598        data = b'the data'1599        s = requests.Session()1600        prep = requests.Request('GET', 'http://example.com', data=data).prepare()1601        assert prep._body_position is None16021603    def test_rewind_body(self):1604        data = io.BytesIO(b'the data')1605        s = requests.Session()1606        prep = requests.Request('GET', 'http://example.com', data=data).prepare()1607        assert prep._body_position == 01608        assert prep.body.read() == b'the data'16091610        # the data has all been read1611        assert prep.body.read() == b''16121613        # rewind it back1614        requests.utils.rewind_body(prep)1615        assert prep.body.read() == b'the data'16161617    def test_rewind_partially_read_body(self):1618        data = io.BytesIO(b'the data')1619        s = requests.Session()1620        data.read(4)  # read some data1621        prep = requests.Request('GET', 'http://example.com', data=data).prepare()1622        assert prep._body_position == 41623        assert prep.body.read() == b'data'16241625        # the data has all been read1626        assert prep.body.read() == b''16271628        # rewind it back1629        requests.utils.rewind_body(prep)1630        assert prep.body.read() == b'data'16311632    def test_rewind_body_no_seek(self):1633        class BadFileObj:1634            def __init__(self, data):1635                self.data = data16361637            def tell(self):1638                return 016391640            def __iter__(self):1641                return16421643        data = BadFileObj('the data')1644        s = requests.Session()1645        prep = requests.Request('GET', 'http://example.com', data=data).prepare()1646        assert prep._body_position == 016471648        with pytest.raises(UnrewindableBodyError) as e:1649            requests.utils.rewind_body(prep)16501651        assert 'Unable to rewind request body' in str(e)16521653    def test_rewind_body_failed_seek(self):1654        class BadFileObj:1655            def __init__(self, data):1656                self.data = data16571658            def tell(self):1659                return 016601661            def seek(self, pos, whence=0):1662                raise OSError()16631664            def __iter__(self):1665                return16661667        data = BadFileObj('the data')1668        s = requests.Session()1669        prep = requests.Request('GET', 'http://example.com', data=data).prepare()1670        assert prep._body_position == 016711672        with pytest.raises(UnrewindableBodyError) as e:1673            requests.utils.rewind_body(prep)16741675        assert 'error occurred when rewinding request body' in str(e)16761677    def test_rewind_body_failed_tell(self):1678        class BadFileObj:1679            def __init__(self, data):1680                self.data = data16811682            def tell(self):1683                raise OSError()16841685            def __iter__(self):1686                return16871688        data = BadFileObj('the data')1689        s = requests.Session()1690        prep = requests.Request('GET', 'http://example.com', data=data).prepare()1691        assert prep._body_position is not None16921693        with pytest.raises(UnrewindableBodyError) as e:1694            requests.utils.rewind_body(prep)16951696        assert 'Unable to rewind request body' in str(e)16971698    def _patch_adapter_gzipped_redirect(self, session, url):1699        adapter = session.get_adapter(url=url)1700        org_build_response = adapter.build_response1701        self._patched_response = False17021703        def build_response(*args, **kwargs):1704            resp = org_build_response(*args, **kwargs)1705            if not self._patched_response:1706                resp.raw.headers['content-encoding'] = 'gzip'1707                self._patched_response = True1708            return resp17091710        adapter.build_response = build_response17111712    def test_redirect_with_wrong_gzipped_header(self, httpbin):1713        s = requests.Session()1714        url = httpbin('redirect/1')1715        self._patch_adapter_gzipped_redirect(s, url)1716        s.get(url)17171718    @pytest.mark.parametrize(1719        'username, password, auth_str', (1720            ('test', 'test', 'Basic dGVzdDp0ZXN0'),1721            (u'имя'.encode('utf-8'), u'пароль'.encode('utf-8'), 'Basic 0LjQvNGPOtC/0LDRgNC+0LvRjA=='),1722        ))1723    def test_basic_auth_str_is_always_native(self, username, password, auth_str):1724        s = _basic_auth_str(username, password)1725        assert isinstance(s, builtin_str)1726        assert s == auth_str17271728    def test_requests_history_is_saved(self, httpbin):1729        r = requests.get(httpbin('redirect/5'))1730        total = r.history[-1].history1731        i = 01732        for item in r.history:1733            assert item.history == total[0:i]1734            i += 117351736    def test_json_param_post_content_type_works(self, httpbin):1737        r = requests.post(1738            httpbin('post'),1739            json={'life': 42}1740        )1741        assert r.status_code == 2001742        assert 'application/json' in r.request.headers['Content-Type']1743        assert {'life': 42} == r.json()['json']17441745    def test_json_param_post_should_not_override_data_param(self, httpbin):1746        r = requests.Request(method='POST', url=httpbin('post'),1747                             data={'stuff': 'elixr'},1748                             json={'music': 'flute'})1749        prep = r.prepare()1750        assert 'stuff=elixr' == prep.body17511752    def test_response_iter_lines(self, httpbin):1753        r = requests.get(httpbin('stream/4'), stream=True)1754        assert r.status_code == 20017551756        it = r.iter_lines()1757        next(it)1758        assert len(list(it)) == 317591760    def test_response_context_manager(self, httpbin):1761        with requests.get(httpbin('stream/4'), stream=True) as response:1762            assert isinstance(response, requests.Response)17631764        assert response.raw.closed17651766    def test_unconsumed_session_response_closes_connection(self, httpbin):1767        s = requests.session()17681769        with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1770            pass17711772        assert response._content_consumed is False1773        assert response.raw.closed17741775    @pytest.mark.xfail1776    def test_response_iter_lines_reentrant(self, httpbin):1777        """Response.iter_lines() is not reentrant safe"""1778        r = requests.get(httpbin('stream/4'), stream=True)1779        assert r.status_code == 20017801781        next(r.iter_lines())1782        assert len(list(r.iter_lines())) == 317831784    def test_session_close_proxy_clear(self, mocker):1785        proxies = {1786          'one': mocker.Mock(),1787          'two': mocker.Mock(),1788        }1789        session = requests.Session()1790        mocker.patch.dict(session.adapters['http://'].proxy_manager, proxies)1791        session.close()1792        proxies['one'].clear.assert_called_once_with()1793        proxies['two'].clear.assert_called_once_with()17941795    def test_proxy_auth(self, httpbin):1796        adapter = HTTPAdapter()1797        headers = adapter.proxy_headers("http://user:pass@httpbin.org")1798        assert headers == {'Proxy-Authorization': 'Basic dXNlcjpwYXNz'}17991800    def test_proxy_auth_empty_pass(self, httpbin):1801        adapter = HTTPAdapter()1802        headers = adapter.proxy_headers("http://user:@httpbin.org")1803        assert headers == {'Proxy-Authorization': 'Basic dXNlcjo='}18041805    def test_response_json_when_content_is_None(self, httpbin):1806        r = requests.get(httpbin('/status/204'))1807        # Make sure r.content is None1808        r.status_code = 01809        r._content = False1810        r._content_consumed = False18111812        assert r.content is None1813        with pytest.raises(ValueError):1814            r.json()18151816    def test_response_without_release_conn(self):1817        """Test `close` call for non-urllib3-like raw objects.1818        Should work when `release_conn` attr doesn't exist on `response.raw`.1819        """1820        resp = requests.Response()1821        resp.raw = StringIO.StringIO('test')1822        assert not resp.raw.closed1823        resp.close()1824        assert resp.raw.closed18251826    def test_empty_stream_with_auth_does_not_set_content_length_header(self, httpbin):1827        """Ensure that a byte stream with size 0 will not set both a Content-Length1828        and Transfer-Encoding header.1829        """1830        auth = ('user', 'pass')1831        url = httpbin('post')1832        file_obj = io.BytesIO(b'')1833        r = requests.Request('POST', url, auth=auth, data=file_obj)1834        prepared_request = r.prepare()1835        assert 'Transfer-Encoding' in prepared_request.headers1836        assert 'Content-Length' not in prepared_request.headers18371838    def test_stream_with_auth_does_not_set_transfer_encoding_header(self, httpbin):1839        """Ensure that a byte stream with size > 0 will not set both a Content-Length1840        and Transfer-Encoding header.1841        """1842        auth = ('user', 'pass')1843        url = httpbin('post')1844        file_obj = io.BytesIO(b'test data')1845        r = requests.Request('POST', url, auth=auth, data=file_obj)1846        prepared_request = r.prepare()1847        assert 'Transfer-Encoding' not in prepared_request.headers1848        assert 'Content-Length' in prepared_request.headers18491850    def test_chunked_upload_does_not_set_content_length_header(self, httpbin):1851        """Ensure that requests with a generator body stream using1852        Transfer-Encoding: chunked, not a Content-Length header.1853        """1854        data = (i for i in [b'a', b'b', b'c'])1855        url = httpbin('post')1856        r = requests.Request('POST', url, data=data)1857        prepared_request = r.prepare()1858        assert 'Transfer-Encoding' in prepared_request.headers1859        assert 'Content-Length' not in prepared_request.headers18601861    def test_custom_redirect_mixin(self, httpbin):1862        """Tests a custom mixin to overwrite ``get_redirect_target``.18631864        Ensures a subclassed ``requests.Session`` can handle a certain type of1865        malformed redirect responses.18661867        1. original request receives a proper response: 302 redirect1868        2. following the redirect, a malformed response is given:1869            status code = HTTP 2001870            location = alternate url1871        3. the custom session catches the edge case and follows the redirect1872        """1873        url_final = httpbin('html')1874        querystring_malformed = urlencode({'location': url_final})1875        url_redirect_malformed = httpbin('response-headers?%s' % querystring_malformed)1876        querystring_redirect = urlencode({'url': url_redirect_malformed})1877        url_redirect = httpbin('redirect-to?%s' % querystring_redirect)1878        urls_test = [url_redirect,1879                     url_redirect_malformed,1880                     url_final,1881                     ]18821883        class CustomRedirectSession(requests.Session):1884            def get_redirect_target(self, resp):1885                # default behavior1886                if resp.is_redirect:1887                    return resp.headers['location']1888                # edge case - check to see if 'location' is in headers anyways1889                location = resp.headers.get('location')1890                if location and (location != resp.url):1891                    return location1892                return None18931894        session = CustomRedirectSession()1895        r = session.get(urls_test[0])1896        assert len(r.history) == 21897        assert r.status_code == 2001898        assert r.history[0].status_code == 3021899        assert r.history[0].is_redirect1900        assert r.history[1].status_code == 2001901        assert not r.history[1].is_redirect1902        assert r.url == urls_test[2]190319041905class TestCaseInsensitiveDict:19061907    @pytest.mark.parametrize(1908        'cid', (1909            CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}),1910            CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')]),1911            CaseInsensitiveDict(FOO='foo', BAr='bar'),1912        ))1913    def test_init(self, cid):1914        assert len(cid) == 21915        assert 'foo' in cid1916        assert 'bar' in cid19171918    def test_docstring_example(self):1919        cid = CaseInsensitiveDict()1920        cid['Accept'] = 'application/json'1921        assert cid['aCCEPT'] == 'application/json'1922        assert list(cid) == ['Accept']19231924    def test_len(self):1925        cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1926        cid['A'] = 'a'1927        assert len(cid) == 219281929    def test_getitem(self):1930        cid = CaseInsensitiveDict({'Spam': 'blueval'})1931        assert cid['spam'] == 'blueval'1932        assert cid['SPAM'] == 'blueval'19331934    def test_fixes_649(self):1935        """__setitem__ should behave case-insensitively."""1936        cid = CaseInsensitiveDict()1937        cid['spam'] = 'oneval'1938        cid['Spam'] = 'twoval'1939        cid['sPAM'] = 'redval'1940        cid['SPAM'] = 'blueval'1941        assert cid['spam'] == 'blueval'1942        assert cid['SPAM'] == 'blueval'1943        assert list(cid.keys()) == ['SPAM']19441945    def test_delitem(self):1946        cid = CaseInsensitiveDict()1947        cid['Spam'] = 'someval'1948        del cid['sPam']1949        assert 'spam' not in cid1950        assert len(cid) == 019511952    def test_contains(self):1953        cid = CaseInsensitiveDict()1954        cid['Spam'] = 'someval'1955        assert 'Spam' in cid1956        assert 'spam' in cid1957        assert 'SPAM' in cid1958        assert 'sPam' in cid1959        assert 'notspam' not in cid19601961    def test_get(self):1962        cid = CaseInsensitiveDict()1963        cid['spam'] = 'oneval'1964        cid['SPAM'] = 'blueval'1965        assert cid.get('spam') == 'blueval'1966        assert cid.get('SPAM') == 'blueval'1967        assert cid.get('sPam') == 'blueval'1968        assert cid.get('notspam', 'default') == 'default'19691970    def test_update(self):1971        cid = CaseInsensitiveDict()1972        cid['spam'] = 'blueval'1973        cid.update({'sPam': 'notblueval'})1974        assert cid['spam'] == 'notblueval'1975        cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1976        cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1977        assert len(cid) == 21978        assert cid['foo'] == 'anotherfoo'1979        assert cid['bar'] == 'anotherbar'19801981    def test_update_retains_unchanged(self):1982        cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1983        cid.update({'foo': 'newfoo'})1984        assert cid['bar'] == 'bar'19851986    def test_iter(self):1987        cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1988        keys = frozenset(['Spam', 'Eggs'])1989        assert frozenset(iter(cid)) == keys19901991    def test_equality(self):1992        cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1993        othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1994        assert cid == othercid1995        del othercid['spam']1996        assert cid != othercid1997        assert cid == {'spam': 'blueval', 'eggs': 'redval'}1998        assert cid != object()19992000    def test_setdefault(self):

The first 2,000 of 2,467 lines.