Skip to content
Myr

test_requests.py

This file

Path

test_requests.py

1,481 lines · 49.2 KiB · Python

Last changed by

Merge pull request #2176 from kevinburke/connectKenneth Reitzbefore adoption32e403a

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 (InvalidURL, MissingSchema, ConnectTimeout,22                                 ReadTimeout, ConnectionError, Timeout)23from requests.models import PreparedRequest24from requests.structures import CaseInsensitiveDict25from requests.sessions import SessionRedirectMixin26from requests.models import urlencode27from requests.hooks import default_hooks2829try:30    import StringIO31except ImportError:32    import io as StringIO3334if is_py3:35    def u(s):36        return s37else:38    def u(s):39        return s.decode('unicode-escape')404142# Requests to this URL should always fail with a connection timeout (nothing43# listening on that port)44TARPIT = "http://10.255.255.1"45HTTPBIN = os.environ.get('HTTPBIN_URL', 'http://httpbin.org/')46# Issue #1483: Make sure the URL always has a trailing slash47HTTPBIN = HTTPBIN.rstrip('/') + '/'484950def httpbin(*suffix):51    """Returns url for HTTPBIN resource."""52    return urljoin(HTTPBIN, '/'.join(suffix))535455class RequestsTestCase(unittest.TestCase):5657    _multiprocess_can_split_ = True5859    def setUp(self):60        """Create simple data set with headers."""61        pass6263    def tearDown(self):64        """Teardown."""65        pass6667    def test_entry_points(self):6869        requests.session70        requests.session().get71        requests.session().head72        requests.get73        requests.head74        requests.put75        requests.patch76        requests.post7778    def test_invalid_url(self):79        with pytest.raises(MissingSchema):80            requests.get('hiwpefhipowhefopw')81        with pytest.raises(InvalidURL):82            requests.get('http://')8384    def test_basic_building(self):85        req = requests.Request()86        req.url = 'http://kennethreitz.org/'87        req.data = {'life': '42'}8889        pr = req.prepare()90        assert pr.url == req.url91        assert pr.body == 'life=42'9293    def test_no_content_length(self):94        get_req = requests.Request('GET', httpbin('get')).prepare()95        assert 'Content-Length' not in get_req.headers96        head_req = requests.Request('HEAD', httpbin('head')).prepare()97        assert 'Content-Length' not in head_req.headers9899    def test_path_is_not_double_encoded(self):100        request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()101102        assert request.path_url == '/get/test%20case'103104    def test_params_are_added_before_fragment(self):105        request = requests.Request('GET',106            "http://example.com/path#fragment", params={"a": "b"}).prepare()107        assert request.url == "http://example.com/path?a=b#fragment"108        request = requests.Request('GET',109            "http://example.com/path?key=value#fragment", params={"a": "b"}).prepare()110        assert request.url == "http://example.com/path?key=value&a=b#fragment"111112    def test_mixed_case_scheme_acceptable(self):113        s = requests.Session()114        s.proxies = getproxies()115        parts = urlparse(httpbin('get'))116        schemes = ['http://', 'HTTP://', 'hTTp://', 'HttP://',117                   'https://', 'HTTPS://', 'hTTps://', 'HttPs://']118        for scheme in schemes:119            url = scheme + parts.netloc + parts.path120            r = requests.Request('GET', url)121            r = s.send(r.prepare())122            assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)123124    def test_HTTP_200_OK_GET_ALTERNATIVE(self):125        r = requests.Request('GET', httpbin('get'))126        s = requests.Session()127        s.proxies = getproxies()128129        r = s.send(r.prepare())130131        assert r.status_code == 200132133    def test_HTTP_302_ALLOW_REDIRECT_GET(self):134        r = requests.get(httpbin('redirect', '1'))135        assert r.status_code == 200136        assert r.history[0].status_code == 302137        assert r.history[0].is_redirect138139    # def test_HTTP_302_ALLOW_REDIRECT_POST(self):140    #     r = requests.post(httpbin('status', '302'), data={'some': 'data'})141    #     self.assertEqual(r.status_code, 200)142143    def test_HTTP_200_OK_GET_WITH_PARAMS(self):144        heads = {'User-agent': 'Mozilla/5.0'}145146        r = requests.get(httpbin('user-agent'), headers=heads)147148        assert heads['User-agent'] in r.text149        assert r.status_code == 200150151    def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):152        heads = {'User-agent': 'Mozilla/5.0'}153154        r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)155        assert r.status_code == 200156157    def test_set_cookie_on_301(self):158        s = requests.session()159        url = httpbin('cookies/set?foo=bar')160        s.get(url)161        assert s.cookies['foo'] == 'bar'162163    def test_cookie_sent_on_redirect(self):164        s = requests.session()165        s.get(httpbin('cookies/set?foo=bar'))166        r = s.get(httpbin('redirect/1'))  # redirects to httpbin('get')167        assert 'Cookie' in r.json()['headers']168169    def test_cookie_removed_on_expire(self):170        s = requests.session()171        s.get(httpbin('cookies/set?foo=bar'))172        assert s.cookies['foo'] == 'bar'173        s.get(174            httpbin('response-headers'),175            params={176                'Set-Cookie':177                    'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'178            }179        )180        assert 'foo' not in s.cookies181182    def test_cookie_quote_wrapped(self):183        s = requests.session()184        s.get(httpbin('cookies/set?foo="bar:baz"'))185        assert s.cookies['foo'] == '"bar:baz"'186187    def test_cookie_persists_via_api(self):188        s = requests.session()189        r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})190        assert 'foo' in r.request.headers['Cookie']191        assert 'foo' in r.history[0].request.headers['Cookie']192193    def test_request_cookie_overrides_session_cookie(self):194        s = requests.session()195        s.cookies['foo'] = 'bar'196        r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})197        assert r.json()['cookies']['foo'] == 'baz'198        # Session cookie should not be modified199        assert s.cookies['foo'] == 'bar'200201    def test_request_cookies_not_persisted(self):202        s = requests.session()203        s.get(httpbin('cookies'), cookies={'foo': 'baz'})204        # Sending a request with cookies should not add cookies to the session205        assert not s.cookies206207    def test_generic_cookiejar_works(self):208        cj = cookielib.CookieJar()209        cookiejar_from_dict({'foo': 'bar'}, cj)210        s = requests.session()211        s.cookies = cj212        r = s.get(httpbin('cookies'))213        # Make sure the cookie was sent214        assert r.json()['cookies']['foo'] == 'bar'215        # Make sure the session cj is still the custom one216        assert s.cookies is cj217218    def test_param_cookiejar_works(self):219        cj = cookielib.CookieJar()220        cookiejar_from_dict({'foo': 'bar'}, cj)221        s = requests.session()222        r = s.get(httpbin('cookies'), cookies=cj)223        # Make sure the cookie was sent224        assert r.json()['cookies']['foo'] == 'bar'225226    def test_requests_in_history_are_not_overridden(self):227        resp = requests.get(httpbin('redirect/3'))228        urls = [r.url for r in resp.history]229        req_urls = [r.request.url for r in resp.history]230        assert urls == req_urls231232    def test_history_is_always_a_list(self):233        """234        Show that even with redirects, Response.history is always a list.235        """236        resp = requests.get(httpbin('get'))237        assert isinstance(resp.history, list)238        resp = requests.get(httpbin('redirect/1'))239        assert isinstance(resp.history, list)240        assert not isinstance(resp.history, tuple)241242    def test_headers_on_session_with_None_are_not_sent(self):243        """Do not send headers in Session.headers with None values."""244        ses = requests.Session()245        ses.headers['Accept-Encoding'] = None246        req = requests.Request('GET', 'http://httpbin.org/get')247        prep = ses.prepare_request(req)248        assert 'Accept-Encoding' not in prep.headers249250    def test_user_agent_transfers(self):251252        heads = {253            'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'254        }255256        r = requests.get(httpbin('user-agent'), headers=heads)257        assert heads['User-agent'] in r.text258259        heads = {260            'user-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'261        }262263        r = requests.get(httpbin('user-agent'), headers=heads)264        assert heads['user-agent'] in r.text265266    def test_HTTP_200_OK_HEAD(self):267        r = requests.head(httpbin('get'))268        assert r.status_code == 200269270    def test_HTTP_200_OK_PUT(self):271        r = requests.put(httpbin('put'))272        assert r.status_code == 200273274    def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):275        auth = ('user', 'pass')276        url = httpbin('basic-auth', 'user', 'pass')277278        r = requests.get(url, auth=auth)279        assert r.status_code == 200280281        r = requests.get(url)282        assert r.status_code == 401283284        s = requests.session()285        s.auth = auth286        r = s.get(url)287        assert r.status_code == 200288289    def test_basicauth_with_netrc(self):290        auth = ('user', 'pass')291        wrong_auth = ('wronguser', 'wrongpass')292        url = httpbin('basic-auth', 'user', 'pass')293294        def get_netrc_auth_mock(url):295            return auth296        requests.sessions.get_netrc_auth = get_netrc_auth_mock297298        # Should use netrc and work.299        r = requests.get(url)300        assert r.status_code == 200301302        # Given auth should override and fail.303        r = requests.get(url, auth=wrong_auth)304        assert r.status_code == 401305306        s = requests.session()307308        # Should use netrc and work.309        r = s.get(url)310        assert r.status_code == 200311312        # Given auth should override and fail.313        s.auth = wrong_auth314        r = s.get(url)315        assert r.status_code == 401316317    def test_DIGEST_HTTP_200_OK_GET(self):318319        auth = HTTPDigestAuth('user', 'pass')320        url = httpbin('digest-auth', 'auth', 'user', 'pass')321322        r = requests.get(url, auth=auth)323        assert r.status_code == 200324325        r = requests.get(url)326        assert r.status_code == 401327328        s = requests.session()329        s.auth = HTTPDigestAuth('user', 'pass')330        r = s.get(url)331        assert r.status_code == 200332333    def test_DIGEST_AUTH_RETURNS_COOKIE(self):334        url = httpbin('digest-auth', 'auth', 'user', 'pass')335        auth = HTTPDigestAuth('user', 'pass')336        r = requests.get(url)337        assert r.cookies['fake'] == 'fake_value'338339        r = requests.get(url, auth=auth)340        assert r.status_code == 200341342    def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self):343        url = httpbin('digest-auth', 'auth', 'user', 'pass')344        auth = HTTPDigestAuth('user', 'pass')345        s = requests.Session()346        s.get(url, auth=auth)347        assert s.cookies['fake'] == 'fake_value'348349    def test_DIGEST_STREAM(self):350351        auth = HTTPDigestAuth('user', 'pass')352        url = httpbin('digest-auth', 'auth', 'user', 'pass')353354        r = requests.get(url, auth=auth, stream=True)355        assert r.raw.read() != b''356357        r = requests.get(url, auth=auth, stream=False)358        assert r.raw.read() == b''359360    def test_DIGESTAUTH_WRONG_HTTP_401_GET(self):361362        auth = HTTPDigestAuth('user', 'wrongpass')363        url = httpbin('digest-auth', 'auth', 'user', 'pass')364365        r = requests.get(url, auth=auth)366        assert r.status_code == 401367368        r = requests.get(url)369        assert r.status_code == 401370371        s = requests.session()372        s.auth = auth373        r = s.get(url)374        assert r.status_code == 401375376    def test_DIGESTAUTH_QUOTES_QOP_VALUE(self):377378        auth = HTTPDigestAuth('user', 'pass')379        url = httpbin('digest-auth', 'auth', 'user', 'pass')380381        r = requests.get(url, auth=auth)382        assert '"auth"' in r.request.headers['Authorization']383384    def test_POSTBIN_GET_POST_FILES(self):385386        url = httpbin('post')387        post1 = requests.post(url).raise_for_status()388389        post1 = requests.post(url, data={'some': 'data'})390        assert post1.status_code == 200391392        with open('requirements.txt') as f:393            post2 = requests.post(url, files={'some': f})394        assert post2.status_code == 200395396        post4 = requests.post(url, data='[{"some": "json"}]')397        assert post4.status_code == 200398399        with pytest.raises(ValueError):400            requests.post(url, files=['bad file data'])401402    def test_POSTBIN_GET_POST_FILES_WITH_DATA(self):403404        url = httpbin('post')405        post1 = requests.post(url).raise_for_status()406407        post1 = requests.post(url, data={'some': 'data'})408        assert post1.status_code == 200409410        with open('requirements.txt') as f:411            post2 = requests.post(url,412                data={'some': 'data'}, files={'some': f})413        assert post2.status_code == 200414415        post4 = requests.post(url, data='[{"some": "json"}]')416        assert post4.status_code == 200417418        with pytest.raises(ValueError):419            requests.post(url, files=['bad file data'])420421    def test_conflicting_post_params(self):422        url = httpbin('post')423        with open('requirements.txt') as f:424            pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")425            pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")426427    def test_request_ok_set(self):428        r = requests.get(httpbin('status', '404'))429        assert not r.ok430431    def test_status_raising(self):432        r = requests.get(httpbin('status', '404'))433        with pytest.raises(requests.exceptions.HTTPError):434            r.raise_for_status()435436        r = requests.get(httpbin('status', '500'))437        assert not r.ok438439    def test_decompress_gzip(self):440        r = requests.get(httpbin('gzip'))441        r.content.decode('ascii')442443    def test_unicode_get(self):444        url = httpbin('/get')445        requests.get(url, params={'foo': 'føø'})446        requests.get(url, params={'føø': 'føø'})447        requests.get(url, params={'føø': 'føø'})448        requests.get(url, params={'foo': 'foo'})449        requests.get(httpbin('ø'), params={'foo': 'foo'})450451    def test_unicode_header_name(self):452        requests.put(453            httpbin('put'),454            headers={str('Content-Type'): 'application/octet-stream'},455            data='\xff')  # compat.str is unicode.456457    def test_pyopenssl_redirect(self):458        requests.get('https://httpbin.org/status/301')459460    def test_urlencoded_get_query_multivalued_param(self):461462        r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))463        assert r.status_code == 200464        assert r.url == httpbin('get?test=foo&test=baz')465466    def test_different_encodings_dont_break_post(self):467        r = requests.post(httpbin('post'),468            data={'stuff': json.dumps({'a': 123})},469            params={'blah': 'asdf1234'},470            files={'file': ('test_requests.py', open(__file__, 'rb'))})471        assert r.status_code == 200472473    def test_unicode_multipart_post(self):474        r = requests.post(httpbin('post'),475            data={'stuff': u('ëlïxr')},476            files={'file': ('test_requests.py', open(__file__, 'rb'))})477        assert r.status_code == 200478479        r = requests.post(httpbin('post'),480            data={'stuff': u('ëlïxr').encode('utf-8')},481            files={'file': ('test_requests.py', open(__file__, 'rb'))})482        assert r.status_code == 200483484        r = requests.post(httpbin('post'),485            data={'stuff': 'elixr'},486            files={'file': ('test_requests.py', open(__file__, 'rb'))})487        assert r.status_code == 200488489        r = requests.post(httpbin('post'),490            data={'stuff': 'elixr'.encode('utf-8')},491            files={'file': ('test_requests.py', open(__file__, 'rb'))})492        assert r.status_code == 200493494    def test_unicode_multipart_post_fieldnames(self):495        filename = os.path.splitext(__file__)[0] + '.py'496        r = requests.Request(method='POST',497                             url=httpbin('post'),498                             data={'stuff'.encode('utf-8'): 'elixr'},499                             files={'file': ('test_requests.py',500                                             open(filename, 'rb'))})501        prep = r.prepare()502        assert b'name="stuff"' in prep.body503        assert b'name="b\'stuff\'"' not in prep.body504505    def test_unicode_method_name(self):506        files = {'file': open('test_requests.py', 'rb')}507        r = requests.request(508            method=u('POST'), url=httpbin('post'), files=files)509        assert r.status_code == 200510511    def test_custom_content_type(self):512        r = requests.post(513            httpbin('post'),514            data={'stuff': json.dumps({'a': 123})},515            files={'file1': ('test_requests.py', open(__file__, 'rb')),516                   'file2': ('test_requests', open(__file__, 'rb'),517                             'text/py-content-type')})518        assert r.status_code == 200519        assert b"text/py-content-type" in r.request.body520521    def test_hook_receives_request_arguments(self):522        def hook(resp, **kwargs):523            assert resp is not None524            assert kwargs != {}525526        requests.Request('GET', HTTPBIN, hooks={'response': hook})527528    def test_session_hooks_are_used_with_no_request_hooks(self):529        hook = lambda x, *args, **kwargs: x530        s = requests.Session()531        s.hooks['response'].append(hook)532        r = requests.Request('GET', HTTPBIN)533        prep = s.prepare_request(r)534        assert prep.hooks['response'] != []535        assert prep.hooks['response'] == [hook]536537    def test_session_hooks_are_overriden_by_request_hooks(self):538        hook1 = lambda x, *args, **kwargs: x539        hook2 = lambda x, *args, **kwargs: x540        assert hook1 is not hook2541        s = requests.Session()542        s.hooks['response'].append(hook2)543        r = requests.Request('GET', HTTPBIN, hooks={'response': [hook1]})544        prep = s.prepare_request(r)545        assert prep.hooks['response'] == [hook1]546547    def test_prepared_request_hook(self):548        def hook(resp, **kwargs):549            resp.hook_working = True550            return resp551552        req = requests.Request('GET', HTTPBIN, hooks={'response': hook})553        prep = req.prepare()554555        s = requests.Session()556        s.proxies = getproxies()557        resp = s.send(prep)558559        assert hasattr(resp, 'hook_working')560561    def test_prepared_from_session(self):562        class DummyAuth(requests.auth.AuthBase):563            def __call__(self, r):564                r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'565                return r566567        req = requests.Request('GET', httpbin('headers'))568        assert not req.auth569570        s = requests.Session()571        s.auth = DummyAuth()572573        prep = s.prepare_request(req)574        resp = s.send(prep)575576        assert resp.json()['headers'][577            'Dummy-Auth-Test'] == 'dummy-auth-test-ok'578579    def test_links(self):580        r = requests.Response()581        r.headers = {582            'cache-control': 'public, max-age=60, s-maxage=60',583            'connection': 'keep-alive',584            'content-encoding': 'gzip',585            'content-type': 'application/json; charset=utf-8',586            'date': 'Sat, 26 Jan 2013 16:47:56 GMT',587            'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',588            'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',589            'link': ('<https://api.github.com/users/kennethreitz/repos?'590                     'page=2&per_page=10>; rel="next", <https://api.github.'591                     'com/users/kennethreitz/repos?page=7&per_page=10>; '592                     ' rel="last"'),593            'server': 'GitHub.com',594            'status': '200 OK',595            'vary': 'Accept',596            'x-content-type-options': 'nosniff',597            'x-github-media-type': 'github.beta',598            'x-ratelimit-limit': '60',599            'x-ratelimit-remaining': '57'600        }601        assert r.links['next']['rel'] == 'next'602603    def test_cookie_parameters(self):604        key = 'some_cookie'605        value = 'some_value'606        secure = True607        domain = 'test.com'608        rest = {'HttpOnly': True}609610        jar = requests.cookies.RequestsCookieJar()611        jar.set(key, value, secure=secure, domain=domain, rest=rest)612613        assert len(jar) == 1614        assert 'some_cookie' in jar615616        cookie = list(jar)[0]617        assert cookie.secure == secure618        assert cookie.domain == domain619        assert cookie._rest['HttpOnly'] == rest['HttpOnly']620621    def test_cookie_as_dict_keeps_len(self):622        key = 'some_cookie'623        value = 'some_value'624625        key1 = 'some_cookie1'626        value1 = 'some_value1'627628        jar = requests.cookies.RequestsCookieJar()629        jar.set(key, value)630        jar.set(key1, value1)631632        d1 = dict(jar)633        d2 = dict(jar.iteritems())634        d3 = dict(jar.items())635636        assert len(jar) == 2637        assert len(d1) == 2638        assert len(d2) == 2639        assert len(d3) == 2640641    def test_cookie_as_dict_keeps_items(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        d1 = dict(jar)653        d2 = dict(jar.iteritems())654        d3 = dict(jar.items())655656        assert d1['some_cookie'] == 'some_value'657        assert d2['some_cookie'] == 'some_value'658        assert d3['some_cookie1'] == 'some_value1'659660    def test_cookie_as_dict_keys(self):661        key = 'some_cookie'662        value = 'some_value'663664        key1 = 'some_cookie1'665        value1 = 'some_value1'666667        jar = requests.cookies.RequestsCookieJar()668        jar.set(key, value)669        jar.set(key1, value1)670671        keys = jar.keys()672        assert keys == list(keys)673        # make sure one can use keys multiple times674        assert list(keys) == list(keys)675676    def test_cookie_as_dict_values(self):677        key = 'some_cookie'678        value = 'some_value'679680        key1 = 'some_cookie1'681        value1 = 'some_value1'682683        jar = requests.cookies.RequestsCookieJar()684        jar.set(key, value)685        jar.set(key1, value1)686687        values = jar.values()688        assert values == list(values)689        # make sure one can use values multiple times690        assert list(values) == list(values)691692    def test_cookie_as_dict_items(self):693        key = 'some_cookie'694        value = 'some_value'695696        key1 = 'some_cookie1'697        value1 = 'some_value1'698699        jar = requests.cookies.RequestsCookieJar()700        jar.set(key, value)701        jar.set(key1, value1)702703        items = jar.items()704        assert items == list(items)705        # make sure one can use items multiple times706        assert list(items) == list(items)707708    def test_time_elapsed_blank(self):709        r = requests.get(httpbin('get'))710        td = r.elapsed711        total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)712                         * 10**6) / 10**6)713        assert total_seconds > 0.0714715    def test_response_is_iterable(self):716        r = requests.Response()717        io = StringIO.StringIO('abc')718        read_ = io.read719720        def read_mock(amt, decode_content=None):721            return read_(amt)722        setattr(io, 'read', read_mock)723        r.raw = io724        assert next(iter(r))725        io.close()726727    def test_response_decode_unicode(self):728        """729        When called with decode_unicode, Response.iter_content should always730        return unicode.731        """732        r = requests.Response()733        r._content_consumed = True734        r._content = b'the content'735        r.encoding = 'ascii'736737        chunks = r.iter_content(decode_unicode=True)738        assert all(isinstance(chunk, str) for chunk in chunks)739740        # also for streaming741        r = requests.Response()742        r.raw = io.BytesIO(b'the content')743        r.encoding = 'ascii'744        chunks = r.iter_content(decode_unicode=True)745        assert all(isinstance(chunk, str) for chunk in chunks)746747    def test_request_and_response_are_pickleable(self):748        r = requests.get(httpbin('get'))749750        # verify we can pickle the original request751        assert pickle.loads(pickle.dumps(r.request))752753        # verify we can pickle the response and that we have access to754        # the original request.755        pr = pickle.loads(pickle.dumps(r))756        assert r.request.url == pr.request.url757        assert r.request.headers == pr.request.headers758759    def test_get_auth_from_url(self):760        url = 'http://user:pass@complex.url.com/path?query=yes'761        assert ('user', 'pass') == requests.utils.get_auth_from_url(url)762763    def test_get_auth_from_url_encoded_spaces(self):764        url = 'http://user:pass%20pass@complex.url.com/path?query=yes'765        assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)766767    def test_get_auth_from_url_not_encoded_spaces(self):768        url = 'http://user:pass pass@complex.url.com/path?query=yes'769        assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)770771    def test_get_auth_from_url_percent_chars(self):772        url = 'http://user%25user:pass@complex.url.com/path?query=yes'773        assert ('user%user', 'pass') == requests.utils.get_auth_from_url(url)774775    def test_get_auth_from_url_encoded_hashes(self):776        url = 'http://user:pass%23pass@complex.url.com/path?query=yes'777        assert ('user', 'pass#pass') == requests.utils.get_auth_from_url(url)778779    def test_cannot_send_unprepared_requests(self):780        r = requests.Request(url=HTTPBIN)781        with pytest.raises(ValueError):782            requests.Session().send(r)783784    def test_http_error(self):785        error = requests.exceptions.HTTPError()786        assert not error.response787        response = requests.Response()788        error = requests.exceptions.HTTPError(response=response)789        assert error.response == response790        error = requests.exceptions.HTTPError('message', response=response)791        assert str(error) == 'message'792        assert error.response == response793794    def test_session_pickling(self):795        r = requests.Request('GET', httpbin('get'))796        s = requests.Session()797798        s = pickle.loads(pickle.dumps(s))799        s.proxies = getproxies()800801        r = s.send(r.prepare())802        assert r.status_code == 200803804    def test_fixes_1329(self):805        """806        Ensure that header updates are done case-insensitively.807        """808        s = requests.Session()809        s.headers.update({'ACCEPT': 'BOGUS'})810        s.headers.update({'accept': 'application/json'})811        r = s.get(httpbin('get'))812        headers = r.request.headers813        assert headers['accept'] == 'application/json'814        assert headers['Accept'] == 'application/json'815        assert headers['ACCEPT'] == 'application/json'816817    def test_uppercase_scheme_redirect(self):818        parts = urlparse(httpbin('html'))819        url = "HTTP://" + parts.netloc + parts.path820        r = requests.get(httpbin('redirect-to'), params={'url': url})821        assert r.status_code == 200822        assert r.url.lower() == url.lower()823824    def test_transport_adapter_ordering(self):825        s = requests.Session()826        order = ['https://', 'http://']827        assert order == list(s.adapters)828        s.mount('http://git', HTTPAdapter())829        s.mount('http://github', HTTPAdapter())830        s.mount('http://github.com', HTTPAdapter())831        s.mount('http://github.com/about/', HTTPAdapter())832        order = [833            'http://github.com/about/',834            'http://github.com',835            'http://github',836            'http://git',837            'https://',838            'http://',839        ]840        assert order == list(s.adapters)841        s.mount('http://gittip', HTTPAdapter())842        s.mount('http://gittip.com', HTTPAdapter())843        s.mount('http://gittip.com/about/', HTTPAdapter())844        order = [845            'http://github.com/about/',846            'http://gittip.com/about/',847            'http://github.com',848            'http://gittip.com',849            'http://github',850            'http://gittip',851            'http://git',852            'https://',853            'http://',854        ]855        assert order == list(s.adapters)856        s2 = requests.Session()857        s2.adapters = {'http://': HTTPAdapter()}858        s2.mount('https://', HTTPAdapter())859        assert 'http://' in s2.adapters860        assert 'https://' in s2.adapters861862    def test_header_remove_is_case_insensitive(self):863        # From issue #1321864        s = requests.Session()865        s.headers['foo'] = 'bar'866        r = s.get(httpbin('get'), headers={'FOO': None})867        assert 'foo' not in r.request.headers868869    def test_params_are_merged_case_sensitive(self):870        s = requests.Session()871        s.params['foo'] = 'bar'872        r = s.get(httpbin('get'), params={'FOO': 'bar'})873        assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}874875    def test_long_authinfo_in_url(self):876        url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(877            'E8A3BE87-9E3F-4620-8858-95478E385B5B',878            'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',879            'exactly-------------sixty-----------three------------characters',880        )881        r = requests.Request('GET', url).prepare()882        assert r.url == url883884    def test_header_keys_are_native(self):885        headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}886        r = requests.Request('GET', httpbin('get'), headers=headers)887        p = r.prepare()888889        # This is testing that they are builtin strings. A bit weird, but there890        # we go.891        assert 'unicode' in p.headers.keys()892        assert 'byte' in p.headers.keys()893894    def test_can_send_nonstring_objects_with_files(self):895        data = {'a': 0.0}896        files = {'b': 'foo'}897        r = requests.Request('POST', httpbin('post'), data=data, files=files)898        p = r.prepare()899900        assert 'multipart/form-data' in p.headers['Content-Type']901902    def test_autoset_header_values_are_native(self):903        data = 'this is a string'904        length = '16'905        req = requests.Request('POST', httpbin('post'), data=data)906        p = req.prepare()907908        assert p.headers['Content-Length'] == length909910    def test_oddball_schemes_dont_check_URLs(self):911        test_urls = (912            'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',913            'file:///etc/passwd',914            'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',915        )916        for test_url in test_urls:917            req = requests.Request('GET', test_url)918            preq = req.prepare()919            assert test_url == preq.url920921    def test_auth_is_stripped_on_redirect_off_host(self):922        r = requests.get(923            httpbin('redirect-to'),924            params={'url': 'http://www.google.co.uk'},925            auth=('user', 'pass'),926        )927        assert r.history[0].request.headers['Authorization']928        assert not r.request.headers.get('Authorization', '')929930    def test_auth_is_retained_for_redirect_on_host(self):931        r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))932        h1 = r.history[0].request.headers['Authorization']933        h2 = r.request.headers['Authorization']934935        assert h1 == h2936937    def test_manual_redirect_with_partial_body_read(self):938        s = requests.Session()939        r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)940        assert r1.is_redirect941        rg = s.resolve_redirects(r1, r1.request, stream=True)942943        # read only the first eight bytes of the response body,944        # then follow the redirect945        r1.iter_content(8)946        r2 = next(rg)947        assert r2.is_redirect948949        # read all of the response via iter_content,950        # then follow the redirect951        for _ in r2.iter_content():952            pass953        r3 = next(rg)954        assert not r3.is_redirect955956    def _patch_adapter_gzipped_redirect(self, session, url):957        adapter = session.get_adapter(url=url)958        org_build_response = adapter.build_response959        self._patched_response = False960961        def build_response(*args, **kwargs):962            resp = org_build_response(*args, **kwargs)963            if not self._patched_response:964                resp.raw.headers['content-encoding'] = 'gzip'965                self._patched_response = True966            return resp967968        adapter.build_response = build_response969970    def test_redirect_with_wrong_gzipped_header(self):971        s = requests.Session()972        url = httpbin('redirect/1')973        self._patch_adapter_gzipped_redirect(s, url)974        s.get(url)975976    def test_basic_auth_str_is_always_native(self):977        s = _basic_auth_str("test", "test")978        assert isinstance(s, builtin_str)979        assert s == "Basic dGVzdDp0ZXN0"980981    def test_requests_history_is_saved(self):982        r = requests.get('https://httpbin.org/redirect/5')983        total = r.history[-1].history984        i = 0985        for item in r.history:986            assert item.history == total[0:i]987            i=i+1988989990class TestContentEncodingDetection(unittest.TestCase):991992    def test_none(self):993        encodings = requests.utils.get_encodings_from_content('')994        assert not len(encodings)995996    def test_html_charset(self):997        """HTML5 meta charset attribute"""998        content = '<meta charset="UTF-8">'999        encodings = requests.utils.get_encodings_from_content(content)1000        assert len(encodings) == 11001        assert encodings[0] == 'UTF-8'10021003    def test_html4_pragma(self):1004        """HTML4 pragma directive"""1005        content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">'1006        encodings = requests.utils.get_encodings_from_content(content)1007        assert len(encodings) == 11008        assert encodings[0] == 'UTF-8'10091010    def test_xhtml_pragma(self):1011        """XHTML 1.x served with text/html MIME type"""1012        content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />'1013        encodings = requests.utils.get_encodings_from_content(content)1014        assert len(encodings) == 11015        assert encodings[0] == 'UTF-8'10161017    def test_xml(self):1018        """XHTML 1.x served as XML"""1019        content = '<?xml version="1.0" encoding="UTF-8"?>'1020        encodings = requests.utils.get_encodings_from_content(content)1021        assert len(encodings) == 11022        assert encodings[0] == 'UTF-8'10231024    def test_precedence(self):1025        content = '''1026        <?xml version="1.0" encoding="XML"?>1027        <meta charset="HTML5">1028        <meta http-equiv="Content-type" content="text/html;charset=HTML4" />1029        '''.strip()1030        encodings = requests.utils.get_encodings_from_content(content)1031        assert encodings == ['HTML5', 'HTML4', 'XML']103210331034class TestCaseInsensitiveDict(unittest.TestCase):10351036    def test_mapping_init(self):1037        cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1038        assert len(cid) == 21039        assert 'foo' in cid1040        assert 'bar' in cid10411042    def test_iterable_init(self):1043        cid = CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')])1044        assert len(cid) == 21045        assert 'foo' in cid1046        assert 'bar' in cid10471048    def test_kwargs_init(self):1049        cid = CaseInsensitiveDict(FOO='foo', BAr='bar')1050        assert len(cid) == 21051        assert 'foo' in cid1052        assert 'bar' in cid10531054    def test_docstring_example(self):1055        cid = CaseInsensitiveDict()1056        cid['Accept'] = 'application/json'1057        assert cid['aCCEPT'] == 'application/json'1058        assert list(cid) == ['Accept']10591060    def test_len(self):1061        cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1062        cid['A'] = 'a'1063        assert len(cid) == 210641065    def test_getitem(self):1066        cid = CaseInsensitiveDict({'Spam': 'blueval'})1067        assert cid['spam'] == 'blueval'1068        assert cid['SPAM'] == 'blueval'10691070    def test_fixes_649(self):1071        """__setitem__ should behave case-insensitively."""1072        cid = CaseInsensitiveDict()1073        cid['spam'] = 'oneval'1074        cid['Spam'] = 'twoval'1075        cid['sPAM'] = 'redval'1076        cid['SPAM'] = 'blueval'1077        assert cid['spam'] == 'blueval'1078        assert cid['SPAM'] == 'blueval'1079        assert list(cid.keys()) == ['SPAM']10801081    def test_delitem(self):1082        cid = CaseInsensitiveDict()1083        cid['Spam'] = 'someval'1084        del cid['sPam']1085        assert 'spam' not in cid1086        assert len(cid) == 010871088    def test_contains(self):1089        cid = CaseInsensitiveDict()1090        cid['Spam'] = 'someval'1091        assert 'Spam' in cid1092        assert 'spam' in cid1093        assert 'SPAM' in cid1094        assert 'sPam' in cid1095        assert 'notspam' not in cid10961097    def test_get(self):1098        cid = CaseInsensitiveDict()1099        cid['spam'] = 'oneval'1100        cid['SPAM'] = 'blueval'1101        assert cid.get('spam') == 'blueval'1102        assert cid.get('SPAM') == 'blueval'1103        assert cid.get('sPam') == 'blueval'1104        assert cid.get('notspam', 'default') == 'default'11051106    def test_update(self):1107        cid = CaseInsensitiveDict()1108        cid['spam'] = 'blueval'1109        cid.update({'sPam': 'notblueval'})1110        assert cid['spam'] == 'notblueval'1111        cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1112        cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1113        assert len(cid) == 21114        assert cid['foo'] == 'anotherfoo'1115        assert cid['bar'] == 'anotherbar'11161117    def test_update_retains_unchanged(self):1118        cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1119        cid.update({'foo': 'newfoo'})1120        assert cid['bar'] == 'bar'11211122    def test_iter(self):1123        cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1124        keys = frozenset(['Spam', 'Eggs'])1125        assert frozenset(iter(cid)) == keys11261127    def test_equality(self):1128        cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1129        othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1130        assert cid == othercid1131        del othercid['spam']1132        assert cid != othercid1133        assert cid == {'spam': 'blueval', 'eggs': 'redval'}11341135    def test_setdefault(self):1136        cid = CaseInsensitiveDict({'Spam': 'blueval'})1137        assert cid.setdefault('spam', 'notblueval') == 'blueval'1138        assert cid.setdefault('notspam', 'notblueval') == 'notblueval'11391140    def test_lower_items(self):1141        cid = CaseInsensitiveDict({1142            'Accept': 'application/json',1143            'user-Agent': 'requests',1144        })1145        keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1146        lowerkeyset = frozenset(['accept', 'user-agent'])1147        assert keyset == lowerkeyset11481149    def test_preserve_key_case(self):1150        cid = CaseInsensitiveDict({1151            'Accept': 'application/json',1152            'user-Agent': 'requests',1153        })1154        keyset = frozenset(['Accept', 'user-Agent'])1155        assert frozenset(i[0] for i in cid.items()) == keyset1156        assert frozenset(cid.keys()) == keyset1157        assert frozenset(cid) == keyset11581159    def test_preserve_last_key_case(self):1160        cid = CaseInsensitiveDict({1161            'Accept': 'application/json',1162            'user-Agent': 'requests',1163        })1164        cid.update({'ACCEPT': 'application/json'})1165        cid['USER-AGENT'] = 'requests'1166        keyset = frozenset(['ACCEPT', 'USER-AGENT'])1167        assert frozenset(i[0] for i in cid.items()) == keyset1168        assert frozenset(cid.keys()) == keyset1169        assert frozenset(cid) == keyset117011711172class UtilsTestCase(unittest.TestCase):11731174    def test_super_len_io_streams(self):1175        """ Ensures that we properly deal with different kinds of IO streams. """1176        # uses StringIO or io.StringIO (see import above)1177        from io import BytesIO1178        from requests.utils import super_len11791180        assert super_len(StringIO.StringIO()) == 01181        assert super_len(1182            StringIO.StringIO('with so much drama in the LBC')) == 2911831184        assert super_len(BytesIO()) == 01185        assert super_len(1186            BytesIO(b"it's kinda hard bein' snoop d-o-double-g")) == 4011871188        try:1189            import cStringIO1190        except ImportError:1191            pass1192        else:1193            assert super_len(1194                cStringIO.StringIO('but some how, some way...')) == 2511951196    def test_get_environ_proxies_ip_ranges(self):1197        """Ensures that IP addresses are correctly matches with ranges1198        in no_proxy variable."""1199        from requests.utils import get_environ_proxies1200        os.environ['no_proxy'] = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"1201        assert get_environ_proxies('http://192.168.0.1:5000/') == {}1202        assert get_environ_proxies('http://192.168.0.1/') == {}1203        assert get_environ_proxies('http://172.16.1.1/') == {}1204        assert get_environ_proxies('http://172.16.1.1:5000/') == {}1205        assert get_environ_proxies('http://192.168.1.1:5000/') != {}1206        assert get_environ_proxies('http://192.168.1.1/') != {}12071208    def test_get_environ_proxies(self):1209        """Ensures that IP addresses are correctly matches with ranges1210        in no_proxy variable."""1211        from requests.utils import get_environ_proxies1212        os.environ['no_proxy'] = "127.0.0.1,localhost.localdomain,192.168.0.0/24,172.16.1.1"1213        assert get_environ_proxies(1214            'http://localhost.localdomain:5000/v1.0/') == {}1215        assert get_environ_proxies('http://www.requests.com/') != {}12161217    def test_is_ipv4_address(self):1218        from requests.utils import is_ipv4_address1219        assert is_ipv4_address('8.8.8.8')1220        assert not is_ipv4_address('8.8.8.8.8')1221        assert not is_ipv4_address('localhost.localdomain')12221223    def test_is_valid_cidr(self):1224        from requests.utils import is_valid_cidr1225        assert not is_valid_cidr('8.8.8.8')1226        assert is_valid_cidr('192.168.1.0/24')12271228    def test_dotted_netmask(self):1229        from requests.utils import dotted_netmask1230        assert dotted_netmask(8) == '255.0.0.0'1231        assert dotted_netmask(24) == '255.255.255.0'1232        assert dotted_netmask(25) == '255.255.255.128'12331234    def test_address_in_network(self):1235        from requests.utils import address_in_network1236        assert address_in_network('192.168.1.1', '192.168.1.0/24')1237        assert not address_in_network('172.16.0.1', '192.168.1.0/24')12381239    def test_get_auth_from_url(self):1240        """Ensures that username and password in well-encoded URI as per1241        RFC 3986 are correclty extracted."""1242        from requests.utils import get_auth_from_url1243        from requests.compat import quote1244        percent_encoding_test_chars = "%!*'();:@&=+$,/?#[] "1245        url_address = "request.com/url.html#test"1246        url = "http://" + quote(1247            percent_encoding_test_chars, '') + ':' + quote(1248            percent_encoding_test_chars, '') + '@' + url_address1249        (username, password) = get_auth_from_url(url)1250        assert username == percent_encoding_test_chars1251        assert password == percent_encoding_test_chars125212531254class TestMorselToCookieExpires(unittest.TestCase):12551256    """Tests for morsel_to_cookie when morsel contains expires."""12571258    def test_expires_valid_str(self):1259        """Test case where we convert expires from string time."""12601261        morsel = Morsel()1262        morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1263        cookie = morsel_to_cookie(morsel)1264        assert cookie.expires == 112651266    def test_expires_invalid_int(self):1267        """Test case where an invalid type is passed for expires."""12681269        morsel = Morsel()1270        morsel['expires'] = 1001271        with pytest.raises(TypeError):1272            morsel_to_cookie(morsel)12731274    def test_expires_invalid_str(self):1275        """Test case where an invalid string is input."""12761277        morsel = Morsel()1278        morsel['expires'] = 'woops'1279        with pytest.raises(ValueError):1280            morsel_to_cookie(morsel)12811282    def test_expires_none(self):1283        """Test case where expires is None."""12841285        morsel = Morsel()1286        morsel['expires'] = None1287        cookie = morsel_to_cookie(morsel)1288        assert cookie.expires is None128912901291class TestMorselToCookieMaxAge(unittest.TestCase):12921293    """Tests for morsel_to_cookie when morsel contains max-age."""12941295    def test_max_age_valid_int(self):1296        """Test case where a valid max age in seconds is passed."""12971298        morsel = Morsel()1299        morsel['max-age'] = 601300        cookie = morsel_to_cookie(morsel)1301        assert isinstance(cookie.expires, int)13021303    def test_max_age_invalid_str(self):1304        """Test case where a invalid max age is passed."""13051306        morsel = Morsel()1307        morsel['max-age'] = 'woops'1308        with pytest.raises(TypeError):1309            morsel_to_cookie(morsel)131013111312class TestTimeout:1313    def test_stream_timeout(self):1314        try:1315            requests.get('https://httpbin.org/delay/10', timeout=2.0)1316        except requests.exceptions.Timeout as e:1317            assert 'Read timed out' in e.args[0].args[0]13181319    def test_invalid_timeout(self):1320        with pytest.raises(ValueError) as e:1321            requests.get(httpbin('get'), timeout=(3, 4, 5))1322        assert '(connect, read)' in str(e)13231324        with pytest.raises(ValueError) as e:1325            requests.get(httpbin('get'), timeout="foo")1326        assert 'must be an int or float' in str(e)13271328    def test_none_timeout(self):1329        """ Check that you can set None as a valid timeout value.13301331        To actually test this behavior, we'd want to check that setting the1332        timeout to None actually lets the request block past the system default1333        timeout. However, this would make the test suite unbearably slow.1334        Instead we verify that setting the timeout to None does not prevent the1335        request from succeeding.1336        """1337        r = requests.get(httpbin('get'), timeout=None)1338        assert r.status_code == 20013391340    def test_read_timeout(self):1341        try:1342            requests.get(httpbin('delay/10'), timeout=(None, 0.1))1343            assert False, "The recv() request should time out."1344        except ReadTimeout:1345            pass13461347    def test_connect_timeout(self):1348        try:1349            requests.get(TARPIT, timeout=(0.1, None))1350            assert False, "The connect() request should time out."1351        except ConnectTimeout as e:1352            assert isinstance(e, ConnectionError)1353            assert isinstance(e, Timeout)13541355    def test_total_timeout_connect(self):1356        try:1357            requests.get(TARPIT, timeout=(0.1, 0.1))1358            assert False, "The connect() request should time out."1359        except ConnectTimeout:1360            pass136113621363SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))136413651366class RedirectSession(SessionRedirectMixin):1367    def __init__(self, order_of_redirects):1368        self.redirects = order_of_redirects1369        self.calls = []1370        self.max_redirects = 301371        self.cookies = {}1372        self.trust_env = False13731374    def send(self, *args, **kwargs):1375        self.calls.append(SendCall(args, kwargs))1376        return self.build_response()13771378    def build_response(self):1379        request = self.calls[-1].args[0]1380        r = requests.Response()13811382        try:1383            r.status_code = int(self.redirects.pop(0))1384        except IndexError:1385            r.status_code = 20013861387        r.headers = CaseInsensitiveDict({'Location': '/'})1388        r.raw = self._build_raw()1389        r.request = request1390        return r13911392    def _build_raw(self):1393        string = StringIO.StringIO('')1394        setattr(string, 'release_conn', lambda *args: args)1395        return string139613971398class TestRedirects:1399    default_keyword_args = {1400        'stream': False,1401        'verify': True,1402        'cert': None,1403        'timeout': None,1404        'allow_redirects': False,1405        'proxies': {},1406    }14071408    def test_requests_are_updated_each_time(self):1409        session = RedirectSession([303, 307])1410        prep = requests.Request('POST', 'http://httpbin.org/post').prepare()1411        r0 = session.send(prep)1412        assert r0.request.method == 'POST'1413        assert session.calls[-1] == SendCall((r0.request,), {})1414        redirect_generator = session.resolve_redirects(r0, prep)1415        for response in redirect_generator:1416            assert response.request.method == 'GET'1417            send_call = SendCall((response.request,),1418                                 TestRedirects.default_keyword_args)1419            assert session.calls[-1] == send_call1420142114221423@pytest.fixture1424def list_of_tuples():1425    return [1426        (('a', 'b'), ('c', 'd')),1427        (('c', 'd'), ('a', 'b')),1428        (('a', 'b'), ('c', 'd'), ('e', 'f')),1429        ]143014311432def test_data_argument_accepts_tuples(list_of_tuples):1433    """1434    Ensure that the data argument will accept tuples of strings1435    and properly encode them.1436    """1437    for data in list_of_tuples:1438        p = PreparedRequest()1439        p.prepare(1440            method='GET',1441            url='http://www.example.com',1442            data=data,1443            hooks=default_hooks()1444        )1445        assert p.body == urlencode(data)144614471448def assert_copy(p, p_copy):1449    for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):1450        assert getattr(p, attr) == getattr(p_copy, attr)145114521453def test_prepared_request_empty_copy():1454    p = PreparedRequest()1455    assert_copy(p, p.copy())145614571458def test_prepared_request_no_cookies_copy():1459    p = PreparedRequest()1460    p.prepare(1461        method='GET',1462        url='http://www.example.com',1463        data='foo=bar',1464        hooks=default_hooks()1465    )1466    assert_copy(p, p.copy())146714681469def test_prepared_request_complete_copy():1470    p = PreparedRequest()1471    p.prepare(1472        method='GET',1473        url='http://www.example.com',1474        data='foo=bar',1475        hooks=default_hooks(),1476        cookies={'foo': 'bar'}1477    )1478    assert_copy(p, p.copy())14791480if __name__ == '__main__':1481    unittest.main()