Skip to content
Myr

test_requests.py

This file

Path

tests/test_requests.py

2,518 lines · 88.4 KiB · Python

Last changed by

Merge pull request #4851 from requests/default_port_handlingIan Stapleton Cordascobefore adoptioneaab47f

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_hooks32from requests.compat import MutableMapping3334from .compat import StringIO, u35from .utils import override_environ36from urllib3.util import Timeout as Urllib3Timeout3738# Requests to this URL should always fail with a connection timeout (nothing39# listening on that port)40TARPIT = 'http://10.255.255.1'4142try:43    from ssl import SSLContext44    del SSLContext45    HAS_MODERN_SSL = True46except ImportError:47    HAS_MODERN_SSL = False4849try:50    requests.pyopenssl51    HAS_PYOPENSSL = True52except AttributeError:53    HAS_PYOPENSSL = False545556class TestRequests:5758    digest_auth_algo = ('MD5', 'SHA-256', 'SHA-512')5960    def test_entry_points(self):6162        requests.session63        requests.session().get64        requests.session().head65        requests.get66        requests.head67        requests.put68        requests.patch69        requests.post70        # Not really an entry point, but people rely on it.71        from requests.packages.urllib3.poolmanager import PoolManager7273    @pytest.mark.parametrize(74        'exception, url', (75            (MissingSchema, 'hiwpefhipowhefopw'),76            (InvalidSchema, 'localhost:3128'),77            (InvalidSchema, 'localhost.localdomain:3128/'),78            (InvalidSchema, '10.122.1.1:3128/'),79            (InvalidURL, 'http://'),80        ))81    def test_invalid_url(self, exception, url):82        with pytest.raises(exception):83            requests.get(url)8485    def test_basic_building(self):86        req = requests.Request()87        req.url = 'http://kennethreitz.org/'88        req.data = {'life': '42'}8990        pr = req.prepare()91        assert pr.url == req.url92        assert pr.body == 'life=42'9394    @pytest.mark.parametrize('method', ('GET', 'HEAD'))95    def test_no_content_length(self, httpbin, method):96        req = requests.Request(method, httpbin(method.lower())).prepare()97        assert 'Content-Length' not in req.headers9899    @pytest.mark.parametrize('method', ('POST', 'PUT', 'PATCH', 'OPTIONS'))100    def test_no_body_content_length(self, httpbin, method):101        req = requests.Request(method, httpbin(method.lower())).prepare()102        assert req.headers['Content-Length'] == '0'103104    @pytest.mark.parametrize('method', ('POST', 'PUT', 'PATCH', 'OPTIONS'))105    def test_empty_content_length(self, httpbin, method):106        req = requests.Request(method, httpbin(method.lower()), data='').prepare()107        assert req.headers['Content-Length'] == '0'108109    def test_override_content_length(self, httpbin):110        headers = {111            'Content-Length': 'not zero'112        }113        r = requests.Request('POST', httpbin('post'), headers=headers).prepare()114        assert 'Content-Length' in r.headers115        assert r.headers['Content-Length'] == 'not zero'116117    def test_path_is_not_double_encoded(self):118        request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()119120        assert request.path_url == '/get/test%20case'121122    @pytest.mark.parametrize(123        'url, expected', (124            ('http://example.com/path#fragment', 'http://example.com/path?a=b#fragment'),125            ('http://example.com/path?key=value#fragment', 'http://example.com/path?key=value&a=b#fragment')126        ))127    def test_params_are_added_before_fragment(self, url, expected):128        request = requests.Request('GET', url, params={"a": "b"}).prepare()129        assert request.url == expected130131    def test_params_original_order_is_preserved_by_default(self):132        param_ordered_dict = OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))133        session = requests.Session()134        request = requests.Request('GET', 'http://example.com/', params=param_ordered_dict)135        prep = session.prepare_request(request)136        assert prep.url == 'http://example.com/?z=1&a=1&k=1&d=1'137138    def test_params_bytes_are_encoded(self):139        request = requests.Request('GET', 'http://example.com',140                                   params=b'test=foo').prepare()141        assert request.url == 'http://example.com/?test=foo'142143    def test_binary_put(self):144        request = requests.Request('PUT', 'http://example.com',145                                   data=u"ööö".encode("utf-8")).prepare()146        assert isinstance(request.body, bytes)147148    def test_whitespaces_are_removed_from_url(self):149        # Test for issue #3696150        request = requests.Request('GET', ' http://example.com').prepare()151        assert request.url == 'http://example.com/'152153    @pytest.mark.parametrize('scheme', ('http://', 'HTTP://', 'hTTp://', 'HttP://'))154    def test_mixed_case_scheme_acceptable(self, httpbin, scheme):155        s = requests.Session()156        s.proxies = getproxies()157        parts = urlparse(httpbin('get'))158        url = scheme + parts.netloc + parts.path159        r = requests.Request('GET', url)160        r = s.send(r.prepare())161        assert r.status_code == 200, 'failed for scheme {}'.format(scheme)162163    def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):164        r = requests.Request('GET', httpbin('get'))165        s = requests.Session()166        s.proxies = getproxies()167168        r = s.send(r.prepare())169170        assert r.status_code == 200171172    def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):173        r = requests.get(httpbin('redirect', '1'))174        assert r.status_code == 200175        assert r.history[0].status_code == 302176        assert r.history[0].is_redirect177178    def test_HTTP_307_ALLOW_REDIRECT_POST(self, httpbin):179        r = requests.post(httpbin('redirect-to'), data='test', params={'url': 'post', 'status_code': 307})180        assert r.status_code == 200181        assert r.history[0].status_code == 307182        assert r.history[0].is_redirect183        assert r.json()['data'] == 'test'184185    def test_HTTP_307_ALLOW_REDIRECT_POST_WITH_SEEKABLE(self, httpbin):186        byte_str = b'test'187        r = requests.post(httpbin('redirect-to'), data=io.BytesIO(byte_str), params={'url': 'post', 'status_code': 307})188        assert r.status_code == 200189        assert r.history[0].status_code == 307190        assert r.history[0].is_redirect191        assert r.json()['data'] == byte_str.decode('utf-8')192193    def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):194        try:195            requests.get(httpbin('relative-redirect', '50'))196        except TooManyRedirects as e:197            url = httpbin('relative-redirect', '20')198            assert e.request.url == url199            assert e.response.url == url200            assert len(e.response.history) == 30201        else:202            pytest.fail('Expected redirect to raise TooManyRedirects but it did not')203204    def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):205        s = requests.session()206        s.max_redirects = 5207        try:208            s.get(httpbin('relative-redirect', '50'))209        except TooManyRedirects as e:210            url = httpbin('relative-redirect', '45')211            assert e.request.url == url212            assert e.response.url == url213            assert len(e.response.history) == 5214        else:215            pytest.fail('Expected custom max number of redirects to be respected but was not')216217    def test_http_301_changes_post_to_get(self, httpbin):218        r = requests.post(httpbin('status', '301'))219        assert r.status_code == 200220        assert r.request.method == 'GET'221        assert r.history[0].status_code == 301222        assert r.history[0].is_redirect223224    def test_http_301_doesnt_change_head_to_get(self, httpbin):225        r = requests.head(httpbin('status', '301'), allow_redirects=True)226        print(r.content)227        assert r.status_code == 200228        assert r.request.method == 'HEAD'229        assert r.history[0].status_code == 301230        assert r.history[0].is_redirect231232    def test_http_302_changes_post_to_get(self, httpbin):233        r = requests.post(httpbin('status', '302'))234        assert r.status_code == 200235        assert r.request.method == 'GET'236        assert r.history[0].status_code == 302237        assert r.history[0].is_redirect238239    def test_http_302_doesnt_change_head_to_get(self, httpbin):240        r = requests.head(httpbin('status', '302'), allow_redirects=True)241        assert r.status_code == 200242        assert r.request.method == 'HEAD'243        assert r.history[0].status_code == 302244        assert r.history[0].is_redirect245246    def test_http_303_changes_post_to_get(self, httpbin):247        r = requests.post(httpbin('status', '303'))248        assert r.status_code == 200249        assert r.request.method == 'GET'250        assert r.history[0].status_code == 303251        assert r.history[0].is_redirect252253    def test_http_303_doesnt_change_head_to_get(self, httpbin):254        r = requests.head(httpbin('status', '303'), allow_redirects=True)255        assert r.status_code == 200256        assert r.request.method == 'HEAD'257        assert r.history[0].status_code == 303258        assert r.history[0].is_redirect259260    def test_header_and_body_removal_on_redirect(self, httpbin):261        purged_headers = ('Content-Length', 'Content-Type')262        ses = requests.Session()263        req = requests.Request('POST', httpbin('post'), data={'test': 'data'})264        prep = ses.prepare_request(req)265        resp = ses.send(prep)266267        # Mimic a redirect response268        resp.status_code = 302269        resp.headers['location'] = 'get'270271        # Run request through resolve_redirects272        next_resp = next(ses.resolve_redirects(resp, prep))273        assert next_resp.request.body is None274        for header in purged_headers:275            assert header not in next_resp.request.headers276277    def test_transfer_enc_removal_on_redirect(self, httpbin):278        purged_headers = ('Transfer-Encoding', 'Content-Type')279        ses = requests.Session()280        req = requests.Request('POST', httpbin('post'), data=(b'x' for x in range(1)))281        prep = ses.prepare_request(req)282        assert 'Transfer-Encoding' in prep.headers283284        # Create Response to avoid https://github.com/kevin1024/pytest-httpbin/issues/33285        resp = requests.Response()286        resp.raw = io.BytesIO(b'the content')287        resp.request = prep288        setattr(resp.raw, 'release_conn', lambda *args: args)289290        # Mimic a redirect response291        resp.status_code = 302292        resp.headers['location'] = httpbin('get')293294        # Run request through resolve_redirect295        next_resp = next(ses.resolve_redirects(resp, prep))296        assert next_resp.request.body is None297        for header in purged_headers:298            assert header not in next_resp.request.headers299300    def test_fragment_maintained_on_redirect(self, httpbin):301        fragment = "#view=edit&token=hunter2"302        r = requests.get(httpbin('redirect-to?url=get')+fragment)303304        assert len(r.history) > 0305        assert r.history[0].request.url == httpbin('redirect-to?url=get')+fragment306        assert r.url == httpbin('get')+fragment307308    def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):309        heads = {'User-agent': 'Mozilla/5.0'}310311        r = requests.get(httpbin('user-agent'), headers=heads)312313        assert heads['User-agent'] in r.text314        assert r.status_code == 200315316    def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):317        heads = {'User-agent': 'Mozilla/5.0'}318319        r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)320        assert r.status_code == 200321322    def test_set_cookie_on_301(self, httpbin):323        s = requests.session()324        url = httpbin('cookies/set?foo=bar')325        s.get(url)326        assert s.cookies['foo'] == 'bar'327328    def test_cookie_sent_on_redirect(self, httpbin):329        s = requests.session()330        s.get(httpbin('cookies/set?foo=bar'))331        r = s.get(httpbin('redirect/1'))  # redirects to httpbin('get')332        assert 'Cookie' in r.json()['headers']333334    def test_cookie_removed_on_expire(self, httpbin):335        s = requests.session()336        s.get(httpbin('cookies/set?foo=bar'))337        assert s.cookies['foo'] == 'bar'338        s.get(339            httpbin('response-headers'),340            params={341                'Set-Cookie':342                    'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'343            }344        )345        assert 'foo' not in s.cookies346347    def test_cookie_quote_wrapped(self, httpbin):348        s = requests.session()349        s.get(httpbin('cookies/set?foo="bar:baz"'))350        assert s.cookies['foo'] == '"bar:baz"'351352    def test_cookie_persists_via_api(self, httpbin):353        s = requests.session()354        r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})355        assert 'foo' in r.request.headers['Cookie']356        assert 'foo' in r.history[0].request.headers['Cookie']357358    def test_request_cookie_overrides_session_cookie(self, httpbin):359        s = requests.session()360        s.cookies['foo'] = 'bar'361        r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})362        assert r.json()['cookies']['foo'] == 'baz'363        # Session cookie should not be modified364        assert s.cookies['foo'] == 'bar'365366    def test_request_cookies_not_persisted(self, httpbin):367        s = requests.session()368        s.get(httpbin('cookies'), cookies={'foo': 'baz'})369        # Sending a request with cookies should not add cookies to the session370        assert not s.cookies371372    def test_generic_cookiejar_works(self, httpbin):373        cj = cookielib.CookieJar()374        cookiejar_from_dict({'foo': 'bar'}, cj)375        s = requests.session()376        s.cookies = cj377        r = s.get(httpbin('cookies'))378        # Make sure the cookie was sent379        assert r.json()['cookies']['foo'] == 'bar'380        # Make sure the session cj is still the custom one381        assert s.cookies is cj382383    def test_param_cookiejar_works(self, httpbin):384        cj = cookielib.CookieJar()385        cookiejar_from_dict({'foo': 'bar'}, cj)386        s = requests.session()387        r = s.get(httpbin('cookies'), cookies=cj)388        # Make sure the cookie was sent389        assert r.json()['cookies']['foo'] == 'bar'390391    def test_cookielib_cookiejar_on_redirect(self, httpbin):392        """Tests resolve_redirect doesn't fail when merging cookies393        with non-RequestsCookieJar cookiejar.394395        See GH #3579396        """397        cj = cookiejar_from_dict({'foo': 'bar'}, cookielib.CookieJar())398        s = requests.Session()399        s.cookies = cookiejar_from_dict({'cookie': 'tasty'})400401        # Prepare request without using Session402        req = requests.Request('GET', httpbin('headers'), cookies=cj)403        prep_req = req.prepare()404405        # Send request and simulate redirect406        resp = s.send(prep_req)407        resp.status_code = 302408        resp.headers['location'] = httpbin('get')409        redirects = s.resolve_redirects(resp, prep_req)410        resp = next(redirects)411412        # Verify CookieJar isn't being converted to RequestsCookieJar413        assert isinstance(prep_req._cookies, cookielib.CookieJar)414        assert isinstance(resp.request._cookies, cookielib.CookieJar)415        assert not isinstance(resp.request._cookies, requests.cookies.RequestsCookieJar)416417        cookies = {}418        for c in resp.request._cookies:419            cookies[c.name] = c.value420        assert cookies['foo'] == 'bar'421        assert cookies['cookie'] == 'tasty'422423    def test_requests_in_history_are_not_overridden(self, httpbin):424        resp = requests.get(httpbin('redirect/3'))425        urls = [r.url for r in resp.history]426        req_urls = [r.request.url for r in resp.history]427        assert urls == req_urls428429    def test_history_is_always_a_list(self, httpbin):430        """Show that even with redirects, Response.history is always a list."""431        resp = requests.get(httpbin('get'))432        assert isinstance(resp.history, list)433        resp = requests.get(httpbin('redirect/1'))434        assert isinstance(resp.history, list)435        assert not isinstance(resp.history, tuple)436437    def test_headers_on_session_with_None_are_not_sent(self, httpbin):438        """Do not send headers in Session.headers with None values."""439        ses = requests.Session()440        ses.headers['Accept-Encoding'] = None441        req = requests.Request('GET', httpbin('get'))442        prep = ses.prepare_request(req)443        assert 'Accept-Encoding' not in prep.headers444445    def test_headers_preserve_order(self, httpbin):446        """Preserve order when headers provided as OrderedDict."""447        ses = requests.Session()448        ses.headers = OrderedDict()449        ses.headers['Accept-Encoding'] = 'identity'450        ses.headers['First'] = '1'451        ses.headers['Second'] = '2'452        headers = OrderedDict([('Third', '3'), ('Fourth', '4')])453        headers['Fifth'] = '5'454        headers['Second'] = '222'455        req = requests.Request('GET', httpbin('get'), headers=headers)456        prep = ses.prepare_request(req)457        items = list(prep.headers.items())458        assert items[0] == ('Accept-Encoding', 'identity')459        assert items[1] == ('First', '1')460        assert items[2] == ('Second', '222')461        assert items[3] == ('Third', '3')462        assert items[4] == ('Fourth', '4')463        assert items[5] == ('Fifth', '5')464465    @pytest.mark.parametrize('key', ('User-agent', 'user-agent'))466    def test_user_agent_transfers(self, httpbin, key):467468        heads = {key: 'Mozilla/5.0 (github.com/requests/requests)'}469470        r = requests.get(httpbin('user-agent'), headers=heads)471        assert heads[key] in r.text472473    def test_HTTP_200_OK_HEAD(self, httpbin):474        r = requests.head(httpbin('get'))475        assert r.status_code == 200476477    def test_HTTP_200_OK_PUT(self, httpbin):478        r = requests.put(httpbin('put'))479        assert r.status_code == 200480481    def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):482        auth = ('user', 'pass')483        url = httpbin('basic-auth', 'user', 'pass')484485        r = requests.get(url, auth=auth)486        assert r.status_code == 200487488        r = requests.get(url)489        assert r.status_code == 401490491        s = requests.session()492        s.auth = auth493        r = s.get(url)494        assert r.status_code == 200495496    @pytest.mark.parametrize(497        'username, password', (498            ('user', 'pass'),499            (u'имя'.encode('utf-8'), u'пароль'.encode('utf-8')),500            (42, 42),501            (None, None),502        ))503    def test_set_basicauth(self, httpbin, username, password):504        auth = (username, password)505        url = httpbin('get')506507        r = requests.Request('GET', url, auth=auth)508        p = r.prepare()509510        assert p.headers['Authorization'] == _basic_auth_str(username, password)511512    def test_basicauth_encodes_byte_strings(self):513        """Ensure b'test' formats as the byte string "test" rather514        than the unicode string "b'test'" in Python 3.515        """516        auth = (b'\xc5\xafsername', b'test\xc6\xb6')517        r = requests.Request('GET', 'http://localhost', auth=auth)518        p = r.prepare()519520        assert p.headers['Authorization'] == 'Basic xa9zZXJuYW1lOnRlc3TGtg=='521522    @pytest.mark.parametrize(523        'url, exception', (524            # Connecting to an unknown domain should raise a ConnectionError525            ('http://doesnotexist.google.com', ConnectionError),526            # Connecting to an invalid port should raise a ConnectionError527            ('http://localhost:1', ConnectionError),528            # Inputing a URL that cannot be parsed should raise an InvalidURL error529            ('http://fe80::5054:ff:fe5a:fc0', InvalidURL)530        ))531    def test_errors(self, url, exception):532        with pytest.raises(exception):533            requests.get(url, timeout=1)534535    def test_proxy_error(self):536        # any proxy related error (address resolution, no route to host, etc) should result in a ProxyError537        with pytest.raises(ProxyError):538            requests.get('http://localhost:1', proxies={'http': 'non-resolvable-address'})539540    def test_proxy_error_on_bad_url(self, httpbin, httpbin_secure):541        with pytest.raises(InvalidProxyURL):542            requests.get(httpbin_secure(), proxies={'https': 'http:/badproxyurl:3128'})543544        with pytest.raises(InvalidProxyURL):545            requests.get(httpbin(), proxies={'http': 'http://:8080'})546547        with pytest.raises(InvalidProxyURL):548            requests.get(httpbin_secure(), proxies={'https': 'https://'})549550        with pytest.raises(InvalidProxyURL):551            requests.get(httpbin(), proxies={'http': 'http:///example.com:8080'})552553    def test_basicauth_with_netrc(self, httpbin):554        auth = ('user', 'pass')555        wrong_auth = ('wronguser', 'wrongpass')556        url = httpbin('basic-auth', 'user', 'pass')557558        old_auth = requests.sessions.get_netrc_auth559560        try:561            def get_netrc_auth_mock(url):562                return auth563            requests.sessions.get_netrc_auth = get_netrc_auth_mock564565            # Should use netrc and work.566            r = requests.get(url)567            assert r.status_code == 200568569            # Given auth should override and fail.570            r = requests.get(url, auth=wrong_auth)571            assert r.status_code == 401572573            s = requests.session()574575            # Should use netrc and work.576            r = s.get(url)577            assert r.status_code == 200578579            # Given auth should override and fail.580            s.auth = wrong_auth581            r = s.get(url)582            assert r.status_code == 401583        finally:584            requests.sessions.get_netrc_auth = old_auth585586    def test_DIGEST_HTTP_200_OK_GET(self, httpbin):587588        for authtype in self.digest_auth_algo:589            auth = HTTPDigestAuth('user', 'pass')590            url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype, 'never')591592            r = requests.get(url, auth=auth)593            assert r.status_code == 200594595            r = requests.get(url)596            assert r.status_code == 401597            print(r.headers['WWW-Authenticate'])598599            s = requests.session()600            s.auth = HTTPDigestAuth('user', 'pass')601            r = s.get(url)602            assert r.status_code == 200603604    def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):605606        for authtype in self.digest_auth_algo:607            url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype)608            auth = HTTPDigestAuth('user', 'pass')609            r = requests.get(url)610            assert r.cookies['fake'] == 'fake_value'611612            r = requests.get(url, auth=auth)613            assert r.status_code == 200614615    def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):616617        for authtype in self.digest_auth_algo:618            url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype)619            auth = HTTPDigestAuth('user', 'pass')620            s = requests.Session()621            s.get(url, auth=auth)622            assert s.cookies['fake'] == 'fake_value'623624    def test_DIGEST_STREAM(self, httpbin):625626        for authtype in self.digest_auth_algo:627            auth = HTTPDigestAuth('user', 'pass')628            url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype)629630            r = requests.get(url, auth=auth, stream=True)631            assert r.raw.read() != b''632633            r = requests.get(url, auth=auth, stream=False)634            assert r.raw.read() == b''635636    def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):637638        for authtype in self.digest_auth_algo:639            auth = HTTPDigestAuth('user', 'wrongpass')640            url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype)641642            r = requests.get(url, auth=auth)643            assert r.status_code == 401644645            r = requests.get(url)646            assert r.status_code == 401647648            s = requests.session()649            s.auth = auth650            r = s.get(url)651            assert r.status_code == 401652653    def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):654655        for authtype in self.digest_auth_algo:656            auth = HTTPDigestAuth('user', 'pass')657            url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype)658659            r = requests.get(url, auth=auth)660            assert '"auth"' in r.request.headers['Authorization']661662    def test_POSTBIN_GET_POST_FILES(self, httpbin):663664        url = httpbin('post')665        requests.post(url).raise_for_status()666667        post1 = requests.post(url, data={'some': 'data'})668        assert post1.status_code == 200669670        with open('Pipfile') as f:671            post2 = requests.post(url, files={'some': f})672        assert post2.status_code == 200673674        post4 = requests.post(url, data='[{"some": "json"}]')675        assert post4.status_code == 200676677        with pytest.raises(ValueError):678            requests.post(url, files=['bad file data'])679680    def test_invalid_files_input(self, httpbin):681682        url = httpbin('post')683        post = requests.post(url,684                             files={"random-file-1": None, "random-file-2": 1})685        assert b'name="random-file-1"' not in post.request.body686        assert b'name="random-file-2"' in post.request.body687688    def test_POSTBIN_SEEKED_OBJECT_WITH_NO_ITER(self, httpbin):689690        class TestStream(object):691            def __init__(self, data):692                self.data = data.encode()693                self.length = len(self.data)694                self.index = 0695696            def __len__(self):697                return self.length698699            def read(self, size=None):700                if size:701                    ret = self.data[self.index:self.index + size]702                    self.index += size703                else:704                    ret = self.data[self.index:]705                    self.index = self.length706                return ret707708            def tell(self):709                return self.index710711            def seek(self, offset, where=0):712                if where == 0:713                    self.index = offset714                elif where == 1:715                    self.index += offset716                elif where == 2:717                    self.index = self.length + offset718719        test = TestStream('test')720        post1 = requests.post(httpbin('post'), data=test)721        assert post1.status_code == 200722        assert post1.json()['data'] == 'test'723724        test = TestStream('test')725        test.seek(2)726        post2 = requests.post(httpbin('post'), data=test)727        assert post2.status_code == 200728        assert post2.json()['data'] == 'st'729730    def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):731732        url = httpbin('post')733        requests.post(url).raise_for_status()734735        post1 = requests.post(url, data={'some': 'data'})736        assert post1.status_code == 200737738        with open('Pipfile') as f:739            post2 = requests.post(url, data={'some': 'data'}, files={'some': f})740        assert post2.status_code == 200741742        post4 = requests.post(url, data='[{"some": "json"}]')743        assert post4.status_code == 200744745        with pytest.raises(ValueError):746            requests.post(url, files=['bad file data'])747748    def test_post_with_custom_mapping(self, httpbin):749        class CustomMapping(MutableMapping):750            def __init__(self, *args, **kwargs):751                self.data = dict(*args, **kwargs)752753            def __delitem__(self, key):754                del self.data[key]755756            def __getitem__(self, key):757                return self.data[key]758759            def __setitem__(self, key, value):760                self.data[key] = value761762            def __iter__(self):763                return iter(self.data)764765            def __len__(self):766                return len(self.data)767768        data = CustomMapping({'some': 'data'})769        url = httpbin('post')770        found_json = requests.post(url, data=data).json().get('form')771        assert found_json == {'some': 'data'}772773    def test_conflicting_post_params(self, httpbin):774        url = httpbin('post')775        with open('Pipfile') as f:776            pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")777            pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")778779    def test_request_ok_set(self, httpbin):780        r = requests.get(httpbin('status', '404'))781        assert not r.ok782783    def test_status_raising(self, httpbin):784        r = requests.get(httpbin('status', '404'))785        with pytest.raises(requests.exceptions.HTTPError):786            r.raise_for_status()787788        r = requests.get(httpbin('status', '500'))789        assert not r.ok790791    def test_decompress_gzip(self, httpbin):792        r = requests.get(httpbin('gzip'))793        r.content.decode('ascii')794795    @pytest.mark.parametrize(796        'url, params', (797            ('/get', {'foo': 'føø'}),798            ('/get', {'føø': 'føø'}),799            ('/get', {'føø': 'føø'}),800            ('/get', {'foo': 'foo'}),801            ('ø', {'foo': 'foo'}),802        ))803    def test_unicode_get(self, httpbin, url, params):804        requests.get(httpbin(url), params=params)805806    def test_unicode_header_name(self, httpbin):807        requests.put(808            httpbin('put'),809            headers={str('Content-Type'): 'application/octet-stream'},810            data='\xff')  # compat.str is unicode.811812    def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):813        requests.get(httpbin_secure('status', '301'), verify=httpbin_ca_bundle)814815    def test_invalid_ca_certificate_path(self, httpbin_secure):816        INVALID_PATH = '/garbage'817        with pytest.raises(IOError) as e:818            requests.get(httpbin_secure(), verify=INVALID_PATH)819        assert str(e.value) == 'Could not find a suitable TLS CA certificate bundle, invalid path: {}'.format(INVALID_PATH)820821    def test_invalid_ssl_certificate_files(self, httpbin_secure):822        INVALID_PATH = '/garbage'823        with pytest.raises(IOError) as e:824            requests.get(httpbin_secure(), cert=INVALID_PATH)825        assert str(e.value) == 'Could not find the TLS certificate file, invalid path: {}'.format(INVALID_PATH)826827        with pytest.raises(IOError) as e:828            requests.get(httpbin_secure(), cert=('.', INVALID_PATH))829        assert str(e.value) == 'Could not find the TLS key file, invalid path: {}'.format(INVALID_PATH)830831    def test_http_with_certificate(self, httpbin):832        r = requests.get(httpbin(), cert='.')833        assert r.status_code == 200834835    def test_https_warnings(self, httpbin_secure, httpbin_ca_bundle):836        """warnings are emitted with requests.get"""837        if HAS_MODERN_SSL or HAS_PYOPENSSL:838            warnings_expected = ('SubjectAltNameWarning', )839        else:840            warnings_expected = ('SNIMissingWarning',841                                 'InsecurePlatformWarning',842                                 'SubjectAltNameWarning', )843844        with pytest.warns(None) as warning_records:845            warnings.simplefilter('always')846            requests.get(httpbin_secure('status', '200'),847                         verify=httpbin_ca_bundle)848849        warning_records = [item for item in warning_records850                           if item.category.__name__ != 'ResourceWarning']851852        warnings_category = tuple(853            item.category.__name__ for item in warning_records)854        assert warnings_category == warnings_expected855856    def test_certificate_failure(self, httpbin_secure):857        """858        When underlying SSL problems occur, an SSLError is raised.859        """860        with pytest.raises(SSLError):861            # Our local httpbin does not have a trusted CA, so this call will862            # fail if we use our default trust bundle.863            requests.get(httpbin_secure('status', '200'))864865    def test_urlencoded_get_query_multivalued_param(self, httpbin):866867        r = requests.get(httpbin('get'), params={'test': ['foo', 'baz']})868        assert r.status_code == 200869        assert r.url == httpbin('get?test=foo&test=baz')870871    def test_form_encoded_post_query_multivalued_element(self, httpbin):872        r = requests.Request(method='POST', url=httpbin('post'),873                             data=dict(test=['foo', 'baz']))874        prep = r.prepare()875        assert prep.body == 'test=foo&test=baz'876877    def test_different_encodings_dont_break_post(self, httpbin):878        r = requests.post(httpbin('post'),879            data={'stuff': json.dumps({'a': 123})},880            params={'blah': 'asdf1234'},881            files={'file': ('test_requests.py', open(__file__, 'rb'))})882        assert r.status_code == 200883884    @pytest.mark.parametrize(885        'data', (886            {'stuff': u('ëlïxr')},887            {'stuff': u('ëlïxr').encode('utf-8')},888            {'stuff': 'elixr'},889            {'stuff': 'elixr'.encode('utf-8')},890        ))891    def test_unicode_multipart_post(self, httpbin, data):892        r = requests.post(httpbin('post'),893            data=data,894            files={'file': ('test_requests.py', open(__file__, 'rb'))})895        assert r.status_code == 200896897    def test_unicode_multipart_post_fieldnames(self, httpbin):898        filename = os.path.splitext(__file__)[0] + '.py'899        r = requests.Request(900            method='POST', url=httpbin('post'),901            data={'stuff'.encode('utf-8'): 'elixr'},902            files={'file': ('test_requests.py', open(filename, 'rb'))})903        prep = r.prepare()904        assert b'name="stuff"' in prep.body905        assert b'name="b\'stuff\'"' not in prep.body906907    def test_unicode_method_name(self, httpbin):908        files = {'file': open(__file__, 'rb')}909        r = requests.request(910            method=u('POST'), url=httpbin('post'), files=files)911        assert r.status_code == 200912913    def test_unicode_method_name_with_request_object(self, httpbin):914        files = {'file': open(__file__, 'rb')}915        s = requests.Session()916        req = requests.Request(u('POST'), httpbin('post'), files=files)917        prep = s.prepare_request(req)918        assert isinstance(prep.method, builtin_str)919        assert prep.method == 'POST'920921        resp = s.send(prep)922        assert resp.status_code == 200923924    def test_non_prepared_request_error(self):925        s = requests.Session()926        req = requests.Request(u('POST'), '/')927928        with pytest.raises(ValueError) as e:929            s.send(req)930        assert str(e.value) == 'You can only send PreparedRequests.'931932    def test_custom_content_type(self, httpbin):933        r = requests.post(934            httpbin('post'),935            data={'stuff': json.dumps({'a': 123})},936            files={937                'file1': ('test_requests.py', open(__file__, 'rb')),938                'file2': ('test_requests', open(__file__, 'rb'),939                    'text/py-content-type')})940        assert r.status_code == 200941        assert b"text/py-content-type" in r.request.body942943    def test_hook_receives_request_arguments(self, httpbin):944        def hook(resp, **kwargs):945            assert resp is not None946            assert kwargs != {}947948        s = requests.Session()949        r = requests.Request('GET', httpbin(), hooks={'response': hook})950        prep = s.prepare_request(r)951        s.send(prep)952953    def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):954        hook = lambda x, *args, **kwargs: x955        s = requests.Session()956        s.hooks['response'].append(hook)957        r = requests.Request('GET', httpbin())958        prep = s.prepare_request(r)959        assert prep.hooks['response'] != []960        assert prep.hooks['response'] == [hook]961962    def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):963        hook1 = lambda x, *args, **kwargs: x964        hook2 = lambda x, *args, **kwargs: x965        assert hook1 is not hook2966        s = requests.Session()967        s.hooks['response'].append(hook2)968        r = requests.Request('GET', httpbin(), hooks={'response': [hook1]})969        prep = s.prepare_request(r)970        assert prep.hooks['response'] == [hook1]971972    def test_prepared_request_hook(self, httpbin):973        def hook(resp, **kwargs):974            resp.hook_working = True975            return resp976977        req = requests.Request('GET', httpbin(), hooks={'response': hook})978        prep = req.prepare()979980        s = requests.Session()981        s.proxies = getproxies()982        resp = s.send(prep)983984        assert hasattr(resp, 'hook_working')985986    def test_prepared_from_session(self, httpbin):987        class DummyAuth(requests.auth.AuthBase):988            def __call__(self, r):989                r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'990                return r991992        req = requests.Request('GET', httpbin('headers'))993        assert not req.auth994995        s = requests.Session()996        s.auth = DummyAuth()997998        prep = s.prepare_request(req)999        resp = s.send(prep)10001001        assert resp.json()['headers'][1002            'Dummy-Auth-Test'] == 'dummy-auth-test-ok'10031004    def test_prepare_request_with_bytestring_url(self):1005        req = requests.Request('GET', b'https://httpbin.org/')1006        s = requests.Session()1007        prep = s.prepare_request(req)1008        assert prep.url == "https://httpbin.org/"10091010    def test_request_with_bytestring_host(self, httpbin):1011        s = requests.Session()1012        resp = s.request(1013            'GET',1014            httpbin('cookies/set?cookie=value'),1015            allow_redirects=False,1016            headers={'Host': b'httpbin.org'}1017        )1018        assert resp.cookies.get('cookie') == 'value'10191020    def test_links(self):1021        r = requests.Response()1022        r.headers = {1023            'cache-control': 'public, max-age=60, s-maxage=60',1024            'connection': 'keep-alive',1025            'content-encoding': 'gzip',1026            'content-type': 'application/json; charset=utf-8',1027            'date': 'Sat, 26 Jan 2013 16:47:56 GMT',1028            'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',1029            'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',1030            'link': ('<https://api.github.com/users/kennethreitz/repos?'1031                     'page=2&per_page=10>; rel="next", <https://api.github.'1032                     'com/users/kennethreitz/repos?page=7&per_page=10>; '1033                     ' rel="last"'),1034            'server': 'GitHub.com',1035            'status': '200 OK',1036            'vary': 'Accept',1037            'x-content-type-options': 'nosniff',1038            'x-github-media-type': 'github.beta',1039            'x-ratelimit-limit': '60',1040            'x-ratelimit-remaining': '57'1041        }1042        assert r.links['next']['rel'] == 'next'10431044    def test_cookie_parameters(self):1045        key = 'some_cookie'1046        value = 'some_value'1047        secure = True1048        domain = 'test.com'1049        rest = {'HttpOnly': True}10501051        jar = requests.cookies.RequestsCookieJar()1052        jar.set(key, value, secure=secure, domain=domain, rest=rest)10531054        assert len(jar) == 11055        assert 'some_cookie' in jar10561057        cookie = list(jar)[0]1058        assert cookie.secure == secure1059        assert cookie.domain == domain1060        assert cookie._rest['HttpOnly'] == rest['HttpOnly']10611062    def test_cookie_as_dict_keeps_len(self):1063        key = 'some_cookie'1064        value = 'some_value'10651066        key1 = 'some_cookie1'1067        value1 = 'some_value1'10681069        jar = requests.cookies.RequestsCookieJar()1070        jar.set(key, value)1071        jar.set(key1, value1)10721073        d1 = dict(jar)1074        d2 = dict(jar.iteritems())1075        d3 = dict(jar.items())10761077        assert len(jar) == 21078        assert len(d1) == 21079        assert len(d2) == 21080        assert len(d3) == 210811082    def test_cookie_as_dict_keeps_items(self):1083        key = 'some_cookie'1084        value = 'some_value'10851086        key1 = 'some_cookie1'1087        value1 = 'some_value1'10881089        jar = requests.cookies.RequestsCookieJar()1090        jar.set(key, value)1091        jar.set(key1, value1)10921093        d1 = dict(jar)1094        d2 = dict(jar.iteritems())1095        d3 = dict(jar.items())10961097        assert d1['some_cookie'] == 'some_value'1098        assert d2['some_cookie'] == 'some_value'1099        assert d3['some_cookie1'] == 'some_value1'11001101    def test_cookie_as_dict_keys(self):1102        key = 'some_cookie'1103        value = 'some_value'11041105        key1 = 'some_cookie1'1106        value1 = 'some_value1'11071108        jar = requests.cookies.RequestsCookieJar()1109        jar.set(key, value)1110        jar.set(key1, value1)11111112        keys = jar.keys()1113        assert keys == list(keys)1114        # make sure one can use keys multiple times1115        assert list(keys) == list(keys)11161117    def test_cookie_as_dict_values(self):1118        key = 'some_cookie'1119        value = 'some_value'11201121        key1 = 'some_cookie1'1122        value1 = 'some_value1'11231124        jar = requests.cookies.RequestsCookieJar()1125        jar.set(key, value)1126        jar.set(key1, value1)11271128        values = jar.values()1129        assert values == list(values)1130        # make sure one can use values multiple times1131        assert list(values) == list(values)11321133    def test_cookie_as_dict_items(self):1134        key = 'some_cookie'1135        value = 'some_value'11361137        key1 = 'some_cookie1'1138        value1 = 'some_value1'11391140        jar = requests.cookies.RequestsCookieJar()1141        jar.set(key, value)1142        jar.set(key1, value1)11431144        items = jar.items()1145        assert items == list(items)1146        # make sure one can use items multiple times1147        assert list(items) == list(items)11481149    def test_cookie_duplicate_names_different_domains(self):1150        key = 'some_cookie'1151        value = 'some_value'1152        domain1 = 'test1.com'1153        domain2 = 'test2.com'11541155        jar = requests.cookies.RequestsCookieJar()1156        jar.set(key, value, domain=domain1)1157        jar.set(key, value, domain=domain2)1158        assert key in jar1159        items = jar.items()1160        assert len(items) == 211611162        # Verify that CookieConflictError is raised if domain is not specified1163        with pytest.raises(requests.cookies.CookieConflictError):1164            jar.get(key)11651166        # Verify that CookieConflictError is not raised if domain is specified1167        cookie = jar.get(key, domain=domain1)1168        assert cookie == value11691170    def test_cookie_duplicate_names_raises_cookie_conflict_error(self):1171        key = 'some_cookie'1172        value = 'some_value'1173        path = 'some_path'11741175        jar = requests.cookies.RequestsCookieJar()1176        jar.set(key, value, path=path)1177        jar.set(key, value)1178        with pytest.raises(requests.cookies.CookieConflictError):1179            jar.get(key)11801181    def test_cookie_policy_copy(self):1182        class MyCookiePolicy(cookielib.DefaultCookiePolicy):1183            pass11841185        jar = requests.cookies.RequestsCookieJar()1186        jar.set_policy(MyCookiePolicy())1187        assert isinstance(jar.copy().get_policy(), MyCookiePolicy)11881189    def test_time_elapsed_blank(self, httpbin):1190        r = requests.get(httpbin('get'))1191        td = r.elapsed1192        total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6)1193        assert total_seconds > 0.011941195    def test_empty_response_has_content_none(self):1196        r = requests.Response()1197        assert r.content is None11981199    def test_response_is_iterable(self):1200        r = requests.Response()1201        io = StringIO.StringIO('abc')1202        read_ = io.read12031204        def read_mock(amt, decode_content=None):1205            return read_(amt)1206        setattr(io, 'read', read_mock)1207        r.raw = io1208        assert next(iter(r))1209        io.close()12101211    def test_response_decode_unicode(self):1212        """When called with decode_unicode, Response.iter_content should always1213        return unicode.1214        """1215        r = requests.Response()1216        r._content_consumed = True1217        r._content = b'the content'1218        r.encoding = 'ascii'12191220        chunks = r.iter_content(decode_unicode=True)1221        assert all(isinstance(chunk, str) for chunk in chunks)12221223        # also for streaming1224        r = requests.Response()1225        r.raw = io.BytesIO(b'the content')1226        r.encoding = 'ascii'1227        chunks = r.iter_content(decode_unicode=True)1228        assert all(isinstance(chunk, str) for chunk in chunks)12291230    def test_response_reason_unicode(self):1231        # check for unicode HTTP status1232        r = requests.Response()1233        r.url = u'unicode URL'1234        r.reason = u'Komponenttia ei löydy'.encode('utf-8')1235        r.status_code = 4041236        r.encoding = None1237        assert not r.ok  # old behaviour - crashes here12381239    def test_response_reason_unicode_fallback(self):1240        # check raise_status falls back to ISO-8859-11241        r = requests.Response()1242        r.url = 'some url'1243        reason = u'Komponenttia ei löydy'1244        r.reason = reason.encode('latin-1')1245        r.status_code = 5001246        r.encoding = None1247        with pytest.raises(requests.exceptions.HTTPError) as e:1248            r.raise_for_status()1249        assert reason in e.value.args[0]12501251    def test_response_chunk_size_type(self):1252        """Ensure that chunk_size is passed as None or an integer, otherwise1253        raise a TypeError.1254        """1255        r = requests.Response()1256        r.raw = io.BytesIO(b'the content')1257        chunks = r.iter_content(1)1258        assert all(len(chunk) == 1 for chunk in chunks)12591260        r = requests.Response()1261        r.raw = io.BytesIO(b'the content')1262        chunks = r.iter_content(None)1263        assert list(chunks) == [b'the content']12641265        r = requests.Response()1266        r.raw = io.BytesIO(b'the content')1267        with pytest.raises(TypeError):1268            chunks = r.iter_content("1024")12691270    def test_request_and_response_are_pickleable(self, httpbin):1271        r = requests.get(httpbin('get'))12721273        # verify we can pickle the original request1274        assert pickle.loads(pickle.dumps(r.request))12751276        # verify we can pickle the response and that we have access to1277        # the original request.1278        pr = pickle.loads(pickle.dumps(r))1279        assert r.request.url == pr.request.url1280        assert r.request.headers == pr.request.headers12811282    def test_prepared_request_is_pickleable(self, httpbin):1283        p = requests.Request('GET', httpbin('get')).prepare()12841285        # Verify PreparedRequest can be pickled and unpickled1286        r = pickle.loads(pickle.dumps(p))1287        assert r.url == p.url1288        assert r.headers == p.headers1289        assert r.body == p.body12901291        # Verify unpickled PreparedRequest sends properly1292        s = requests.Session()1293        resp = s.send(r)1294        assert resp.status_code == 20012951296    def test_prepared_request_with_file_is_pickleable(self, httpbin):1297        files = {'file': open(__file__, 'rb')}1298        r = requests.Request('POST', httpbin('post'), files=files)1299        p = r.prepare()13001301        # Verify PreparedRequest can be pickled and unpickled1302        r = pickle.loads(pickle.dumps(p))1303        assert r.url == p.url1304        assert r.headers == p.headers1305        assert r.body == p.body13061307        # Verify unpickled PreparedRequest sends properly1308        s = requests.Session()1309        resp = s.send(r)1310        assert resp.status_code == 20013111312    def test_prepared_request_with_hook_is_pickleable(self, httpbin):1313        r = requests.Request('GET', httpbin('get'), hooks=default_hooks())1314        p = r.prepare()13151316        # Verify PreparedRequest can be pickled1317        r = pickle.loads(pickle.dumps(p))1318        assert r.url == p.url1319        assert r.headers == p.headers1320        assert r.body == p.body1321        assert r.hooks == p.hooks13221323        # Verify unpickled PreparedRequest sends properly1324        s = requests.Session()1325        resp = s.send(r)1326        assert resp.status_code == 20013271328    def test_cannot_send_unprepared_requests(self, httpbin):1329        r = requests.Request(url=httpbin())1330        with pytest.raises(ValueError):1331            requests.Session().send(r)13321333    def test_http_error(self):1334        error = requests.exceptions.HTTPError()1335        assert not error.response1336        response = requests.Response()1337        error = requests.exceptions.HTTPError(response=response)1338        assert error.response == response1339        error = requests.exceptions.HTTPError('message', response=response)1340        assert str(error) == 'message'1341        assert error.response == response13421343    def test_session_pickling(self, httpbin):1344        r = requests.Request('GET', httpbin('get'))1345        s = requests.Session()13461347        s = pickle.loads(pickle.dumps(s))1348        s.proxies = getproxies()13491350        r = s.send(r.prepare())1351        assert r.status_code == 20013521353    def test_fixes_1329(self, httpbin):1354        """Ensure that header updates are done case-insensitively."""1355        s = requests.Session()1356        s.headers.update({'ACCEPT': 'BOGUS'})1357        s.headers.update({'accept': 'application/json'})1358        r = s.get(httpbin('get'))1359        headers = r.request.headers1360        assert headers['accept'] == 'application/json'1361        assert headers['Accept'] == 'application/json'1362        assert headers['ACCEPT'] == 'application/json'13631364    def test_uppercase_scheme_redirect(self, httpbin):1365        parts = urlparse(httpbin('html'))1366        url = "HTTP://" + parts.netloc + parts.path1367        r = requests.get(httpbin('redirect-to'), params={'url': url})1368        assert r.status_code == 2001369        assert r.url.lower() == url.lower()13701371    def test_transport_adapter_ordering(self):1372        s = requests.Session()1373        order = ['https://', 'http://']1374        assert order == list(s.adapters)1375        s.mount('http://git', HTTPAdapter())1376        s.mount('http://github', HTTPAdapter())1377        s.mount('http://github.com', HTTPAdapter())1378        s.mount('http://github.com/about/', HTTPAdapter())1379        order = [1380            'http://github.com/about/',1381            'http://github.com',1382            'http://github',1383            'http://git',1384            'https://',1385            'http://',1386        ]1387        assert order == list(s.adapters)1388        s.mount('http://gittip', HTTPAdapter())1389        s.mount('http://gittip.com', HTTPAdapter())1390        s.mount('http://gittip.com/about/', HTTPAdapter())1391        order = [1392            'http://github.com/about/',1393            'http://gittip.com/about/',1394            'http://github.com',1395            'http://gittip.com',1396            'http://github',1397            'http://gittip',1398            'http://git',1399            'https://',1400            'http://',1401        ]1402        assert order == list(s.adapters)1403        s2 = requests.Session()1404        s2.adapters = {'http://': HTTPAdapter()}1405        s2.mount('https://', HTTPAdapter())1406        assert 'http://' in s2.adapters1407        assert 'https://' in s2.adapters14081409    def test_session_get_adapter_prefix_matching(self):1410        prefix = 'https://example.com'1411        more_specific_prefix = prefix + '/some/path'14121413        url_matching_only_prefix = prefix + '/another/path'1414        url_matching_more_specific_prefix = more_specific_prefix + '/longer/path'1415        url_not_matching_prefix = 'https://another.example.com/'14161417        s = requests.Session()1418        prefix_adapter = HTTPAdapter()1419        more_specific_prefix_adapter = HTTPAdapter()1420        s.mount(prefix, prefix_adapter)1421        s.mount(more_specific_prefix, more_specific_prefix_adapter)14221423        assert s.get_adapter(url_matching_only_prefix) is prefix_adapter1424        assert s.get_adapter(url_matching_more_specific_prefix) is more_specific_prefix_adapter1425        assert s.get_adapter(url_not_matching_prefix) not in (prefix_adapter, more_specific_prefix_adapter)14261427    def test_session_get_adapter_prefix_matching_mixed_case(self):1428        mixed_case_prefix = 'hTtPs://eXamPle.CoM/MixEd_CAse_PREfix'1429        url_matching_prefix = mixed_case_prefix + '/full_url'14301431        s = requests.Session()1432        my_adapter = HTTPAdapter()1433        s.mount(mixed_case_prefix, my_adapter)14341435        assert s.get_adapter(url_matching_prefix) is my_adapter14361437    def test_session_get_adapter_prefix_matching_is_case_insensitive(self):1438        mixed_case_prefix = 'hTtPs://eXamPle.CoM/MixEd_CAse_PREfix'1439        url_matching_prefix_with_different_case = 'HtTpS://exaMPLe.cOm/MiXeD_caSE_preFIX/another_url'14401441        s = requests.Session()1442        my_adapter = HTTPAdapter()1443        s.mount(mixed_case_prefix, my_adapter)14441445        assert s.get_adapter(url_matching_prefix_with_different_case) is my_adapter14461447    def test_header_remove_is_case_insensitive(self, httpbin):1448        # From issue #13211449        s = requests.Session()1450        s.headers['foo'] = 'bar'1451        r = s.get(httpbin('get'), headers={'FOO': None})1452        assert 'foo' not in r.request.headers14531454    def test_params_are_merged_case_sensitive(self, httpbin):1455        s = requests.Session()1456        s.params['foo'] = 'bar'1457        r = s.get(httpbin('get'), params={'FOO': 'bar'})1458        assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}14591460    def test_long_authinfo_in_url(self):1461        url = 'http://{}:{}@{}:9000/path?query#frag'.format(1462            'E8A3BE87-9E3F-4620-8858-95478E385B5B',1463            'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',1464            'exactly-------------sixty-----------three------------characters',1465        )1466        r = requests.Request('GET', url).prepare()1467        assert r.url == url14681469    def test_header_keys_are_native(self, httpbin):1470        headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}1471        r = requests.Request('GET', httpbin('get'), headers=headers)1472        p = r.prepare()14731474        # This is testing that they are builtin strings. A bit weird, but there1475        # we go.1476        assert 'unicode' in p.headers.keys()1477        assert 'byte' in p.headers.keys()14781479    def test_header_validation(self, httpbin):1480        """Ensure prepare_headers regex isn't flagging valid header contents."""1481        headers_ok = {'foo': 'bar baz qux',1482                      'bar': u'fbbq'.encode('utf8'),1483                      'baz': '',1484                      'qux': '1'}1485        r = requests.get(httpbin('get'), headers=headers_ok)1486        assert r.request.headers['foo'] == headers_ok['foo']14871488    def test_header_value_not_str(self, httpbin):1489        """Ensure the header value is of type string or bytes as1490        per discussion in GH issue #33861491        """1492        headers_int = {'foo': 3}1493        headers_dict = {'bar': {'foo': 'bar'}}1494        headers_list = {'baz': ['foo', 'bar']}14951496        # Test for int1497        with pytest.raises(InvalidHeader) as excinfo:1498            r = requests.get(httpbin('get'), headers=headers_int)1499        assert 'foo' in str(excinfo.value)1500        # Test for dict1501        with pytest.raises(InvalidHeader) as excinfo:1502            r = requests.get(httpbin('get'), headers=headers_dict)1503        assert 'bar' in str(excinfo.value)1504        # Test for list1505        with pytest.raises(InvalidHeader) as excinfo:1506            r = requests.get(httpbin('get'), headers=headers_list)1507        assert 'baz' in str(excinfo.value)15081509    def test_header_no_return_chars(self, httpbin):1510        """Ensure that a header containing return character sequences raise an1511        exception. Otherwise, multiple headers are created from single string.1512        """1513        headers_ret = {'foo': 'bar\r\nbaz: qux'}1514        headers_lf = {'foo': 'bar\nbaz: qux'}1515        headers_cr = {'foo': 'bar\rbaz: qux'}15161517        # Test for newline1518        with pytest.raises(InvalidHeader):1519            r = requests.get(httpbin('get'), headers=headers_ret)1520        # Test for line feed1521        with pytest.raises(InvalidHeader):1522            r = requests.get(httpbin('get'), headers=headers_lf)1523        # Test for carriage return1524        with pytest.raises(InvalidHeader):1525            r = requests.get(httpbin('get'), headers=headers_cr)15261527    def test_header_no_leading_space(self, httpbin):1528        """Ensure headers containing leading whitespace raise1529        InvalidHeader Error before sending.1530        """1531        headers_space = {'foo': ' bar'}1532        headers_tab = {'foo': '   bar'}15331534        # Test for whitespace1535        with pytest.raises(InvalidHeader):1536            r = requests.get(httpbin('get'), headers=headers_space)1537        # Test for tab1538        with pytest.raises(InvalidHeader):1539            r = requests.get(httpbin('get'), headers=headers_tab)15401541    @pytest.mark.parametrize('files', ('foo', b'foo', bytearray(b'foo')))1542    def test_can_send_objects_with_files(self, httpbin, files):1543        data = {'a': 'this is a string'}1544        files = {'b': files}1545        r = requests.Request('POST', httpbin('post'), data=data, files=files)1546        p = r.prepare()1547        assert 'multipart/form-data' in p.headers['Content-Type']15481549    def test_can_send_file_object_with_non_string_filename(self, httpbin):1550        f = io.BytesIO()1551        f.name = 21552        r = requests.Request('POST', httpbin('post'), files={'f': f})1553        p = r.prepare()15541555        assert 'multipart/form-data' in p.headers['Content-Type']15561557    def test_autoset_header_values_are_native(self, httpbin):1558        data = 'this is a string'1559        length = '16'1560        req = requests.Request('POST', httpbin('post'), data=data)1561        p = req.prepare()15621563        assert p.headers['Content-Length'] == length15641565    def test_nonhttp_schemes_dont_check_URLs(self):1566        test_urls = (1567            'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',1568            'file:///etc/passwd',1569            'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',1570        )1571        for test_url in test_urls:1572            req = requests.Request('GET', test_url)1573            preq = req.prepare()1574            assert test_url == preq.url15751576    def test_auth_is_stripped_on_http_downgrade(self, httpbin, httpbin_secure, httpbin_ca_bundle):1577        r = requests.get(1578            httpbin_secure('redirect-to'),1579            params={'url': httpbin('get')},1580            auth=('user', 'pass'),1581            verify=httpbin_ca_bundle1582        )1583        assert r.history[0].request.headers['Authorization']1584        assert 'Authorization' not in r.request.headers15851586    def test_auth_is_retained_for_redirect_on_host(self, httpbin):1587        r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))1588        h1 = r.history[0].request.headers['Authorization']1589        h2 = r.request.headers['Authorization']15901591        assert h1 == h215921593    def test_should_strip_auth_host_change(self):1594        s = requests.Session()1595        assert s.should_strip_auth('http://example.com/foo', 'http://another.example.com/')15961597    def test_should_strip_auth_http_downgrade(self):1598        s = requests.Session()1599        assert s.should_strip_auth('https://example.com/foo', 'http://example.com/bar')16001601    def test_should_strip_auth_https_upgrade(self):1602        s = requests.Session()1603        assert not s.should_strip_auth('http://example.com/foo', 'https://example.com/bar')1604        assert not s.should_strip_auth('http://example.com:80/foo', 'https://example.com/bar')1605        assert not s.should_strip_auth('http://example.com/foo', 'https://example.com:443/bar')1606        # Non-standard ports should trigger stripping1607        assert s.should_strip_auth('http://example.com:8080/foo', 'https://example.com/bar')1608        assert s.should_strip_auth('http://example.com/foo', 'https://example.com:8443/bar')16091610    def test_should_strip_auth_port_change(self):1611        s = requests.Session()1612        assert s.should_strip_auth('http://example.com:1234/foo', 'https://example.com:4321/bar')16131614    @pytest.mark.parametrize(1615        'old_uri, new_uri', (1616            ('https://example.com:443/foo', 'https://example.com/bar'),1617            ('http://example.com:80/foo', 'http://example.com/bar'),1618            ('https://example.com/foo', 'https://example.com:443/bar'),1619            ('http://example.com/foo', 'http://example.com:80/bar')1620        ))1621    def test_should_strip_auth_default_port(self, old_uri, new_uri):1622        s = requests.Session()1623        assert not s.should_strip_auth(old_uri, new_uri)16241625    def test_manual_redirect_with_partial_body_read(self, httpbin):1626        s = requests.Session()1627        r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)1628        assert r1.is_redirect1629        rg = s.resolve_redirects(r1, r1.request, stream=True)16301631        # read only the first eight bytes of the response body,1632        # then follow the redirect1633        r1.iter_content(8)1634        r2 = next(rg)1635        assert r2.is_redirect16361637        # read all of the response via iter_content,1638        # then follow the redirect1639        for _ in r2.iter_content():1640            pass1641        r3 = next(rg)1642        assert not r3.is_redirect16431644    def test_prepare_body_position_non_stream(self):1645        data = b'the data'1646        prep = requests.Request('GET', 'http://example.com', data=data).prepare()1647        assert prep._body_position is None16481649    def test_rewind_body(self):1650        data = io.BytesIO(b'the data')1651        prep = requests.Request('GET', 'http://example.com', data=data).prepare()1652        assert prep._body_position == 01653        assert prep.body.read() == b'the data'16541655        # the data has all been read1656        assert prep.body.read() == b''16571658        # rewind it back1659        requests.utils.rewind_body(prep)1660        assert prep.body.read() == b'the data'16611662    def test_rewind_partially_read_body(self):1663        data = io.BytesIO(b'the data')1664        data.read(4)  # read some data1665        prep = requests.Request('GET', 'http://example.com', data=data).prepare()1666        assert prep._body_position == 41667        assert prep.body.read() == b'data'16681669        # the data has all been read1670        assert prep.body.read() == b''16711672        # rewind it back1673        requests.utils.rewind_body(prep)1674        assert prep.body.read() == b'data'16751676    def test_rewind_body_no_seek(self):1677        class BadFileObj:1678            def __init__(self, data):1679                self.data = data16801681            def tell(self):1682                return 016831684            def __iter__(self):1685                return16861687        data = BadFileObj('the data')1688        prep = requests.Request('GET', 'http://example.com', data=data).prepare()1689        assert prep._body_position == 016901691        with pytest.raises(UnrewindableBodyError) as e:1692            requests.utils.rewind_body(prep)16931694        assert 'Unable to rewind request body' in str(e)16951696    def test_rewind_body_failed_seek(self):1697        class BadFileObj:1698            def __init__(self, data):1699                self.data = data17001701            def tell(self):1702                return 017031704            def seek(self, pos, whence=0):1705                raise OSError()17061707            def __iter__(self):1708                return17091710        data = BadFileObj('the data')1711        prep = requests.Request('GET', 'http://example.com', data=data).prepare()1712        assert prep._body_position == 017131714        with pytest.raises(UnrewindableBodyError) as e:1715            requests.utils.rewind_body(prep)17161717        assert 'error occurred when rewinding request body' in str(e)17181719    def test_rewind_body_failed_tell(self):1720        class BadFileObj:1721            def __init__(self, data):1722                self.data = data17231724            def tell(self):1725                raise OSError()17261727            def __iter__(self):1728                return17291730        data = BadFileObj('the data')1731        prep = requests.Request('GET', 'http://example.com', data=data).prepare()1732        assert prep._body_position is not None17331734        with pytest.raises(UnrewindableBodyError) as e:1735            requests.utils.rewind_body(prep)17361737        assert 'Unable to rewind request body' in str(e)17381739    def _patch_adapter_gzipped_redirect(self, session, url):1740        adapter = session.get_adapter(url=url)1741        org_build_response = adapter.build_response1742        self._patched_response = False17431744        def build_response(*args, **kwargs):1745            resp = org_build_response(*args, **kwargs)1746            if not self._patched_response:1747                resp.raw.headers['content-encoding'] = 'gzip'1748                self._patched_response = True1749            return resp17501751        adapter.build_response = build_response17521753    def test_redirect_with_wrong_gzipped_header(self, httpbin):1754        s = requests.Session()1755        url = httpbin('redirect/1')1756        self._patch_adapter_gzipped_redirect(s, url)1757        s.get(url)17581759    @pytest.mark.parametrize(1760        'username, password, auth_str', (1761            ('test', 'test', 'Basic dGVzdDp0ZXN0'),1762            (u'имя'.encode('utf-8'), u'пароль'.encode('utf-8'), 'Basic 0LjQvNGPOtC/0LDRgNC+0LvRjA=='),1763        ))1764    def test_basic_auth_str_is_always_native(self, username, password, auth_str):1765        s = _basic_auth_str(username, password)1766        assert isinstance(s, builtin_str)1767        assert s == auth_str17681769    def test_requests_history_is_saved(self, httpbin):1770        r = requests.get(httpbin('redirect/5'))1771        total = r.history[-1].history1772        i = 01773        for item in r.history:1774            assert item.history == total[0:i]1775            i += 117761777    def test_json_param_post_content_type_works(self, httpbin):1778        r = requests.post(1779            httpbin('post'),1780            json={'life': 42}1781        )1782        assert r.status_code == 2001783        assert 'application/json' in r.request.headers['Content-Type']1784        assert {'life': 42} == r.json()['json']17851786    def test_json_param_post_should_not_override_data_param(self, httpbin):1787        r = requests.Request(method='POST', url=httpbin('post'),1788                             data={'stuff': 'elixr'},1789                             json={'music': 'flute'})1790        prep = r.prepare()1791        assert 'stuff=elixr' == prep.body17921793    def test_response_iter_lines(self, httpbin):1794        r = requests.get(httpbin('stream/4'), stream=True)1795        assert r.status_code == 20017961797        it = r.iter_lines()1798        next(it)1799        assert len(list(it)) == 318001801    def test_response_context_manager(self, httpbin):1802        with requests.get(httpbin('stream/4'), stream=True) as response:1803            assert isinstance(response, requests.Response)18041805        assert response.raw.closed18061807    def test_unconsumed_session_response_closes_connection(self, httpbin):1808        s = requests.session()18091810        with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1811            pass18121813        assert response._content_consumed is False1814        assert response.raw.closed18151816    @pytest.mark.xfail1817    def test_response_iter_lines_reentrant(self, httpbin):1818        """Response.iter_lines() is not reentrant safe"""1819        r = requests.get(httpbin('stream/4'), stream=True)1820        assert r.status_code == 20018211822        next(r.iter_lines())1823        assert len(list(r.iter_lines())) == 318241825    def test_session_close_proxy_clear(self, mocker):1826        proxies = {1827          'one': mocker.Mock(),1828          'two': mocker.Mock(),1829        }1830        session = requests.Session()1831        mocker.patch.dict(session.adapters['http://'].proxy_manager, proxies)1832        session.close()1833        proxies['one'].clear.assert_called_once_with()1834        proxies['two'].clear.assert_called_once_with()18351836    def test_proxy_auth(self):1837        adapter = HTTPAdapter()1838        headers = adapter.proxy_headers("http://user:pass@httpbin.org")1839        assert headers == {'Proxy-Authorization': 'Basic dXNlcjpwYXNz'}18401841    def test_proxy_auth_empty_pass(self):1842        adapter = HTTPAdapter()1843        headers = adapter.proxy_headers("http://user:@httpbin.org")1844        assert headers == {'Proxy-Authorization': 'Basic dXNlcjo='}18451846    def test_response_json_when_content_is_None(self, httpbin):1847        r = requests.get(httpbin('/status/204'))1848        # Make sure r.content is None1849        r.status_code = 01850        r._content = False1851        r._content_consumed = False18521853        assert r.content is None1854        with pytest.raises(ValueError):1855            r.json()18561857    def test_response_without_release_conn(self):1858        """Test `close` call for non-urllib3-like raw objects.1859        Should work when `release_conn` attr doesn't exist on `response.raw`.1860        """1861        resp = requests.Response()1862        resp.raw = StringIO.StringIO('test')1863        assert not resp.raw.closed1864        resp.close()1865        assert resp.raw.closed18661867    def test_empty_stream_with_auth_does_not_set_content_length_header(self, httpbin):1868        """Ensure that a byte stream with size 0 will not set both a Content-Length1869        and Transfer-Encoding header.1870        """1871        auth = ('user', 'pass')1872        url = httpbin('post')1873        file_obj = io.BytesIO(b'')1874        r = requests.Request('POST', url, auth=auth, data=file_obj)1875        prepared_request = r.prepare()1876        assert 'Transfer-Encoding' in prepared_request.headers1877        assert 'Content-Length' not in prepared_request.headers18781879    def test_stream_with_auth_does_not_set_transfer_encoding_header(self, httpbin):1880        """Ensure that a byte stream with size > 0 will not set both a Content-Length1881        and Transfer-Encoding header.1882        """1883        auth = ('user', 'pass')1884        url = httpbin('post')1885        file_obj = io.BytesIO(b'test data')1886        r = requests.Request('POST', url, auth=auth, data=file_obj)1887        prepared_request = r.prepare()1888        assert 'Transfer-Encoding' not in prepared_request.headers1889        assert 'Content-Length' in prepared_request.headers18901891    def test_chunked_upload_does_not_set_content_length_header(self, httpbin):1892        """Ensure that requests with a generator body stream using1893        Transfer-Encoding: chunked, not a Content-Length header.1894        """1895        data = (i for i in [b'a', b'b', b'c'])1896        url = httpbin('post')1897        r = requests.Request('POST', url, data=data)1898        prepared_request = r.prepare()1899        assert 'Transfer-Encoding' in prepared_request.headers1900        assert 'Content-Length' not in prepared_request.headers19011902    def test_custom_redirect_mixin(self, httpbin):1903        """Tests a custom mixin to overwrite ``get_redirect_target``.19041905        Ensures a subclassed ``requests.Session`` can handle a certain type of1906        malformed redirect responses.19071908        1. original request receives a proper response: 302 redirect1909        2. following the redirect, a malformed response is given:1910            status code = HTTP 2001911            location = alternate url1912        3. the custom session catches the edge case and follows the redirect1913        """1914        url_final = httpbin('html')1915        querystring_malformed = urlencode({'location': url_final})1916        url_redirect_malformed = httpbin('response-headers?%s' % querystring_malformed)1917        querystring_redirect = urlencode({'url': url_redirect_malformed})1918        url_redirect = httpbin('redirect-to?%s' % querystring_redirect)1919        urls_test = [url_redirect,1920                     url_redirect_malformed,1921                     url_final,1922                     ]19231924        class CustomRedirectSession(requests.Session):1925            def get_redirect_target(self, resp):1926                # default behavior1927                if resp.is_redirect:1928                    return resp.headers['location']1929                # edge case - check to see if 'location' is in headers anyways1930                location = resp.headers.get('location')1931                if location and (location != resp.url):1932                    return location1933                return None19341935        session = CustomRedirectSession()1936        r = session.get(urls_test[0])1937        assert len(r.history) == 21938        assert r.status_code == 2001939        assert r.history[0].status_code == 3021940        assert r.history[0].is_redirect1941        assert r.history[1].status_code == 2001942        assert not r.history[1].is_redirect1943        assert r.url == urls_test[2]194419451946class TestCaseInsensitiveDict:19471948    @pytest.mark.parametrize(1949        'cid', (1950            CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}),1951            CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')]),1952            CaseInsensitiveDict(FOO='foo', BAr='bar'),1953        ))1954    def test_init(self, cid):1955        assert len(cid) == 21956        assert 'foo' in cid1957        assert 'bar' in cid19581959    def test_docstring_example(self):1960        cid = CaseInsensitiveDict()1961        cid['Accept'] = 'application/json'1962        assert cid['aCCEPT'] == 'application/json'1963        assert list(cid) == ['Accept']19641965    def test_len(self):1966        cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1967        cid['A'] = 'a'1968        assert len(cid) == 219691970    def test_getitem(self):1971        cid = CaseInsensitiveDict({'Spam': 'blueval'})1972        assert cid['spam'] == 'blueval'1973        assert cid['SPAM'] == 'blueval'19741975    def test_fixes_649(self):1976        """__setitem__ should behave case-insensitively."""1977        cid = CaseInsensitiveDict()1978        cid['spam'] = 'oneval'1979        cid['Spam'] = 'twoval'1980        cid['sPAM'] = 'redval'1981        cid['SPAM'] = 'blueval'1982        assert cid['spam'] == 'blueval'1983        assert cid['SPAM'] == 'blueval'1984        assert list(cid.keys()) == ['SPAM']19851986    def test_delitem(self):1987        cid = CaseInsensitiveDict()1988        cid['Spam'] = 'someval'1989        del cid['sPam']1990        assert 'spam' not in cid1991        assert len(cid) == 019921993    def test_contains(self):1994        cid = CaseInsensitiveDict()1995        cid['Spam'] = 'someval'1996        assert 'Spam' in cid1997        assert 'spam' in cid1998        assert 'SPAM' in cid1999        assert 'sPam' in cid2000        assert 'notspam' not in cid

The first 2,000 of 2,518 lines.