Skip to content
Myr

test_requests.py

This file

Path

tests/test_requests.py

2,527 lines · 88.8 KiB · Python

Last changed by

Merge pull request #4922 from jdufresne/orderedKenneth Reitzbefore adoptionbbc3d43

History of this file

Take it

1# -*- coding: utf-8 -*-23"""Tests for Requests."""45from __future__ import division6import json7import os8import pickle9import collections10import contextlib11import warnings12import re1314import io15import requests16import pytest17from requests.adapters import HTTPAdapter18from requests.auth import HTTPDigestAuth, _basic_auth_str19from requests.compat import (20    Morsel, cookielib, getproxies, str, urlparse,21    builtin_str)22from requests.cookies import (23    cookiejar_from_dict, morsel_to_cookie)24from requests.exceptions import (25    ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,26    MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects,27    ProxyError, InvalidHeader, UnrewindableBodyError, SSLError, InvalidProxyURL)28from requests.models import PreparedRequest29from requests.structures import CaseInsensitiveDict30from requests.sessions import SessionRedirectMixin31from requests.models import urlencode32from requests.hooks import default_hooks33from requests.compat import MutableMapping3435from .compat import StringIO, u36from .utils import override_environ37from urllib3.util import Timeout as Urllib3Timeout3839# Requests to this URL should always fail with a connection timeout (nothing40# listening on that port)41TARPIT = 'http://10.255.255.1'4243try:44    from ssl import SSLContext45    del SSLContext46    HAS_MODERN_SSL = True47except ImportError:48    HAS_MODERN_SSL = False4950try:51    requests.pyopenssl52    HAS_PYOPENSSL = True53except AttributeError:54    HAS_PYOPENSSL = False555657class TestRequests:5859    digest_auth_algo = ('MD5', 'SHA-256', 'SHA-512')6061    def test_entry_points(self):6263        requests.session64        requests.session().get65        requests.session().head66        requests.get67        requests.head68        requests.put69        requests.patch70        requests.post71        # Not really an entry point, but people rely on it.72        from requests.packages.urllib3.poolmanager import PoolManager7374    @pytest.mark.parametrize(75        'exception, url', (76            (MissingSchema, 'hiwpefhipowhefopw'),77            (InvalidSchema, 'localhost:3128'),78            (InvalidSchema, 'localhost.localdomain:3128/'),79            (InvalidSchema, '10.122.1.1:3128/'),80            (InvalidURL, 'http://'),81        ))82    def test_invalid_url(self, exception, url):83        with pytest.raises(exception):84            requests.get(url)8586    def test_basic_building(self):87        req = requests.Request()88        req.url = 'http://kennethreitz.org/'89        req.data = {'life': '42'}9091        pr = req.prepare()92        assert pr.url == req.url93        assert pr.body == 'life=42'9495    @pytest.mark.parametrize('method', ('GET', 'HEAD'))96    def test_no_content_length(self, httpbin, method):97        req = requests.Request(method, httpbin(method.lower())).prepare()98        assert 'Content-Length' not in req.headers99100    @pytest.mark.parametrize('method', ('POST', 'PUT', 'PATCH', 'OPTIONS'))101    def test_no_body_content_length(self, httpbin, method):102        req = requests.Request(method, httpbin(method.lower())).prepare()103        assert req.headers['Content-Length'] == '0'104105    @pytest.mark.parametrize('method', ('POST', 'PUT', 'PATCH', 'OPTIONS'))106    def test_empty_content_length(self, httpbin, method):107        req = requests.Request(method, httpbin(method.lower()), data='').prepare()108        assert req.headers['Content-Length'] == '0'109110    def test_override_content_length(self, httpbin):111        headers = {112            'Content-Length': 'not zero'113        }114        r = requests.Request('POST', httpbin('post'), headers=headers).prepare()115        assert 'Content-Length' in r.headers116        assert r.headers['Content-Length'] == 'not zero'117118    def test_path_is_not_double_encoded(self):119        request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()120121        assert request.path_url == '/get/test%20case'122123    @pytest.mark.parametrize(124        'url, expected', (125            ('http://example.com/path#fragment', 'http://example.com/path?a=b#fragment'),126            ('http://example.com/path?key=value#fragment', 'http://example.com/path?key=value&a=b#fragment')127        ))128    def test_params_are_added_before_fragment(self, url, expected):129        request = requests.Request('GET', url, params={"a": "b"}).prepare()130        assert request.url == expected131132    def test_params_original_order_is_preserved_by_default(self):133        param_ordered_dict = collections.OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))134        session = requests.Session()135        request = requests.Request('GET', 'http://example.com/', params=param_ordered_dict)136        prep = session.prepare_request(request)137        assert prep.url == 'http://example.com/?z=1&a=1&k=1&d=1'138139    def test_params_bytes_are_encoded(self):140        request = requests.Request('GET', 'http://example.com',141                                   params=b'test=foo').prepare()142        assert request.url == 'http://example.com/?test=foo'143144    def test_binary_put(self):145        request = requests.Request('PUT', 'http://example.com',146                                   data=u"ööö".encode("utf-8")).prepare()147        assert isinstance(request.body, bytes)148149    def test_whitespaces_are_removed_from_url(self):150        # Test for issue #3696151        request = requests.Request('GET', ' http://example.com').prepare()152        assert request.url == 'http://example.com/'153154    @pytest.mark.parametrize('scheme', ('http://', 'HTTP://', 'hTTp://', 'HttP://'))155    def test_mixed_case_scheme_acceptable(self, httpbin, scheme):156        s = requests.Session()157        s.proxies = getproxies()158        parts = urlparse(httpbin('get'))159        url = scheme + parts.netloc + parts.path160        r = requests.Request('GET', url)161        r = s.send(r.prepare())162        assert r.status_code == 200, 'failed for scheme {}'.format(scheme)163164    def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):165        r = requests.Request('GET', httpbin('get'))166        s = requests.Session()167        s.proxies = getproxies()168169        r = s.send(r.prepare())170171        assert r.status_code == 200172173    def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):174        r = requests.get(httpbin('redirect', '1'))175        assert r.status_code == 200176        assert r.history[0].status_code == 302177        assert r.history[0].is_redirect178179    def test_HTTP_307_ALLOW_REDIRECT_POST(self, httpbin):180        r = requests.post(httpbin('redirect-to'), data='test', params={'url': 'post', 'status_code': 307})181        assert r.status_code == 200182        assert r.history[0].status_code == 307183        assert r.history[0].is_redirect184        assert r.json()['data'] == 'test'185186    def test_HTTP_307_ALLOW_REDIRECT_POST_WITH_SEEKABLE(self, httpbin):187        byte_str = b'test'188        r = requests.post(httpbin('redirect-to'), data=io.BytesIO(byte_str), params={'url': 'post', 'status_code': 307})189        assert r.status_code == 200190        assert r.history[0].status_code == 307191        assert r.history[0].is_redirect192        assert r.json()['data'] == byte_str.decode('utf-8')193194    def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):195        try:196            requests.get(httpbin('relative-redirect', '50'))197        except TooManyRedirects as e:198            url = httpbin('relative-redirect', '20')199            assert e.request.url == url200            assert e.response.url == url201            assert len(e.response.history) == 30202        else:203            pytest.fail('Expected redirect to raise TooManyRedirects but it did not')204205    def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):206        s = requests.session()207        s.max_redirects = 5208        try:209            s.get(httpbin('relative-redirect', '50'))210        except TooManyRedirects as e:211            url = httpbin('relative-redirect', '45')212            assert e.request.url == url213            assert e.response.url == url214            assert len(e.response.history) == 5215        else:216            pytest.fail('Expected custom max number of redirects to be respected but was not')217218    def test_http_301_changes_post_to_get(self, httpbin):219        r = requests.post(httpbin('status', '301'))220        assert r.status_code == 200221        assert r.request.method == 'GET'222        assert r.history[0].status_code == 301223        assert r.history[0].is_redirect224225    def test_http_301_doesnt_change_head_to_get(self, httpbin):226        r = requests.head(httpbin('status', '301'), allow_redirects=True)227        print(r.content)228        assert r.status_code == 200229        assert r.request.method == 'HEAD'230        assert r.history[0].status_code == 301231        assert r.history[0].is_redirect232233    def test_http_302_changes_post_to_get(self, httpbin):234        r = requests.post(httpbin('status', '302'))235        assert r.status_code == 200236        assert r.request.method == 'GET'237        assert r.history[0].status_code == 302238        assert r.history[0].is_redirect239240    def test_http_302_doesnt_change_head_to_get(self, httpbin):241        r = requests.head(httpbin('status', '302'), allow_redirects=True)242        assert r.status_code == 200243        assert r.request.method == 'HEAD'244        assert r.history[0].status_code == 302245        assert r.history[0].is_redirect246247    def test_http_303_changes_post_to_get(self, httpbin):248        r = requests.post(httpbin('status', '303'))249        assert r.status_code == 200250        assert r.request.method == 'GET'251        assert r.history[0].status_code == 303252        assert r.history[0].is_redirect253254    def test_http_303_doesnt_change_head_to_get(self, httpbin):255        r = requests.head(httpbin('status', '303'), allow_redirects=True)256        assert r.status_code == 200257        assert r.request.method == 'HEAD'258        assert r.history[0].status_code == 303259        assert r.history[0].is_redirect260261    def test_header_and_body_removal_on_redirect(self, httpbin):262        purged_headers = ('Content-Length', 'Content-Type')263        ses = requests.Session()264        req = requests.Request('POST', httpbin('post'), data={'test': 'data'})265        prep = ses.prepare_request(req)266        resp = ses.send(prep)267268        # Mimic a redirect response269        resp.status_code = 302270        resp.headers['location'] = 'get'271272        # Run request through resolve_redirects273        next_resp = next(ses.resolve_redirects(resp, prep))274        assert next_resp.request.body is None275        for header in purged_headers:276            assert header not in next_resp.request.headers277278    def test_transfer_enc_removal_on_redirect(self, httpbin):279        purged_headers = ('Transfer-Encoding', 'Content-Type')280        ses = requests.Session()281        req = requests.Request('POST', httpbin('post'), data=(b'x' for x in range(1)))282        prep = ses.prepare_request(req)283        assert 'Transfer-Encoding' in prep.headers284285        # Create Response to avoid https://github.com/kevin1024/pytest-httpbin/issues/33286        resp = requests.Response()287        resp.raw = io.BytesIO(b'the content')288        resp.request = prep289        setattr(resp.raw, 'release_conn', lambda *args: args)290291        # Mimic a redirect response292        resp.status_code = 302293        resp.headers['location'] = httpbin('get')294295        # Run request through resolve_redirect296        next_resp = next(ses.resolve_redirects(resp, prep))297        assert next_resp.request.body is None298        for header in purged_headers:299            assert header not in next_resp.request.headers300301    def test_fragment_maintained_on_redirect(self, httpbin):302        fragment = "#view=edit&token=hunter2"303        r = requests.get(httpbin('redirect-to?url=get')+fragment)304305        assert len(r.history) > 0306        assert r.history[0].request.url == httpbin('redirect-to?url=get')+fragment307        assert r.url == httpbin('get')+fragment308309    def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):310        heads = {'User-agent': 'Mozilla/5.0'}311312        r = requests.get(httpbin('user-agent'), headers=heads)313314        assert heads['User-agent'] in r.text315        assert r.status_code == 200316317    def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):318        heads = {'User-agent': 'Mozilla/5.0'}319320        r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)321        assert r.status_code == 200322323    def test_set_cookie_on_301(self, httpbin):324        s = requests.session()325        url = httpbin('cookies/set?foo=bar')326        s.get(url)327        assert s.cookies['foo'] == 'bar'328329    def test_cookie_sent_on_redirect(self, httpbin):330        s = requests.session()331        s.get(httpbin('cookies/set?foo=bar'))332        r = s.get(httpbin('redirect/1'))  # redirects to httpbin('get')333        assert 'Cookie' in r.json()['headers']334335    def test_cookie_removed_on_expire(self, httpbin):336        s = requests.session()337        s.get(httpbin('cookies/set?foo=bar'))338        assert s.cookies['foo'] == 'bar'339        s.get(340            httpbin('response-headers'),341            params={342                'Set-Cookie':343                    'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'344            }345        )346        assert 'foo' not in s.cookies347348    def test_cookie_quote_wrapped(self, httpbin):349        s = requests.session()350        s.get(httpbin('cookies/set?foo="bar:baz"'))351        assert s.cookies['foo'] == '"bar:baz"'352353    def test_cookie_persists_via_api(self, httpbin):354        s = requests.session()355        r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})356        assert 'foo' in r.request.headers['Cookie']357        assert 'foo' in r.history[0].request.headers['Cookie']358359    def test_request_cookie_overrides_session_cookie(self, httpbin):360        s = requests.session()361        s.cookies['foo'] = 'bar'362        r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})363        assert r.json()['cookies']['foo'] == 'baz'364        # Session cookie should not be modified365        assert s.cookies['foo'] == 'bar'366367    def test_request_cookies_not_persisted(self, httpbin):368        s = requests.session()369        s.get(httpbin('cookies'), cookies={'foo': 'baz'})370        # Sending a request with cookies should not add cookies to the session371        assert not s.cookies372373    def test_generic_cookiejar_works(self, httpbin):374        cj = cookielib.CookieJar()375        cookiejar_from_dict({'foo': 'bar'}, cj)376        s = requests.session()377        s.cookies = cj378        r = s.get(httpbin('cookies'))379        # Make sure the cookie was sent380        assert r.json()['cookies']['foo'] == 'bar'381        # Make sure the session cj is still the custom one382        assert s.cookies is cj383384    def test_param_cookiejar_works(self, httpbin):385        cj = cookielib.CookieJar()386        cookiejar_from_dict({'foo': 'bar'}, cj)387        s = requests.session()388        r = s.get(httpbin('cookies'), cookies=cj)389        # Make sure the cookie was sent390        assert r.json()['cookies']['foo'] == 'bar'391392    def test_cookielib_cookiejar_on_redirect(self, httpbin):393        """Tests resolve_redirect doesn't fail when merging cookies394        with non-RequestsCookieJar cookiejar.395396        See GH #3579397        """398        cj = cookiejar_from_dict({'foo': 'bar'}, cookielib.CookieJar())399        s = requests.Session()400        s.cookies = cookiejar_from_dict({'cookie': 'tasty'})401402        # Prepare request without using Session403        req = requests.Request('GET', httpbin('headers'), cookies=cj)404        prep_req = req.prepare()405406        # Send request and simulate redirect407        resp = s.send(prep_req)408        resp.status_code = 302409        resp.headers['location'] = httpbin('get')410        redirects = s.resolve_redirects(resp, prep_req)411        resp = next(redirects)412413        # Verify CookieJar isn't being converted to RequestsCookieJar414        assert isinstance(prep_req._cookies, cookielib.CookieJar)415        assert isinstance(resp.request._cookies, cookielib.CookieJar)416        assert not isinstance(resp.request._cookies, requests.cookies.RequestsCookieJar)417418        cookies = {}419        for c in resp.request._cookies:420            cookies[c.name] = c.value421        assert cookies['foo'] == 'bar'422        assert cookies['cookie'] == 'tasty'423424    def test_requests_in_history_are_not_overridden(self, httpbin):425        resp = requests.get(httpbin('redirect/3'))426        urls = [r.url for r in resp.history]427        req_urls = [r.request.url for r in resp.history]428        assert urls == req_urls429430    def test_history_is_always_a_list(self, httpbin):431        """Show that even with redirects, Response.history is always a list."""432        resp = requests.get(httpbin('get'))433        assert isinstance(resp.history, list)434        resp = requests.get(httpbin('redirect/1'))435        assert isinstance(resp.history, list)436        assert not isinstance(resp.history, tuple)437438    def test_headers_on_session_with_None_are_not_sent(self, httpbin):439        """Do not send headers in Session.headers with None values."""440        ses = requests.Session()441        ses.headers['Accept-Encoding'] = None442        req = requests.Request('GET', httpbin('get'))443        prep = ses.prepare_request(req)444        assert 'Accept-Encoding' not in prep.headers445446    def test_headers_preserve_order(self, httpbin):447        """Preserve order when headers provided as OrderedDict."""448        ses = requests.Session()449        ses.headers = collections.OrderedDict()450        ses.headers['Accept-Encoding'] = 'identity'451        ses.headers['First'] = '1'452        ses.headers['Second'] = '2'453        headers = collections.OrderedDict([('Third', '3'), ('Fourth', '4')])454        headers['Fifth'] = '5'455        headers['Second'] = '222'456        req = requests.Request('GET', httpbin('get'), headers=headers)457        prep = ses.prepare_request(req)458        items = list(prep.headers.items())459        assert items[0] == ('Accept-Encoding', 'identity')460        assert items[1] == ('First', '1')461        assert items[2] == ('Second', '222')462        assert items[3] == ('Third', '3')463        assert items[4] == ('Fourth', '4')464        assert items[5] == ('Fifth', '5')465466    @pytest.mark.parametrize('key', ('User-agent', 'user-agent'))467    def test_user_agent_transfers(self, httpbin, key):468469        heads = {key: 'Mozilla/5.0 (github.com/psf/requests)'}470471        r = requests.get(httpbin('user-agent'), headers=heads)472        assert heads[key] in r.text473474    def test_HTTP_200_OK_HEAD(self, httpbin):475        r = requests.head(httpbin('get'))476        assert r.status_code == 200477478    def test_HTTP_200_OK_PUT(self, httpbin):479        r = requests.put(httpbin('put'))480        assert r.status_code == 200481482    def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):483        auth = ('user', 'pass')484        url = httpbin('basic-auth', 'user', 'pass')485486        r = requests.get(url, auth=auth)487        assert r.status_code == 200488489        r = requests.get(url)490        assert r.status_code == 401491492        s = requests.session()493        s.auth = auth494        r = s.get(url)495        assert r.status_code == 200496497    @pytest.mark.parametrize(498        'username, password', (499            ('user', 'pass'),500            (u'имя'.encode('utf-8'), u'пароль'.encode('utf-8')),501            (42, 42),502            (None, None),503        ))504    def test_set_basicauth(self, httpbin, username, password):505        auth = (username, password)506        url = httpbin('get')507508        r = requests.Request('GET', url, auth=auth)509        p = r.prepare()510511        assert p.headers['Authorization'] == _basic_auth_str(username, password)512513    def test_basicauth_encodes_byte_strings(self):514        """Ensure b'test' formats as the byte string "test" rather515        than the unicode string "b'test'" in Python 3.516        """517        auth = (b'\xc5\xafsername', b'test\xc6\xb6')518        r = requests.Request('GET', 'http://localhost', auth=auth)519        p = r.prepare()520521        assert p.headers['Authorization'] == 'Basic xa9zZXJuYW1lOnRlc3TGtg=='522523    @pytest.mark.parametrize(524        'url, exception', (525            # Connecting to an unknown domain should raise a ConnectionError526            ('http://doesnotexist.google.com', ConnectionError),527            # Connecting to an invalid port should raise a ConnectionError528            ('http://localhost:1', ConnectionError),529            # Inputing a URL that cannot be parsed should raise an InvalidURL error530            ('http://fe80::5054:ff:fe5a:fc0', InvalidURL)531        ))532    def test_errors(self, url, exception):533        with pytest.raises(exception):534            requests.get(url, timeout=1)535536    def test_proxy_error(self):537        # any proxy related error (address resolution, no route to host, etc) should result in a ProxyError538        with pytest.raises(ProxyError):539            requests.get('http://localhost:1', proxies={'http': 'non-resolvable-address'})540541    def test_proxy_error_on_bad_url(self, httpbin, httpbin_secure):542        with pytest.raises(InvalidProxyURL):543            requests.get(httpbin_secure(), proxies={'https': 'http:/badproxyurl:3128'})544545        with pytest.raises(InvalidProxyURL):546            requests.get(httpbin(), proxies={'http': 'http://:8080'})547548        with pytest.raises(InvalidProxyURL):549            requests.get(httpbin_secure(), proxies={'https': 'https://'})550551        with pytest.raises(InvalidProxyURL):552            requests.get(httpbin(), proxies={'http': 'http:///example.com:8080'})553554    def test_basicauth_with_netrc(self, httpbin):555        auth = ('user', 'pass')556        wrong_auth = ('wronguser', 'wrongpass')557        url = httpbin('basic-auth', 'user', 'pass')558559        old_auth = requests.sessions.get_netrc_auth560561        try:562            def get_netrc_auth_mock(url):563                return auth564            requests.sessions.get_netrc_auth = get_netrc_auth_mock565566            # Should use netrc and work.567            r = requests.get(url)568            assert r.status_code == 200569570            # Given auth should override and fail.571            r = requests.get(url, auth=wrong_auth)572            assert r.status_code == 401573574            s = requests.session()575576            # Should use netrc and work.577            r = s.get(url)578            assert r.status_code == 200579580            # Given auth should override and fail.581            s.auth = wrong_auth582            r = s.get(url)583            assert r.status_code == 401584        finally:585            requests.sessions.get_netrc_auth = old_auth586587    def test_DIGEST_HTTP_200_OK_GET(self, httpbin):588589        for authtype in self.digest_auth_algo:590            auth = HTTPDigestAuth('user', 'pass')591            url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype, 'never')592593            r = requests.get(url, auth=auth)594            assert r.status_code == 200595596            r = requests.get(url)597            assert r.status_code == 401598            print(r.headers['WWW-Authenticate'])599600            s = requests.session()601            s.auth = HTTPDigestAuth('user', 'pass')602            r = s.get(url)603            assert r.status_code == 200604605    def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):606607        for authtype in self.digest_auth_algo:608            url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype)609            auth = HTTPDigestAuth('user', 'pass')610            r = requests.get(url)611            assert r.cookies['fake'] == 'fake_value'612613            r = requests.get(url, auth=auth)614            assert r.status_code == 200615616    def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):617618        for authtype in self.digest_auth_algo:619            url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype)620            auth = HTTPDigestAuth('user', 'pass')621            s = requests.Session()622            s.get(url, auth=auth)623            assert s.cookies['fake'] == 'fake_value'624625    def test_DIGEST_STREAM(self, httpbin):626627        for authtype in self.digest_auth_algo:628            auth = HTTPDigestAuth('user', 'pass')629            url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype)630631            r = requests.get(url, auth=auth, stream=True)632            assert r.raw.read() != b''633634            r = requests.get(url, auth=auth, stream=False)635            assert r.raw.read() == b''636637    def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):638639        for authtype in self.digest_auth_algo:640            auth = HTTPDigestAuth('user', 'wrongpass')641            url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype)642643            r = requests.get(url, auth=auth)644            assert r.status_code == 401645646            r = requests.get(url)647            assert r.status_code == 401648649            s = requests.session()650            s.auth = auth651            r = s.get(url)652            assert r.status_code == 401653654    def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):655656        for authtype in self.digest_auth_algo:657            auth = HTTPDigestAuth('user', 'pass')658            url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype)659660            r = requests.get(url, auth=auth)661            assert '"auth"' in r.request.headers['Authorization']662663    def test_POSTBIN_GET_POST_FILES(self, httpbin):664665        url = httpbin('post')666        requests.post(url).raise_for_status()667668        post1 = requests.post(url, data={'some': 'data'})669        assert post1.status_code == 200670671        with open('Pipfile') as f:672            post2 = requests.post(url, files={'some': f})673        assert post2.status_code == 200674675        post4 = requests.post(url, data='[{"some": "json"}]')676        assert post4.status_code == 200677678        with pytest.raises(ValueError):679            requests.post(url, files=['bad file data'])680681    def test_invalid_files_input(self, httpbin):682683        url = httpbin('post')684        post = requests.post(url,685                             files={"random-file-1": None, "random-file-2": 1})686        assert b'name="random-file-1"' not in post.request.body687        assert b'name="random-file-2"' in post.request.body688689    def test_POSTBIN_SEEKED_OBJECT_WITH_NO_ITER(self, httpbin):690691        class TestStream(object):692            def __init__(self, data):693                self.data = data.encode()694                self.length = len(self.data)695                self.index = 0696697            def __len__(self):698                return self.length699700            def read(self, size=None):701                if size:702                    ret = self.data[self.index:self.index + size]703                    self.index += size704                else:705                    ret = self.data[self.index:]706                    self.index = self.length707                return ret708709            def tell(self):710                return self.index711712            def seek(self, offset, where=0):713                if where == 0:714                    self.index = offset715                elif where == 1:716                    self.index += offset717                elif where == 2:718                    self.index = self.length + offset719720        test = TestStream('test')721        post1 = requests.post(httpbin('post'), data=test)722        assert post1.status_code == 200723        assert post1.json()['data'] == 'test'724725        test = TestStream('test')726        test.seek(2)727        post2 = requests.post(httpbin('post'), data=test)728        assert post2.status_code == 200729        assert post2.json()['data'] == 'st'730731    def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):732733        url = httpbin('post')734        requests.post(url).raise_for_status()735736        post1 = requests.post(url, data={'some': 'data'})737        assert post1.status_code == 200738739        with open('Pipfile') as f:740            post2 = requests.post(url, data={'some': 'data'}, files={'some': f})741        assert post2.status_code == 200742743        post4 = requests.post(url, data='[{"some": "json"}]')744        assert post4.status_code == 200745746        with pytest.raises(ValueError):747            requests.post(url, files=['bad file data'])748749    def test_post_with_custom_mapping(self, httpbin):750        class CustomMapping(MutableMapping):751            def __init__(self, *args, **kwargs):752                self.data = dict(*args, **kwargs)753754            def __delitem__(self, key):755                del self.data[key]756757            def __getitem__(self, key):758                return self.data[key]759760            def __setitem__(self, key, value):761                self.data[key] = value762763            def __iter__(self):764                return iter(self.data)765766            def __len__(self):767                return len(self.data)768769        data = CustomMapping({'some': 'data'})770        url = httpbin('post')771        found_json = requests.post(url, data=data).json().get('form')772        assert found_json == {'some': 'data'}773774    def test_conflicting_post_params(self, httpbin):775        url = httpbin('post')776        with open('Pipfile') as f:777            pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")778            pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")779780    def test_request_ok_set(self, httpbin):781        r = requests.get(httpbin('status', '404'))782        assert not r.ok783784    def test_status_raising(self, httpbin):785        r = requests.get(httpbin('status', '404'))786        with pytest.raises(requests.exceptions.HTTPError):787            r.raise_for_status()788789        r = requests.get(httpbin('status', '500'))790        assert not r.ok791792    def test_decompress_gzip(self, httpbin):793        r = requests.get(httpbin('gzip'))794        r.content.decode('ascii')795796    @pytest.mark.parametrize(797        'url, params', (798            ('/get', {'foo': 'føø'}),799            ('/get', {'føø': 'føø'}),800            ('/get', {'føø': 'føø'}),801            ('/get', {'foo': 'foo'}),802            ('ø', {'foo': 'foo'}),803        ))804    def test_unicode_get(self, httpbin, url, params):805        requests.get(httpbin(url), params=params)806807    def test_unicode_header_name(self, httpbin):808        requests.put(809            httpbin('put'),810            headers={str('Content-Type'): 'application/octet-stream'},811            data='\xff')  # compat.str is unicode.812813    def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):814        requests.get(httpbin_secure('status', '301'), verify=httpbin_ca_bundle)815816    def test_invalid_ca_certificate_path(self, httpbin_secure):817        INVALID_PATH = '/garbage'818        with pytest.raises(IOError) as e:819            requests.get(httpbin_secure(), verify=INVALID_PATH)820        assert str(e.value) == 'Could not find a suitable TLS CA certificate bundle, invalid path: {}'.format(INVALID_PATH)821822    def test_invalid_ssl_certificate_files(self, httpbin_secure):823        INVALID_PATH = '/garbage'824        with pytest.raises(IOError) as e:825            requests.get(httpbin_secure(), cert=INVALID_PATH)826        assert str(e.value) == 'Could not find the TLS certificate file, invalid path: {}'.format(INVALID_PATH)827828        with pytest.raises(IOError) as e:829            requests.get(httpbin_secure(), cert=('.', INVALID_PATH))830        assert str(e.value) == 'Could not find the TLS key file, invalid path: {}'.format(INVALID_PATH)831832    def test_http_with_certificate(self, httpbin):833        r = requests.get(httpbin(), cert='.')834        assert r.status_code == 200835836    def test_https_warnings(self, httpbin_secure, httpbin_ca_bundle):837        """warnings are emitted with requests.get"""838        if HAS_MODERN_SSL or HAS_PYOPENSSL:839            warnings_expected = ('SubjectAltNameWarning', )840        else:841            warnings_expected = ('SNIMissingWarning',842                                 'InsecurePlatformWarning',843                                 'SubjectAltNameWarning', )844845        with pytest.warns(None) as warning_records:846            warnings.simplefilter('always')847            requests.get(httpbin_secure('status', '200'),848                         verify=httpbin_ca_bundle)849850        warning_records = [item for item in warning_records851                           if item.category.__name__ != 'ResourceWarning']852853        warnings_category = tuple(854            item.category.__name__ for item in warning_records)855        assert warnings_category == warnings_expected856857    def test_certificate_failure(self, httpbin_secure):858        """859        When underlying SSL problems occur, an SSLError is raised.860        """861        with pytest.raises(SSLError):862            # Our local httpbin does not have a trusted CA, so this call will863            # fail if we use our default trust bundle.864            requests.get(httpbin_secure('status', '200'))865866    def test_urlencoded_get_query_multivalued_param(self, httpbin):867868        r = requests.get(httpbin('get'), params={'test': ['foo', 'baz']})869        assert r.status_code == 200870        assert r.url == httpbin('get?test=foo&test=baz')871872    def test_form_encoded_post_query_multivalued_element(self, httpbin):873        r = requests.Request(method='POST', url=httpbin('post'),874                             data=dict(test=['foo', 'baz']))875        prep = r.prepare()876        assert prep.body == 'test=foo&test=baz'877878    def test_different_encodings_dont_break_post(self, httpbin):879        r = requests.post(httpbin('post'),880            data={'stuff': json.dumps({'a': 123})},881            params={'blah': 'asdf1234'},882            files={'file': ('test_requests.py', open(__file__, 'rb'))})883        assert r.status_code == 200884885    @pytest.mark.parametrize(886        'data', (887            {'stuff': u('ëlïxr')},888            {'stuff': u('ëlïxr').encode('utf-8')},889            {'stuff': 'elixr'},890            {'stuff': 'elixr'.encode('utf-8')},891        ))892    def test_unicode_multipart_post(self, httpbin, data):893        r = requests.post(httpbin('post'),894            data=data,895            files={'file': ('test_requests.py', open(__file__, 'rb'))})896        assert r.status_code == 200897898    def test_unicode_multipart_post_fieldnames(self, httpbin):899        filename = os.path.splitext(__file__)[0] + '.py'900        r = requests.Request(901            method='POST', url=httpbin('post'),902            data={'stuff'.encode('utf-8'): 'elixr'},903            files={'file': ('test_requests.py', open(filename, 'rb'))})904        prep = r.prepare()905        assert b'name="stuff"' in prep.body906        assert b'name="b\'stuff\'"' not in prep.body907908    def test_unicode_method_name(self, httpbin):909        files = {'file': open(__file__, 'rb')}910        r = requests.request(911            method=u('POST'), url=httpbin('post'), files=files)912        assert r.status_code == 200913914    def test_unicode_method_name_with_request_object(self, httpbin):915        files = {'file': open(__file__, 'rb')}916        s = requests.Session()917        req = requests.Request(u('POST'), httpbin('post'), files=files)918        prep = s.prepare_request(req)919        assert isinstance(prep.method, builtin_str)920        assert prep.method == 'POST'921922        resp = s.send(prep)923        assert resp.status_code == 200924925    def test_non_prepared_request_error(self):926        s = requests.Session()927        req = requests.Request(u('POST'), '/')928929        with pytest.raises(ValueError) as e:930            s.send(req)931        assert str(e.value) == 'You can only send PreparedRequests.'932933    def test_custom_content_type(self, httpbin):934        r = requests.post(935            httpbin('post'),936            data={'stuff': json.dumps({'a': 123})},937            files={938                'file1': ('test_requests.py', open(__file__, 'rb')),939                'file2': ('test_requests', open(__file__, 'rb'),940                    'text/py-content-type')})941        assert r.status_code == 200942        assert b"text/py-content-type" in r.request.body943944    def test_hook_receives_request_arguments(self, httpbin):945        def hook(resp, **kwargs):946            assert resp is not None947            assert kwargs != {}948949        s = requests.Session()950        r = requests.Request('GET', httpbin(), hooks={'response': hook})951        prep = s.prepare_request(r)952        s.send(prep)953954    def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):955        hook = lambda x, *args, **kwargs: x956        s = requests.Session()957        s.hooks['response'].append(hook)958        r = requests.Request('GET', httpbin())959        prep = s.prepare_request(r)960        assert prep.hooks['response'] != []961        assert prep.hooks['response'] == [hook]962963    def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):964        hook1 = lambda x, *args, **kwargs: x965        hook2 = lambda x, *args, **kwargs: x966        assert hook1 is not hook2967        s = requests.Session()968        s.hooks['response'].append(hook2)969        r = requests.Request('GET', httpbin(), hooks={'response': [hook1]})970        prep = s.prepare_request(r)971        assert prep.hooks['response'] == [hook1]972973    def test_prepared_request_hook(self, httpbin):974        def hook(resp, **kwargs):975            resp.hook_working = True976            return resp977978        req = requests.Request('GET', httpbin(), hooks={'response': hook})979        prep = req.prepare()980981        s = requests.Session()982        s.proxies = getproxies()983        resp = s.send(prep)984985        assert hasattr(resp, 'hook_working')986987    def test_prepared_from_session(self, httpbin):988        class DummyAuth(requests.auth.AuthBase):989            def __call__(self, r):990                r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'991                return r992993        req = requests.Request('GET', httpbin('headers'))994        assert not req.auth995996        s = requests.Session()997        s.auth = DummyAuth()998999        prep = s.prepare_request(req)1000        resp = s.send(prep)10011002        assert resp.json()['headers'][1003            'Dummy-Auth-Test'] == 'dummy-auth-test-ok'10041005    def test_prepare_request_with_bytestring_url(self):1006        req = requests.Request('GET', b'https://httpbin.org/')1007        s = requests.Session()1008        prep = s.prepare_request(req)1009        assert prep.url == "https://httpbin.org/"10101011    def test_request_with_bytestring_host(self, httpbin):1012        s = requests.Session()1013        resp = s.request(1014            'GET',1015            httpbin('cookies/set?cookie=value'),1016            allow_redirects=False,1017            headers={'Host': b'httpbin.org'}1018        )1019        assert resp.cookies.get('cookie') == 'value'10201021    def test_links(self):1022        r = requests.Response()1023        r.headers = {1024            'cache-control': 'public, max-age=60, s-maxage=60',1025            'connection': 'keep-alive',1026            'content-encoding': 'gzip',1027            'content-type': 'application/json; charset=utf-8',1028            'date': 'Sat, 26 Jan 2013 16:47:56 GMT',1029            'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',1030            'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',1031            'link': ('<https://api.github.com/users/kennethreitz/repos?'1032                     'page=2&per_page=10>; rel="next", <https://api.github.'1033                     'com/users/kennethreitz/repos?page=7&per_page=10>; '1034                     ' rel="last"'),1035            'server': 'GitHub.com',1036            'status': '200 OK',1037            'vary': 'Accept',1038            'x-content-type-options': 'nosniff',1039            'x-github-media-type': 'github.beta',1040            'x-ratelimit-limit': '60',1041            'x-ratelimit-remaining': '57'1042        }1043        assert r.links['next']['rel'] == 'next'10441045    def test_cookie_parameters(self):1046        key = 'some_cookie'1047        value = 'some_value'1048        secure = True1049        domain = 'test.com'1050        rest = {'HttpOnly': True}10511052        jar = requests.cookies.RequestsCookieJar()1053        jar.set(key, value, secure=secure, domain=domain, rest=rest)10541055        assert len(jar) == 11056        assert 'some_cookie' in jar10571058        cookie = list(jar)[0]1059        assert cookie.secure == secure1060        assert cookie.domain == domain1061        assert cookie._rest['HttpOnly'] == rest['HttpOnly']10621063    def test_cookie_as_dict_keeps_len(self):1064        key = 'some_cookie'1065        value = 'some_value'10661067        key1 = 'some_cookie1'1068        value1 = 'some_value1'10691070        jar = requests.cookies.RequestsCookieJar()1071        jar.set(key, value)1072        jar.set(key1, value1)10731074        d1 = dict(jar)1075        d2 = dict(jar.iteritems())1076        d3 = dict(jar.items())10771078        assert len(jar) == 21079        assert len(d1) == 21080        assert len(d2) == 21081        assert len(d3) == 210821083    def test_cookie_as_dict_keeps_items(self):1084        key = 'some_cookie'1085        value = 'some_value'10861087        key1 = 'some_cookie1'1088        value1 = 'some_value1'10891090        jar = requests.cookies.RequestsCookieJar()1091        jar.set(key, value)1092        jar.set(key1, value1)10931094        d1 = dict(jar)1095        d2 = dict(jar.iteritems())1096        d3 = dict(jar.items())10971098        assert d1['some_cookie'] == 'some_value'1099        assert d2['some_cookie'] == 'some_value'1100        assert d3['some_cookie1'] == 'some_value1'11011102    def test_cookie_as_dict_keys(self):1103        key = 'some_cookie'1104        value = 'some_value'11051106        key1 = 'some_cookie1'1107        value1 = 'some_value1'11081109        jar = requests.cookies.RequestsCookieJar()1110        jar.set(key, value)1111        jar.set(key1, value1)11121113        keys = jar.keys()1114        assert keys == list(keys)1115        # make sure one can use keys multiple times1116        assert list(keys) == list(keys)11171118    def test_cookie_as_dict_values(self):1119        key = 'some_cookie'1120        value = 'some_value'11211122        key1 = 'some_cookie1'1123        value1 = 'some_value1'11241125        jar = requests.cookies.RequestsCookieJar()1126        jar.set(key, value)1127        jar.set(key1, value1)11281129        values = jar.values()1130        assert values == list(values)1131        # make sure one can use values multiple times1132        assert list(values) == list(values)11331134    def test_cookie_as_dict_items(self):1135        key = 'some_cookie'1136        value = 'some_value'11371138        key1 = 'some_cookie1'1139        value1 = 'some_value1'11401141        jar = requests.cookies.RequestsCookieJar()1142        jar.set(key, value)1143        jar.set(key1, value1)11441145        items = jar.items()1146        assert items == list(items)1147        # make sure one can use items multiple times1148        assert list(items) == list(items)11491150    def test_cookie_duplicate_names_different_domains(self):1151        key = 'some_cookie'1152        value = 'some_value'1153        domain1 = 'test1.com'1154        domain2 = 'test2.com'11551156        jar = requests.cookies.RequestsCookieJar()1157        jar.set(key, value, domain=domain1)1158        jar.set(key, value, domain=domain2)1159        assert key in jar1160        items = jar.items()1161        assert len(items) == 211621163        # Verify that CookieConflictError is raised if domain is not specified1164        with pytest.raises(requests.cookies.CookieConflictError):1165            jar.get(key)11661167        # Verify that CookieConflictError is not raised if domain is specified1168        cookie = jar.get(key, domain=domain1)1169        assert cookie == value11701171    def test_cookie_duplicate_names_raises_cookie_conflict_error(self):1172        key = 'some_cookie'1173        value = 'some_value'1174        path = 'some_path'11751176        jar = requests.cookies.RequestsCookieJar()1177        jar.set(key, value, path=path)1178        jar.set(key, value)1179        with pytest.raises(requests.cookies.CookieConflictError):1180            jar.get(key)11811182    def test_cookie_policy_copy(self):1183        class MyCookiePolicy(cookielib.DefaultCookiePolicy):1184            pass11851186        jar = requests.cookies.RequestsCookieJar()1187        jar.set_policy(MyCookiePolicy())1188        assert isinstance(jar.copy().get_policy(), MyCookiePolicy)11891190    def test_time_elapsed_blank(self, httpbin):1191        r = requests.get(httpbin('get'))1192        td = r.elapsed1193        total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6)1194        assert total_seconds > 0.011951196    def test_empty_response_has_content_none(self):1197        r = requests.Response()1198        assert r.content is None11991200    def test_response_is_iterable(self):1201        r = requests.Response()1202        io = StringIO.StringIO('abc')1203        read_ = io.read12041205        def read_mock(amt, decode_content=None):1206            return read_(amt)1207        setattr(io, 'read', read_mock)1208        r.raw = io1209        assert next(iter(r))1210        io.close()12111212    def test_response_decode_unicode(self):1213        """When called with decode_unicode, Response.iter_content should always1214        return unicode.1215        """1216        r = requests.Response()1217        r._content_consumed = True1218        r._content = b'the content'1219        r.encoding = 'ascii'12201221        chunks = r.iter_content(decode_unicode=True)1222        assert all(isinstance(chunk, str) for chunk in chunks)12231224        # also for streaming1225        r = requests.Response()1226        r.raw = io.BytesIO(b'the content')1227        r.encoding = 'ascii'1228        chunks = r.iter_content(decode_unicode=True)1229        assert all(isinstance(chunk, str) for chunk in chunks)12301231    def test_response_reason_unicode(self):1232        # check for unicode HTTP status1233        r = requests.Response()1234        r.url = u'unicode URL'1235        r.reason = u'Komponenttia ei löydy'.encode('utf-8')1236        r.status_code = 4041237        r.encoding = None1238        assert not r.ok  # old behaviour - crashes here12391240    def test_response_reason_unicode_fallback(self):1241        # check raise_status falls back to ISO-8859-11242        r = requests.Response()1243        r.url = 'some url'1244        reason = u'Komponenttia ei löydy'1245        r.reason = reason.encode('latin-1')1246        r.status_code = 5001247        r.encoding = None1248        with pytest.raises(requests.exceptions.HTTPError) as e:1249            r.raise_for_status()1250        assert reason in e.value.args[0]12511252    def test_response_chunk_size_type(self):1253        """Ensure that chunk_size is passed as None or an integer, otherwise1254        raise a TypeError.1255        """1256        r = requests.Response()1257        r.raw = io.BytesIO(b'the content')1258        chunks = r.iter_content(1)1259        assert all(len(chunk) == 1 for chunk in chunks)12601261        r = requests.Response()1262        r.raw = io.BytesIO(b'the content')1263        chunks = r.iter_content(None)1264        assert list(chunks) == [b'the content']12651266        r = requests.Response()1267        r.raw = io.BytesIO(b'the content')1268        with pytest.raises(TypeError):1269            chunks = r.iter_content("1024")12701271    def test_request_and_response_are_pickleable(self, httpbin):1272        r = requests.get(httpbin('get'))12731274        # verify we can pickle the original request1275        assert pickle.loads(pickle.dumps(r.request))12761277        # verify we can pickle the response and that we have access to1278        # the original request.1279        pr = pickle.loads(pickle.dumps(r))1280        assert r.request.url == pr.request.url1281        assert r.request.headers == pr.request.headers12821283    def test_prepared_request_is_pickleable(self, httpbin):1284        p = requests.Request('GET', httpbin('get')).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_file_is_pickleable(self, httpbin):1298        files = {'file': open(__file__, 'rb')}1299        r = requests.Request('POST', httpbin('post'), files=files)1300        p = r.prepare()13011302        # Verify PreparedRequest can be pickled and unpickled1303        r = pickle.loads(pickle.dumps(p))1304        assert r.url == p.url1305        assert r.headers == p.headers1306        assert r.body == p.body13071308        # Verify unpickled PreparedRequest sends properly1309        s = requests.Session()1310        resp = s.send(r)1311        assert resp.status_code == 20013121313    def test_prepared_request_with_hook_is_pickleable(self, httpbin):1314        r = requests.Request('GET', httpbin('get'), hooks=default_hooks())1315        p = r.prepare()13161317        # Verify PreparedRequest can be pickled1318        r = pickle.loads(pickle.dumps(p))1319        assert r.url == p.url1320        assert r.headers == p.headers1321        assert r.body == p.body1322        assert r.hooks == p.hooks13231324        # Verify unpickled PreparedRequest sends properly1325        s = requests.Session()1326        resp = s.send(r)1327        assert resp.status_code == 20013281329    def test_cannot_send_unprepared_requests(self, httpbin):1330        r = requests.Request(url=httpbin())1331        with pytest.raises(ValueError):1332            requests.Session().send(r)13331334    def test_http_error(self):1335        error = requests.exceptions.HTTPError()1336        assert not error.response1337        response = requests.Response()1338        error = requests.exceptions.HTTPError(response=response)1339        assert error.response == response1340        error = requests.exceptions.HTTPError('message', response=response)1341        assert str(error) == 'message'1342        assert error.response == response13431344    def test_session_pickling(self, httpbin):1345        r = requests.Request('GET', httpbin('get'))1346        s = requests.Session()13471348        s = pickle.loads(pickle.dumps(s))1349        s.proxies = getproxies()13501351        r = s.send(r.prepare())1352        assert r.status_code == 20013531354    def test_fixes_1329(self, httpbin):1355        """Ensure that header updates are done case-insensitively."""1356        s = requests.Session()1357        s.headers.update({'ACCEPT': 'BOGUS'})1358        s.headers.update({'accept': 'application/json'})1359        r = s.get(httpbin('get'))1360        headers = r.request.headers1361        assert headers['accept'] == 'application/json'1362        assert headers['Accept'] == 'application/json'1363        assert headers['ACCEPT'] == 'application/json'13641365    def test_uppercase_scheme_redirect(self, httpbin):1366        parts = urlparse(httpbin('html'))1367        url = "HTTP://" + parts.netloc + parts.path1368        r = requests.get(httpbin('redirect-to'), params={'url': url})1369        assert r.status_code == 2001370        assert r.url.lower() == url.lower()13711372    def test_transport_adapter_ordering(self):1373        s = requests.Session()1374        order = ['https://', 'http://']1375        assert order == list(s.adapters)1376        s.mount('http://git', HTTPAdapter())1377        s.mount('http://github', HTTPAdapter())1378        s.mount('http://github.com', HTTPAdapter())1379        s.mount('http://github.com/about/', HTTPAdapter())1380        order = [1381            'http://github.com/about/',1382            'http://github.com',1383            'http://github',1384            'http://git',1385            'https://',1386            'http://',1387        ]1388        assert order == list(s.adapters)1389        s.mount('http://gittip', HTTPAdapter())1390        s.mount('http://gittip.com', HTTPAdapter())1391        s.mount('http://gittip.com/about/', HTTPAdapter())1392        order = [1393            'http://github.com/about/',1394            'http://gittip.com/about/',1395            'http://github.com',1396            'http://gittip.com',1397            'http://github',1398            'http://gittip',1399            'http://git',1400            'https://',1401            'http://',1402        ]1403        assert order == list(s.adapters)1404        s2 = requests.Session()1405        s2.adapters = {'http://': HTTPAdapter()}1406        s2.mount('https://', HTTPAdapter())1407        assert 'http://' in s2.adapters1408        assert 'https://' in s2.adapters14091410    def test_session_get_adapter_prefix_matching(self):1411        prefix = 'https://example.com'1412        more_specific_prefix = prefix + '/some/path'14131414        url_matching_only_prefix = prefix + '/another/path'1415        url_matching_more_specific_prefix = more_specific_prefix + '/longer/path'1416        url_not_matching_prefix = 'https://another.example.com/'14171418        s = requests.Session()1419        prefix_adapter = HTTPAdapter()1420        more_specific_prefix_adapter = HTTPAdapter()1421        s.mount(prefix, prefix_adapter)1422        s.mount(more_specific_prefix, more_specific_prefix_adapter)14231424        assert s.get_adapter(url_matching_only_prefix) is prefix_adapter1425        assert s.get_adapter(url_matching_more_specific_prefix) is more_specific_prefix_adapter1426        assert s.get_adapter(url_not_matching_prefix) not in (prefix_adapter, more_specific_prefix_adapter)14271428    def test_session_get_adapter_prefix_matching_mixed_case(self):1429        mixed_case_prefix = 'hTtPs://eXamPle.CoM/MixEd_CAse_PREfix'1430        url_matching_prefix = mixed_case_prefix + '/full_url'14311432        s = requests.Session()1433        my_adapter = HTTPAdapter()1434        s.mount(mixed_case_prefix, my_adapter)14351436        assert s.get_adapter(url_matching_prefix) is my_adapter14371438    def test_session_get_adapter_prefix_matching_is_case_insensitive(self):1439        mixed_case_prefix = 'hTtPs://eXamPle.CoM/MixEd_CAse_PREfix'1440        url_matching_prefix_with_different_case = 'HtTpS://exaMPLe.cOm/MiXeD_caSE_preFIX/another_url'14411442        s = requests.Session()1443        my_adapter = HTTPAdapter()1444        s.mount(mixed_case_prefix, my_adapter)14451446        assert s.get_adapter(url_matching_prefix_with_different_case) is my_adapter14471448    def test_header_remove_is_case_insensitive(self, httpbin):1449        # From issue #13211450        s = requests.Session()1451        s.headers['foo'] = 'bar'1452        r = s.get(httpbin('get'), headers={'FOO': None})1453        assert 'foo' not in r.request.headers14541455    def test_params_are_merged_case_sensitive(self, httpbin):1456        s = requests.Session()1457        s.params['foo'] = 'bar'1458        r = s.get(httpbin('get'), params={'FOO': 'bar'})1459        assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}14601461    def test_long_authinfo_in_url(self):1462        url = 'http://{}:{}@{}:9000/path?query#frag'.format(1463            'E8A3BE87-9E3F-4620-8858-95478E385B5B',1464            'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',1465            'exactly-------------sixty-----------three------------characters',1466        )1467        r = requests.Request('GET', url).prepare()1468        assert r.url == url14691470    def test_header_keys_are_native(self, httpbin):1471        headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}1472        r = requests.Request('GET', httpbin('get'), headers=headers)1473        p = r.prepare()14741475        # This is testing that they are builtin strings. A bit weird, but there1476        # we go.1477        assert 'unicode' in p.headers.keys()1478        assert 'byte' in p.headers.keys()14791480    def test_header_validation(self, httpbin):1481        """Ensure prepare_headers regex isn't flagging valid header contents."""1482        headers_ok = {'foo': 'bar baz qux',1483                      'bar': u'fbbq'.encode('utf8'),1484                      'baz': '',1485                      'qux': '1'}1486        r = requests.get(httpbin('get'), headers=headers_ok)1487        assert r.request.headers['foo'] == headers_ok['foo']14881489    def test_header_value_not_str(self, httpbin):1490        """Ensure the header value is of type string or bytes as1491        per discussion in GH issue #33861492        """1493        headers_int = {'foo': 3}1494        headers_dict = {'bar': {'foo': 'bar'}}1495        headers_list = {'baz': ['foo', 'bar']}14961497        # Test for int1498        with pytest.raises(InvalidHeader) as excinfo:1499            r = requests.get(httpbin('get'), headers=headers_int)1500        assert 'foo' in str(excinfo.value)1501        # Test for dict1502        with pytest.raises(InvalidHeader) as excinfo:1503            r = requests.get(httpbin('get'), headers=headers_dict)1504        assert 'bar' in str(excinfo.value)1505        # Test for list1506        with pytest.raises(InvalidHeader) as excinfo:1507            r = requests.get(httpbin('get'), headers=headers_list)1508        assert 'baz' in str(excinfo.value)15091510    def test_header_no_return_chars(self, httpbin):1511        """Ensure that a header containing return character sequences raise an1512        exception. Otherwise, multiple headers are created from single string.1513        """1514        headers_ret = {'foo': 'bar\r\nbaz: qux'}1515        headers_lf = {'foo': 'bar\nbaz: qux'}1516        headers_cr = {'foo': 'bar\rbaz: qux'}15171518        # Test for newline1519        with pytest.raises(InvalidHeader):1520            r = requests.get(httpbin('get'), headers=headers_ret)1521        # Test for line feed1522        with pytest.raises(InvalidHeader):1523            r = requests.get(httpbin('get'), headers=headers_lf)1524        # Test for carriage return1525        with pytest.raises(InvalidHeader):1526            r = requests.get(httpbin('get'), headers=headers_cr)15271528    def test_header_no_leading_space(self, httpbin):1529        """Ensure headers containing leading whitespace raise1530        InvalidHeader Error before sending.1531        """1532        headers_space = {'foo': ' bar'}1533        headers_tab = {'foo': '   bar'}15341535        # Test for whitespace1536        with pytest.raises(InvalidHeader):1537            r = requests.get(httpbin('get'), headers=headers_space)1538        # Test for tab1539        with pytest.raises(InvalidHeader):1540            r = requests.get(httpbin('get'), headers=headers_tab)15411542    @pytest.mark.parametrize('files', ('foo', b'foo', bytearray(b'foo')))1543    def test_can_send_objects_with_files(self, httpbin, files):1544        data = {'a': 'this is a string'}1545        files = {'b': files}1546        r = requests.Request('POST', httpbin('post'), data=data, files=files)1547        p = r.prepare()1548        assert 'multipart/form-data' in p.headers['Content-Type']15491550    def test_can_send_file_object_with_non_string_filename(self, httpbin):1551        f = io.BytesIO()1552        f.name = 21553        r = requests.Request('POST', httpbin('post'), files={'f': f})1554        p = r.prepare()15551556        assert 'multipart/form-data' in p.headers['Content-Type']15571558    def test_autoset_header_values_are_native(self, httpbin):1559        data = 'this is a string'1560        length = '16'1561        req = requests.Request('POST', httpbin('post'), data=data)1562        p = req.prepare()15631564        assert p.headers['Content-Length'] == length15651566    def test_nonhttp_schemes_dont_check_URLs(self):1567        test_urls = (1568            'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',1569            'file:///etc/passwd',1570            'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',1571        )1572        for test_url in test_urls:1573            req = requests.Request('GET', test_url)1574            preq = req.prepare()1575            assert test_url == preq.url15761577    def test_auth_is_stripped_on_http_downgrade(self, httpbin, httpbin_secure, httpbin_ca_bundle):1578        r = requests.get(1579            httpbin_secure('redirect-to'),1580            params={'url': httpbin('get')},1581            auth=('user', 'pass'),1582            verify=httpbin_ca_bundle1583        )1584        assert r.history[0].request.headers['Authorization']1585        assert 'Authorization' not in r.request.headers15861587    def test_auth_is_retained_for_redirect_on_host(self, httpbin):1588        r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))1589        h1 = r.history[0].request.headers['Authorization']1590        h2 = r.request.headers['Authorization']15911592        assert h1 == h215931594    def test_should_strip_auth_host_change(self):1595        s = requests.Session()1596        assert s.should_strip_auth('http://example.com/foo', 'http://another.example.com/')15971598    def test_should_strip_auth_http_downgrade(self):1599        s = requests.Session()1600        assert s.should_strip_auth('https://example.com/foo', 'http://example.com/bar')16011602    def test_should_strip_auth_https_upgrade(self):1603        s = requests.Session()1604        assert not s.should_strip_auth('http://example.com/foo', 'https://example.com/bar')1605        assert not s.should_strip_auth('http://example.com:80/foo', 'https://example.com/bar')1606        assert not s.should_strip_auth('http://example.com/foo', 'https://example.com:443/bar')1607        # Non-standard ports should trigger stripping1608        assert s.should_strip_auth('http://example.com:8080/foo', 'https://example.com/bar')1609        assert s.should_strip_auth('http://example.com/foo', 'https://example.com:8443/bar')16101611    def test_should_strip_auth_port_change(self):1612        s = requests.Session()1613        assert s.should_strip_auth('http://example.com:1234/foo', 'https://example.com:4321/bar')16141615    @pytest.mark.parametrize(1616        'old_uri, new_uri', (1617            ('https://example.com:443/foo', 'https://example.com/bar'),1618            ('http://example.com:80/foo', 'http://example.com/bar'),1619            ('https://example.com/foo', 'https://example.com:443/bar'),1620            ('http://example.com/foo', 'http://example.com:80/bar')1621        ))1622    def test_should_strip_auth_default_port(self, old_uri, new_uri):1623        s = requests.Session()1624        assert not s.should_strip_auth(old_uri, new_uri)16251626    def test_manual_redirect_with_partial_body_read(self, httpbin):1627        s = requests.Session()1628        r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)1629        assert r1.is_redirect1630        rg = s.resolve_redirects(r1, r1.request, stream=True)16311632        # read only the first eight bytes of the response body,1633        # then follow the redirect1634        r1.iter_content(8)1635        r2 = next(rg)1636        assert r2.is_redirect16371638        # read all of the response via iter_content,1639        # then follow the redirect1640        for _ in r2.iter_content():1641            pass1642        r3 = next(rg)1643        assert not r3.is_redirect16441645    def test_prepare_body_position_non_stream(self):1646        data = b'the data'1647        prep = requests.Request('GET', 'http://example.com', data=data).prepare()1648        assert prep._body_position is None16491650    def test_rewind_body(self):1651        data = io.BytesIO(b'the data')1652        prep = requests.Request('GET', 'http://example.com', data=data).prepare()1653        assert prep._body_position == 01654        assert prep.body.read() == b'the data'16551656        # the data has all been read1657        assert prep.body.read() == b''16581659        # rewind it back1660        requests.utils.rewind_body(prep)1661        assert prep.body.read() == b'the data'16621663    def test_rewind_partially_read_body(self):1664        data = io.BytesIO(b'the data')1665        data.read(4)  # read some data1666        prep = requests.Request('GET', 'http://example.com', data=data).prepare()1667        assert prep._body_position == 41668        assert prep.body.read() == b'data'16691670        # the data has all been read1671        assert prep.body.read() == b''16721673        # rewind it back1674        requests.utils.rewind_body(prep)1675        assert prep.body.read() == b'data'16761677    def test_rewind_body_no_seek(self):1678        class BadFileObj:1679            def __init__(self, data):1680                self.data = data16811682            def tell(self):1683                return 016841685            def __iter__(self):1686                return16871688        data = BadFileObj('the data')1689        prep = requests.Request('GET', 'http://example.com', data=data).prepare()1690        assert prep._body_position == 016911692        with pytest.raises(UnrewindableBodyError) as e:1693            requests.utils.rewind_body(prep)16941695        assert 'Unable to rewind request body' in str(e)16961697    def test_rewind_body_failed_seek(self):1698        class BadFileObj:1699            def __init__(self, data):1700                self.data = data17011702            def tell(self):1703                return 017041705            def seek(self, pos, whence=0):1706                raise OSError()17071708            def __iter__(self):1709                return17101711        data = BadFileObj('the data')1712        prep = requests.Request('GET', 'http://example.com', data=data).prepare()1713        assert prep._body_position == 017141715        with pytest.raises(UnrewindableBodyError) as e:1716            requests.utils.rewind_body(prep)17171718        assert 'error occurred when rewinding request body' in str(e)17191720    def test_rewind_body_failed_tell(self):1721        class BadFileObj:1722            def __init__(self, data):1723                self.data = data17241725            def tell(self):1726                raise OSError()17271728            def __iter__(self):1729                return17301731        data = BadFileObj('the data')1732        prep = requests.Request('GET', 'http://example.com', data=data).prepare()1733        assert prep._body_position is not None17341735        with pytest.raises(UnrewindableBodyError) as e:1736            requests.utils.rewind_body(prep)17371738        assert 'Unable to rewind request body' in str(e)17391740    def _patch_adapter_gzipped_redirect(self, session, url):1741        adapter = session.get_adapter(url=url)1742        org_build_response = adapter.build_response1743        self._patched_response = False17441745        def build_response(*args, **kwargs):1746            resp = org_build_response(*args, **kwargs)1747            if not self._patched_response:1748                resp.raw.headers['content-encoding'] = 'gzip'1749                self._patched_response = True1750            return resp17511752        adapter.build_response = build_response17531754    def test_redirect_with_wrong_gzipped_header(self, httpbin):1755        s = requests.Session()1756        url = httpbin('redirect/1')1757        self._patch_adapter_gzipped_redirect(s, url)1758        s.get(url)17591760    @pytest.mark.parametrize(1761        'username, password, auth_str', (1762            ('test', 'test', 'Basic dGVzdDp0ZXN0'),1763            (u'имя'.encode('utf-8'), u'пароль'.encode('utf-8'), 'Basic 0LjQvNGPOtC/0LDRgNC+0LvRjA=='),1764        ))1765    def test_basic_auth_str_is_always_native(self, username, password, auth_str):1766        s = _basic_auth_str(username, password)1767        assert isinstance(s, builtin_str)1768        assert s == auth_str17691770    def test_requests_history_is_saved(self, httpbin):1771        r = requests.get(httpbin('redirect/5'))1772        total = r.history[-1].history1773        i = 01774        for item in r.history:1775            assert item.history == total[0:i]1776            i += 117771778    def test_json_param_post_content_type_works(self, httpbin):1779        r = requests.post(1780            httpbin('post'),1781            json={'life': 42}1782        )1783        assert r.status_code == 2001784        assert 'application/json' in r.request.headers['Content-Type']1785        assert {'life': 42} == r.json()['json']17861787    def test_json_param_post_should_not_override_data_param(self, httpbin):1788        r = requests.Request(method='POST', url=httpbin('post'),1789                             data={'stuff': 'elixr'},1790                             json={'music': 'flute'})1791        prep = r.prepare()1792        assert 'stuff=elixr' == prep.body17931794    def test_response_iter_lines(self, httpbin):1795        r = requests.get(httpbin('stream/4'), stream=True)1796        assert r.status_code == 20017971798        it = r.iter_lines()1799        next(it)1800        assert len(list(it)) == 318011802    def test_response_context_manager(self, httpbin):1803        with requests.get(httpbin('stream/4'), stream=True) as response:1804            assert isinstance(response, requests.Response)18051806        assert response.raw.closed18071808    def test_unconsumed_session_response_closes_connection(self, httpbin):1809        s = requests.session()18101811        with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1812            pass18131814        assert response._content_consumed is False1815        assert response.raw.closed18161817    @pytest.mark.xfail1818    def test_response_iter_lines_reentrant(self, httpbin):1819        """Response.iter_lines() is not reentrant safe"""1820        r = requests.get(httpbin('stream/4'), stream=True)1821        assert r.status_code == 20018221823        next(r.iter_lines())1824        assert len(list(r.iter_lines())) == 318251826    def test_session_close_proxy_clear(self, mocker):1827        proxies = {1828          'one': mocker.Mock(),1829          'two': mocker.Mock(),1830        }1831        session = requests.Session()1832        mocker.patch.dict(session.adapters['http://'].proxy_manager, proxies)1833        session.close()1834        proxies['one'].clear.assert_called_once_with()1835        proxies['two'].clear.assert_called_once_with()18361837    def test_proxy_auth(self):1838        adapter = HTTPAdapter()1839        headers = adapter.proxy_headers("http://user:pass@httpbin.org")1840        assert headers == {'Proxy-Authorization': 'Basic dXNlcjpwYXNz'}18411842    def test_proxy_auth_empty_pass(self):1843        adapter = HTTPAdapter()1844        headers = adapter.proxy_headers("http://user:@httpbin.org")1845        assert headers == {'Proxy-Authorization': 'Basic dXNlcjo='}18461847    def test_response_json_when_content_is_None(self, httpbin):1848        r = requests.get(httpbin('/status/204'))1849        # Make sure r.content is None1850        r.status_code = 01851        r._content = False1852        r._content_consumed = False18531854        assert r.content is None1855        with pytest.raises(ValueError):1856            r.json()18571858    def test_response_without_release_conn(self):1859        """Test `close` call for non-urllib3-like raw objects.1860        Should work when `release_conn` attr doesn't exist on `response.raw`.1861        """1862        resp = requests.Response()1863        resp.raw = StringIO.StringIO('test')1864        assert not resp.raw.closed1865        resp.close()1866        assert resp.raw.closed18671868    def test_empty_stream_with_auth_does_not_set_content_length_header(self, httpbin):1869        """Ensure that a byte stream with size 0 will not set both a Content-Length1870        and Transfer-Encoding header.1871        """1872        auth = ('user', 'pass')1873        url = httpbin('post')1874        file_obj = io.BytesIO(b'')1875        r = requests.Request('POST', url, auth=auth, data=file_obj)1876        prepared_request = r.prepare()1877        assert 'Transfer-Encoding' in prepared_request.headers1878        assert 'Content-Length' not in prepared_request.headers18791880    def test_stream_with_auth_does_not_set_transfer_encoding_header(self, httpbin):1881        """Ensure that a byte stream with size > 0 will not set both a Content-Length1882        and Transfer-Encoding header.1883        """1884        auth = ('user', 'pass')1885        url = httpbin('post')1886        file_obj = io.BytesIO(b'test data')1887        r = requests.Request('POST', url, auth=auth, data=file_obj)1888        prepared_request = r.prepare()1889        assert 'Transfer-Encoding' not in prepared_request.headers1890        assert 'Content-Length' in prepared_request.headers18911892    def test_chunked_upload_does_not_set_content_length_header(self, httpbin):1893        """Ensure that requests with a generator body stream using1894        Transfer-Encoding: chunked, not a Content-Length header.1895        """1896        data = (i for i in [b'a', b'b', b'c'])1897        url = httpbin('post')1898        r = requests.Request('POST', url, data=data)1899        prepared_request = r.prepare()1900        assert 'Transfer-Encoding' in prepared_request.headers1901        assert 'Content-Length' not in prepared_request.headers19021903    def test_custom_redirect_mixin(self, httpbin):1904        """Tests a custom mixin to overwrite ``get_redirect_target``.19051906        Ensures a subclassed ``requests.Session`` can handle a certain type of1907        malformed redirect responses.19081909        1. original request receives a proper response: 302 redirect1910        2. following the redirect, a malformed response is given:1911            status code = HTTP 2001912            location = alternate url1913        3. the custom session catches the edge case and follows the redirect1914        """1915        url_final = httpbin('html')1916        querystring_malformed = urlencode({'location': url_final})1917        url_redirect_malformed = httpbin('response-headers?%s' % querystring_malformed)1918        querystring_redirect = urlencode({'url': url_redirect_malformed})1919        url_redirect = httpbin('redirect-to?%s' % querystring_redirect)1920        urls_test = [url_redirect,1921                     url_redirect_malformed,1922                     url_final,1923                     ]19241925        class CustomRedirectSession(requests.Session):1926            def get_redirect_target(self, resp):1927                # default behavior1928                if resp.is_redirect:1929                    return resp.headers['location']1930                # edge case - check to see if 'location' is in headers anyways1931                location = resp.headers.get('location')1932                if location and (location != resp.url):1933                    return location1934                return None19351936        session = CustomRedirectSession()1937        r = session.get(urls_test[0])1938        assert len(r.history) == 21939        assert r.status_code == 2001940        assert r.history[0].status_code == 3021941        assert r.history[0].is_redirect1942        assert r.history[1].status_code == 2001943        assert not r.history[1].is_redirect1944        assert r.url == urls_test[2]194519461947class TestCaseInsensitiveDict:19481949    @pytest.mark.parametrize(1950        'cid', (1951            CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}),1952            CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')]),1953            CaseInsensitiveDict(FOO='foo', BAr='bar'),1954        ))1955    def test_init(self, cid):1956        assert len(cid) == 21957        assert 'foo' in cid1958        assert 'bar' in cid19591960    def test_docstring_example(self):1961        cid = CaseInsensitiveDict()1962        cid['Accept'] = 'application/json'1963        assert cid['aCCEPT'] == 'application/json'1964        assert list(cid) == ['Accept']19651966    def test_len(self):1967        cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1968        cid['A'] = 'a'1969        assert len(cid) == 219701971    def test_getitem(self):1972        cid = CaseInsensitiveDict({'Spam': 'blueval'})1973        assert cid['spam'] == 'blueval'1974        assert cid['SPAM'] == 'blueval'19751976    def test_fixes_649(self):1977        """__setitem__ should behave case-insensitively."""1978        cid = CaseInsensitiveDict()1979        cid['spam'] = 'oneval'1980        cid['Spam'] = 'twoval'1981        cid['sPAM'] = 'redval'1982        cid['SPAM'] = 'blueval'1983        assert cid['spam'] == 'blueval'1984        assert cid['SPAM'] == 'blueval'1985        assert list(cid.keys()) == ['SPAM']19861987    def test_delitem(self):1988        cid = CaseInsensitiveDict()1989        cid['Spam'] = 'someval'1990        del cid['sPam']1991        assert 'spam' not in cid1992        assert len(cid) == 019931994    def test_contains(self):1995        cid = CaseInsensitiveDict()1996        cid['Spam'] = 'someval'1997        assert 'Spam' in cid1998        assert 'spam' in cid1999        assert 'SPAM' in cid2000        assert 'sPam' in cid

The first 2,000 of 2,527 lines.