test_requests.py
This file
Path
test_requests.py
1,545 lines · 51.3 KiB · Python
Last changed by
Merge pull request #2363 from sigmavirus24/fix-testsKenneth Reitzbefore adoption4e90aa7
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, RetryError)24from requests.models import PreparedRequest25from requests.structures import CaseInsensitiveDict26from requests.sessions import SessionRedirectMixin27from requests.models import urlencode28from requests.hooks import default_hooks2930try:31 import StringIO32except ImportError:33 import io as StringIO3435if is_py3:36 def u(s):37 return s38else:39 def u(s):40 return s.decode('unicode-escape')414243# Requests to this URL should always fail with a connection timeout (nothing44# listening on that port)45TARPIT = "http://10.255.255.1"46HTTPBIN = os.environ.get('HTTPBIN_URL', 'http://httpbin.org/')47# Issue #1483: Make sure the URL always has a trailing slash48HTTPBIN = HTTPBIN.rstrip('/') + '/'495051def httpbin(*suffix):52 """Returns url for HTTPBIN resource."""53 return urljoin(HTTPBIN, '/'.join(suffix))545556class RequestsTestCase(unittest.TestCase):5758 _multiprocess_can_split_ = True5960 def setUp(self):61 """Create simple data set with headers."""62 pass6364 def tearDown(self):65 """Teardown."""66 pass6768 def test_entry_points(self):6970 requests.session71 requests.session().get72 requests.session().head73 requests.get74 requests.head75 requests.put76 requests.patch77 requests.post7879 def test_invalid_url(self):80 with pytest.raises(MissingSchema):81 requests.get('hiwpefhipowhefopw')82 with pytest.raises(InvalidSchema):83 requests.get('localhost:3128')84 with pytest.raises(InvalidSchema):85 requests.get('localhost.localdomain:3128/')86 with pytest.raises(InvalidSchema):87 requests.get('10.122.1.1:3128/')88 with pytest.raises(InvalidURL):89 requests.get('http://')9091 def test_basic_building(self):92 req = requests.Request()93 req.url = 'http://kennethreitz.org/'94 req.data = {'life': '42'}9596 pr = req.prepare()97 assert pr.url == req.url98 assert pr.body == 'life=42'99100 def test_no_content_length(self):101 get_req = requests.Request('GET', httpbin('get')).prepare()102 assert 'Content-Length' not in get_req.headers103 head_req = requests.Request('HEAD', httpbin('head')).prepare()104 assert 'Content-Length' not in head_req.headers105106 def test_override_content_length(self):107 headers = {108 'Content-Length': 'not zero'109 }110 r = requests.Request('POST', httpbin('post'), headers=headers).prepare()111 assert 'Content-Length' in r.headers112 assert r.headers['Content-Length'] == 'not zero'113114 def test_path_is_not_double_encoded(self):115 request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()116117 assert request.path_url == '/get/test%20case'118119 def test_params_are_added_before_fragment(self):120 request = requests.Request('GET',121 "http://example.com/path#fragment", params={"a": "b"}).prepare()122 assert request.url == "http://example.com/path?a=b#fragment"123 request = requests.Request('GET',124 "http://example.com/path?key=value#fragment", params={"a": "b"}).prepare()125 assert request.url == "http://example.com/path?key=value&a=b#fragment"126127 def test_mixed_case_scheme_acceptable(self):128 s = requests.Session()129 s.proxies = getproxies()130 parts = urlparse(httpbin('get'))131 schemes = ['http://', 'HTTP://', 'hTTp://', 'HttP://',132 'https://', 'HTTPS://', 'hTTps://', 'HttPs://']133 for scheme in schemes:134 url = scheme + parts.netloc + parts.path135 r = requests.Request('GET', url)136 r = s.send(r.prepare())137 assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)138139 def test_HTTP_200_OK_GET_ALTERNATIVE(self):140 r = requests.Request('GET', httpbin('get'))141 s = requests.Session()142 s.proxies = getproxies()143144 r = s.send(r.prepare())145146 assert r.status_code == 200147148 def test_HTTP_302_ALLOW_REDIRECT_GET(self):149 r = requests.get(httpbin('redirect', '1'))150 assert r.status_code == 200151 assert r.history[0].status_code == 302152 assert r.history[0].is_redirect153154 # def test_HTTP_302_ALLOW_REDIRECT_POST(self):155 # r = requests.post(httpbin('status', '302'), data={'some': 'data'})156 # self.assertEqual(r.status_code, 200)157158 def test_HTTP_200_OK_GET_WITH_PARAMS(self):159 heads = {'User-agent': 'Mozilla/5.0'}160161 r = requests.get(httpbin('user-agent'), headers=heads)162163 assert heads['User-agent'] in r.text164 assert r.status_code == 200165166 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):167 heads = {'User-agent': 'Mozilla/5.0'}168169 r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)170 assert r.status_code == 200171172 def test_set_cookie_on_301(self):173 s = requests.session()174 url = httpbin('cookies/set?foo=bar')175 s.get(url)176 assert s.cookies['foo'] == 'bar'177178 def test_cookie_sent_on_redirect(self):179 s = requests.session()180 s.get(httpbin('cookies/set?foo=bar'))181 r = s.get(httpbin('redirect/1')) # redirects to httpbin('get')182 assert 'Cookie' in r.json()['headers']183184 def test_cookie_removed_on_expire(self):185 s = requests.session()186 s.get(httpbin('cookies/set?foo=bar'))187 assert s.cookies['foo'] == 'bar'188 s.get(189 httpbin('response-headers'),190 params={191 'Set-Cookie':192 'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'193 }194 )195 assert 'foo' not in s.cookies196197 def test_cookie_quote_wrapped(self):198 s = requests.session()199 s.get(httpbin('cookies/set?foo="bar:baz"'))200 assert s.cookies['foo'] == '"bar:baz"'201202 def test_cookie_persists_via_api(self):203 s = requests.session()204 r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})205 assert 'foo' in r.request.headers['Cookie']206 assert 'foo' in r.history[0].request.headers['Cookie']207208 def test_request_cookie_overrides_session_cookie(self):209 s = requests.session()210 s.cookies['foo'] = 'bar'211 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})212 assert r.json()['cookies']['foo'] == 'baz'213 # Session cookie should not be modified214 assert s.cookies['foo'] == 'bar'215216 def test_request_cookies_not_persisted(self):217 s = requests.session()218 s.get(httpbin('cookies'), cookies={'foo': 'baz'})219 # Sending a request with cookies should not add cookies to the session220 assert not s.cookies221222 def test_generic_cookiejar_works(self):223 cj = cookielib.CookieJar()224 cookiejar_from_dict({'foo': 'bar'}, cj)225 s = requests.session()226 s.cookies = cj227 r = s.get(httpbin('cookies'))228 # Make sure the cookie was sent229 assert r.json()['cookies']['foo'] == 'bar'230 # Make sure the session cj is still the custom one231 assert s.cookies is cj232233 def test_param_cookiejar_works(self):234 cj = cookielib.CookieJar()235 cookiejar_from_dict({'foo': 'bar'}, cj)236 s = requests.session()237 r = s.get(httpbin('cookies'), cookies=cj)238 # Make sure the cookie was sent239 assert r.json()['cookies']['foo'] == 'bar'240241 def test_requests_in_history_are_not_overridden(self):242 resp = requests.get(httpbin('redirect/3'))243 urls = [r.url for r in resp.history]244 req_urls = [r.request.url for r in resp.history]245 assert urls == req_urls246247 def test_history_is_always_a_list(self):248 """249 Show that even with redirects, Response.history is always a list.250 """251 resp = requests.get(httpbin('get'))252 assert isinstance(resp.history, list)253 resp = requests.get(httpbin('redirect/1'))254 assert isinstance(resp.history, list)255 assert not isinstance(resp.history, tuple)256257 def test_headers_on_session_with_None_are_not_sent(self):258 """Do not send headers in Session.headers with None values."""259 ses = requests.Session()260 ses.headers['Accept-Encoding'] = None261 req = requests.Request('GET', httpbin('get'))262 prep = ses.prepare_request(req)263 assert 'Accept-Encoding' not in prep.headers264265 def test_user_agent_transfers(self):266267 heads = {268 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'269 }270271 r = requests.get(httpbin('user-agent'), headers=heads)272 assert heads['User-agent'] in r.text273274 heads = {275 'user-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'276 }277278 r = requests.get(httpbin('user-agent'), headers=heads)279 assert heads['user-agent'] in r.text280281 def test_HTTP_200_OK_HEAD(self):282 r = requests.head(httpbin('get'))283 assert r.status_code == 200284285 def test_HTTP_200_OK_PUT(self):286 r = requests.put(httpbin('put'))287 assert r.status_code == 200288289 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):290 auth = ('user', 'pass')291 url = httpbin('basic-auth', 'user', 'pass')292293 r = requests.get(url, auth=auth)294 assert r.status_code == 200295296 r = requests.get(url)297 assert r.status_code == 401298299 s = requests.session()300 s.auth = auth301 r = s.get(url)302 assert r.status_code == 200303304 def test_connection_error(self):305 """Connecting to an unknown domain should raise a ConnectionError"""306 with pytest.raises(ConnectionError):307 requests.get("http://fooobarbangbazbing.httpbin.org")308309 with pytest.raises(ConnectionError):310 requests.get("http://httpbin.org:1")311312 def test_basicauth_with_netrc(self):313 auth = ('user', 'pass')314 wrong_auth = ('wronguser', 'wrongpass')315 url = httpbin('basic-auth', 'user', 'pass')316317 def get_netrc_auth_mock(url):318 return auth319 requests.sessions.get_netrc_auth = get_netrc_auth_mock320321 # Should use netrc and work.322 r = requests.get(url)323 assert r.status_code == 200324325 # Given auth should override and fail.326 r = requests.get(url, auth=wrong_auth)327 assert r.status_code == 401328329 s = requests.session()330331 # Should use netrc and work.332 r = s.get(url)333 assert r.status_code == 200334335 # Given auth should override and fail.336 s.auth = wrong_auth337 r = s.get(url)338 assert r.status_code == 401339340 def test_DIGEST_HTTP_200_OK_GET(self):341342 auth = HTTPDigestAuth('user', 'pass')343 url = httpbin('digest-auth', 'auth', 'user', 'pass')344345 r = requests.get(url, auth=auth)346 assert r.status_code == 200347348 r = requests.get(url)349 assert r.status_code == 401350351 s = requests.session()352 s.auth = HTTPDigestAuth('user', 'pass')353 r = s.get(url)354 assert r.status_code == 200355356 def test_DIGEST_AUTH_RETURNS_COOKIE(self):357 url = httpbin('digest-auth', 'auth', 'user', 'pass')358 auth = HTTPDigestAuth('user', 'pass')359 r = requests.get(url)360 assert r.cookies['fake'] == 'fake_value'361362 r = requests.get(url, auth=auth)363 assert r.status_code == 200364365 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self):366 url = httpbin('digest-auth', 'auth', 'user', 'pass')367 auth = HTTPDigestAuth('user', 'pass')368 s = requests.Session()369 s.get(url, auth=auth)370 assert s.cookies['fake'] == 'fake_value'371372 def test_DIGEST_STREAM(self):373374 auth = HTTPDigestAuth('user', 'pass')375 url = httpbin('digest-auth', 'auth', 'user', 'pass')376377 r = requests.get(url, auth=auth, stream=True)378 assert r.raw.read() != b''379380 r = requests.get(url, auth=auth, stream=False)381 assert r.raw.read() == b''382383 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self):384385 auth = HTTPDigestAuth('user', 'wrongpass')386 url = httpbin('digest-auth', 'auth', 'user', 'pass')387388 r = requests.get(url, auth=auth)389 assert r.status_code == 401390391 r = requests.get(url)392 assert r.status_code == 401393394 s = requests.session()395 s.auth = auth396 r = s.get(url)397 assert r.status_code == 401398399 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self):400401 auth = HTTPDigestAuth('user', 'pass')402 url = httpbin('digest-auth', 'auth', 'user', 'pass')403404 r = requests.get(url, auth=auth)405 assert '"auth"' in r.request.headers['Authorization']406407 def test_POSTBIN_GET_POST_FILES(self):408409 url = httpbin('post')410 post1 = requests.post(url).raise_for_status()411412 post1 = requests.post(url, data={'some': 'data'})413 assert post1.status_code == 200414415 with open('requirements.txt') as f:416 post2 = requests.post(url, files={'some': f})417 assert post2.status_code == 200418419 post4 = requests.post(url, data='[{"some": "json"}]')420 assert post4.status_code == 200421422 with pytest.raises(ValueError):423 requests.post(url, files=['bad file data'])424425 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self):426427 url = httpbin('post')428 post1 = requests.post(url).raise_for_status()429430 post1 = requests.post(url, data={'some': 'data'})431 assert post1.status_code == 200432433 with open('requirements.txt') as f:434 post2 = requests.post(url,435 data={'some': 'data'}, files={'some': f})436 assert post2.status_code == 200437438 post4 = requests.post(url, data='[{"some": "json"}]')439 assert post4.status_code == 200440441 with pytest.raises(ValueError):442 requests.post(url, files=['bad file data'])443444 def test_conflicting_post_params(self):445 url = httpbin('post')446 with open('requirements.txt') as f:447 pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")448 pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")449450 def test_request_ok_set(self):451 r = requests.get(httpbin('status', '404'))452 assert not r.ok453454 def test_status_raising(self):455 r = requests.get(httpbin('status', '404'))456 with pytest.raises(requests.exceptions.HTTPError):457 r.raise_for_status()458459 r = requests.get(httpbin('status', '500'))460 assert not r.ok461462 def test_decompress_gzip(self):463 r = requests.get(httpbin('gzip'))464 r.content.decode('ascii')465466 def test_unicode_get(self):467 url = httpbin('/get')468 requests.get(url, params={'foo': 'føø'})469 requests.get(url, params={'føø': 'føø'})470 requests.get(url, params={'føø': 'føø'})471 requests.get(url, params={'foo': 'foo'})472 requests.get(httpbin('ø'), params={'foo': 'foo'})473474 def test_unicode_header_name(self):475 requests.put(476 httpbin('put'),477 headers={str('Content-Type'): 'application/octet-stream'},478 data='\xff') # compat.str is unicode.479480 def test_pyopenssl_redirect(self):481 requests.get('https://httpbin.org/status/301')482483 def test_urlencoded_get_query_multivalued_param(self):484485 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))486 assert r.status_code == 200487 assert r.url == httpbin('get?test=foo&test=baz')488489 def test_different_encodings_dont_break_post(self):490 r = requests.post(httpbin('post'),491 data={'stuff': json.dumps({'a': 123})},492 params={'blah': 'asdf1234'},493 files={'file': ('test_requests.py', open(__file__, 'rb'))})494 assert r.status_code == 200495496 def test_unicode_multipart_post(self):497 r = requests.post(httpbin('post'),498 data={'stuff': u('ëlïxr')},499 files={'file': ('test_requests.py', open(__file__, 'rb'))})500 assert r.status_code == 200501502 r = requests.post(httpbin('post'),503 data={'stuff': u('ëlïxr').encode('utf-8')},504 files={'file': ('test_requests.py', open(__file__, 'rb'))})505 assert r.status_code == 200506507 r = requests.post(httpbin('post'),508 data={'stuff': 'elixr'},509 files={'file': ('test_requests.py', open(__file__, 'rb'))})510 assert r.status_code == 200511512 r = requests.post(httpbin('post'),513 data={'stuff': 'elixr'.encode('utf-8')},514 files={'file': ('test_requests.py', open(__file__, 'rb'))})515 assert r.status_code == 200516517 def test_unicode_multipart_post_fieldnames(self):518 filename = os.path.splitext(__file__)[0] + '.py'519 r = requests.Request(method='POST',520 url=httpbin('post'),521 data={'stuff'.encode('utf-8'): 'elixr'},522 files={'file': ('test_requests.py',523 open(filename, 'rb'))})524 prep = r.prepare()525 assert b'name="stuff"' in prep.body526 assert b'name="b\'stuff\'"' not in prep.body527528 def test_unicode_method_name(self):529 files = {'file': open('test_requests.py', 'rb')}530 r = requests.request(531 method=u('POST'), url=httpbin('post'), files=files)532 assert r.status_code == 200533534 def test_custom_content_type(self):535 r = requests.post(536 httpbin('post'),537 data={'stuff': json.dumps({'a': 123})},538 files={'file1': ('test_requests.py', open(__file__, 'rb')),539 'file2': ('test_requests', open(__file__, 'rb'),540 'text/py-content-type')})541 assert r.status_code == 200542 assert b"text/py-content-type" in r.request.body543544 def test_hook_receives_request_arguments(self):545 def hook(resp, **kwargs):546 assert resp is not None547 assert kwargs != {}548549 requests.Request('GET', HTTPBIN, hooks={'response': hook})550551 def test_session_hooks_are_used_with_no_request_hooks(self):552 hook = lambda x, *args, **kwargs: x553 s = requests.Session()554 s.hooks['response'].append(hook)555 r = requests.Request('GET', HTTPBIN)556 prep = s.prepare_request(r)557 assert prep.hooks['response'] != []558 assert prep.hooks['response'] == [hook]559560 def test_session_hooks_are_overriden_by_request_hooks(self):561 hook1 = lambda x, *args, **kwargs: x562 hook2 = lambda x, *args, **kwargs: x563 assert hook1 is not hook2564 s = requests.Session()565 s.hooks['response'].append(hook2)566 r = requests.Request('GET', HTTPBIN, hooks={'response': [hook1]})567 prep = s.prepare_request(r)568 assert prep.hooks['response'] == [hook1]569570 def test_prepared_request_hook(self):571 def hook(resp, **kwargs):572 resp.hook_working = True573 return resp574575 req = requests.Request('GET', HTTPBIN, hooks={'response': hook})576 prep = req.prepare()577578 s = requests.Session()579 s.proxies = getproxies()580 resp = s.send(prep)581582 assert hasattr(resp, 'hook_working')583584 def test_prepared_from_session(self):585 class DummyAuth(requests.auth.AuthBase):586 def __call__(self, r):587 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'588 return r589590 req = requests.Request('GET', httpbin('headers'))591 assert not req.auth592593 s = requests.Session()594 s.auth = DummyAuth()595596 prep = s.prepare_request(req)597 resp = s.send(prep)598599 assert resp.json()['headers'][600 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'601602 def test_prepare_request_with_bytestring_url(self):603 req = requests.Request('GET', b'https://httpbin.org/')604 s = requests.Session()605 prep = s.prepare_request(req)606 assert prep.url == "https://httpbin.org/"607608 def test_links(self):609 r = requests.Response()610 r.headers = {611 'cache-control': 'public, max-age=60, s-maxage=60',612 'connection': 'keep-alive',613 'content-encoding': 'gzip',614 'content-type': 'application/json; charset=utf-8',615 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',616 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',617 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',618 'link': ('<https://api.github.com/users/kennethreitz/repos?'619 'page=2&per_page=10>; rel="next", <https://api.github.'620 'com/users/kennethreitz/repos?page=7&per_page=10>; '621 ' rel="last"'),622 'server': 'GitHub.com',623 'status': '200 OK',624 'vary': 'Accept',625 'x-content-type-options': 'nosniff',626 'x-github-media-type': 'github.beta',627 'x-ratelimit-limit': '60',628 'x-ratelimit-remaining': '57'629 }630 assert r.links['next']['rel'] == 'next'631632 def test_cookie_parameters(self):633 key = 'some_cookie'634 value = 'some_value'635 secure = True636 domain = 'test.com'637 rest = {'HttpOnly': True}638639 jar = requests.cookies.RequestsCookieJar()640 jar.set(key, value, secure=secure, domain=domain, rest=rest)641642 assert len(jar) == 1643 assert 'some_cookie' in jar644645 cookie = list(jar)[0]646 assert cookie.secure == secure647 assert cookie.domain == domain648 assert cookie._rest['HttpOnly'] == rest['HttpOnly']649650 def test_cookie_as_dict_keeps_len(self):651 key = 'some_cookie'652 value = 'some_value'653654 key1 = 'some_cookie1'655 value1 = 'some_value1'656657 jar = requests.cookies.RequestsCookieJar()658 jar.set(key, value)659 jar.set(key1, value1)660661 d1 = dict(jar)662 d2 = dict(jar.iteritems())663 d3 = dict(jar.items())664665 assert len(jar) == 2666 assert len(d1) == 2667 assert len(d2) == 2668 assert len(d3) == 2669670 def test_cookie_as_dict_keeps_items(self):671 key = 'some_cookie'672 value = 'some_value'673674 key1 = 'some_cookie1'675 value1 = 'some_value1'676677 jar = requests.cookies.RequestsCookieJar()678 jar.set(key, value)679 jar.set(key1, value1)680681 d1 = dict(jar)682 d2 = dict(jar.iteritems())683 d3 = dict(jar.items())684685 assert d1['some_cookie'] == 'some_value'686 assert d2['some_cookie'] == 'some_value'687 assert d3['some_cookie1'] == 'some_value1'688689 def test_cookie_as_dict_keys(self):690 key = 'some_cookie'691 value = 'some_value'692693 key1 = 'some_cookie1'694 value1 = 'some_value1'695696 jar = requests.cookies.RequestsCookieJar()697 jar.set(key, value)698 jar.set(key1, value1)699700 keys = jar.keys()701 assert keys == list(keys)702 # make sure one can use keys multiple times703 assert list(keys) == list(keys)704705 def test_cookie_as_dict_values(self):706 key = 'some_cookie'707 value = 'some_value'708709 key1 = 'some_cookie1'710 value1 = 'some_value1'711712 jar = requests.cookies.RequestsCookieJar()713 jar.set(key, value)714 jar.set(key1, value1)715716 values = jar.values()717 assert values == list(values)718 # make sure one can use values multiple times719 assert list(values) == list(values)720721 def test_cookie_as_dict_items(self):722 key = 'some_cookie'723 value = 'some_value'724725 key1 = 'some_cookie1'726 value1 = 'some_value1'727728 jar = requests.cookies.RequestsCookieJar()729 jar.set(key, value)730 jar.set(key1, value1)731732 items = jar.items()733 assert items == list(items)734 # make sure one can use items multiple times735 assert list(items) == list(items)736737 def test_time_elapsed_blank(self):738 r = requests.get(httpbin('get'))739 td = r.elapsed740 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)741 * 10**6) / 10**6)742 assert total_seconds > 0.0743744 def test_response_is_iterable(self):745 r = requests.Response()746 io = StringIO.StringIO('abc')747 read_ = io.read748749 def read_mock(amt, decode_content=None):750 return read_(amt)751 setattr(io, 'read', read_mock)752 r.raw = io753 assert next(iter(r))754 io.close()755756 def test_response_decode_unicode(self):757 """758 When called with decode_unicode, Response.iter_content should always759 return unicode.760 """761 r = requests.Response()762 r._content_consumed = True763 r._content = b'the content'764 r.encoding = 'ascii'765766 chunks = r.iter_content(decode_unicode=True)767 assert all(isinstance(chunk, str) for chunk in chunks)768769 # also for streaming770 r = requests.Response()771 r.raw = io.BytesIO(b'the content')772 r.encoding = 'ascii'773 chunks = r.iter_content(decode_unicode=True)774 assert all(isinstance(chunk, str) for chunk in chunks)775776 def test_request_and_response_are_pickleable(self):777 r = requests.get(httpbin('get'))778779 # verify we can pickle the original request780 assert pickle.loads(pickle.dumps(r.request))781782 # verify we can pickle the response and that we have access to783 # the original request.784 pr = pickle.loads(pickle.dumps(r))785 assert r.request.url == pr.request.url786 assert r.request.headers == pr.request.headers787788 def test_get_auth_from_url(self):789 url = 'http://user:pass@complex.url.com/path?query=yes'790 assert ('user', 'pass') == requests.utils.get_auth_from_url(url)791792 def test_get_auth_from_url_encoded_spaces(self):793 url = 'http://user:pass%20pass@complex.url.com/path?query=yes'794 assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)795796 def test_get_auth_from_url_not_encoded_spaces(self):797 url = 'http://user:pass pass@complex.url.com/path?query=yes'798 assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)799800 def test_get_auth_from_url_percent_chars(self):801 url = 'http://user%25user:pass@complex.url.com/path?query=yes'802 assert ('user%user', 'pass') == requests.utils.get_auth_from_url(url)803804 def test_get_auth_from_url_encoded_hashes(self):805 url = 'http://user:pass%23pass@complex.url.com/path?query=yes'806 assert ('user', 'pass#pass') == requests.utils.get_auth_from_url(url)807808 def test_cannot_send_unprepared_requests(self):809 r = requests.Request(url=HTTPBIN)810 with pytest.raises(ValueError):811 requests.Session().send(r)812813 def test_http_error(self):814 error = requests.exceptions.HTTPError()815 assert not error.response816 response = requests.Response()817 error = requests.exceptions.HTTPError(response=response)818 assert error.response == response819 error = requests.exceptions.HTTPError('message', response=response)820 assert str(error) == 'message'821 assert error.response == response822823 def test_session_pickling(self):824 r = requests.Request('GET', httpbin('get'))825 s = requests.Session()826827 s = pickle.loads(pickle.dumps(s))828 s.proxies = getproxies()829830 r = s.send(r.prepare())831 assert r.status_code == 200832833 def test_fixes_1329(self):834 """835 Ensure that header updates are done case-insensitively.836 """837 s = requests.Session()838 s.headers.update({'ACCEPT': 'BOGUS'})839 s.headers.update({'accept': 'application/json'})840 r = s.get(httpbin('get'))841 headers = r.request.headers842 assert headers['accept'] == 'application/json'843 assert headers['Accept'] == 'application/json'844 assert headers['ACCEPT'] == 'application/json'845846 def test_uppercase_scheme_redirect(self):847 parts = urlparse(httpbin('html'))848 url = "HTTP://" + parts.netloc + parts.path849 r = requests.get(httpbin('redirect-to'), params={'url': url})850 assert r.status_code == 200851 assert r.url.lower() == url.lower()852853 def test_transport_adapter_ordering(self):854 s = requests.Session()855 order = ['https://', 'http://']856 assert order == list(s.adapters)857 s.mount('http://git', HTTPAdapter())858 s.mount('http://github', HTTPAdapter())859 s.mount('http://github.com', HTTPAdapter())860 s.mount('http://github.com/about/', HTTPAdapter())861 order = [862 'http://github.com/about/',863 'http://github.com',864 'http://github',865 'http://git',866 'https://',867 'http://',868 ]869 assert order == list(s.adapters)870 s.mount('http://gittip', HTTPAdapter())871 s.mount('http://gittip.com', HTTPAdapter())872 s.mount('http://gittip.com/about/', HTTPAdapter())873 order = [874 'http://github.com/about/',875 'http://gittip.com/about/',876 'http://github.com',877 'http://gittip.com',878 'http://github',879 'http://gittip',880 'http://git',881 'https://',882 'http://',883 ]884 assert order == list(s.adapters)885 s2 = requests.Session()886 s2.adapters = {'http://': HTTPAdapter()}887 s2.mount('https://', HTTPAdapter())888 assert 'http://' in s2.adapters889 assert 'https://' in s2.adapters890891 def test_header_remove_is_case_insensitive(self):892 # From issue #1321893 s = requests.Session()894 s.headers['foo'] = 'bar'895 r = s.get(httpbin('get'), headers={'FOO': None})896 assert 'foo' not in r.request.headers897898 def test_params_are_merged_case_sensitive(self):899 s = requests.Session()900 s.params['foo'] = 'bar'901 r = s.get(httpbin('get'), params={'FOO': 'bar'})902 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}903904 def test_long_authinfo_in_url(self):905 url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(906 'E8A3BE87-9E3F-4620-8858-95478E385B5B',907 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',908 'exactly-------------sixty-----------three------------characters',909 )910 r = requests.Request('GET', url).prepare()911 assert r.url == url912913 def test_header_keys_are_native(self):914 headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}915 r = requests.Request('GET', httpbin('get'), headers=headers)916 p = r.prepare()917918 # This is testing that they are builtin strings. A bit weird, but there919 # we go.920 assert 'unicode' in p.headers.keys()921 assert 'byte' in p.headers.keys()922923 def test_can_send_nonstring_objects_with_files(self):924 data = {'a': 0.0}925 files = {'b': 'foo'}926 r = requests.Request('POST', httpbin('post'), data=data, files=files)927 p = r.prepare()928929 assert 'multipart/form-data' in p.headers['Content-Type']930931 def test_autoset_header_values_are_native(self):932 data = 'this is a string'933 length = '16'934 req = requests.Request('POST', httpbin('post'), data=data)935 p = req.prepare()936937 assert p.headers['Content-Length'] == length938939 def test_nonhttp_schemes_dont_check_URLs(self):940 test_urls = (941 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',942 'file:///etc/passwd',943 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',944 )945 for test_url in test_urls:946 req = requests.Request('GET', test_url)947 preq = req.prepare()948 assert test_url == preq.url949950 def test_auth_is_stripped_on_redirect_off_host(self):951 r = requests.get(952 httpbin('redirect-to'),953 params={'url': 'http://www.google.co.uk'},954 auth=('user', 'pass'),955 )956 assert r.history[0].request.headers['Authorization']957 assert not r.request.headers.get('Authorization', '')958959 def test_auth_is_retained_for_redirect_on_host(self):960 r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))961 h1 = r.history[0].request.headers['Authorization']962 h2 = r.request.headers['Authorization']963964 assert h1 == h2965966 def test_manual_redirect_with_partial_body_read(self):967 s = requests.Session()968 r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)969 assert r1.is_redirect970 rg = s.resolve_redirects(r1, r1.request, stream=True)971972 # read only the first eight bytes of the response body,973 # then follow the redirect974 r1.iter_content(8)975 r2 = next(rg)976 assert r2.is_redirect977978 # read all of the response via iter_content,979 # then follow the redirect980 for _ in r2.iter_content():981 pass982 r3 = next(rg)983 assert not r3.is_redirect984985 def _patch_adapter_gzipped_redirect(self, session, url):986 adapter = session.get_adapter(url=url)987 org_build_response = adapter.build_response988 self._patched_response = False989990 def build_response(*args, **kwargs):991 resp = org_build_response(*args, **kwargs)992 if not self._patched_response:993 resp.raw.headers['content-encoding'] = 'gzip'994 self._patched_response = True995 return resp996997 adapter.build_response = build_response998999 def test_redirect_with_wrong_gzipped_header(self):1000 s = requests.Session()1001 url = httpbin('redirect/1')1002 self._patch_adapter_gzipped_redirect(s, url)1003 s.get(url)10041005 def test_basic_auth_str_is_always_native(self):1006 s = _basic_auth_str("test", "test")1007 assert isinstance(s, builtin_str)1008 assert s == "Basic dGVzdDp0ZXN0"10091010 def test_requests_history_is_saved(self):1011 r = requests.get(httpbin('redirect/5'))1012 total = r.history[-1].history1013 i = 01014 for item in r.history:1015 assert item.history == total[0:i]1016 i = i + 110171018 def test_json_param_post_content_type_works(self):1019 r = requests.post(1020 httpbin('post'),1021 json={'life': 42}1022 )1023 assert r.status_code == 2001024 assert 'application/json' in r.request.headers['Content-Type']1025 assert {'life': 42} == r.json()['json']102610271028class TestContentEncodingDetection(unittest.TestCase):10291030 def test_none(self):1031 encodings = requests.utils.get_encodings_from_content('')1032 assert not len(encodings)10331034 def test_html_charset(self):1035 """HTML5 meta charset attribute"""1036 content = '<meta charset="UTF-8">'1037 encodings = requests.utils.get_encodings_from_content(content)1038 assert len(encodings) == 11039 assert encodings[0] == 'UTF-8'10401041 def test_html4_pragma(self):1042 """HTML4 pragma directive"""1043 content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">'1044 encodings = requests.utils.get_encodings_from_content(content)1045 assert len(encodings) == 11046 assert encodings[0] == 'UTF-8'10471048 def test_xhtml_pragma(self):1049 """XHTML 1.x served with text/html MIME type"""1050 content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />'1051 encodings = requests.utils.get_encodings_from_content(content)1052 assert len(encodings) == 11053 assert encodings[0] == 'UTF-8'10541055 def test_xml(self):1056 """XHTML 1.x served as XML"""1057 content = '<?xml version="1.0" encoding="UTF-8"?>'1058 encodings = requests.utils.get_encodings_from_content(content)1059 assert len(encodings) == 11060 assert encodings[0] == 'UTF-8'10611062 def test_precedence(self):1063 content = '''1064 <?xml version="1.0" encoding="XML"?>1065 <meta charset="HTML5">1066 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />1067 '''.strip()1068 encodings = requests.utils.get_encodings_from_content(content)1069 assert encodings == ['HTML5', 'HTML4', 'XML']107010711072class TestCaseInsensitiveDict(unittest.TestCase):10731074 def test_mapping_init(self):1075 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1076 assert len(cid) == 21077 assert 'foo' in cid1078 assert 'bar' in cid10791080 def test_iterable_init(self):1081 cid = CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')])1082 assert len(cid) == 21083 assert 'foo' in cid1084 assert 'bar' in cid10851086 def test_kwargs_init(self):1087 cid = CaseInsensitiveDict(FOO='foo', BAr='bar')1088 assert len(cid) == 21089 assert 'foo' in cid1090 assert 'bar' in cid10911092 def test_docstring_example(self):1093 cid = CaseInsensitiveDict()1094 cid['Accept'] = 'application/json'1095 assert cid['aCCEPT'] == 'application/json'1096 assert list(cid) == ['Accept']10971098 def test_len(self):1099 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1100 cid['A'] = 'a'1101 assert len(cid) == 211021103 def test_getitem(self):1104 cid = CaseInsensitiveDict({'Spam': 'blueval'})1105 assert cid['spam'] == 'blueval'1106 assert cid['SPAM'] == 'blueval'11071108 def test_fixes_649(self):1109 """__setitem__ should behave case-insensitively."""1110 cid = CaseInsensitiveDict()1111 cid['spam'] = 'oneval'1112 cid['Spam'] = 'twoval'1113 cid['sPAM'] = 'redval'1114 cid['SPAM'] = 'blueval'1115 assert cid['spam'] == 'blueval'1116 assert cid['SPAM'] == 'blueval'1117 assert list(cid.keys()) == ['SPAM']11181119 def test_delitem(self):1120 cid = CaseInsensitiveDict()1121 cid['Spam'] = 'someval'1122 del cid['sPam']1123 assert 'spam' not in cid1124 assert len(cid) == 011251126 def test_contains(self):1127 cid = CaseInsensitiveDict()1128 cid['Spam'] = 'someval'1129 assert 'Spam' in cid1130 assert 'spam' in cid1131 assert 'SPAM' in cid1132 assert 'sPam' in cid1133 assert 'notspam' not in cid11341135 def test_get(self):1136 cid = CaseInsensitiveDict()1137 cid['spam'] = 'oneval'1138 cid['SPAM'] = 'blueval'1139 assert cid.get('spam') == 'blueval'1140 assert cid.get('SPAM') == 'blueval'1141 assert cid.get('sPam') == 'blueval'1142 assert cid.get('notspam', 'default') == 'default'11431144 def test_update(self):1145 cid = CaseInsensitiveDict()1146 cid['spam'] = 'blueval'1147 cid.update({'sPam': 'notblueval'})1148 assert cid['spam'] == 'notblueval'1149 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1150 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1151 assert len(cid) == 21152 assert cid['foo'] == 'anotherfoo'1153 assert cid['bar'] == 'anotherbar'11541155 def test_update_retains_unchanged(self):1156 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1157 cid.update({'foo': 'newfoo'})1158 assert cid['bar'] == 'bar'11591160 def test_iter(self):1161 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1162 keys = frozenset(['Spam', 'Eggs'])1163 assert frozenset(iter(cid)) == keys11641165 def test_equality(self):1166 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1167 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1168 assert cid == othercid1169 del othercid['spam']1170 assert cid != othercid1171 assert cid == {'spam': 'blueval', 'eggs': 'redval'}11721173 def test_setdefault(self):1174 cid = CaseInsensitiveDict({'Spam': 'blueval'})1175 assert cid.setdefault('spam', 'notblueval') == 'blueval'1176 assert cid.setdefault('notspam', 'notblueval') == 'notblueval'11771178 def test_lower_items(self):1179 cid = CaseInsensitiveDict({1180 'Accept': 'application/json',1181 'user-Agent': 'requests',1182 })1183 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1184 lowerkeyset = frozenset(['accept', 'user-agent'])1185 assert keyset == lowerkeyset11861187 def test_preserve_key_case(self):1188 cid = CaseInsensitiveDict({1189 'Accept': 'application/json',1190 'user-Agent': 'requests',1191 })1192 keyset = frozenset(['Accept', 'user-Agent'])1193 assert frozenset(i[0] for i in cid.items()) == keyset1194 assert frozenset(cid.keys()) == keyset1195 assert frozenset(cid) == keyset11961197 def test_preserve_last_key_case(self):1198 cid = CaseInsensitiveDict({1199 'Accept': 'application/json',1200 'user-Agent': 'requests',1201 })1202 cid.update({'ACCEPT': 'application/json'})1203 cid['USER-AGENT'] = 'requests'1204 keyset = frozenset(['ACCEPT', 'USER-AGENT'])1205 assert frozenset(i[0] for i in cid.items()) == keyset1206 assert frozenset(cid.keys()) == keyset1207 assert frozenset(cid) == keyset120812091210class UtilsTestCase(unittest.TestCase):12111212 def test_super_len_io_streams(self):1213 """ Ensures that we properly deal with different kinds of IO streams. """1214 # uses StringIO or io.StringIO (see import above)1215 from io import BytesIO1216 from requests.utils import super_len12171218 assert super_len(StringIO.StringIO()) == 01219 assert super_len(1220 StringIO.StringIO('with so much drama in the LBC')) == 2912211222 assert super_len(BytesIO()) == 01223 assert super_len(1224 BytesIO(b"it's kinda hard bein' snoop d-o-double-g")) == 4012251226 try:1227 import cStringIO1228 except ImportError:1229 pass1230 else:1231 assert super_len(1232 cStringIO.StringIO('but some how, some way...')) == 2512331234 def test_get_environ_proxies_ip_ranges(self):1235 """Ensures that IP addresses are correctly matches with ranges1236 in no_proxy variable."""1237 from requests.utils import get_environ_proxies1238 os.environ['no_proxy'] = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"1239 assert get_environ_proxies('http://192.168.0.1:5000/') == {}1240 assert get_environ_proxies('http://192.168.0.1/') == {}1241 assert get_environ_proxies('http://172.16.1.1/') == {}1242 assert get_environ_proxies('http://172.16.1.1:5000/') == {}1243 assert get_environ_proxies('http://192.168.1.1:5000/') != {}1244 assert get_environ_proxies('http://192.168.1.1/') != {}12451246 def test_get_environ_proxies(self):1247 """Ensures that IP addresses are correctly matches with ranges1248 in no_proxy variable."""1249 from requests.utils import get_environ_proxies1250 os.environ['no_proxy'] = "127.0.0.1,localhost.localdomain,192.168.0.0/24,172.16.1.1"1251 assert get_environ_proxies(1252 'http://localhost.localdomain:5000/v1.0/') == {}1253 assert get_environ_proxies('http://www.requests.com/') != {}12541255 def test_is_ipv4_address(self):1256 from requests.utils import is_ipv4_address1257 assert is_ipv4_address('8.8.8.8')1258 assert not is_ipv4_address('8.8.8.8.8')1259 assert not is_ipv4_address('localhost.localdomain')12601261 def test_is_valid_cidr(self):1262 from requests.utils import is_valid_cidr1263 assert not is_valid_cidr('8.8.8.8')1264 assert is_valid_cidr('192.168.1.0/24')12651266 def test_dotted_netmask(self):1267 from requests.utils import dotted_netmask1268 assert dotted_netmask(8) == '255.0.0.0'1269 assert dotted_netmask(24) == '255.255.255.0'1270 assert dotted_netmask(25) == '255.255.255.128'12711272 def test_address_in_network(self):1273 from requests.utils import address_in_network1274 assert address_in_network('192.168.1.1', '192.168.1.0/24')1275 assert not address_in_network('172.16.0.1', '192.168.1.0/24')12761277 def test_get_auth_from_url(self):1278 """Ensures that username and password in well-encoded URI as per1279 RFC 3986 are correclty extracted."""1280 from requests.utils import get_auth_from_url1281 from requests.compat import quote1282 percent_encoding_test_chars = "%!*'();:@&=+$,/?#[] "1283 url_address = "request.com/url.html#test"1284 url = "http://" + quote(1285 percent_encoding_test_chars, '') + ':' + quote(1286 percent_encoding_test_chars, '') + '@' + url_address1287 (username, password) = get_auth_from_url(url)1288 assert username == percent_encoding_test_chars1289 assert password == percent_encoding_test_chars129012911292class TestMorselToCookieExpires(unittest.TestCase):12931294 """Tests for morsel_to_cookie when morsel contains expires."""12951296 def test_expires_valid_str(self):1297 """Test case where we convert expires from string time."""12981299 morsel = Morsel()1300 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1301 cookie = morsel_to_cookie(morsel)1302 assert cookie.expires == 113031304 def test_expires_invalid_int(self):1305 """Test case where an invalid type is passed for expires."""13061307 morsel = Morsel()1308 morsel['expires'] = 1001309 with pytest.raises(TypeError):1310 morsel_to_cookie(morsel)13111312 def test_expires_invalid_str(self):1313 """Test case where an invalid string is input."""13141315 morsel = Morsel()1316 morsel['expires'] = 'woops'1317 with pytest.raises(ValueError):1318 morsel_to_cookie(morsel)13191320 def test_expires_none(self):1321 """Test case where expires is None."""13221323 morsel = Morsel()1324 morsel['expires'] = None1325 cookie = morsel_to_cookie(morsel)1326 assert cookie.expires is None132713281329class TestMorselToCookieMaxAge(unittest.TestCase):13301331 """Tests for morsel_to_cookie when morsel contains max-age."""13321333 def test_max_age_valid_int(self):1334 """Test case where a valid max age in seconds is passed."""13351336 morsel = Morsel()1337 morsel['max-age'] = 601338 cookie = morsel_to_cookie(morsel)1339 assert isinstance(cookie.expires, int)13401341 def test_max_age_invalid_str(self):1342 """Test case where a invalid max age is passed."""13431344 morsel = Morsel()1345 morsel['max-age'] = 'woops'1346 with pytest.raises(TypeError):1347 morsel_to_cookie(morsel)134813491350class TestTimeout:1351 def test_stream_timeout(self):1352 try:1353 requests.get(httpbin('delay/10'), timeout=2.0)1354 except requests.exceptions.Timeout as e:1355 assert 'Read timed out' in e.args[0].args[0]13561357 def test_invalid_timeout(self):1358 with pytest.raises(ValueError) as e:1359 requests.get(httpbin('get'), timeout=(3, 4, 5))1360 assert '(connect, read)' in str(e)13611362 with pytest.raises(ValueError) as e:1363 requests.get(httpbin('get'), timeout="foo")1364 assert 'must be an int or float' in str(e)13651366 def test_none_timeout(self):1367 """ Check that you can set None as a valid timeout value.13681369 To actually test this behavior, we'd want to check that setting the1370 timeout to None actually lets the request block past the system default1371 timeout. However, this would make the test suite unbearably slow.1372 Instead we verify that setting the timeout to None does not prevent the1373 request from succeeding.1374 """1375 r = requests.get(httpbin('get'), timeout=None)1376 assert r.status_code == 20013771378 def test_read_timeout(self):1379 try:1380 requests.get(httpbin('delay/10'), timeout=(None, 0.1))1381 assert False, "The recv() request should time out."1382 except ReadTimeout:1383 pass13841385 def test_connect_timeout(self):1386 try:1387 requests.get(TARPIT, timeout=(0.1, None))1388 assert False, "The connect() request should time out."1389 except ConnectTimeout as e:1390 assert isinstance(e, ConnectionError)1391 assert isinstance(e, Timeout)13921393 def test_total_timeout_connect(self):1394 try:1395 requests.get(TARPIT, timeout=(0.1, 0.1))1396 assert False, "The connect() request should time out."1397 except ConnectTimeout:1398 pass13991400 def test_encoded_methods(self):1401 """See: https://github.com/kennethreitz/requests/issues/2316"""1402 r = requests.request(b'GET', httpbin('get'))1403 assert r.ok140414051406SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))140714081409class RedirectSession(SessionRedirectMixin):1410 def __init__(self, order_of_redirects):1411 self.redirects = order_of_redirects1412 self.calls = []1413 self.max_redirects = 301414 self.cookies = {}1415 self.trust_env = False14161417 def send(self, *args, **kwargs):1418 self.calls.append(SendCall(args, kwargs))1419 return self.build_response()14201421 def build_response(self):1422 request = self.calls[-1].args[0]1423 r = requests.Response()14241425 try:1426 r.status_code = int(self.redirects.pop(0))1427 except IndexError:1428 r.status_code = 20014291430 r.headers = CaseInsensitiveDict({'Location': '/'})1431 r.raw = self._build_raw()1432 r.request = request1433 return r14341435 def _build_raw(self):1436 string = StringIO.StringIO('')1437 setattr(string, 'release_conn', lambda *args: args)1438 return string143914401441class TestRedirects:1442 default_keyword_args = {1443 'stream': False,1444 'verify': True,1445 'cert': None,1446 'timeout': None,1447 'allow_redirects': False,1448 'proxies': {},1449 }14501451 def test_requests_are_updated_each_time(self):1452 session = RedirectSession([303, 307])1453 prep = requests.Request('POST', httpbin('post')).prepare()1454 r0 = session.send(prep)1455 assert r0.request.method == 'POST'1456 assert session.calls[-1] == SendCall((r0.request,), {})1457 redirect_generator = session.resolve_redirects(r0, prep)1458 for response in redirect_generator:1459 assert response.request.method == 'GET'1460 send_call = SendCall((response.request,),1461 TestRedirects.default_keyword_args)1462 assert session.calls[-1] == send_call1463146414651466@pytest.fixture1467def list_of_tuples():1468 return [1469 (('a', 'b'), ('c', 'd')),1470 (('c', 'd'), ('a', 'b')),1471 (('a', 'b'), ('c', 'd'), ('e', 'f')),1472 ]147314741475def test_data_argument_accepts_tuples(list_of_tuples):1476 """1477 Ensure that the data argument will accept tuples of strings1478 and properly encode them.1479 """1480 for data in list_of_tuples:1481 p = PreparedRequest()1482 p.prepare(1483 method='GET',1484 url='http://www.example.com',1485 data=data,1486 hooks=default_hooks()1487 )1488 assert p.body == urlencode(data)148914901491def assert_copy(p, p_copy):1492 for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):1493 assert getattr(p, attr) == getattr(p_copy, attr)149414951496def test_prepared_request_empty_copy():1497 p = PreparedRequest()1498 assert_copy(p, p.copy())149915001501def test_prepared_request_no_cookies_copy():1502 p = PreparedRequest()1503 p.prepare(1504 method='GET',1505 url='http://www.example.com',1506 data='foo=bar',1507 hooks=default_hooks()1508 )1509 assert_copy(p, p.copy())151015111512def test_prepared_request_complete_copy():1513 p = PreparedRequest()1514 p.prepare(1515 method='GET',1516 url='http://www.example.com',1517 data='foo=bar',1518 hooks=default_hooks(),1519 cookies={'foo': 'bar'}1520 )1521 assert_copy(p, p.copy())152215231524def test_prepare_unicode_url():1525 p = PreparedRequest()1526 p.prepare(1527 method='GET',1528 url=u('http://www.example.com/üniçø∂é'),1529 hooks=[]1530 )1531 assert_copy(p, p.copy())153215331534def test_urllib3_retries():1535 from requests.packages.urllib3.util import Retry1536 s = requests.Session()1537 s.mount('http://', HTTPAdapter(max_retries=Retry(1538 total=2, status_forcelist=[500]1539 )))15401541 with pytest.raises(RetryError):1542 s.get(httpbin('status/500'))15431544if __name__ == '__main__':1545 unittest.main()