Skip to content
Myr

test_requests.py

This file

Path

test_requests.py

1,191 lines · 40.6 KiB · Python

Last changed by

Merge pull request #1935 from cjstapleton/masterKenneth Reitzbefore adoptiond8557a2

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 unittest1112import requests13import pytest14from requests.adapters import HTTPAdapter15from requests.auth import HTTPDigestAuth16from requests.compat import (17    Morsel, cookielib, getproxies, str, urljoin, urlparse)18from requests.cookies import cookiejar_from_dict, morsel_to_cookie19from requests.exceptions import InvalidURL, MissingSchema20from requests.structures import CaseInsensitiveDict2122try:23    import StringIO24except ImportError:25    import io as StringIO2627HTTPBIN = os.environ.get('HTTPBIN_URL', 'http://httpbin.org/')28# Issue #1483: Make sure the URL always has a trailing slash29HTTPBIN = HTTPBIN.rstrip('/') + '/'303132def httpbin(*suffix):33    """Returns url for HTTPBIN resource."""34    return urljoin(HTTPBIN, '/'.join(suffix))353637class RequestsTestCase(unittest.TestCase):3839    _multiprocess_can_split_ = True4041    def setUp(self):42        """Create simple data set with headers."""43        pass4445    def tearDown(self):46        """Teardown."""47        pass4849    def test_entry_points(self):5051        requests.session52        requests.session().get53        requests.session().head54        requests.get55        requests.head56        requests.put57        requests.patch58        requests.post5960    def test_invalid_url(self):61        with pytest.raises(MissingSchema):62            requests.get('hiwpefhipowhefopw')63        with pytest.raises(InvalidURL):64            requests.get('http://')6566    def test_basic_building(self):67        req = requests.Request()68        req.url = 'http://kennethreitz.org/'69        req.data = {'life': '42'}7071        pr = req.prepare()72        assert pr.url == req.url73        assert pr.body == 'life=42'7475    def test_no_content_length(self):76        get_req = requests.Request('GET', httpbin('get')).prepare()77        assert 'Content-Length' not in get_req.headers78        head_req = requests.Request('HEAD', httpbin('head')).prepare()79        assert 'Content-Length' not in head_req.headers8081    def test_path_is_not_double_encoded(self):82        request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()8384        assert request.path_url == '/get/test%20case'8586    def test_params_are_added_before_fragment(self):87        request = requests.Request('GET',88            "http://example.com/path#fragment", params={"a": "b"}).prepare()89        assert request.url == "http://example.com/path?a=b#fragment"90        request = requests.Request('GET',91            "http://example.com/path?key=value#fragment", params={"a": "b"}).prepare()92        assert request.url == "http://example.com/path?key=value&a=b#fragment"9394    def test_mixed_case_scheme_acceptable(self):95        s = requests.Session()96        s.proxies = getproxies()97        parts = urlparse(httpbin('get'))98        schemes = ['http://', 'HTTP://', 'hTTp://', 'HttP://',99                   'https://', 'HTTPS://', 'hTTps://', 'HttPs://']100        for scheme in schemes:101            url = scheme + parts.netloc + parts.path102            r = requests.Request('GET', url)103            r = s.send(r.prepare())104            assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)105106    def test_HTTP_200_OK_GET_ALTERNATIVE(self):107        r = requests.Request('GET', httpbin('get'))108        s = requests.Session()109        s.proxies = getproxies()110111        r = s.send(r.prepare())112113        assert r.status_code == 200114115    def test_HTTP_302_ALLOW_REDIRECT_GET(self):116        r = requests.get(httpbin('redirect', '1'))117        assert r.status_code == 200118        assert r.history[0].status_code == 302119        assert r.history[0].is_redirect120121    # def test_HTTP_302_ALLOW_REDIRECT_POST(self):122    #     r = requests.post(httpbin('status', '302'), data={'some': 'data'})123    #     self.assertEqual(r.status_code, 200)124125    def test_HTTP_200_OK_GET_WITH_PARAMS(self):126        heads = {'User-agent': 'Mozilla/5.0'}127128        r = requests.get(httpbin('user-agent'), headers=heads)129130        assert heads['User-agent'] in r.text131        assert r.status_code == 200132133    def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):134        heads = {'User-agent': 'Mozilla/5.0'}135136        r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)137        assert r.status_code == 200138139    def test_set_cookie_on_301(self):140        s = requests.session()141        url = httpbin('cookies/set?foo=bar')142        r = s.get(url)143        assert s.cookies['foo'] == 'bar'144145    def test_cookie_sent_on_redirect(self):146        s = requests.session()147        s.get(httpbin('cookies/set?foo=bar'))148        r = s.get(httpbin('redirect/1'))  # redirects to httpbin('get')149        assert 'Cookie' in r.json()['headers']150151    def test_cookie_removed_on_expire(self):152        s = requests.session()153        s.get(httpbin('cookies/set?foo=bar'))154        assert s.cookies['foo'] == 'bar'155        s.get(156            httpbin('response-headers'),157            params={158                'Set-Cookie':159                    'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'160            }161        )162        assert 'foo' not in s.cookies163164    def test_cookie_quote_wrapped(self):165        s = requests.session()166        s.get(httpbin('cookies/set?foo="bar:baz"'))167        assert s.cookies['foo'] == '"bar:baz"'168169    def test_cookie_persists_via_api(self):170        s = requests.session()171        r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})172        assert 'foo' in r.request.headers['Cookie']173        assert 'foo' in r.history[0].request.headers['Cookie']174175    def test_request_cookie_overrides_session_cookie(self):176        s = requests.session()177        s.cookies['foo'] = 'bar'178        r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})179        assert r.json()['cookies']['foo'] == 'baz'180        # Session cookie should not be modified181        assert s.cookies['foo'] == 'bar'182183    def test_request_cookies_not_persisted(self):184        s = requests.session()185        s.get(httpbin('cookies'), cookies={'foo': 'baz'})186        # Sending a request with cookies should not add cookies to the session187        assert not s.cookies188189    def test_generic_cookiejar_works(self):190        cj = cookielib.CookieJar()191        cookiejar_from_dict({'foo': 'bar'}, cj)192        s = requests.session()193        s.cookies = cj194        r = s.get(httpbin('cookies'))195        # Make sure the cookie was sent196        assert r.json()['cookies']['foo'] == 'bar'197        # Make sure the session cj is still the custom one198        assert s.cookies is cj199200    def test_param_cookiejar_works(self):201        cj = cookielib.CookieJar()202        cookiejar_from_dict({'foo' : 'bar'}, cj)203        s = requests.session()204        r = s.get(httpbin('cookies'), cookies=cj)205        # Make sure the cookie was sent206        assert r.json()['cookies']['foo'] == 'bar'207208    def test_requests_in_history_are_not_overridden(self):209        resp = requests.get(httpbin('redirect/3'))210        urls = [r.url for r in resp.history]211        req_urls = [r.request.url for r in resp.history]212        assert urls == req_urls213214    def test_headers_on_session_with_None_are_not_sent(self):215        """Do not send headers in Session.headers with None values."""216        ses = requests.Session()217        ses.headers['Accept-Encoding'] = None218        req = requests.Request('GET', 'http://httpbin.org/get')219        prep = ses.prepare_request(req)220        assert 'Accept-Encoding' not in prep.headers221222    def test_user_agent_transfers(self):223224        heads = {225            'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'226        }227228        r = requests.get(httpbin('user-agent'), headers=heads)229        assert heads['User-agent'] in r.text230231        heads = {232            'user-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'233        }234235        r = requests.get(httpbin('user-agent'), headers=heads)236        assert heads['user-agent'] in r.text237238    def test_HTTP_200_OK_HEAD(self):239        r = requests.head(httpbin('get'))240        assert r.status_code == 200241242    def test_HTTP_200_OK_PUT(self):243        r = requests.put(httpbin('put'))244        assert r.status_code == 200245246    def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):247        auth = ('user', 'pass')248        url = httpbin('basic-auth', 'user', 'pass')249250        r = requests.get(url, auth=auth)251        assert r.status_code == 200252253        r = requests.get(url)254        assert r.status_code == 401255256        s = requests.session()257        s.auth = auth258        r = s.get(url)259        assert r.status_code == 200260261    def test_basicauth_with_netrc(self):262        auth = ('user', 'pass')263        wrong_auth = ('wronguser', 'wrongpass')264        url = httpbin('basic-auth', 'user', 'pass')265266        def get_netrc_auth_mock(url):267            return auth268        requests.sessions.get_netrc_auth = get_netrc_auth_mock269270        # Should use netrc and work.271        r = requests.get(url)272        assert r.status_code == 200273274        # Given auth should override and fail.275        r = requests.get(url, auth=wrong_auth)276        assert r.status_code == 401277278        s = requests.session()279280        # Should use netrc and work.281        r = s.get(url)282        assert r.status_code == 200283284        # Given auth should override and fail.285        s.auth = wrong_auth286        r = s.get(url)287        assert r.status_code == 401288289    def test_DIGEST_HTTP_200_OK_GET(self):290291        auth = HTTPDigestAuth('user', 'pass')292        url = httpbin('digest-auth', 'auth', 'user', 'pass')293294        r = requests.get(url, auth=auth)295        assert r.status_code == 200296297        r = requests.get(url)298        assert r.status_code == 401299300        s = requests.session()301        s.auth = HTTPDigestAuth('user', 'pass')302        r = s.get(url)303        assert r.status_code == 200304305    def test_DIGEST_AUTH_RETURNS_COOKIE(self):306        url = httpbin('digest-auth', 'auth', 'user', 'pass')307        auth = HTTPDigestAuth('user', 'pass')308        r = requests.get(url)309        assert r.cookies['fake'] == 'fake_value'310311        r = requests.get(url, auth=auth)312        assert r.status_code == 200313314    def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self):315        url = httpbin('digest-auth', 'auth', 'user', 'pass')316        auth = HTTPDigestAuth('user', 'pass')317        s = requests.Session()318        s.get(url, auth=auth)319        assert s.cookies['fake'] == 'fake_value'320321    def test_DIGEST_STREAM(self):322323        auth = HTTPDigestAuth('user', 'pass')324        url = httpbin('digest-auth', 'auth', 'user', 'pass')325326        r = requests.get(url, auth=auth, stream=True)327        assert r.raw.read() != b''328329        r = requests.get(url, auth=auth, stream=False)330        assert r.raw.read() == b''331332    def test_DIGESTAUTH_WRONG_HTTP_401_GET(self):333334        auth = HTTPDigestAuth('user', 'wrongpass')335        url = httpbin('digest-auth', 'auth', 'user', 'pass')336337        r = requests.get(url, auth=auth)338        assert r.status_code == 401339340        r = requests.get(url)341        assert r.status_code == 401342343        s = requests.session()344        s.auth = auth345        r = s.get(url)346        assert r.status_code == 401347348    def test_DIGESTAUTH_QUOTES_QOP_VALUE(self):349350        auth = HTTPDigestAuth('user', 'pass')351        url = httpbin('digest-auth', 'auth', 'user', 'pass')352353        r = requests.get(url, auth=auth)354        assert '"auth"' in r.request.headers['Authorization']355356    def test_POSTBIN_GET_POST_FILES(self):357358        url = httpbin('post')359        post1 = requests.post(url).raise_for_status()360361        post1 = requests.post(url, data={'some': 'data'})362        assert post1.status_code == 200363364        with open('requirements.txt') as f:365            post2 = requests.post(url, files={'some': f})366        assert post2.status_code == 200367368        post4 = requests.post(url, data='[{"some": "json"}]')369        assert post4.status_code == 200370371        with pytest.raises(ValueError):372            requests.post(url, files = ['bad file data'])373374    def test_POSTBIN_GET_POST_FILES_WITH_DATA(self):375376        url = httpbin('post')377        post1 = requests.post(url).raise_for_status()378379        post1 = requests.post(url, data={'some': 'data'})380        assert post1.status_code == 200381382        with open('requirements.txt') as f:383            post2 = requests.post(url, data={'some': 'data'}, files={'some': f})384        assert post2.status_code == 200385386        post4 = requests.post(url, data='[{"some": "json"}]')387        assert post4.status_code == 200388389        with pytest.raises(ValueError):390            requests.post(url, files = ['bad file data'])391392    def test_conflicting_post_params(self):393        url = httpbin('post')394        with open('requirements.txt') as f:395            pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")396            pytest.raises(ValueError, "requests.post(url, data=u'[{\"some\": \"data\"}]', files={'some': f})")397398    def test_request_ok_set(self):399        r = requests.get(httpbin('status', '404'))400        assert not r.ok401402    def test_status_raising(self):403        r = requests.get(httpbin('status', '404'))404        with pytest.raises(requests.exceptions.HTTPError):405            r.raise_for_status()406407        r = requests.get(httpbin('status', '500'))408        assert not r.ok409410    def test_decompress_gzip(self):411        r = requests.get(httpbin('gzip'))412        r.content.decode('ascii')413414    def test_unicode_get(self):415        url = httpbin('/get')416        requests.get(url, params={'foo': 'føø'})417        requests.get(url, params={'føø': 'føø'})418        requests.get(url, params={'føø': 'føø'})419        requests.get(url, params={'foo': 'foo'})420        requests.get(httpbin('ø'), params={'foo': 'foo'})421422    def test_unicode_header_name(self):423        requests.put(httpbin('put'), headers={str('Content-Type'): 'application/octet-stream'}, data='\xff') # compat.str is unicode.424425    def test_pyopenssl_redirect(self):426        requests.get('https://httpbin.org/status/301')427428    def test_urlencoded_get_query_multivalued_param(self):429430        r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))431        assert r.status_code == 200432        assert r.url == httpbin('get?test=foo&test=baz')433434    def test_different_encodings_dont_break_post(self):435        r = requests.post(httpbin('post'),436                          data={'stuff': json.dumps({'a': 123})},437                          params={'blah': 'asdf1234'},438                          files={'file': ('test_requests.py', open(__file__, 'rb'))})439        assert r.status_code == 200440441    def test_unicode_multipart_post(self):442        r = requests.post(httpbin('post'),443                          data={'stuff': u'ëlïxr'},444                          files={'file': ('test_requests.py', open(__file__, 'rb'))})445        assert r.status_code == 200446447        r = requests.post(httpbin('post'),448                          data={'stuff': u'ëlïxr'.encode('utf-8')},449                          files={'file': ('test_requests.py', open(__file__, 'rb'))})450        assert r.status_code == 200451452        r = requests.post(httpbin('post'),453                          data={'stuff': 'elixr'},454                          files={'file': ('test_requests.py', open(__file__, 'rb'))})455        assert r.status_code == 200456457        r = requests.post(httpbin('post'),458                          data={'stuff': 'elixr'.encode('utf-8')},459                          files={'file': ('test_requests.py', open(__file__, 'rb'))})460        assert r.status_code == 200461462    def test_unicode_multipart_post_fieldnames(self):463        filename = os.path.splitext(__file__)[0] + '.py'464        r = requests.Request(method='POST',465                             url=httpbin('post'),466                             data={'stuff'.encode('utf-8'): 'elixr'},467                             files={'file': ('test_requests.py',468                                             open(filename, 'rb'))})469        prep = r.prepare()470        assert b'name="stuff"' in prep.body471        assert b'name="b\'stuff\'"' not in prep.body472473    def test_unicode_method_name(self):474        files = {'file': open('test_requests.py', 'rb')}475        r = requests.request(method=u'POST', url=httpbin('post'), files=files)476        assert r.status_code == 200477478    def test_custom_content_type(self):479        r = requests.post(httpbin('post'),480                          data={'stuff': json.dumps({'a': 123})},481                          files={'file1': ('test_requests.py', open(__file__, 'rb')),482                                 'file2': ('test_requests', open(__file__, 'rb'),483                                           'text/py-content-type')})484        assert r.status_code == 200485        assert b"text/py-content-type" in r.request.body486487    def test_hook_receives_request_arguments(self):488        def hook(resp, **kwargs):489            assert resp is not None490            assert kwargs != {}491492        requests.Request('GET', HTTPBIN, hooks={'response': hook})493494    def test_session_hooks_are_used_with_no_request_hooks(self):495        hook = lambda x, *args, **kwargs: x496        s = requests.Session()497        s.hooks['response'].append(hook)498        r = requests.Request('GET', HTTPBIN)499        prep = s.prepare_request(r)500        assert prep.hooks['response'] != []501        assert prep.hooks['response'] == [hook]502503    def test_session_hooks_are_overriden_by_request_hooks(self):504        hook1 = lambda x, *args, **kwargs: x505        hook2 = lambda x, *args, **kwargs: x506        assert hook1 is not hook2507        s = requests.Session()508        s.hooks['response'].append(hook2)509        r = requests.Request('GET', HTTPBIN, hooks={'response': [hook1]})510        prep = s.prepare_request(r)511        assert prep.hooks['response'] == [hook1]512513    def test_prepared_request_hook(self):514        def hook(resp, **kwargs):515            resp.hook_working = True516            return resp517518        req = requests.Request('GET', HTTPBIN, hooks={'response': hook})519        prep = req.prepare()520521        s = requests.Session()522        s.proxies = getproxies()523        resp = s.send(prep)524525        assert hasattr(resp, 'hook_working')526527    def test_prepared_from_session(self):528        class DummyAuth(requests.auth.AuthBase):529            def __call__(self, r):530                r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'531                return r532533        req = requests.Request('GET', httpbin('headers'))534        assert not req.auth535536        s = requests.Session()537        s.auth = DummyAuth()538539        prep = s.prepare_request(req)540        resp = s.send(prep)541542        assert resp.json()['headers']['Dummy-Auth-Test'] == 'dummy-auth-test-ok'543544    def test_links(self):545        r = requests.Response()546        r.headers = {547            'cache-control': 'public, max-age=60, s-maxage=60',548            'connection': 'keep-alive',549            'content-encoding': 'gzip',550            'content-type': 'application/json; charset=utf-8',551            'date': 'Sat, 26 Jan 2013 16:47:56 GMT',552            'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',553            'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',554            'link': ('<https://api.github.com/users/kennethreitz/repos?'555                     'page=2&per_page=10>; rel="next", <https://api.github.'556                     'com/users/kennethreitz/repos?page=7&per_page=10>; '557                     ' rel="last"'),558            'server': 'GitHub.com',559            'status': '200 OK',560            'vary': 'Accept',561            'x-content-type-options': 'nosniff',562            'x-github-media-type': 'github.beta',563            'x-ratelimit-limit': '60',564            'x-ratelimit-remaining': '57'565        }566        assert r.links['next']['rel'] == 'next'567568    def test_cookie_parameters(self):569        key = 'some_cookie'570        value = 'some_value'571        secure = True572        domain = 'test.com'573        rest = {'HttpOnly': True}574575        jar = requests.cookies.RequestsCookieJar()576        jar.set(key, value, secure=secure, domain=domain, rest=rest)577578        assert len(jar) == 1579        assert 'some_cookie' in jar580581        cookie = list(jar)[0]582        assert cookie.secure == secure583        assert cookie.domain == domain584        assert cookie._rest['HttpOnly'] == rest['HttpOnly']585586    def test_cookie_as_dict_keeps_len(self):587        key = 'some_cookie'588        value = 'some_value'589590        key1 = 'some_cookie1'591        value1 = 'some_value1'592593        jar = requests.cookies.RequestsCookieJar()594        jar.set(key, value)595        jar.set(key1, value1)596597        d1 = dict(jar)598        d2 = dict(jar.iteritems())599        d3 = dict(jar.items())600601        assert len(jar) == 2602        assert len(d1) == 2603        assert len(d2) == 2604        assert len(d3) == 2605606    def test_cookie_as_dict_keeps_items(self):607        key = 'some_cookie'608        value = 'some_value'609610        key1 = 'some_cookie1'611        value1 = 'some_value1'612613        jar = requests.cookies.RequestsCookieJar()614        jar.set(key, value)615        jar.set(key1, value1)616617        d1 = dict(jar)618        d2 = dict(jar.iteritems())619        d3 = dict(jar.items())620621        assert d1['some_cookie'] == 'some_value'622        assert d2['some_cookie'] == 'some_value'623        assert d3['some_cookie1'] == 'some_value1'624625    def test_cookie_as_dict_keys(self):626        key = 'some_cookie'627        value = 'some_value'628629        key1 = 'some_cookie1'630        value1 = 'some_value1'631632        jar = requests.cookies.RequestsCookieJar()633        jar.set(key, value)634        jar.set(key1, value1)635636        keys = jar.keys()637        assert keys == list(keys)638        # make sure one can use keys multiple times639        assert list(keys) == list(keys)640641    def test_cookie_as_dict_values(self):642        key = 'some_cookie'643        value = 'some_value'644645        key1 = 'some_cookie1'646        value1 = 'some_value1'647648        jar = requests.cookies.RequestsCookieJar()649        jar.set(key, value)650        jar.set(key1, value1)651652        values = jar.values()653        assert values == list(values)654        # make sure one can use values multiple times655        assert list(values) == list(values)656657    def test_cookie_as_dict_items(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        items = jar.items()669        assert items == list(items)670        # make sure one can use items multiple times671        assert list(items) == list(items)672673674    def test_time_elapsed_blank(self):675        r = requests.get(httpbin('get'))676        td = r.elapsed677        total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)678                         * 10**6) / 10**6)679        assert total_seconds > 0.0680681    def test_response_is_iterable(self):682        r = requests.Response()683        io = StringIO.StringIO('abc')684        read_ = io.read685686        def read_mock(amt, decode_content=None):687            return read_(amt)688        setattr(io, 'read', read_mock)689        r.raw = io690        assert next(iter(r))691        io.close()692693    def test_request_and_response_are_pickleable(self):694        r = requests.get(httpbin('get'))695696        # verify we can pickle the original request697        assert pickle.loads(pickle.dumps(r.request))698699        # verify we can pickle the response and that we have access to700        # the original request.701        pr = pickle.loads(pickle.dumps(r))702        assert r.request.url == pr.request.url703        assert r.request.headers == pr.request.headers704705    def test_get_auth_from_url(self):706        url = 'http://user:pass@complex.url.com/path?query=yes'707        assert ('user', 'pass') == requests.utils.get_auth_from_url(url)708709    def test_get_auth_from_url_encoded_spaces(self):710        url = 'http://user:pass%20pass@complex.url.com/path?query=yes'711        assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)712713    def test_get_auth_from_url_not_encoded_spaces(self):714        url = 'http://user:pass pass@complex.url.com/path?query=yes'715        assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)716717    def test_get_auth_from_url_percent_chars(self):718        url = 'http://user%25user:pass@complex.url.com/path?query=yes'719        assert ('user%user', 'pass') == requests.utils.get_auth_from_url(url)720721    def test_get_auth_from_url_encoded_hashes(self):722        url = 'http://user:pass%23pass@complex.url.com/path?query=yes'723        assert ('user', 'pass#pass') == requests.utils.get_auth_from_url(url)724725    def test_cannot_send_unprepared_requests(self):726        r = requests.Request(url=HTTPBIN)727        with pytest.raises(ValueError):728            requests.Session().send(r)729730    def test_http_error(self):731        error = requests.exceptions.HTTPError()732        assert not error.response733        response = requests.Response()734        error = requests.exceptions.HTTPError(response=response)735        assert error.response == response736        error = requests.exceptions.HTTPError('message', response=response)737        assert str(error) == 'message'738        assert error.response == response739740    def test_session_pickling(self):741        r = requests.Request('GET', httpbin('get'))742        s = requests.Session()743744        s = pickle.loads(pickle.dumps(s))745        s.proxies = getproxies()746747        r = s.send(r.prepare())748        assert r.status_code == 200749750    def test_fixes_1329(self):751        """752        Ensure that header updates are done case-insensitively.753        """754        s = requests.Session()755        s.headers.update({'ACCEPT': 'BOGUS'})756        s.headers.update({'accept': 'application/json'})757        r = s.get(httpbin('get'))758        headers = r.request.headers759        assert headers['accept'] == 'application/json'760        assert headers['Accept'] == 'application/json'761        assert headers['ACCEPT'] == 'application/json'762763    def test_uppercase_scheme_redirect(self):764        parts = urlparse(httpbin('html'))765        url = "HTTP://" + parts.netloc + parts.path766        r = requests.get(httpbin('redirect-to'), params={'url': url})767        assert r.status_code == 200768        assert r.url.lower() == url.lower()769770    def test_transport_adapter_ordering(self):771        s = requests.Session()772        order = ['https://', 'http://']773        assert order == list(s.adapters)774        s.mount('http://git', HTTPAdapter())775        s.mount('http://github', HTTPAdapter())776        s.mount('http://github.com', HTTPAdapter())777        s.mount('http://github.com/about/', HTTPAdapter())778        order = [779            'http://github.com/about/',780            'http://github.com',781            'http://github',782            'http://git',783            'https://',784            'http://',785        ]786        assert order == list(s.adapters)787        s.mount('http://gittip', HTTPAdapter())788        s.mount('http://gittip.com', HTTPAdapter())789        s.mount('http://gittip.com/about/', HTTPAdapter())790        order = [791            'http://github.com/about/',792            'http://gittip.com/about/',793            'http://github.com',794            'http://gittip.com',795            'http://github',796            'http://gittip',797            'http://git',798            'https://',799            'http://',800        ]801        assert order == list(s.adapters)802        s2 = requests.Session()803        s2.adapters = {'http://': HTTPAdapter()}804        s2.mount('https://', HTTPAdapter())805        assert 'http://' in s2.adapters806        assert 'https://' in s2.adapters807808    def test_header_remove_is_case_insensitive(self):809        # From issue #1321810        s = requests.Session()811        s.headers['foo'] = 'bar'812        r = s.get(httpbin('get'), headers={'FOO': None})813        assert 'foo' not in r.request.headers814815    def test_params_are_merged_case_sensitive(self):816        s = requests.Session()817        s.params['foo'] = 'bar'818        r = s.get(httpbin('get'), params={'FOO': 'bar'})819        assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}820821822    def test_long_authinfo_in_url(self):823        url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(824            'E8A3BE87-9E3F-4620-8858-95478E385B5B',825            'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',826            'exactly-------------sixty-----------three------------characters',827        )828        r = requests.Request('GET', url).prepare()829        assert r.url == url830831    def test_header_keys_are_native(self):832        headers = {u'unicode': 'blah', 'byte'.encode('ascii'): 'blah'}833        r = requests.Request('GET', httpbin('get'), headers=headers)834        p = r.prepare()835836        # This is testing that they are builtin strings. A bit weird, but there837        # we go.838        assert 'unicode' in p.headers.keys()839        assert 'byte' in p.headers.keys()840841    def test_can_send_nonstring_objects_with_files(self):842        data = {'a': 0.0}843        files = {'b': 'foo'}844        r = requests.Request('POST', httpbin('post'), data=data, files=files)845        p = r.prepare()846847        assert 'multipart/form-data' in p.headers['Content-Type']848849    def test_autoset_header_values_are_native(self):850        data = 'this is a string'851        length = '16'852        req = requests.Request('POST', httpbin('post'), data=data)853        p = req.prepare()854855        assert p.headers['Content-Length'] == length856857    def test_oddball_schemes_dont_check_URLs(self):858        test_urls = (859            'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',860            'file:///etc/passwd',861            'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',862        )863        for test_url in test_urls:864            req = requests.Request('GET', test_url)865            preq = req.prepare()866            assert test_url == preq.url867868869class TestContentEncodingDetection(unittest.TestCase):870871    def test_none(self):872        encodings = requests.utils.get_encodings_from_content('')873        assert not len(encodings)874875    def test_html_charset(self):876        """HTML5 meta charset attribute"""877        content = '<meta charset="UTF-8">'878        encodings = requests.utils.get_encodings_from_content(content)879        assert len(encodings) == 1880        assert encodings[0] == 'UTF-8'881882    def test_html4_pragma(self):883        """HTML4 pragma directive"""884        content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">'885        encodings = requests.utils.get_encodings_from_content(content)886        assert len(encodings) == 1887        assert encodings[0] == 'UTF-8'888889    def test_xhtml_pragma(self):890        """XHTML 1.x served with text/html MIME type"""891        content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />'892        encodings = requests.utils.get_encodings_from_content(content)893        assert len(encodings) == 1894        assert encodings[0] == 'UTF-8'895896    def test_xml(self):897        """XHTML 1.x served as XML"""898        content = '<?xml version="1.0" encoding="UTF-8"?>'899        encodings = requests.utils.get_encodings_from_content(content)900        assert len(encodings) == 1901        assert encodings[0] == 'UTF-8'902903    def test_precedence(self):904        content = '''905        <?xml version="1.0" encoding="XML"?>906        <meta charset="HTML5">907        <meta http-equiv="Content-type" content="text/html;charset=HTML4" />908        '''.strip()909        encodings = requests.utils.get_encodings_from_content(content)910        assert encodings == ['HTML5', 'HTML4', 'XML']911912913class TestCaseInsensitiveDict(unittest.TestCase):914915    def test_mapping_init(self):916        cid = CaseInsensitiveDict({'Foo': 'foo','BAr': 'bar'})917        assert len(cid) == 2918        assert 'foo' in cid919        assert 'bar' in cid920921    def test_iterable_init(self):922        cid = CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')])923        assert len(cid) == 2924        assert 'foo' in cid925        assert 'bar' in cid926927    def test_kwargs_init(self):928        cid = CaseInsensitiveDict(FOO='foo', BAr='bar')929        assert len(cid) == 2930        assert 'foo' in cid931        assert 'bar' in cid932933    def test_docstring_example(self):934        cid = CaseInsensitiveDict()935        cid['Accept'] = 'application/json'936        assert cid['aCCEPT'] == 'application/json'937        assert list(cid) == ['Accept']938939    def test_len(self):940        cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})941        cid['A'] = 'a'942        assert len(cid) == 2943944    def test_getitem(self):945        cid = CaseInsensitiveDict({'Spam': 'blueval'})946        assert cid['spam'] == 'blueval'947        assert cid['SPAM'] == 'blueval'948949    def test_fixes_649(self):950        """__setitem__ should behave case-insensitively."""951        cid = CaseInsensitiveDict()952        cid['spam'] = 'oneval'953        cid['Spam'] = 'twoval'954        cid['sPAM'] = 'redval'955        cid['SPAM'] = 'blueval'956        assert cid['spam'] == 'blueval'957        assert cid['SPAM'] == 'blueval'958        assert list(cid.keys()) == ['SPAM']959960    def test_delitem(self):961        cid = CaseInsensitiveDict()962        cid['Spam'] = 'someval'963        del cid['sPam']964        assert 'spam' not in cid965        assert len(cid) == 0966967    def test_contains(self):968        cid = CaseInsensitiveDict()969        cid['Spam'] = 'someval'970        assert 'Spam' in cid971        assert 'spam' in cid972        assert 'SPAM' in cid973        assert 'sPam' in cid974        assert 'notspam' not in cid975976    def test_get(self):977        cid = CaseInsensitiveDict()978        cid['spam'] = 'oneval'979        cid['SPAM'] = 'blueval'980        assert cid.get('spam') == 'blueval'981        assert cid.get('SPAM') == 'blueval'982        assert cid.get('sPam') == 'blueval'983        assert cid.get('notspam', 'default') == 'default'984985    def test_update(self):986        cid = CaseInsensitiveDict()987        cid['spam'] = 'blueval'988        cid.update({'sPam': 'notblueval'})989        assert cid['spam'] == 'notblueval'990        cid = CaseInsensitiveDict({'Foo': 'foo','BAr': 'bar'})991        cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})992        assert len(cid) == 2993        assert cid['foo'] == 'anotherfoo'994        assert cid['bar'] == 'anotherbar'995996    def test_update_retains_unchanged(self):997        cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})998        cid.update({'foo': 'newfoo'})999        assert cid['bar'] == 'bar'10001001    def test_iter(self):1002        cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1003        keys = frozenset(['Spam', 'Eggs'])1004        assert frozenset(iter(cid)) == keys10051006    def test_equality(self):1007        cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1008        othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1009        assert cid == othercid1010        del othercid['spam']1011        assert cid != othercid1012        assert cid == {'spam': 'blueval', 'eggs': 'redval'}10131014    def test_setdefault(self):1015        cid = CaseInsensitiveDict({'Spam': 'blueval'})1016        assert cid.setdefault('spam', 'notblueval') == 'blueval'1017        assert cid.setdefault('notspam', 'notblueval') == 'notblueval'10181019    def test_lower_items(self):1020        cid = CaseInsensitiveDict({1021            'Accept': 'application/json',1022            'user-Agent': 'requests',1023        })1024        keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1025        lowerkeyset = frozenset(['accept', 'user-agent'])1026        assert keyset == lowerkeyset10271028    def test_preserve_key_case(self):1029        cid = CaseInsensitiveDict({1030            'Accept': 'application/json',1031            'user-Agent': 'requests',1032        })1033        keyset = frozenset(['Accept', 'user-Agent'])1034        assert frozenset(i[0] for i in cid.items()) == keyset1035        assert frozenset(cid.keys()) == keyset1036        assert frozenset(cid) == keyset10371038    def test_preserve_last_key_case(self):1039        cid = CaseInsensitiveDict({1040            'Accept': 'application/json',1041            'user-Agent': 'requests',1042        })1043        cid.update({'ACCEPT': 'application/json'})1044        cid['USER-AGENT'] = 'requests'1045        keyset = frozenset(['ACCEPT', 'USER-AGENT'])1046        assert frozenset(i[0] for i in cid.items()) == keyset1047        assert frozenset(cid.keys()) == keyset1048        assert frozenset(cid) == keyset104910501051class UtilsTestCase(unittest.TestCase):10521053    def test_super_len_io_streams(self):1054        """ Ensures that we properly deal with different kinds of IO streams. """1055        # uses StringIO or io.StringIO (see import above)1056        from io import BytesIO1057        from requests.utils import super_len10581059        assert super_len(StringIO.StringIO()) == 01060        assert super_len(StringIO.StringIO('with so much drama in the LBC')) == 2910611062        assert super_len(BytesIO()) == 01063        assert super_len(BytesIO(b"it's kinda hard bein' snoop d-o-double-g")) == 4010641065        try:1066            import cStringIO1067        except ImportError:1068            pass1069        else:1070            assert super_len(cStringIO.StringIO('but some how, some way...')) == 2510711072    def test_get_environ_proxies_ip_ranges(self):1073        """ Ensures that IP addresses are correctly matches with ranges in no_proxy variable """1074        from requests.utils import get_environ_proxies1075        os.environ['no_proxy'] = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"1076        assert get_environ_proxies('http://192.168.0.1:5000/') == {}1077        assert get_environ_proxies('http://192.168.0.1/') == {}1078        assert get_environ_proxies('http://172.16.1.1/') == {}1079        assert get_environ_proxies('http://172.16.1.1:5000/') == {}1080        assert get_environ_proxies('http://192.168.1.1:5000/') != {}1081        assert get_environ_proxies('http://192.168.1.1/') != {}10821083    def test_get_environ_proxies(self):1084        """ Ensures that IP addresses are correctly matches with ranges in no_proxy variable """1085        from requests.utils import get_environ_proxies1086        os.environ['no_proxy'] = "127.0.0.1,localhost.localdomain,192.168.0.0/24,172.16.1.1"1087        assert get_environ_proxies('http://localhost.localdomain:5000/v1.0/') == {}1088        assert get_environ_proxies('http://www.requests.com/') != {}10891090    def test_is_ipv4_address(self):1091        from requests.utils import is_ipv4_address1092        assert is_ipv4_address('8.8.8.8')1093        assert not is_ipv4_address('8.8.8.8.8')1094        assert not is_ipv4_address('localhost.localdomain')10951096    def test_is_valid_cidr(self):1097        from requests.utils import is_valid_cidr1098        assert not is_valid_cidr('8.8.8.8')1099        assert is_valid_cidr('192.168.1.0/24')11001101    def test_dotted_netmask(self):1102        from requests.utils import dotted_netmask1103        assert dotted_netmask(8) == '255.0.0.0'1104        assert dotted_netmask(24) == '255.255.255.0'1105        assert dotted_netmask(25) == '255.255.255.128'11061107    def test_address_in_network(self):1108        from requests.utils import address_in_network1109        assert address_in_network('192.168.1.1', '192.168.1.0/24')1110        assert not address_in_network('172.16.0.1', '192.168.1.0/24')11111112    def test_get_auth_from_url(self):1113        """ Ensures that username and password in well-encoded URI as per RFC 3986 are correclty extracted """1114        from requests.utils import get_auth_from_url1115        from requests.compat import quote1116        percent_encoding_test_chars = "%!*'();:@&=+$,/?#[] "1117        url_address = "request.com/url.html#test"1118        url = "http://" + quote(percent_encoding_test_chars, '') + ':' + quote(percent_encoding_test_chars, '') + '@' + url_address1119        (username, password) = get_auth_from_url(url)1120        assert username == percent_encoding_test_chars1121        assert password == percent_encoding_test_chars112211231124class TestMorselToCookieExpires(unittest.TestCase):11251126    """Tests for morsel_to_cookie when morsel contains expires."""11271128    def test_expires_valid_str(self):1129        """Test case where we convert expires from string time."""11301131        morsel = Morsel()1132        morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1133        cookie = morsel_to_cookie(morsel)1134        assert cookie.expires == 111351136    def test_expires_invalid_int(self):1137        """Test case where an invalid type is passed for expires."""11381139        morsel = Morsel()1140        morsel['expires'] = 1001141        with pytest.raises(TypeError):1142            morsel_to_cookie(morsel)11431144    def test_expires_invalid_str(self):1145        """Test case where an invalid string is input."""11461147        morsel = Morsel()1148        morsel['expires'] = 'woops'1149        with pytest.raises(ValueError):1150            morsel_to_cookie(morsel)11511152    def test_expires_none(self):1153        """Test case where expires is None."""11541155        morsel = Morsel()1156        morsel['expires'] = None1157        cookie = morsel_to_cookie(morsel)1158        assert cookie.expires is None115911601161class TestMorselToCookieMaxAge(unittest.TestCase):11621163    """Tests for morsel_to_cookie when morsel contains max-age."""11641165    def test_max_age_valid_int(self):1166        """Test case where a valid max age in seconds is passed."""11671168        morsel = Morsel()1169        morsel['max-age'] = 601170        cookie = morsel_to_cookie(morsel)1171        assert isinstance(cookie.expires, int)11721173    def test_max_age_invalid_str(self):1174        """Test case where a invalid max age is passed."""11751176        morsel = Morsel()1177        morsel['max-age'] = 'woops'1178        with pytest.raises(TypeError):1179            morsel_to_cookie(morsel)118011811182class TestTimeout:1183    def test_stream_timeout(self):1184        try:1185            r = requests.get('https://httpbin.org/delay/10', timeout=5.0)1186        except requests.exceptions.Timeout as e:1187            assert 'Read timed out' in e.args[0].args[0]118811891190if __name__ == '__main__':1191    unittest.main()