Skip to content
Myr

test_requests.py

This file

Path

test_requests.py

1,639 lines · 54.9 KiB · Python

Last changed by

Merge pull request #2478 from plaes/iter-linesCory Benfieldbefore adoption14b653a

History of this file

Take it

1#!/usr/bin/env python2# -*- coding: utf-8 -*-34"""Tests for Requests."""56from __future__ import division7import json8import os9import pickle10import unittest11import collections1213import io14import requests15import pytest16from requests.adapters import HTTPAdapter17from requests.auth import HTTPDigestAuth, _basic_auth_str18from requests.compat import (19    Morsel, cookielib, getproxies, str, urljoin, urlparse, is_py3, builtin_str)20from requests.cookies import cookiejar_from_dict, morsel_to_cookie21from requests.exceptions import (ConnectionError, ConnectTimeout,22                                 InvalidSchema, InvalidURL, MissingSchema,23                                 ReadTimeout, Timeout, RetryError)24from requests.models import PreparedRequest25from requests.structures import CaseInsensitiveDict26from requests.sessions import SessionRedirectMixin27from requests.models import urlencode28from requests.hooks import default_hooks2930try:31    import StringIO32except ImportError:33    import io as StringIO3435if is_py3:36    def u(s):37        return s38else:39    def u(s):40        return s.decode('unicode-escape')414243# Requests to this URL should always fail with a connection timeout (nothing44# listening on that port)45TARPIT = "http://10.255.255.1"46HTTPBIN = os.environ.get('HTTPBIN_URL', 'http://httpbin.org/')47# Issue #1483: Make sure the URL always has a trailing slash48HTTPBIN = HTTPBIN.rstrip('/') + '/'495051def httpbin(*suffix):52    """Returns url for HTTPBIN resource."""53    return urljoin(HTTPBIN, '/'.join(suffix))545556class RequestsTestCase(unittest.TestCase):5758    _multiprocess_can_split_ = True5960    def setUp(self):61        """Create simple data set with headers."""62        pass6364    def tearDown(self):65        """Teardown."""66        pass6768    def test_entry_points(self):6970        requests.session71        requests.session().get72        requests.session().head73        requests.get74        requests.head75        requests.put76        requests.patch77        requests.post7879    def test_invalid_url(self):80        with pytest.raises(MissingSchema):81            requests.get('hiwpefhipowhefopw')82        with pytest.raises(InvalidSchema):83            requests.get('localhost:3128')84        with pytest.raises(InvalidSchema):85            requests.get('localhost.localdomain:3128/')86        with pytest.raises(InvalidSchema):87            requests.get('10.122.1.1:3128/')88        with pytest.raises(InvalidURL):89            requests.get('http://')9091    def test_basic_building(self):92        req = requests.Request()93        req.url = 'http://kennethreitz.org/'94        req.data = {'life': '42'}9596        pr = req.prepare()97        assert pr.url == req.url98        assert pr.body == 'life=42'99100    def test_no_content_length(self):101        get_req = requests.Request('GET', httpbin('get')).prepare()102        assert 'Content-Length' not in get_req.headers103        head_req = requests.Request('HEAD', httpbin('head')).prepare()104        assert 'Content-Length' not in head_req.headers105106    def test_override_content_length(self):107        headers = {108            'Content-Length': 'not zero'109        }110        r = requests.Request('POST', httpbin('post'), headers=headers).prepare()111        assert 'Content-Length' in r.headers112        assert r.headers['Content-Length'] == 'not zero'113114    def test_path_is_not_double_encoded(self):115        request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()116117        assert request.path_url == '/get/test%20case'118119    def test_params_are_added_before_fragment(self):120        request = requests.Request('GET',121            "http://example.com/path#fragment", params={"a": "b"}).prepare()122        assert request.url == "http://example.com/path?a=b#fragment"123        request = requests.Request('GET',124            "http://example.com/path?key=value#fragment", params={"a": "b"}).prepare()125        assert request.url == "http://example.com/path?key=value&a=b#fragment"126127    def test_mixed_case_scheme_acceptable(self):128        s = requests.Session()129        s.proxies = getproxies()130        parts = urlparse(httpbin('get'))131        schemes = ['http://', 'HTTP://', 'hTTp://', 'HttP://',132                   'https://', 'HTTPS://', 'hTTps://', 'HttPs://']133        for scheme in schemes:134            url = scheme + parts.netloc + parts.path135            r = requests.Request('GET', url)136            r = s.send(r.prepare())137            assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)138139    def test_HTTP_200_OK_GET_ALTERNATIVE(self):140        r = requests.Request('GET', httpbin('get'))141        s = requests.Session()142        s.proxies = getproxies()143144        r = s.send(r.prepare())145146        assert r.status_code == 200147148    def test_HTTP_302_ALLOW_REDIRECT_GET(self):149        r = requests.get(httpbin('redirect', '1'))150        assert r.status_code == 200151        assert r.history[0].status_code == 302152        assert r.history[0].is_redirect153154    # def test_HTTP_302_ALLOW_REDIRECT_POST(self):155    #     r = requests.post(httpbin('status', '302'), data={'some': 'data'})156    #     self.assertEqual(r.status_code, 200)157158    def test_HTTP_200_OK_GET_WITH_PARAMS(self):159        heads = {'User-agent': 'Mozilla/5.0'}160161        r = requests.get(httpbin('user-agent'), headers=heads)162163        assert heads['User-agent'] in r.text164        assert r.status_code == 200165166    def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):167        heads = {'User-agent': 'Mozilla/5.0'}168169        r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)170        assert r.status_code == 200171172    def test_set_cookie_on_301(self):173        s = requests.session()174        url = httpbin('cookies/set?foo=bar')175        s.get(url)176        assert s.cookies['foo'] == 'bar'177178    def test_cookie_sent_on_redirect(self):179        s = requests.session()180        s.get(httpbin('cookies/set?foo=bar'))181        r = s.get(httpbin('redirect/1'))  # redirects to httpbin('get')182        assert 'Cookie' in r.json()['headers']183184    def test_cookie_removed_on_expire(self):185        s = requests.session()186        s.get(httpbin('cookies/set?foo=bar'))187        assert s.cookies['foo'] == 'bar'188        s.get(189            httpbin('response-headers'),190            params={191                'Set-Cookie':192                    'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'193            }194        )195        assert 'foo' not in s.cookies196197    def test_cookie_quote_wrapped(self):198        s = requests.session()199        s.get(httpbin('cookies/set?foo="bar:baz"'))200        assert s.cookies['foo'] == '"bar:baz"'201202    def test_cookie_persists_via_api(self):203        s = requests.session()204        r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})205        assert 'foo' in r.request.headers['Cookie']206        assert 'foo' in r.history[0].request.headers['Cookie']207208    def test_request_cookie_overrides_session_cookie(self):209        s = requests.session()210        s.cookies['foo'] = 'bar'211        r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})212        assert r.json()['cookies']['foo'] == 'baz'213        # Session cookie should not be modified214        assert s.cookies['foo'] == 'bar'215216    def test_request_cookies_not_persisted(self):217        s = requests.session()218        s.get(httpbin('cookies'), cookies={'foo': 'baz'})219        # Sending a request with cookies should not add cookies to the session220        assert not s.cookies221222    def test_generic_cookiejar_works(self):223        cj = cookielib.CookieJar()224        cookiejar_from_dict({'foo': 'bar'}, cj)225        s = requests.session()226        s.cookies = cj227        r = s.get(httpbin('cookies'))228        # Make sure the cookie was sent229        assert r.json()['cookies']['foo'] == 'bar'230        # Make sure the session cj is still the custom one231        assert s.cookies is cj232233    def test_param_cookiejar_works(self):234        cj = cookielib.CookieJar()235        cookiejar_from_dict({'foo': 'bar'}, cj)236        s = requests.session()237        r = s.get(httpbin('cookies'), cookies=cj)238        # Make sure the cookie was sent239        assert r.json()['cookies']['foo'] == 'bar'240241    def test_requests_in_history_are_not_overridden(self):242        resp = requests.get(httpbin('redirect/3'))243        urls = [r.url for r in resp.history]244        req_urls = [r.request.url for r in resp.history]245        assert urls == req_urls246247    def test_history_is_always_a_list(self):248        """249        Show that even with redirects, Response.history is always a list.250        """251        resp = requests.get(httpbin('get'))252        assert isinstance(resp.history, list)253        resp = requests.get(httpbin('redirect/1'))254        assert isinstance(resp.history, list)255        assert not isinstance(resp.history, tuple)256257    def test_headers_on_session_with_None_are_not_sent(self):258        """Do not send headers in Session.headers with None values."""259        ses = requests.Session()260        ses.headers['Accept-Encoding'] = None261        req = requests.Request('GET', httpbin('get'))262        prep = ses.prepare_request(req)263        assert 'Accept-Encoding' not in prep.headers264265    def test_user_agent_transfers(self):266267        heads = {268            'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'269        }270271        r = requests.get(httpbin('user-agent'), headers=heads)272        assert heads['User-agent'] in r.text273274        heads = {275            'user-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'276        }277278        r = requests.get(httpbin('user-agent'), headers=heads)279        assert heads['user-agent'] in r.text280281    def test_HTTP_200_OK_HEAD(self):282        r = requests.head(httpbin('get'))283        assert r.status_code == 200284285    def test_HTTP_200_OK_PUT(self):286        r = requests.put(httpbin('put'))287        assert r.status_code == 200288289    def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):290        auth = ('user', 'pass')291        url = httpbin('basic-auth', 'user', 'pass')292293        r = requests.get(url, auth=auth)294        assert r.status_code == 200295296        r = requests.get(url)297        assert r.status_code == 401298299        s = requests.session()300        s.auth = auth301        r = s.get(url)302        assert r.status_code == 200303304    def test_connection_error_invalid_domain(self):305        """Connecting to an unknown domain should raise a ConnectionError"""306        with pytest.raises(ConnectionError):307            requests.get("http://doesnotexist.google.com")308309    def test_connection_error_invalid_port(self):310        """Connecting to an invalid port should raise a ConnectionError"""311        with pytest.raises(ConnectionError):312            requests.get("http://httpbin.org:1", timeout=1)313314    def test_LocationParseError(self):315        """Inputing a URL that cannot be parsed should raise an InvalidURL error"""316        with pytest.raises(InvalidURL):317            requests.get("http://fe80::5054:ff:fe5a:fc0")318319    def test_basicauth_with_netrc(self):320        auth = ('user', 'pass')321        wrong_auth = ('wronguser', 'wrongpass')322        url = httpbin('basic-auth', 'user', 'pass')323324        def get_netrc_auth_mock(url):325            return auth326        requests.sessions.get_netrc_auth = get_netrc_auth_mock327328        # Should use netrc and work.329        r = requests.get(url)330        assert r.status_code == 200331332        # Given auth should override and fail.333        r = requests.get(url, auth=wrong_auth)334        assert r.status_code == 401335336        s = requests.session()337338        # Should use netrc and work.339        r = s.get(url)340        assert r.status_code == 200341342        # Given auth should override and fail.343        s.auth = wrong_auth344        r = s.get(url)345        assert r.status_code == 401346347    def test_DIGEST_HTTP_200_OK_GET(self):348349        auth = HTTPDigestAuth('user', 'pass')350        url = httpbin('digest-auth', 'auth', 'user', 'pass')351352        r = requests.get(url, auth=auth)353        assert r.status_code == 200354355        r = requests.get(url)356        assert r.status_code == 401357358        s = requests.session()359        s.auth = HTTPDigestAuth('user', 'pass')360        r = s.get(url)361        assert r.status_code == 200362363    def test_DIGEST_AUTH_RETURNS_COOKIE(self):364        url = httpbin('digest-auth', 'auth', 'user', 'pass')365        auth = HTTPDigestAuth('user', 'pass')366        r = requests.get(url)367        assert r.cookies['fake'] == 'fake_value'368369        r = requests.get(url, auth=auth)370        assert r.status_code == 200371372    def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self):373        url = httpbin('digest-auth', 'auth', 'user', 'pass')374        auth = HTTPDigestAuth('user', 'pass')375        s = requests.Session()376        s.get(url, auth=auth)377        assert s.cookies['fake'] == 'fake_value'378379    def test_DIGEST_STREAM(self):380381        auth = HTTPDigestAuth('user', 'pass')382        url = httpbin('digest-auth', 'auth', 'user', 'pass')383384        r = requests.get(url, auth=auth, stream=True)385        assert r.raw.read() != b''386387        r = requests.get(url, auth=auth, stream=False)388        assert r.raw.read() == b''389390    def test_DIGESTAUTH_WRONG_HTTP_401_GET(self):391392        auth = HTTPDigestAuth('user', 'wrongpass')393        url = httpbin('digest-auth', 'auth', 'user', 'pass')394395        r = requests.get(url, auth=auth)396        assert r.status_code == 401397398        r = requests.get(url)399        assert r.status_code == 401400401        s = requests.session()402        s.auth = auth403        r = s.get(url)404        assert r.status_code == 401405406    def test_DIGESTAUTH_QUOTES_QOP_VALUE(self):407408        auth = HTTPDigestAuth('user', 'pass')409        url = httpbin('digest-auth', 'auth', 'user', 'pass')410411        r = requests.get(url, auth=auth)412        assert '"auth"' in r.request.headers['Authorization']413414    def test_POSTBIN_GET_POST_FILES(self):415416        url = httpbin('post')417        post1 = requests.post(url).raise_for_status()418419        post1 = requests.post(url, data={'some': 'data'})420        assert post1.status_code == 200421422        with open('requirements.txt') as f:423            post2 = requests.post(url, files={'some': f})424        assert post2.status_code == 200425426        post4 = requests.post(url, data='[{"some": "json"}]')427        assert post4.status_code == 200428429        with pytest.raises(ValueError):430            requests.post(url, files=['bad file data'])431432    def test_POSTBIN_GET_POST_FILES_WITH_DATA(self):433434        url = httpbin('post')435        post1 = requests.post(url).raise_for_status()436437        post1 = requests.post(url, data={'some': 'data'})438        assert post1.status_code == 200439440        with open('requirements.txt') as f:441            post2 = requests.post(url,442                data={'some': 'data'}, files={'some': f})443        assert post2.status_code == 200444445        post4 = requests.post(url, data='[{"some": "json"}]')446        assert post4.status_code == 200447448        with pytest.raises(ValueError):449            requests.post(url, files=['bad file data'])450451    def test_conflicting_post_params(self):452        url = httpbin('post')453        with open('requirements.txt') as f:454            pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")455            pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")456457    def test_request_ok_set(self):458        r = requests.get(httpbin('status', '404'))459        assert not r.ok460461    def test_status_raising(self):462        r = requests.get(httpbin('status', '404'))463        with pytest.raises(requests.exceptions.HTTPError):464            r.raise_for_status()465466        r = requests.get(httpbin('status', '500'))467        assert not r.ok468469    def test_decompress_gzip(self):470        r = requests.get(httpbin('gzip'))471        r.content.decode('ascii')472473    def test_unicode_get(self):474        url = httpbin('/get')475        requests.get(url, params={'foo': 'føø'})476        requests.get(url, params={'føø': 'føø'})477        requests.get(url, params={'føø': 'føø'})478        requests.get(url, params={'foo': 'foo'})479        requests.get(httpbin('ø'), params={'foo': 'foo'})480481    def test_unicode_header_name(self):482        requests.put(483            httpbin('put'),484            headers={str('Content-Type'): 'application/octet-stream'},485            data='\xff')  # compat.str is unicode.486487    def test_pyopenssl_redirect(self):488        requests.get('https://httpbin.org/status/301')489490    def test_urlencoded_get_query_multivalued_param(self):491492        r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))493        assert r.status_code == 200494        assert r.url == httpbin('get?test=foo&test=baz')495496    def test_different_encodings_dont_break_post(self):497        r = requests.post(httpbin('post'),498            data={'stuff': json.dumps({'a': 123})},499            params={'blah': 'asdf1234'},500            files={'file': ('test_requests.py', open(__file__, 'rb'))})501        assert r.status_code == 200502503    def test_unicode_multipart_post(self):504        r = requests.post(httpbin('post'),505            data={'stuff': u('ëlïxr')},506            files={'file': ('test_requests.py', open(__file__, 'rb'))})507        assert r.status_code == 200508509        r = requests.post(httpbin('post'),510            data={'stuff': u('ëlïxr').encode('utf-8')},511            files={'file': ('test_requests.py', open(__file__, 'rb'))})512        assert r.status_code == 200513514        r = requests.post(httpbin('post'),515            data={'stuff': 'elixr'},516            files={'file': ('test_requests.py', open(__file__, 'rb'))})517        assert r.status_code == 200518519        r = requests.post(httpbin('post'),520            data={'stuff': 'elixr'.encode('utf-8')},521            files={'file': ('test_requests.py', open(__file__, 'rb'))})522        assert r.status_code == 200523524    def test_unicode_multipart_post_fieldnames(self):525        filename = os.path.splitext(__file__)[0] + '.py'526        r = requests.Request(method='POST',527                             url=httpbin('post'),528                             data={'stuff'.encode('utf-8'): 'elixr'},529                             files={'file': ('test_requests.py',530                                             open(filename, 'rb'))})531        prep = r.prepare()532        assert b'name="stuff"' in prep.body533        assert b'name="b\'stuff\'"' not in prep.body534535    def test_unicode_method_name(self):536        files = {'file': open('test_requests.py', 'rb')}537        r = requests.request(538            method=u('POST'), url=httpbin('post'), files=files)539        assert r.status_code == 200540541    def test_custom_content_type(self):542        r = requests.post(543            httpbin('post'),544            data={'stuff': json.dumps({'a': 123})},545            files={'file1': ('test_requests.py', open(__file__, 'rb')),546                   'file2': ('test_requests', open(__file__, 'rb'),547                             'text/py-content-type')})548        assert r.status_code == 200549        assert b"text/py-content-type" in r.request.body550551    def test_hook_receives_request_arguments(self):552        def hook(resp, **kwargs):553            assert resp is not None554            assert kwargs != {}555556        requests.Request('GET', HTTPBIN, hooks={'response': hook})557558    def test_session_hooks_are_used_with_no_request_hooks(self):559        hook = lambda x, *args, **kwargs: x560        s = requests.Session()561        s.hooks['response'].append(hook)562        r = requests.Request('GET', HTTPBIN)563        prep = s.prepare_request(r)564        assert prep.hooks['response'] != []565        assert prep.hooks['response'] == [hook]566567    def test_session_hooks_are_overriden_by_request_hooks(self):568        hook1 = lambda x, *args, **kwargs: x569        hook2 = lambda x, *args, **kwargs: x570        assert hook1 is not hook2571        s = requests.Session()572        s.hooks['response'].append(hook2)573        r = requests.Request('GET', HTTPBIN, hooks={'response': [hook1]})574        prep = s.prepare_request(r)575        assert prep.hooks['response'] == [hook1]576577    def test_prepared_request_hook(self):578        def hook(resp, **kwargs):579            resp.hook_working = True580            return resp581582        req = requests.Request('GET', HTTPBIN, hooks={'response': hook})583        prep = req.prepare()584585        s = requests.Session()586        s.proxies = getproxies()587        resp = s.send(prep)588589        assert hasattr(resp, 'hook_working')590591    def test_prepared_from_session(self):592        class DummyAuth(requests.auth.AuthBase):593            def __call__(self, r):594                r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'595                return r596597        req = requests.Request('GET', httpbin('headers'))598        assert not req.auth599600        s = requests.Session()601        s.auth = DummyAuth()602603        prep = s.prepare_request(req)604        resp = s.send(prep)605606        assert resp.json()['headers'][607            'Dummy-Auth-Test'] == 'dummy-auth-test-ok'608609    def test_prepare_request_with_bytestring_url(self):610        req = requests.Request('GET', b'https://httpbin.org/')611        s = requests.Session()612        prep = s.prepare_request(req)613        assert prep.url == "https://httpbin.org/"614615    def test_links(self):616        r = requests.Response()617        r.headers = {618            'cache-control': 'public, max-age=60, s-maxage=60',619            'connection': 'keep-alive',620            'content-encoding': 'gzip',621            'content-type': 'application/json; charset=utf-8',622            'date': 'Sat, 26 Jan 2013 16:47:56 GMT',623            'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',624            'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',625            'link': ('<https://api.github.com/users/kennethreitz/repos?'626                     'page=2&per_page=10>; rel="next", <https://api.github.'627                     'com/users/kennethreitz/repos?page=7&per_page=10>; '628                     ' rel="last"'),629            'server': 'GitHub.com',630            'status': '200 OK',631            'vary': 'Accept',632            'x-content-type-options': 'nosniff',633            'x-github-media-type': 'github.beta',634            'x-ratelimit-limit': '60',635            'x-ratelimit-remaining': '57'636        }637        assert r.links['next']['rel'] == 'next'638639    def test_cookie_parameters(self):640        key = 'some_cookie'641        value = 'some_value'642        secure = True643        domain = 'test.com'644        rest = {'HttpOnly': True}645646        jar = requests.cookies.RequestsCookieJar()647        jar.set(key, value, secure=secure, domain=domain, rest=rest)648649        assert len(jar) == 1650        assert 'some_cookie' in jar651652        cookie = list(jar)[0]653        assert cookie.secure == secure654        assert cookie.domain == domain655        assert cookie._rest['HttpOnly'] == rest['HttpOnly']656657    def test_cookie_as_dict_keeps_len(self):658        key = 'some_cookie'659        value = 'some_value'660661        key1 = 'some_cookie1'662        value1 = 'some_value1'663664        jar = requests.cookies.RequestsCookieJar()665        jar.set(key, value)666        jar.set(key1, value1)667668        d1 = dict(jar)669        d2 = dict(jar.iteritems())670        d3 = dict(jar.items())671672        assert len(jar) == 2673        assert len(d1) == 2674        assert len(d2) == 2675        assert len(d3) == 2676677    def test_cookie_as_dict_keeps_items(self):678        key = 'some_cookie'679        value = 'some_value'680681        key1 = 'some_cookie1'682        value1 = 'some_value1'683684        jar = requests.cookies.RequestsCookieJar()685        jar.set(key, value)686        jar.set(key1, value1)687688        d1 = dict(jar)689        d2 = dict(jar.iteritems())690        d3 = dict(jar.items())691692        assert d1['some_cookie'] == 'some_value'693        assert d2['some_cookie'] == 'some_value'694        assert d3['some_cookie1'] == 'some_value1'695696    def test_cookie_as_dict_keys(self):697        key = 'some_cookie'698        value = 'some_value'699700        key1 = 'some_cookie1'701        value1 = 'some_value1'702703        jar = requests.cookies.RequestsCookieJar()704        jar.set(key, value)705        jar.set(key1, value1)706707        keys = jar.keys()708        assert keys == list(keys)709        # make sure one can use keys multiple times710        assert list(keys) == list(keys)711712    def test_cookie_as_dict_values(self):713        key = 'some_cookie'714        value = 'some_value'715716        key1 = 'some_cookie1'717        value1 = 'some_value1'718719        jar = requests.cookies.RequestsCookieJar()720        jar.set(key, value)721        jar.set(key1, value1)722723        values = jar.values()724        assert values == list(values)725        # make sure one can use values multiple times726        assert list(values) == list(values)727728    def test_cookie_as_dict_items(self):729        key = 'some_cookie'730        value = 'some_value'731732        key1 = 'some_cookie1'733        value1 = 'some_value1'734735        jar = requests.cookies.RequestsCookieJar()736        jar.set(key, value)737        jar.set(key1, value1)738739        items = jar.items()740        assert items == list(items)741        # make sure one can use items multiple times742        assert list(items) == list(items)743744    def test_time_elapsed_blank(self):745        r = requests.get(httpbin('get'))746        td = r.elapsed747        total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)748                         * 10**6) / 10**6)749        assert total_seconds > 0.0750751    def test_response_is_iterable(self):752        r = requests.Response()753        io = StringIO.StringIO('abc')754        read_ = io.read755756        def read_mock(amt, decode_content=None):757            return read_(amt)758        setattr(io, 'read', read_mock)759        r.raw = io760        assert next(iter(r))761        io.close()762763    def test_response_decode_unicode(self):764        """765        When called with decode_unicode, Response.iter_content should always766        return unicode.767        """768        r = requests.Response()769        r._content_consumed = True770        r._content = b'the content'771        r.encoding = 'ascii'772773        chunks = r.iter_content(decode_unicode=True)774        assert all(isinstance(chunk, str) for chunk in chunks)775776        # also for streaming777        r = requests.Response()778        r.raw = io.BytesIO(b'the content')779        r.encoding = 'ascii'780        chunks = r.iter_content(decode_unicode=True)781        assert all(isinstance(chunk, str) for chunk in chunks)782783    def test_request_and_response_are_pickleable(self):784        r = requests.get(httpbin('get'))785786        # verify we can pickle the original request787        assert pickle.loads(pickle.dumps(r.request))788789        # verify we can pickle the response and that we have access to790        # the original request.791        pr = pickle.loads(pickle.dumps(r))792        assert r.request.url == pr.request.url793        assert r.request.headers == pr.request.headers794795    def test_get_auth_from_url(self):796        url = 'http://user:pass@complex.url.com/path?query=yes'797        assert ('user', 'pass') == requests.utils.get_auth_from_url(url)798799    def test_get_auth_from_url_encoded_spaces(self):800        url = 'http://user:pass%20pass@complex.url.com/path?query=yes'801        assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)802803    def test_get_auth_from_url_not_encoded_spaces(self):804        url = 'http://user:pass pass@complex.url.com/path?query=yes'805        assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)806807    def test_get_auth_from_url_percent_chars(self):808        url = 'http://user%25user:pass@complex.url.com/path?query=yes'809        assert ('user%user', 'pass') == requests.utils.get_auth_from_url(url)810811    def test_get_auth_from_url_encoded_hashes(self):812        url = 'http://user:pass%23pass@complex.url.com/path?query=yes'813        assert ('user', 'pass#pass') == requests.utils.get_auth_from_url(url)814815    def test_cannot_send_unprepared_requests(self):816        r = requests.Request(url=HTTPBIN)817        with pytest.raises(ValueError):818            requests.Session().send(r)819820    def test_http_error(self):821        error = requests.exceptions.HTTPError()822        assert not error.response823        response = requests.Response()824        error = requests.exceptions.HTTPError(response=response)825        assert error.response == response826        error = requests.exceptions.HTTPError('message', response=response)827        assert str(error) == 'message'828        assert error.response == response829830    def test_session_pickling(self):831        r = requests.Request('GET', httpbin('get'))832        s = requests.Session()833834        s = pickle.loads(pickle.dumps(s))835        s.proxies = getproxies()836837        r = s.send(r.prepare())838        assert r.status_code == 200839840    def test_fixes_1329(self):841        """842        Ensure that header updates are done case-insensitively.843        """844        s = requests.Session()845        s.headers.update({'ACCEPT': 'BOGUS'})846        s.headers.update({'accept': 'application/json'})847        r = s.get(httpbin('get'))848        headers = r.request.headers849        assert headers['accept'] == 'application/json'850        assert headers['Accept'] == 'application/json'851        assert headers['ACCEPT'] == 'application/json'852853    def test_uppercase_scheme_redirect(self):854        parts = urlparse(httpbin('html'))855        url = "HTTP://" + parts.netloc + parts.path856        r = requests.get(httpbin('redirect-to'), params={'url': url})857        assert r.status_code == 200858        assert r.url.lower() == url.lower()859860    def test_transport_adapter_ordering(self):861        s = requests.Session()862        order = ['https://', 'http://']863        assert order == list(s.adapters)864        s.mount('http://git', HTTPAdapter())865        s.mount('http://github', HTTPAdapter())866        s.mount('http://github.com', HTTPAdapter())867        s.mount('http://github.com/about/', HTTPAdapter())868        order = [869            'http://github.com/about/',870            'http://github.com',871            'http://github',872            'http://git',873            'https://',874            'http://',875        ]876        assert order == list(s.adapters)877        s.mount('http://gittip', HTTPAdapter())878        s.mount('http://gittip.com', HTTPAdapter())879        s.mount('http://gittip.com/about/', HTTPAdapter())880        order = [881            'http://github.com/about/',882            'http://gittip.com/about/',883            'http://github.com',884            'http://gittip.com',885            'http://github',886            'http://gittip',887            'http://git',888            'https://',889            'http://',890        ]891        assert order == list(s.adapters)892        s2 = requests.Session()893        s2.adapters = {'http://': HTTPAdapter()}894        s2.mount('https://', HTTPAdapter())895        assert 'http://' in s2.adapters896        assert 'https://' in s2.adapters897898    def test_header_remove_is_case_insensitive(self):899        # From issue #1321900        s = requests.Session()901        s.headers['foo'] = 'bar'902        r = s.get(httpbin('get'), headers={'FOO': None})903        assert 'foo' not in r.request.headers904905    def test_params_are_merged_case_sensitive(self):906        s = requests.Session()907        s.params['foo'] = 'bar'908        r = s.get(httpbin('get'), params={'FOO': 'bar'})909        assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}910911    def test_long_authinfo_in_url(self):912        url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(913            'E8A3BE87-9E3F-4620-8858-95478E385B5B',914            'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',915            'exactly-------------sixty-----------three------------characters',916        )917        r = requests.Request('GET', url).prepare()918        assert r.url == url919920    def test_header_keys_are_native(self):921        headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}922        r = requests.Request('GET', httpbin('get'), headers=headers)923        p = r.prepare()924925        # This is testing that they are builtin strings. A bit weird, but there926        # we go.927        assert 'unicode' in p.headers.keys()928        assert 'byte' in p.headers.keys()929930    def test_can_send_nonstring_objects_with_files(self):931        data = {'a': 0.0}932        files = {'b': 'foo'}933        r = requests.Request('POST', httpbin('post'), data=data, files=files)934        p = r.prepare()935936        assert 'multipart/form-data' in p.headers['Content-Type']937938    def test_can_send_bytes_bytearray_objects_with_files(self):939        # Test bytes:940        data = {'a': 'this is a string'}941        files = {'b': b'foo'}942        r = requests.Request('POST', httpbin('post'), data=data, files=files)943        p = r.prepare()944        assert 'multipart/form-data' in p.headers['Content-Type']945        # Test bytearrays:946        files = {'b': bytearray(b'foo')}947        r = requests.Request('POST', httpbin('post'), data=data, files=files)948        p = r.prepare()949        assert 'multipart/form-data' in p.headers['Content-Type']950951    def test_can_send_file_object_with_non_string_filename(self):952        f = io.BytesIO()953        f.name = 2954        r = requests.Request('POST', httpbin('post'), files={'f': f})955        p = r.prepare()956957        assert 'multipart/form-data' in p.headers['Content-Type']958959    def test_autoset_header_values_are_native(self):960        data = 'this is a string'961        length = '16'962        req = requests.Request('POST', httpbin('post'), data=data)963        p = req.prepare()964965        assert p.headers['Content-Length'] == length966967    def test_nonhttp_schemes_dont_check_URLs(self):968        test_urls = (969            'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',970            'file:///etc/passwd',971            'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',972        )973        for test_url in test_urls:974            req = requests.Request('GET', test_url)975            preq = req.prepare()976            assert test_url == preq.url977978    def test_auth_is_stripped_on_redirect_off_host(self):979        r = requests.get(980            httpbin('redirect-to'),981            params={'url': 'http://www.google.co.uk'},982            auth=('user', 'pass'),983        )984        assert r.history[0].request.headers['Authorization']985        assert not r.request.headers.get('Authorization', '')986987    def test_auth_is_retained_for_redirect_on_host(self):988        r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))989        h1 = r.history[0].request.headers['Authorization']990        h2 = r.request.headers['Authorization']991992        assert h1 == h2993994    def test_manual_redirect_with_partial_body_read(self):995        s = requests.Session()996        r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)997        assert r1.is_redirect998        rg = s.resolve_redirects(r1, r1.request, stream=True)9991000        # read only the first eight bytes of the response body,1001        # then follow the redirect1002        r1.iter_content(8)1003        r2 = next(rg)1004        assert r2.is_redirect10051006        # read all of the response via iter_content,1007        # then follow the redirect1008        for _ in r2.iter_content():1009            pass1010        r3 = next(rg)1011        assert not r3.is_redirect10121013    def _patch_adapter_gzipped_redirect(self, session, url):1014        adapter = session.get_adapter(url=url)1015        org_build_response = adapter.build_response1016        self._patched_response = False10171018        def build_response(*args, **kwargs):1019            resp = org_build_response(*args, **kwargs)1020            if not self._patched_response:1021                resp.raw.headers['content-encoding'] = 'gzip'1022                self._patched_response = True1023            return resp10241025        adapter.build_response = build_response10261027    def test_redirect_with_wrong_gzipped_header(self):1028        s = requests.Session()1029        url = httpbin('redirect/1')1030        self._patch_adapter_gzipped_redirect(s, url)1031        s.get(url)10321033    def test_basic_auth_str_is_always_native(self):1034        s = _basic_auth_str("test", "test")1035        assert isinstance(s, builtin_str)1036        assert s == "Basic dGVzdDp0ZXN0"10371038    def test_requests_history_is_saved(self):1039        r = requests.get(httpbin('redirect/5'))1040        total = r.history[-1].history1041        i = 01042        for item in r.history:1043            assert item.history == total[0:i]1044            i = i + 110451046    def test_json_param_post_content_type_works(self):1047        r = requests.post(1048            httpbin('post'),1049            json={'life': 42}1050        )1051        assert r.status_code == 2001052        assert 'application/json' in r.request.headers['Content-Type']1053        assert {'life': 42} == r.json()['json']10541055    def test_response_iter_lines(self):1056        r = requests.get(httpbin('stream/4'), stream=True)1057        assert r.status_code == 20010581059        it = r.iter_lines()1060        next(it)1061        assert len(list(it)) == 310621063    @pytest.mark.xfail1064    def test_response_iter_lines_reentrant(self):1065        """Response.iter_lines() is not reentrant safe"""1066        r = requests.get(httpbin('stream/4'), stream=True)1067        assert r.status_code == 20010681069        next(r.iter_lines())1070        assert len(list(r.iter_lines())) == 3107110721073class TestContentEncodingDetection(unittest.TestCase):10741075    def test_none(self):1076        encodings = requests.utils.get_encodings_from_content('')1077        assert not len(encodings)10781079    def test_html_charset(self):1080        """HTML5 meta charset attribute"""1081        content = '<meta charset="UTF-8">'1082        encodings = requests.utils.get_encodings_from_content(content)1083        assert len(encodings) == 11084        assert encodings[0] == 'UTF-8'10851086    def test_html4_pragma(self):1087        """HTML4 pragma directive"""1088        content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">'1089        encodings = requests.utils.get_encodings_from_content(content)1090        assert len(encodings) == 11091        assert encodings[0] == 'UTF-8'10921093    def test_xhtml_pragma(self):1094        """XHTML 1.x served with text/html MIME type"""1095        content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />'1096        encodings = requests.utils.get_encodings_from_content(content)1097        assert len(encodings) == 11098        assert encodings[0] == 'UTF-8'10991100    def test_xml(self):1101        """XHTML 1.x served as XML"""1102        content = '<?xml version="1.0" encoding="UTF-8"?>'1103        encodings = requests.utils.get_encodings_from_content(content)1104        assert len(encodings) == 11105        assert encodings[0] == 'UTF-8'11061107    def test_precedence(self):1108        content = '''1109        <?xml version="1.0" encoding="XML"?>1110        <meta charset="HTML5">1111        <meta http-equiv="Content-type" content="text/html;charset=HTML4" />1112        '''.strip()1113        encodings = requests.utils.get_encodings_from_content(content)1114        assert encodings == ['HTML5', 'HTML4', 'XML']111511161117class TestCaseInsensitiveDict(unittest.TestCase):11181119    def test_mapping_init(self):1120        cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1121        assert len(cid) == 21122        assert 'foo' in cid1123        assert 'bar' in cid11241125    def test_iterable_init(self):1126        cid = CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')])1127        assert len(cid) == 21128        assert 'foo' in cid1129        assert 'bar' in cid11301131    def test_kwargs_init(self):1132        cid = CaseInsensitiveDict(FOO='foo', BAr='bar')1133        assert len(cid) == 21134        assert 'foo' in cid1135        assert 'bar' in cid11361137    def test_docstring_example(self):1138        cid = CaseInsensitiveDict()1139        cid['Accept'] = 'application/json'1140        assert cid['aCCEPT'] == 'application/json'1141        assert list(cid) == ['Accept']11421143    def test_len(self):1144        cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1145        cid['A'] = 'a'1146        assert len(cid) == 211471148    def test_getitem(self):1149        cid = CaseInsensitiveDict({'Spam': 'blueval'})1150        assert cid['spam'] == 'blueval'1151        assert cid['SPAM'] == 'blueval'11521153    def test_fixes_649(self):1154        """__setitem__ should behave case-insensitively."""1155        cid = CaseInsensitiveDict()1156        cid['spam'] = 'oneval'1157        cid['Spam'] = 'twoval'1158        cid['sPAM'] = 'redval'1159        cid['SPAM'] = 'blueval'1160        assert cid['spam'] == 'blueval'1161        assert cid['SPAM'] == 'blueval'1162        assert list(cid.keys()) == ['SPAM']11631164    def test_delitem(self):1165        cid = CaseInsensitiveDict()1166        cid['Spam'] = 'someval'1167        del cid['sPam']1168        assert 'spam' not in cid1169        assert len(cid) == 011701171    def test_contains(self):1172        cid = CaseInsensitiveDict()1173        cid['Spam'] = 'someval'1174        assert 'Spam' in cid1175        assert 'spam' in cid1176        assert 'SPAM' in cid1177        assert 'sPam' in cid1178        assert 'notspam' not in cid11791180    def test_get(self):1181        cid = CaseInsensitiveDict()1182        cid['spam'] = 'oneval'1183        cid['SPAM'] = 'blueval'1184        assert cid.get('spam') == 'blueval'1185        assert cid.get('SPAM') == 'blueval'1186        assert cid.get('sPam') == 'blueval'1187        assert cid.get('notspam', 'default') == 'default'11881189    def test_update(self):1190        cid = CaseInsensitiveDict()1191        cid['spam'] = 'blueval'1192        cid.update({'sPam': 'notblueval'})1193        assert cid['spam'] == 'notblueval'1194        cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1195        cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1196        assert len(cid) == 21197        assert cid['foo'] == 'anotherfoo'1198        assert cid['bar'] == 'anotherbar'11991200    def test_update_retains_unchanged(self):1201        cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1202        cid.update({'foo': 'newfoo'})1203        assert cid['bar'] == 'bar'12041205    def test_iter(self):1206        cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1207        keys = frozenset(['Spam', 'Eggs'])1208        assert frozenset(iter(cid)) == keys12091210    def test_equality(self):1211        cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1212        othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1213        assert cid == othercid1214        del othercid['spam']1215        assert cid != othercid1216        assert cid == {'spam': 'blueval', 'eggs': 'redval'}12171218    def test_setdefault(self):1219        cid = CaseInsensitiveDict({'Spam': 'blueval'})1220        assert cid.setdefault('spam', 'notblueval') == 'blueval'1221        assert cid.setdefault('notspam', 'notblueval') == 'notblueval'12221223    def test_lower_items(self):1224        cid = CaseInsensitiveDict({1225            'Accept': 'application/json',1226            'user-Agent': 'requests',1227        })1228        keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1229        lowerkeyset = frozenset(['accept', 'user-agent'])1230        assert keyset == lowerkeyset12311232    def test_preserve_key_case(self):1233        cid = CaseInsensitiveDict({1234            'Accept': 'application/json',1235            'user-Agent': 'requests',1236        })1237        keyset = frozenset(['Accept', 'user-Agent'])1238        assert frozenset(i[0] for i in cid.items()) == keyset1239        assert frozenset(cid.keys()) == keyset1240        assert frozenset(cid) == keyset12411242    def test_preserve_last_key_case(self):1243        cid = CaseInsensitiveDict({1244            'Accept': 'application/json',1245            'user-Agent': 'requests',1246        })1247        cid.update({'ACCEPT': 'application/json'})1248        cid['USER-AGENT'] = 'requests'1249        keyset = frozenset(['ACCEPT', 'USER-AGENT'])1250        assert frozenset(i[0] for i in cid.items()) == keyset1251        assert frozenset(cid.keys()) == keyset1252        assert frozenset(cid) == keyset125312541255class UtilsTestCase(unittest.TestCase):12561257    def test_super_len_io_streams(self):1258        """ Ensures that we properly deal with different kinds of IO streams. """1259        # uses StringIO or io.StringIO (see import above)1260        from io import BytesIO1261        from requests.utils import super_len12621263        assert super_len(StringIO.StringIO()) == 01264        assert super_len(1265            StringIO.StringIO('with so much drama in the LBC')) == 2912661267        assert super_len(BytesIO()) == 01268        assert super_len(1269            BytesIO(b"it's kinda hard bein' snoop d-o-double-g")) == 4012701271        try:1272            import cStringIO1273        except ImportError:1274            pass1275        else:1276            assert super_len(1277                cStringIO.StringIO('but some how, some way...')) == 2512781279    def test_get_environ_proxies_ip_ranges(self):1280        """Ensures that IP addresses are correctly matches with ranges1281        in no_proxy variable."""1282        from requests.utils import get_environ_proxies1283        os.environ['no_proxy'] = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"1284        assert get_environ_proxies('http://192.168.0.1:5000/') == {}1285        assert get_environ_proxies('http://192.168.0.1/') == {}1286        assert get_environ_proxies('http://172.16.1.1/') == {}1287        assert get_environ_proxies('http://172.16.1.1:5000/') == {}1288        assert get_environ_proxies('http://192.168.1.1:5000/') != {}1289        assert get_environ_proxies('http://192.168.1.1/') != {}12901291    def test_get_environ_proxies(self):1292        """Ensures that IP addresses are correctly matches with ranges1293        in no_proxy variable."""1294        from requests.utils import get_environ_proxies1295        os.environ['no_proxy'] = "127.0.0.1,localhost.localdomain,192.168.0.0/24,172.16.1.1"1296        assert get_environ_proxies(1297            'http://localhost.localdomain:5000/v1.0/') == {}1298        assert get_environ_proxies('http://www.requests.com/') != {}12991300    def test_guess_filename_when_int(self):1301        from requests.utils import guess_filename1302        assert None is guess_filename(1)13031304    def test_guess_filename_when_filename_is_an_int(self):1305        from requests.utils import guess_filename1306        fake = type('Fake', (object,), {'name': 1})()1307        assert None is guess_filename(fake)13081309    def test_guess_filename_with_file_like_obj(self):1310        from requests.utils import guess_filename1311        from requests import compat1312        fake = type('Fake', (object,), {'name': b'value'})()1313        guessed_name = guess_filename(fake)1314        assert b'value' == guessed_name1315        assert isinstance(guessed_name, compat.bytes)13161317    def test_guess_filename_with_unicode_name(self):1318        from requests.utils import guess_filename1319        from requests import compat1320        filename = b'value'.decode('utf-8')1321        fake = type('Fake', (object,), {'name': filename})()1322        guessed_name = guess_filename(fake)1323        assert filename == guessed_name1324        assert isinstance(guessed_name, compat.str)13251326    def test_is_ipv4_address(self):1327        from requests.utils import is_ipv4_address1328        assert is_ipv4_address('8.8.8.8')1329        assert not is_ipv4_address('8.8.8.8.8')1330        assert not is_ipv4_address('localhost.localdomain')13311332    def test_is_valid_cidr(self):1333        from requests.utils import is_valid_cidr1334        assert not is_valid_cidr('8.8.8.8')1335        assert is_valid_cidr('192.168.1.0/24')13361337    def test_dotted_netmask(self):1338        from requests.utils import dotted_netmask1339        assert dotted_netmask(8) == '255.0.0.0'1340        assert dotted_netmask(24) == '255.255.255.0'1341        assert dotted_netmask(25) == '255.255.255.128'13421343    def test_address_in_network(self):1344        from requests.utils import address_in_network1345        assert address_in_network('192.168.1.1', '192.168.1.0/24')1346        assert not address_in_network('172.16.0.1', '192.168.1.0/24')13471348    def test_get_auth_from_url(self):1349        """Ensures that username and password in well-encoded URI as per1350        RFC 3986 are correclty extracted."""1351        from requests.utils import get_auth_from_url1352        from requests.compat import quote1353        percent_encoding_test_chars = "%!*'();:@&=+$,/?#[] "1354        url_address = "request.com/url.html#test"1355        url = "http://" + quote(1356            percent_encoding_test_chars, '') + ':' + quote(1357            percent_encoding_test_chars, '') + '@' + url_address1358        (username, password) = get_auth_from_url(url)1359        assert username == percent_encoding_test_chars1360        assert password == percent_encoding_test_chars13611362    def test_requote_uri_with_unquoted_percents(self):1363        """Ensure we handle unquoted percent signs in redirects.13641365        See: https://github.com/kennethreitz/requests/issues/23561366        """1367        from requests.utils import requote_uri1368        bad_uri = 'http://example.com/fiz?buz=%ppicture'1369        quoted = 'http://example.com/fiz?buz=%25ppicture'1370        assert quoted == requote_uri(bad_uri)13711372    def test_requote_uri_properly_requotes(self):1373        """Ensure requoting doesn't break expectations."""1374        from requests.utils import requote_uri1375        quoted = 'http://example.com/fiz?buz=%25ppicture'1376        assert quoted == requote_uri(quoted)137713781379class TestMorselToCookieExpires(unittest.TestCase):13801381    """Tests for morsel_to_cookie when morsel contains expires."""13821383    def test_expires_valid_str(self):1384        """Test case where we convert expires from string time."""13851386        morsel = Morsel()1387        morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1388        cookie = morsel_to_cookie(morsel)1389        assert cookie.expires == 113901391    def test_expires_invalid_int(self):1392        """Test case where an invalid type is passed for expires."""13931394        morsel = Morsel()1395        morsel['expires'] = 1001396        with pytest.raises(TypeError):1397            morsel_to_cookie(morsel)13981399    def test_expires_invalid_str(self):1400        """Test case where an invalid string is input."""14011402        morsel = Morsel()1403        morsel['expires'] = 'woops'1404        with pytest.raises(ValueError):1405            morsel_to_cookie(morsel)14061407    def test_expires_none(self):1408        """Test case where expires is None."""14091410        morsel = Morsel()1411        morsel['expires'] = None1412        cookie = morsel_to_cookie(morsel)1413        assert cookie.expires is None141414151416class TestMorselToCookieMaxAge(unittest.TestCase):14171418    """Tests for morsel_to_cookie when morsel contains max-age."""14191420    def test_max_age_valid_int(self):1421        """Test case where a valid max age in seconds is passed."""14221423        morsel = Morsel()1424        morsel['max-age'] = 601425        cookie = morsel_to_cookie(morsel)1426        assert isinstance(cookie.expires, int)14271428    def test_max_age_invalid_str(self):1429        """Test case where a invalid max age is passed."""14301431        morsel = Morsel()1432        morsel['max-age'] = 'woops'1433        with pytest.raises(TypeError):1434            morsel_to_cookie(morsel)143514361437class TestTimeout:1438    def test_stream_timeout(self):1439        try:1440            requests.get(httpbin('delay/10'), timeout=2.0)1441        except requests.exceptions.Timeout as e:1442            assert 'Read timed out' in e.args[0].args[0]14431444    def test_invalid_timeout(self):1445        with pytest.raises(ValueError) as e:1446            requests.get(httpbin('get'), timeout=(3, 4, 5))1447        assert '(connect, read)' in str(e)14481449        with pytest.raises(ValueError) as e:1450            requests.get(httpbin('get'), timeout="foo")1451        assert 'must be an int or float' in str(e)14521453    def test_none_timeout(self):1454        """ Check that you can set None as a valid timeout value.14551456        To actually test this behavior, we'd want to check that setting the1457        timeout to None actually lets the request block past the system default1458        timeout. However, this would make the test suite unbearably slow.1459        Instead we verify that setting the timeout to None does not prevent the1460        request from succeeding.1461        """1462        r = requests.get(httpbin('get'), timeout=None)1463        assert r.status_code == 20014641465    def test_read_timeout(self):1466        try:1467            requests.get(httpbin('delay/10'), timeout=(None, 0.1))1468            assert False, "The recv() request should time out."1469        except ReadTimeout:1470            pass14711472    def test_connect_timeout(self):1473        try:1474            requests.get(TARPIT, timeout=(0.1, None))1475            assert False, "The connect() request should time out."1476        except ConnectTimeout as e:1477            assert isinstance(e, ConnectionError)1478            assert isinstance(e, Timeout)14791480    def test_total_timeout_connect(self):1481        try:1482            requests.get(TARPIT, timeout=(0.1, 0.1))1483            assert False, "The connect() request should time out."1484        except ConnectTimeout:1485            pass14861487    def test_encoded_methods(self):1488        """See: https://github.com/kennethreitz/requests/issues/2316"""1489        r = requests.request(b'GET', httpbin('get'))1490        assert r.ok149114921493SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))149414951496class RedirectSession(SessionRedirectMixin):1497    def __init__(self, order_of_redirects):1498        self.redirects = order_of_redirects1499        self.calls = []1500        self.max_redirects = 301501        self.cookies = {}1502        self.trust_env = False15031504    def send(self, *args, **kwargs):1505        self.calls.append(SendCall(args, kwargs))1506        return self.build_response()15071508    def build_response(self):1509        request = self.calls[-1].args[0]1510        r = requests.Response()15111512        try:1513            r.status_code = int(self.redirects.pop(0))1514        except IndexError:1515            r.status_code = 20015161517        r.headers = CaseInsensitiveDict({'Location': '/'})1518        r.raw = self._build_raw()1519        r.request = request1520        return r15211522    def _build_raw(self):1523        string = StringIO.StringIO('')1524        setattr(string, 'release_conn', lambda *args: args)1525        return string152615271528class TestRedirects:1529    default_keyword_args = {1530        'stream': False,1531        'verify': True,1532        'cert': None,1533        'timeout': None,1534        'allow_redirects': False,1535        'proxies': {},1536    }15371538    def test_requests_are_updated_each_time(self):1539        session = RedirectSession([303, 307])1540        prep = requests.Request('POST', httpbin('post')).prepare()1541        r0 = session.send(prep)1542        assert r0.request.method == 'POST'1543        assert session.calls[-1] == SendCall((r0.request,), {})1544        redirect_generator = session.resolve_redirects(r0, prep)1545        for response in redirect_generator:1546            assert response.request.method == 'GET'1547            send_call = SendCall((response.request,),1548                                 TestRedirects.default_keyword_args)1549            assert session.calls[-1] == send_call1550155115521553@pytest.fixture1554def list_of_tuples():1555    return [1556        (('a', 'b'), ('c', 'd')),1557        (('c', 'd'), ('a', 'b')),1558        (('a', 'b'), ('c', 'd'), ('e', 'f')),1559        ]156015611562def test_data_argument_accepts_tuples(list_of_tuples):1563    """1564    Ensure that the data argument will accept tuples of strings1565    and properly encode them.1566    """1567    for data in list_of_tuples:1568        p = PreparedRequest()1569        p.prepare(1570            method='GET',1571            url='http://www.example.com',1572            data=data,1573            hooks=default_hooks()1574        )1575        assert p.body == urlencode(data)157615771578def assert_copy(p, p_copy):1579    for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):1580        assert getattr(p, attr) == getattr(p_copy, attr)158115821583def test_prepared_request_empty_copy():1584    p = PreparedRequest()1585    assert_copy(p, p.copy())158615871588def test_prepared_request_no_cookies_copy():1589    p = PreparedRequest()1590    p.prepare(1591        method='GET',1592        url='http://www.example.com',1593        data='foo=bar',1594        hooks=default_hooks()1595    )1596    assert_copy(p, p.copy())159715981599def test_prepared_request_complete_copy():1600    p = PreparedRequest()1601    p.prepare(1602        method='GET',1603        url='http://www.example.com',1604        data='foo=bar',1605        hooks=default_hooks(),1606        cookies={'foo': 'bar'}1607    )1608    assert_copy(p, p.copy())160916101611def test_prepare_unicode_url():1612    p = PreparedRequest()1613    p.prepare(1614        method='GET',1615        url=u('http://www.example.com/üniçø∂é'),1616        hooks=[]1617    )1618    assert_copy(p, p.copy())161916201621def test_urllib3_retries():1622    from requests.packages.urllib3.util import Retry1623    s = requests.Session()1624    s.mount('http://', HTTPAdapter(max_retries=Retry(1625        total=2, status_forcelist=[500]1626    )))16271628    with pytest.raises(RetryError):1629        s.get(httpbin('status/500'))16301631def test_vendor_aliases():1632    from requests.packages import urllib31633    from requests.packages import chardet16341635    with pytest.raises(ImportError):1636        from requests.packages import webbrowser16371638if __name__ == '__main__':1639    unittest.main()