test_requests.py
This file
Path
test_requests.py
1,519 lines · 50.6 KiB · Python
Last changed by
allow unicode URLs on Python 2MinRKbefore adoptionca2ebc5
History of this fileTake it
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34"""Tests for Requests."""56from __future__ import division7import json8import os9import pickle10import unittest11import collections1213import io14import requests15import pytest16from requests.adapters import HTTPAdapter17from requests.auth import HTTPDigestAuth, _basic_auth_str18from requests.compat import (19 Morsel, cookielib, getproxies, str, urljoin, urlparse, is_py3, builtin_str)20from requests.cookies import cookiejar_from_dict, morsel_to_cookie21from requests.exceptions import (ConnectionError, ConnectTimeout,22 InvalidSchema, InvalidURL, MissingSchema,23 ReadTimeout, Timeout)24from requests.models import PreparedRequest25from requests.structures import CaseInsensitiveDict26from requests.sessions import SessionRedirectMixin27from requests.models import urlencode28from requests.hooks import default_hooks2930try:31 import StringIO32except ImportError:33 import io as StringIO3435if is_py3:36 def u(s):37 return s38else:39 def u(s):40 return s.decode('unicode-escape')414243# Requests to this URL should always fail with a connection timeout (nothing44# listening on that port)45TARPIT = "http://10.255.255.1"46HTTPBIN = os.environ.get('HTTPBIN_URL', 'http://httpbin.org/')47# Issue #1483: Make sure the URL always has a trailing slash48HTTPBIN = HTTPBIN.rstrip('/') + '/'495051def httpbin(*suffix):52 """Returns url for HTTPBIN resource."""53 return urljoin(HTTPBIN, '/'.join(suffix))545556class RequestsTestCase(unittest.TestCase):5758 _multiprocess_can_split_ = True5960 def setUp(self):61 """Create simple data set with headers."""62 pass6364 def tearDown(self):65 """Teardown."""66 pass6768 def test_entry_points(self):6970 requests.session71 requests.session().get72 requests.session().head73 requests.get74 requests.head75 requests.put76 requests.patch77 requests.post7879 def test_invalid_url(self):80 with pytest.raises(MissingSchema):81 requests.get('hiwpefhipowhefopw')82 with pytest.raises(InvalidSchema):83 requests.get('localhost:3128')84 with pytest.raises(InvalidSchema):85 requests.get('localhost.localdomain:3128/')86 with pytest.raises(InvalidSchema):87 requests.get('10.122.1.1:3128/')88 with pytest.raises(InvalidURL):89 requests.get('http://')9091 def test_basic_building(self):92 req = requests.Request()93 req.url = 'http://kennethreitz.org/'94 req.data = {'life': '42'}9596 pr = req.prepare()97 assert pr.url == req.url98 assert pr.body == 'life=42'99100 def test_no_content_length(self):101 get_req = requests.Request('GET', httpbin('get')).prepare()102 assert 'Content-Length' not in get_req.headers103 head_req = requests.Request('HEAD', httpbin('head')).prepare()104 assert 'Content-Length' not in head_req.headers105106 def test_path_is_not_double_encoded(self):107 request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()108109 assert request.path_url == '/get/test%20case'110111 def test_params_are_added_before_fragment(self):112 request = requests.Request('GET',113 "http://example.com/path#fragment", params={"a": "b"}).prepare()114 assert request.url == "http://example.com/path?a=b#fragment"115 request = requests.Request('GET',116 "http://example.com/path?key=value#fragment", params={"a": "b"}).prepare()117 assert request.url == "http://example.com/path?key=value&a=b#fragment"118119 def test_mixed_case_scheme_acceptable(self):120 s = requests.Session()121 s.proxies = getproxies()122 parts = urlparse(httpbin('get'))123 schemes = ['http://', 'HTTP://', 'hTTp://', 'HttP://',124 'https://', 'HTTPS://', 'hTTps://', 'HttPs://']125 for scheme in schemes:126 url = scheme + parts.netloc + parts.path127 r = requests.Request('GET', url)128 r = s.send(r.prepare())129 assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)130131 def test_HTTP_200_OK_GET_ALTERNATIVE(self):132 r = requests.Request('GET', httpbin('get'))133 s = requests.Session()134 s.proxies = getproxies()135136 r = s.send(r.prepare())137138 assert r.status_code == 200139140 def test_HTTP_302_ALLOW_REDIRECT_GET(self):141 r = requests.get(httpbin('redirect', '1'))142 assert r.status_code == 200143 assert r.history[0].status_code == 302144 assert r.history[0].is_redirect145146 # def test_HTTP_302_ALLOW_REDIRECT_POST(self):147 # r = requests.post(httpbin('status', '302'), data={'some': 'data'})148 # self.assertEqual(r.status_code, 200)149150 def test_HTTP_200_OK_GET_WITH_PARAMS(self):151 heads = {'User-agent': 'Mozilla/5.0'}152153 r = requests.get(httpbin('user-agent'), headers=heads)154155 assert heads['User-agent'] in r.text156 assert r.status_code == 200157158 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):159 heads = {'User-agent': 'Mozilla/5.0'}160161 r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)162 assert r.status_code == 200163164 def test_set_cookie_on_301(self):165 s = requests.session()166 url = httpbin('cookies/set?foo=bar')167 s.get(url)168 assert s.cookies['foo'] == 'bar'169170 def test_cookie_sent_on_redirect(self):171 s = requests.session()172 s.get(httpbin('cookies/set?foo=bar'))173 r = s.get(httpbin('redirect/1')) # redirects to httpbin('get')174 assert 'Cookie' in r.json()['headers']175176 def test_cookie_removed_on_expire(self):177 s = requests.session()178 s.get(httpbin('cookies/set?foo=bar'))179 assert s.cookies['foo'] == 'bar'180 s.get(181 httpbin('response-headers'),182 params={183 'Set-Cookie':184 'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'185 }186 )187 assert 'foo' not in s.cookies188189 def test_cookie_quote_wrapped(self):190 s = requests.session()191 s.get(httpbin('cookies/set?foo="bar:baz"'))192 assert s.cookies['foo'] == '"bar:baz"'193194 def test_cookie_persists_via_api(self):195 s = requests.session()196 r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})197 assert 'foo' in r.request.headers['Cookie']198 assert 'foo' in r.history[0].request.headers['Cookie']199200 def test_request_cookie_overrides_session_cookie(self):201 s = requests.session()202 s.cookies['foo'] = 'bar'203 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})204 assert r.json()['cookies']['foo'] == 'baz'205 # Session cookie should not be modified206 assert s.cookies['foo'] == 'bar'207208 def test_request_cookies_not_persisted(self):209 s = requests.session()210 s.get(httpbin('cookies'), cookies={'foo': 'baz'})211 # Sending a request with cookies should not add cookies to the session212 assert not s.cookies213214 def test_generic_cookiejar_works(self):215 cj = cookielib.CookieJar()216 cookiejar_from_dict({'foo': 'bar'}, cj)217 s = requests.session()218 s.cookies = cj219 r = s.get(httpbin('cookies'))220 # Make sure the cookie was sent221 assert r.json()['cookies']['foo'] == 'bar'222 # Make sure the session cj is still the custom one223 assert s.cookies is cj224225 def test_param_cookiejar_works(self):226 cj = cookielib.CookieJar()227 cookiejar_from_dict({'foo': 'bar'}, cj)228 s = requests.session()229 r = s.get(httpbin('cookies'), cookies=cj)230 # Make sure the cookie was sent231 assert r.json()['cookies']['foo'] == 'bar'232233 def test_requests_in_history_are_not_overridden(self):234 resp = requests.get(httpbin('redirect/3'))235 urls = [r.url for r in resp.history]236 req_urls = [r.request.url for r in resp.history]237 assert urls == req_urls238239 def test_history_is_always_a_list(self):240 """241 Show that even with redirects, Response.history is always a list.242 """243 resp = requests.get(httpbin('get'))244 assert isinstance(resp.history, list)245 resp = requests.get(httpbin('redirect/1'))246 assert isinstance(resp.history, list)247 assert not isinstance(resp.history, tuple)248249 def test_headers_on_session_with_None_are_not_sent(self):250 """Do not send headers in Session.headers with None values."""251 ses = requests.Session()252 ses.headers['Accept-Encoding'] = None253 req = requests.Request('GET', 'http://httpbin.org/get')254 prep = ses.prepare_request(req)255 assert 'Accept-Encoding' not in prep.headers256257 def test_user_agent_transfers(self):258259 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 heads = {267 'user-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'268 }269270 r = requests.get(httpbin('user-agent'), headers=heads)271 assert heads['user-agent'] in r.text272273 def test_HTTP_200_OK_HEAD(self):274 r = requests.head(httpbin('get'))275 assert r.status_code == 200276277 def test_HTTP_200_OK_PUT(self):278 r = requests.put(httpbin('put'))279 assert r.status_code == 200280281 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):282 auth = ('user', 'pass')283 url = httpbin('basic-auth', 'user', 'pass')284285 r = requests.get(url, auth=auth)286 assert r.status_code == 200287288 r = requests.get(url)289 assert r.status_code == 401290291 s = requests.session()292 s.auth = auth293 r = s.get(url)294 assert r.status_code == 200295296 def test_connection_error(self):297 """Connecting to an unknown domain should raise a ConnectionError"""298 with pytest.raises(ConnectionError):299 requests.get("http://fooobarbangbazbing.httpbin.org")300301 with pytest.raises(ConnectionError):302 requests.get("http://httpbin.org:1")303304 def test_basicauth_with_netrc(self):305 auth = ('user', 'pass')306 wrong_auth = ('wronguser', 'wrongpass')307 url = httpbin('basic-auth', 'user', 'pass')308309 def get_netrc_auth_mock(url):310 return auth311 requests.sessions.get_netrc_auth = get_netrc_auth_mock312313 # Should use netrc and work.314 r = requests.get(url)315 assert r.status_code == 200316317 # Given auth should override and fail.318 r = requests.get(url, auth=wrong_auth)319 assert r.status_code == 401320321 s = requests.session()322323 # Should use netrc and work.324 r = s.get(url)325 assert r.status_code == 200326327 # Given auth should override and fail.328 s.auth = wrong_auth329 r = s.get(url)330 assert r.status_code == 401331332 def test_DIGEST_HTTP_200_OK_GET(self):333334 auth = HTTPDigestAuth('user', 'pass')335 url = httpbin('digest-auth', 'auth', 'user', 'pass')336337 r = requests.get(url, auth=auth)338 assert r.status_code == 200339340 r = requests.get(url)341 assert r.status_code == 401342343 s = requests.session()344 s.auth = HTTPDigestAuth('user', 'pass')345 r = s.get(url)346 assert r.status_code == 200347348 def test_DIGEST_AUTH_RETURNS_COOKIE(self):349 url = httpbin('digest-auth', 'auth', 'user', 'pass')350 auth = HTTPDigestAuth('user', 'pass')351 r = requests.get(url)352 assert r.cookies['fake'] == 'fake_value'353354 r = requests.get(url, auth=auth)355 assert r.status_code == 200356357 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self):358 url = httpbin('digest-auth', 'auth', 'user', 'pass')359 auth = HTTPDigestAuth('user', 'pass')360 s = requests.Session()361 s.get(url, auth=auth)362 assert s.cookies['fake'] == 'fake_value'363364 def test_DIGEST_STREAM(self):365366 auth = HTTPDigestAuth('user', 'pass')367 url = httpbin('digest-auth', 'auth', 'user', 'pass')368369 r = requests.get(url, auth=auth, stream=True)370 assert r.raw.read() != b''371372 r = requests.get(url, auth=auth, stream=False)373 assert r.raw.read() == b''374375 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self):376377 auth = HTTPDigestAuth('user', 'wrongpass')378 url = httpbin('digest-auth', 'auth', 'user', 'pass')379380 r = requests.get(url, auth=auth)381 assert r.status_code == 401382383 r = requests.get(url)384 assert r.status_code == 401385386 s = requests.session()387 s.auth = auth388 r = s.get(url)389 assert r.status_code == 401390391 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self):392393 auth = HTTPDigestAuth('user', 'pass')394 url = httpbin('digest-auth', 'auth', 'user', 'pass')395396 r = requests.get(url, auth=auth)397 assert '"auth"' in r.request.headers['Authorization']398399 def test_POSTBIN_GET_POST_FILES(self):400401 url = httpbin('post')402 post1 = requests.post(url).raise_for_status()403404 post1 = requests.post(url, data={'some': 'data'})405 assert post1.status_code == 200406407 with open('requirements.txt') as f:408 post2 = requests.post(url, files={'some': f})409 assert post2.status_code == 200410411 post4 = requests.post(url, data='[{"some": "json"}]')412 assert post4.status_code == 200413414 with pytest.raises(ValueError):415 requests.post(url, files=['bad file data'])416417 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self):418419 url = httpbin('post')420 post1 = requests.post(url).raise_for_status()421422 post1 = requests.post(url, data={'some': 'data'})423 assert post1.status_code == 200424425 with open('requirements.txt') as f:426 post2 = requests.post(url,427 data={'some': 'data'}, files={'some': f})428 assert post2.status_code == 200429430 post4 = requests.post(url, data='[{"some": "json"}]')431 assert post4.status_code == 200432433 with pytest.raises(ValueError):434 requests.post(url, files=['bad file data'])435436 def test_conflicting_post_params(self):437 url = httpbin('post')438 with open('requirements.txt') as f:439 pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")440 pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")441442 def test_request_ok_set(self):443 r = requests.get(httpbin('status', '404'))444 assert not r.ok445446 def test_status_raising(self):447 r = requests.get(httpbin('status', '404'))448 with pytest.raises(requests.exceptions.HTTPError):449 r.raise_for_status()450451 r = requests.get(httpbin('status', '500'))452 assert not r.ok453454 def test_decompress_gzip(self):455 r = requests.get(httpbin('gzip'))456 r.content.decode('ascii')457458 def test_unicode_get(self):459 url = httpbin('/get')460 requests.get(url, params={'foo': 'føø'})461 requests.get(url, params={'føø': 'føø'})462 requests.get(url, params={'føø': 'føø'})463 requests.get(url, params={'foo': 'foo'})464 requests.get(httpbin('ø'), params={'foo': 'foo'})465466 def test_unicode_header_name(self):467 requests.put(468 httpbin('put'),469 headers={str('Content-Type'): 'application/octet-stream'},470 data='\xff') # compat.str is unicode.471472 def test_pyopenssl_redirect(self):473 requests.get('https://httpbin.org/status/301')474475 def test_urlencoded_get_query_multivalued_param(self):476477 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))478 assert r.status_code == 200479 assert r.url == httpbin('get?test=foo&test=baz')480481 def test_different_encodings_dont_break_post(self):482 r = requests.post(httpbin('post'),483 data={'stuff': json.dumps({'a': 123})},484 params={'blah': 'asdf1234'},485 files={'file': ('test_requests.py', open(__file__, 'rb'))})486 assert r.status_code == 200487488 def test_unicode_multipart_post(self):489 r = requests.post(httpbin('post'),490 data={'stuff': u('ëlïxr')},491 files={'file': ('test_requests.py', open(__file__, 'rb'))})492 assert r.status_code == 200493494 r = requests.post(httpbin('post'),495 data={'stuff': u('ëlïxr').encode('utf-8')},496 files={'file': ('test_requests.py', open(__file__, 'rb'))})497 assert r.status_code == 200498499 r = requests.post(httpbin('post'),500 data={'stuff': 'elixr'},501 files={'file': ('test_requests.py', open(__file__, 'rb'))})502 assert r.status_code == 200503504 r = requests.post(httpbin('post'),505 data={'stuff': 'elixr'.encode('utf-8')},506 files={'file': ('test_requests.py', open(__file__, 'rb'))})507 assert r.status_code == 200508509 def test_unicode_multipart_post_fieldnames(self):510 filename = os.path.splitext(__file__)[0] + '.py'511 r = requests.Request(method='POST',512 url=httpbin('post'),513 data={'stuff'.encode('utf-8'): 'elixr'},514 files={'file': ('test_requests.py',515 open(filename, 'rb'))})516 prep = r.prepare()517 assert b'name="stuff"' in prep.body518 assert b'name="b\'stuff\'"' not in prep.body519520 def test_unicode_method_name(self):521 files = {'file': open('test_requests.py', 'rb')}522 r = requests.request(523 method=u('POST'), url=httpbin('post'), files=files)524 assert r.status_code == 200525526 def test_custom_content_type(self):527 r = requests.post(528 httpbin('post'),529 data={'stuff': json.dumps({'a': 123})},530 files={'file1': ('test_requests.py', open(__file__, 'rb')),531 'file2': ('test_requests', open(__file__, 'rb'),532 'text/py-content-type')})533 assert r.status_code == 200534 assert b"text/py-content-type" in r.request.body535536 def test_hook_receives_request_arguments(self):537 def hook(resp, **kwargs):538 assert resp is not None539 assert kwargs != {}540541 requests.Request('GET', HTTPBIN, hooks={'response': hook})542543 def test_session_hooks_are_used_with_no_request_hooks(self):544 hook = lambda x, *args, **kwargs: x545 s = requests.Session()546 s.hooks['response'].append(hook)547 r = requests.Request('GET', HTTPBIN)548 prep = s.prepare_request(r)549 assert prep.hooks['response'] != []550 assert prep.hooks['response'] == [hook]551552 def test_session_hooks_are_overriden_by_request_hooks(self):553 hook1 = lambda x, *args, **kwargs: x554 hook2 = lambda x, *args, **kwargs: x555 assert hook1 is not hook2556 s = requests.Session()557 s.hooks['response'].append(hook2)558 r = requests.Request('GET', HTTPBIN, hooks={'response': [hook1]})559 prep = s.prepare_request(r)560 assert prep.hooks['response'] == [hook1]561562 def test_prepared_request_hook(self):563 def hook(resp, **kwargs):564 resp.hook_working = True565 return resp566567 req = requests.Request('GET', HTTPBIN, hooks={'response': hook})568 prep = req.prepare()569570 s = requests.Session()571 s.proxies = getproxies()572 resp = s.send(prep)573574 assert hasattr(resp, 'hook_working')575576 def test_prepared_from_session(self):577 class DummyAuth(requests.auth.AuthBase):578 def __call__(self, r):579 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'580 return r581582 req = requests.Request('GET', httpbin('headers'))583 assert not req.auth584585 s = requests.Session()586 s.auth = DummyAuth()587588 prep = s.prepare_request(req)589 resp = s.send(prep)590591 assert resp.json()['headers'][592 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'593594 def test_prepare_request_with_bytestring_url(self):595 req = requests.Request('GET', b'https://httpbin.org/')596 s = requests.Session()597 prep = s.prepare_request(req)598 assert prep.url == "https://httpbin.org/"599600 def test_links(self):601 r = requests.Response()602 r.headers = {603 'cache-control': 'public, max-age=60, s-maxage=60',604 'connection': 'keep-alive',605 'content-encoding': 'gzip',606 'content-type': 'application/json; charset=utf-8',607 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',608 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',609 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',610 'link': ('<https://api.github.com/users/kennethreitz/repos?'611 'page=2&per_page=10>; rel="next", <https://api.github.'612 'com/users/kennethreitz/repos?page=7&per_page=10>; '613 ' rel="last"'),614 'server': 'GitHub.com',615 'status': '200 OK',616 'vary': 'Accept',617 'x-content-type-options': 'nosniff',618 'x-github-media-type': 'github.beta',619 'x-ratelimit-limit': '60',620 'x-ratelimit-remaining': '57'621 }622 assert r.links['next']['rel'] == 'next'623624 def test_cookie_parameters(self):625 key = 'some_cookie'626 value = 'some_value'627 secure = True628 domain = 'test.com'629 rest = {'HttpOnly': True}630631 jar = requests.cookies.RequestsCookieJar()632 jar.set(key, value, secure=secure, domain=domain, rest=rest)633634 assert len(jar) == 1635 assert 'some_cookie' in jar636637 cookie = list(jar)[0]638 assert cookie.secure == secure639 assert cookie.domain == domain640 assert cookie._rest['HttpOnly'] == rest['HttpOnly']641642 def test_cookie_as_dict_keeps_len(self):643 key = 'some_cookie'644 value = 'some_value'645646 key1 = 'some_cookie1'647 value1 = 'some_value1'648649 jar = requests.cookies.RequestsCookieJar()650 jar.set(key, value)651 jar.set(key1, value1)652653 d1 = dict(jar)654 d2 = dict(jar.iteritems())655 d3 = dict(jar.items())656657 assert len(jar) == 2658 assert len(d1) == 2659 assert len(d2) == 2660 assert len(d3) == 2661662 def test_cookie_as_dict_keeps_items(self):663 key = 'some_cookie'664 value = 'some_value'665666 key1 = 'some_cookie1'667 value1 = 'some_value1'668669 jar = requests.cookies.RequestsCookieJar()670 jar.set(key, value)671 jar.set(key1, value1)672673 d1 = dict(jar)674 d2 = dict(jar.iteritems())675 d3 = dict(jar.items())676677 assert d1['some_cookie'] == 'some_value'678 assert d2['some_cookie'] == 'some_value'679 assert d3['some_cookie1'] == 'some_value1'680681 def test_cookie_as_dict_keys(self):682 key = 'some_cookie'683 value = 'some_value'684685 key1 = 'some_cookie1'686 value1 = 'some_value1'687688 jar = requests.cookies.RequestsCookieJar()689 jar.set(key, value)690 jar.set(key1, value1)691692 keys = jar.keys()693 assert keys == list(keys)694 # make sure one can use keys multiple times695 assert list(keys) == list(keys)696697 def test_cookie_as_dict_values(self):698 key = 'some_cookie'699 value = 'some_value'700701 key1 = 'some_cookie1'702 value1 = 'some_value1'703704 jar = requests.cookies.RequestsCookieJar()705 jar.set(key, value)706 jar.set(key1, value1)707708 values = jar.values()709 assert values == list(values)710 # make sure one can use values multiple times711 assert list(values) == list(values)712713 def test_cookie_as_dict_items(self):714 key = 'some_cookie'715 value = 'some_value'716717 key1 = 'some_cookie1'718 value1 = 'some_value1'719720 jar = requests.cookies.RequestsCookieJar()721 jar.set(key, value)722 jar.set(key1, value1)723724 items = jar.items()725 assert items == list(items)726 # make sure one can use items multiple times727 assert list(items) == list(items)728729 def test_time_elapsed_blank(self):730 r = requests.get(httpbin('get'))731 td = r.elapsed732 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)733 * 10**6) / 10**6)734 assert total_seconds > 0.0735736 def test_response_is_iterable(self):737 r = requests.Response()738 io = StringIO.StringIO('abc')739 read_ = io.read740741 def read_mock(amt, decode_content=None):742 return read_(amt)743 setattr(io, 'read', read_mock)744 r.raw = io745 assert next(iter(r))746 io.close()747748 def test_response_decode_unicode(self):749 """750 When called with decode_unicode, Response.iter_content should always751 return unicode.752 """753 r = requests.Response()754 r._content_consumed = True755 r._content = b'the content'756 r.encoding = 'ascii'757758 chunks = r.iter_content(decode_unicode=True)759 assert all(isinstance(chunk, str) for chunk in chunks)760761 # also for streaming762 r = requests.Response()763 r.raw = io.BytesIO(b'the content')764 r.encoding = 'ascii'765 chunks = r.iter_content(decode_unicode=True)766 assert all(isinstance(chunk, str) for chunk in chunks)767768 def test_request_and_response_are_pickleable(self):769 r = requests.get(httpbin('get'))770771 # verify we can pickle the original request772 assert pickle.loads(pickle.dumps(r.request))773774 # verify we can pickle the response and that we have access to775 # the original request.776 pr = pickle.loads(pickle.dumps(r))777 assert r.request.url == pr.request.url778 assert r.request.headers == pr.request.headers779780 def test_get_auth_from_url(self):781 url = 'http://user:pass@complex.url.com/path?query=yes'782 assert ('user', 'pass') == requests.utils.get_auth_from_url(url)783784 def test_get_auth_from_url_encoded_spaces(self):785 url = 'http://user:pass%20pass@complex.url.com/path?query=yes'786 assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)787788 def test_get_auth_from_url_not_encoded_spaces(self):789 url = 'http://user:pass pass@complex.url.com/path?query=yes'790 assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)791792 def test_get_auth_from_url_percent_chars(self):793 url = 'http://user%25user:pass@complex.url.com/path?query=yes'794 assert ('user%user', 'pass') == requests.utils.get_auth_from_url(url)795796 def test_get_auth_from_url_encoded_hashes(self):797 url = 'http://user:pass%23pass@complex.url.com/path?query=yes'798 assert ('user', 'pass#pass') == requests.utils.get_auth_from_url(url)799800 def test_cannot_send_unprepared_requests(self):801 r = requests.Request(url=HTTPBIN)802 with pytest.raises(ValueError):803 requests.Session().send(r)804805 def test_http_error(self):806 error = requests.exceptions.HTTPError()807 assert not error.response808 response = requests.Response()809 error = requests.exceptions.HTTPError(response=response)810 assert error.response == response811 error = requests.exceptions.HTTPError('message', response=response)812 assert str(error) == 'message'813 assert error.response == response814815 def test_session_pickling(self):816 r = requests.Request('GET', httpbin('get'))817 s = requests.Session()818819 s = pickle.loads(pickle.dumps(s))820 s.proxies = getproxies()821822 r = s.send(r.prepare())823 assert r.status_code == 200824825 def test_fixes_1329(self):826 """827 Ensure that header updates are done case-insensitively.828 """829 s = requests.Session()830 s.headers.update({'ACCEPT': 'BOGUS'})831 s.headers.update({'accept': 'application/json'})832 r = s.get(httpbin('get'))833 headers = r.request.headers834 assert headers['accept'] == 'application/json'835 assert headers['Accept'] == 'application/json'836 assert headers['ACCEPT'] == 'application/json'837838 def test_uppercase_scheme_redirect(self):839 parts = urlparse(httpbin('html'))840 url = "HTTP://" + parts.netloc + parts.path841 r = requests.get(httpbin('redirect-to'), params={'url': url})842 assert r.status_code == 200843 assert r.url.lower() == url.lower()844845 def test_transport_adapter_ordering(self):846 s = requests.Session()847 order = ['https://', 'http://']848 assert order == list(s.adapters)849 s.mount('http://git', HTTPAdapter())850 s.mount('http://github', HTTPAdapter())851 s.mount('http://github.com', HTTPAdapter())852 s.mount('http://github.com/about/', HTTPAdapter())853 order = [854 'http://github.com/about/',855 'http://github.com',856 'http://github',857 'http://git',858 'https://',859 'http://',860 ]861 assert order == list(s.adapters)862 s.mount('http://gittip', HTTPAdapter())863 s.mount('http://gittip.com', HTTPAdapter())864 s.mount('http://gittip.com/about/', HTTPAdapter())865 order = [866 'http://github.com/about/',867 'http://gittip.com/about/',868 'http://github.com',869 'http://gittip.com',870 'http://github',871 'http://gittip',872 'http://git',873 'https://',874 'http://',875 ]876 assert order == list(s.adapters)877 s2 = requests.Session()878 s2.adapters = {'http://': HTTPAdapter()}879 s2.mount('https://', HTTPAdapter())880 assert 'http://' in s2.adapters881 assert 'https://' in s2.adapters882883 def test_header_remove_is_case_insensitive(self):884 # From issue #1321885 s = requests.Session()886 s.headers['foo'] = 'bar'887 r = s.get(httpbin('get'), headers={'FOO': None})888 assert 'foo' not in r.request.headers889890 def test_params_are_merged_case_sensitive(self):891 s = requests.Session()892 s.params['foo'] = 'bar'893 r = s.get(httpbin('get'), params={'FOO': 'bar'})894 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}895896 def test_long_authinfo_in_url(self):897 url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(898 'E8A3BE87-9E3F-4620-8858-95478E385B5B',899 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',900 'exactly-------------sixty-----------three------------characters',901 )902 r = requests.Request('GET', url).prepare()903 assert r.url == url904905 def test_header_keys_are_native(self):906 headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}907 r = requests.Request('GET', httpbin('get'), headers=headers)908 p = r.prepare()909910 # This is testing that they are builtin strings. A bit weird, but there911 # we go.912 assert 'unicode' in p.headers.keys()913 assert 'byte' in p.headers.keys()914915 def test_can_send_nonstring_objects_with_files(self):916 data = {'a': 0.0}917 files = {'b': 'foo'}918 r = requests.Request('POST', httpbin('post'), data=data, files=files)919 p = r.prepare()920921 assert 'multipart/form-data' in p.headers['Content-Type']922923 def test_autoset_header_values_are_native(self):924 data = 'this is a string'925 length = '16'926 req = requests.Request('POST', httpbin('post'), data=data)927 p = req.prepare()928929 assert p.headers['Content-Length'] == length930931 def test_nonhttp_schemes_dont_check_URLs(self):932 test_urls = (933 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',934 'file:///etc/passwd',935 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',936 )937 for test_url in test_urls:938 req = requests.Request('GET', test_url)939 preq = req.prepare()940 assert test_url == preq.url941942 def test_auth_is_stripped_on_redirect_off_host(self):943 r = requests.get(944 httpbin('redirect-to'),945 params={'url': 'http://www.google.co.uk'},946 auth=('user', 'pass'),947 )948 assert r.history[0].request.headers['Authorization']949 assert not r.request.headers.get('Authorization', '')950951 def test_auth_is_retained_for_redirect_on_host(self):952 r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))953 h1 = r.history[0].request.headers['Authorization']954 h2 = r.request.headers['Authorization']955956 assert h1 == h2957958 def test_manual_redirect_with_partial_body_read(self):959 s = requests.Session()960 r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)961 assert r1.is_redirect962 rg = s.resolve_redirects(r1, r1.request, stream=True)963964 # read only the first eight bytes of the response body,965 # then follow the redirect966 r1.iter_content(8)967 r2 = next(rg)968 assert r2.is_redirect969970 # read all of the response via iter_content,971 # then follow the redirect972 for _ in r2.iter_content():973 pass974 r3 = next(rg)975 assert not r3.is_redirect976977 def _patch_adapter_gzipped_redirect(self, session, url):978 adapter = session.get_adapter(url=url)979 org_build_response = adapter.build_response980 self._patched_response = False981982 def build_response(*args, **kwargs):983 resp = org_build_response(*args, **kwargs)984 if not self._patched_response:985 resp.raw.headers['content-encoding'] = 'gzip'986 self._patched_response = True987 return resp988989 adapter.build_response = build_response990991 def test_redirect_with_wrong_gzipped_header(self):992 s = requests.Session()993 url = httpbin('redirect/1')994 self._patch_adapter_gzipped_redirect(s, url)995 s.get(url)996997 def test_basic_auth_str_is_always_native(self):998 s = _basic_auth_str("test", "test")999 assert isinstance(s, builtin_str)1000 assert s == "Basic dGVzdDp0ZXN0"10011002 def test_requests_history_is_saved(self):1003 r = requests.get('https://httpbin.org/redirect/5')1004 total = r.history[-1].history1005 i = 01006 for item in r.history:1007 assert item.history == total[0:i]1008 i=i+110091010 def test_json_param_post_content_type_works(self):1011 r = requests.post(1012 httpbin('post'),1013 json={'life': 42}1014 )1015 assert r.status_code == 2001016 assert 'application/json' in r.request.headers['Content-Type']1017 assert {'life': 42} == r.json()['json']101810191020class TestContentEncodingDetection(unittest.TestCase):10211022 def test_none(self):1023 encodings = requests.utils.get_encodings_from_content('')1024 assert not len(encodings)10251026 def test_html_charset(self):1027 """HTML5 meta charset attribute"""1028 content = '<meta charset="UTF-8">'1029 encodings = requests.utils.get_encodings_from_content(content)1030 assert len(encodings) == 11031 assert encodings[0] == 'UTF-8'10321033 def test_html4_pragma(self):1034 """HTML4 pragma directive"""1035 content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">'1036 encodings = requests.utils.get_encodings_from_content(content)1037 assert len(encodings) == 11038 assert encodings[0] == 'UTF-8'10391040 def test_xhtml_pragma(self):1041 """XHTML 1.x served with text/html MIME type"""1042 content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />'1043 encodings = requests.utils.get_encodings_from_content(content)1044 assert len(encodings) == 11045 assert encodings[0] == 'UTF-8'10461047 def test_xml(self):1048 """XHTML 1.x served as XML"""1049 content = '<?xml version="1.0" encoding="UTF-8"?>'1050 encodings = requests.utils.get_encodings_from_content(content)1051 assert len(encodings) == 11052 assert encodings[0] == 'UTF-8'10531054 def test_precedence(self):1055 content = '''1056 <?xml version="1.0" encoding="XML"?>1057 <meta charset="HTML5">1058 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />1059 '''.strip()1060 encodings = requests.utils.get_encodings_from_content(content)1061 assert encodings == ['HTML5', 'HTML4', 'XML']106210631064class TestCaseInsensitiveDict(unittest.TestCase):10651066 def test_mapping_init(self):1067 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1068 assert len(cid) == 21069 assert 'foo' in cid1070 assert 'bar' in cid10711072 def test_iterable_init(self):1073 cid = CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')])1074 assert len(cid) == 21075 assert 'foo' in cid1076 assert 'bar' in cid10771078 def test_kwargs_init(self):1079 cid = CaseInsensitiveDict(FOO='foo', BAr='bar')1080 assert len(cid) == 21081 assert 'foo' in cid1082 assert 'bar' in cid10831084 def test_docstring_example(self):1085 cid = CaseInsensitiveDict()1086 cid['Accept'] = 'application/json'1087 assert cid['aCCEPT'] == 'application/json'1088 assert list(cid) == ['Accept']10891090 def test_len(self):1091 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1092 cid['A'] = 'a'1093 assert len(cid) == 210941095 def test_getitem(self):1096 cid = CaseInsensitiveDict({'Spam': 'blueval'})1097 assert cid['spam'] == 'blueval'1098 assert cid['SPAM'] == 'blueval'10991100 def test_fixes_649(self):1101 """__setitem__ should behave case-insensitively."""1102 cid = CaseInsensitiveDict()1103 cid['spam'] = 'oneval'1104 cid['Spam'] = 'twoval'1105 cid['sPAM'] = 'redval'1106 cid['SPAM'] = 'blueval'1107 assert cid['spam'] == 'blueval'1108 assert cid['SPAM'] == 'blueval'1109 assert list(cid.keys()) == ['SPAM']11101111 def test_delitem(self):1112 cid = CaseInsensitiveDict()1113 cid['Spam'] = 'someval'1114 del cid['sPam']1115 assert 'spam' not in cid1116 assert len(cid) == 011171118 def test_contains(self):1119 cid = CaseInsensitiveDict()1120 cid['Spam'] = 'someval'1121 assert 'Spam' in cid1122 assert 'spam' in cid1123 assert 'SPAM' in cid1124 assert 'sPam' in cid1125 assert 'notspam' not in cid11261127 def test_get(self):1128 cid = CaseInsensitiveDict()1129 cid['spam'] = 'oneval'1130 cid['SPAM'] = 'blueval'1131 assert cid.get('spam') == 'blueval'1132 assert cid.get('SPAM') == 'blueval'1133 assert cid.get('sPam') == 'blueval'1134 assert cid.get('notspam', 'default') == 'default'11351136 def test_update(self):1137 cid = CaseInsensitiveDict()1138 cid['spam'] = 'blueval'1139 cid.update({'sPam': 'notblueval'})1140 assert cid['spam'] == 'notblueval'1141 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1142 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1143 assert len(cid) == 21144 assert cid['foo'] == 'anotherfoo'1145 assert cid['bar'] == 'anotherbar'11461147 def test_update_retains_unchanged(self):1148 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1149 cid.update({'foo': 'newfoo'})1150 assert cid['bar'] == 'bar'11511152 def test_iter(self):1153 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1154 keys = frozenset(['Spam', 'Eggs'])1155 assert frozenset(iter(cid)) == keys11561157 def test_equality(self):1158 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1159 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1160 assert cid == othercid1161 del othercid['spam']1162 assert cid != othercid1163 assert cid == {'spam': 'blueval', 'eggs': 'redval'}11641165 def test_setdefault(self):1166 cid = CaseInsensitiveDict({'Spam': 'blueval'})1167 assert cid.setdefault('spam', 'notblueval') == 'blueval'1168 assert cid.setdefault('notspam', 'notblueval') == 'notblueval'11691170 def test_lower_items(self):1171 cid = CaseInsensitiveDict({1172 'Accept': 'application/json',1173 'user-Agent': 'requests',1174 })1175 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1176 lowerkeyset = frozenset(['accept', 'user-agent'])1177 assert keyset == lowerkeyset11781179 def test_preserve_key_case(self):1180 cid = CaseInsensitiveDict({1181 'Accept': 'application/json',1182 'user-Agent': 'requests',1183 })1184 keyset = frozenset(['Accept', 'user-Agent'])1185 assert frozenset(i[0] for i in cid.items()) == keyset1186 assert frozenset(cid.keys()) == keyset1187 assert frozenset(cid) == keyset11881189 def test_preserve_last_key_case(self):1190 cid = CaseInsensitiveDict({1191 'Accept': 'application/json',1192 'user-Agent': 'requests',1193 })1194 cid.update({'ACCEPT': 'application/json'})1195 cid['USER-AGENT'] = 'requests'1196 keyset = frozenset(['ACCEPT', 'USER-AGENT'])1197 assert frozenset(i[0] for i in cid.items()) == keyset1198 assert frozenset(cid.keys()) == keyset1199 assert frozenset(cid) == keyset120012011202class UtilsTestCase(unittest.TestCase):12031204 def test_super_len_io_streams(self):1205 """ Ensures that we properly deal with different kinds of IO streams. """1206 # uses StringIO or io.StringIO (see import above)1207 from io import BytesIO1208 from requests.utils import super_len12091210 assert super_len(StringIO.StringIO()) == 01211 assert super_len(1212 StringIO.StringIO('with so much drama in the LBC')) == 2912131214 assert super_len(BytesIO()) == 01215 assert super_len(1216 BytesIO(b"it's kinda hard bein' snoop d-o-double-g")) == 4012171218 try:1219 import cStringIO1220 except ImportError:1221 pass1222 else:1223 assert super_len(1224 cStringIO.StringIO('but some how, some way...')) == 2512251226 def test_get_environ_proxies_ip_ranges(self):1227 """Ensures that IP addresses are correctly matches with ranges1228 in no_proxy variable."""1229 from requests.utils import get_environ_proxies1230 os.environ['no_proxy'] = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"1231 assert get_environ_proxies('http://192.168.0.1:5000/') == {}1232 assert get_environ_proxies('http://192.168.0.1/') == {}1233 assert get_environ_proxies('http://172.16.1.1/') == {}1234 assert get_environ_proxies('http://172.16.1.1:5000/') == {}1235 assert get_environ_proxies('http://192.168.1.1:5000/') != {}1236 assert get_environ_proxies('http://192.168.1.1/') != {}12371238 def test_get_environ_proxies(self):1239 """Ensures that IP addresses are correctly matches with ranges1240 in no_proxy variable."""1241 from requests.utils import get_environ_proxies1242 os.environ['no_proxy'] = "127.0.0.1,localhost.localdomain,192.168.0.0/24,172.16.1.1"1243 assert get_environ_proxies(1244 'http://localhost.localdomain:5000/v1.0/') == {}1245 assert get_environ_proxies('http://www.requests.com/') != {}12461247 def test_is_ipv4_address(self):1248 from requests.utils import is_ipv4_address1249 assert is_ipv4_address('8.8.8.8')1250 assert not is_ipv4_address('8.8.8.8.8')1251 assert not is_ipv4_address('localhost.localdomain')12521253 def test_is_valid_cidr(self):1254 from requests.utils import is_valid_cidr1255 assert not is_valid_cidr('8.8.8.8')1256 assert is_valid_cidr('192.168.1.0/24')12571258 def test_dotted_netmask(self):1259 from requests.utils import dotted_netmask1260 assert dotted_netmask(8) == '255.0.0.0'1261 assert dotted_netmask(24) == '255.255.255.0'1262 assert dotted_netmask(25) == '255.255.255.128'12631264 def test_address_in_network(self):1265 from requests.utils import address_in_network1266 assert address_in_network('192.168.1.1', '192.168.1.0/24')1267 assert not address_in_network('172.16.0.1', '192.168.1.0/24')12681269 def test_get_auth_from_url(self):1270 """Ensures that username and password in well-encoded URI as per1271 RFC 3986 are correclty extracted."""1272 from requests.utils import get_auth_from_url1273 from requests.compat import quote1274 percent_encoding_test_chars = "%!*'();:@&=+$,/?#[] "1275 url_address = "request.com/url.html#test"1276 url = "http://" + quote(1277 percent_encoding_test_chars, '') + ':' + quote(1278 percent_encoding_test_chars, '') + '@' + url_address1279 (username, password) = get_auth_from_url(url)1280 assert username == percent_encoding_test_chars1281 assert password == percent_encoding_test_chars128212831284class TestMorselToCookieExpires(unittest.TestCase):12851286 """Tests for morsel_to_cookie when morsel contains expires."""12871288 def test_expires_valid_str(self):1289 """Test case where we convert expires from string time."""12901291 morsel = Morsel()1292 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1293 cookie = morsel_to_cookie(morsel)1294 assert cookie.expires == 112951296 def test_expires_invalid_int(self):1297 """Test case where an invalid type is passed for expires."""12981299 morsel = Morsel()1300 morsel['expires'] = 1001301 with pytest.raises(TypeError):1302 morsel_to_cookie(morsel)13031304 def test_expires_invalid_str(self):1305 """Test case where an invalid string is input."""13061307 morsel = Morsel()1308 morsel['expires'] = 'woops'1309 with pytest.raises(ValueError):1310 morsel_to_cookie(morsel)13111312 def test_expires_none(self):1313 """Test case where expires is None."""13141315 morsel = Morsel()1316 morsel['expires'] = None1317 cookie = morsel_to_cookie(morsel)1318 assert cookie.expires is None131913201321class TestMorselToCookieMaxAge(unittest.TestCase):13221323 """Tests for morsel_to_cookie when morsel contains max-age."""13241325 def test_max_age_valid_int(self):1326 """Test case where a valid max age in seconds is passed."""13271328 morsel = Morsel()1329 morsel['max-age'] = 601330 cookie = morsel_to_cookie(morsel)1331 assert isinstance(cookie.expires, int)13321333 def test_max_age_invalid_str(self):1334 """Test case where a invalid max age is passed."""13351336 morsel = Morsel()1337 morsel['max-age'] = 'woops'1338 with pytest.raises(TypeError):1339 morsel_to_cookie(morsel)134013411342class TestTimeout:1343 def test_stream_timeout(self):1344 try:1345 requests.get('https://httpbin.org/delay/10', timeout=2.0)1346 except requests.exceptions.Timeout as e:1347 assert 'Read timed out' in e.args[0].args[0]13481349 def test_invalid_timeout(self):1350 with pytest.raises(ValueError) as e:1351 requests.get(httpbin('get'), timeout=(3, 4, 5))1352 assert '(connect, read)' in str(e)13531354 with pytest.raises(ValueError) as e:1355 requests.get(httpbin('get'), timeout="foo")1356 assert 'must be an int or float' in str(e)13571358 def test_none_timeout(self):1359 """ Check that you can set None as a valid timeout value.13601361 To actually test this behavior, we'd want to check that setting the1362 timeout to None actually lets the request block past the system default1363 timeout. However, this would make the test suite unbearably slow.1364 Instead we verify that setting the timeout to None does not prevent the1365 request from succeeding.1366 """1367 r = requests.get(httpbin('get'), timeout=None)1368 assert r.status_code == 20013691370 def test_read_timeout(self):1371 try:1372 requests.get(httpbin('delay/10'), timeout=(None, 0.1))1373 assert False, "The recv() request should time out."1374 except ReadTimeout:1375 pass13761377 def test_connect_timeout(self):1378 try:1379 requests.get(TARPIT, timeout=(0.1, None))1380 assert False, "The connect() request should time out."1381 except ConnectTimeout as e:1382 assert isinstance(e, ConnectionError)1383 assert isinstance(e, Timeout)13841385 def test_total_timeout_connect(self):1386 try:1387 requests.get(TARPIT, timeout=(0.1, 0.1))1388 assert False, "The connect() request should time out."1389 except ConnectTimeout:1390 pass139113921393SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))139413951396class RedirectSession(SessionRedirectMixin):1397 def __init__(self, order_of_redirects):1398 self.redirects = order_of_redirects1399 self.calls = []1400 self.max_redirects = 301401 self.cookies = {}1402 self.trust_env = False14031404 def send(self, *args, **kwargs):1405 self.calls.append(SendCall(args, kwargs))1406 return self.build_response()14071408 def build_response(self):1409 request = self.calls[-1].args[0]1410 r = requests.Response()14111412 try:1413 r.status_code = int(self.redirects.pop(0))1414 except IndexError:1415 r.status_code = 20014161417 r.headers = CaseInsensitiveDict({'Location': '/'})1418 r.raw = self._build_raw()1419 r.request = request1420 return r14211422 def _build_raw(self):1423 string = StringIO.StringIO('')1424 setattr(string, 'release_conn', lambda *args: args)1425 return string142614271428class TestRedirects:1429 default_keyword_args = {1430 'stream': False,1431 'verify': True,1432 'cert': None,1433 'timeout': None,1434 'allow_redirects': False,1435 'proxies': {},1436 }14371438 def test_requests_are_updated_each_time(self):1439 session = RedirectSession([303, 307])1440 prep = requests.Request('POST', 'http://httpbin.org/post').prepare()1441 r0 = session.send(prep)1442 assert r0.request.method == 'POST'1443 assert session.calls[-1] == SendCall((r0.request,), {})1444 redirect_generator = session.resolve_redirects(r0, prep)1445 for response in redirect_generator:1446 assert response.request.method == 'GET'1447 send_call = SendCall((response.request,),1448 TestRedirects.default_keyword_args)1449 assert session.calls[-1] == send_call1450145114521453@pytest.fixture1454def list_of_tuples():1455 return [1456 (('a', 'b'), ('c', 'd')),1457 (('c', 'd'), ('a', 'b')),1458 (('a', 'b'), ('c', 'd'), ('e', 'f')),1459 ]146014611462def test_data_argument_accepts_tuples(list_of_tuples):1463 """1464 Ensure that the data argument will accept tuples of strings1465 and properly encode them.1466 """1467 for data in list_of_tuples:1468 p = PreparedRequest()1469 p.prepare(1470 method='GET',1471 url='http://www.example.com',1472 data=data,1473 hooks=default_hooks()1474 )1475 assert p.body == urlencode(data)147614771478def assert_copy(p, p_copy):1479 for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):1480 assert getattr(p, attr) == getattr(p_copy, attr)148114821483def test_prepared_request_empty_copy():1484 p = PreparedRequest()1485 assert_copy(p, p.copy())148614871488def test_prepared_request_no_cookies_copy():1489 p = PreparedRequest()1490 p.prepare(1491 method='GET',1492 url='http://www.example.com',1493 data='foo=bar',1494 hooks=default_hooks()1495 )1496 assert_copy(p, p.copy())149714981499def test_prepared_request_complete_copy():1500 p = PreparedRequest()1501 p.prepare(1502 method='GET',1503 url='http://www.example.com',1504 data='foo=bar',1505 hooks=default_hooks(),1506 cookies={'foo': 'bar'}1507 )1508 assert_copy(p, p.copy())15091510def test_prepare_unicode_url():1511 p = PreparedRequest()1512 p.prepare(1513 method='GET',1514 url=u('http://www.example.com/üniçø∂é')1515 )1516 assert_copy(p, p.copy())15171518if __name__ == '__main__':1519 unittest.main()