test_requests.py
This file
Path
test_requests.py
1,553 lines · 51.6 KiB · Python
Last changed by
utils.guess_filename fails if the given parameter looks like a file object but has a non-string name attributeArthur Darcetbefore adoptione8d02ea
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_can_send_file_object_with_non_string_filename(self):932 f = io.BytesIO()933 f.name = 2934 r = requests.Request('POST', httpbin('post'), files={'f': f})935 p = r.prepare()936937 assert 'multipart/form-data' in p.headers['Content-Type']938939 def test_autoset_header_values_are_native(self):940 data = 'this is a string'941 length = '16'942 req = requests.Request('POST', httpbin('post'), data=data)943 p = req.prepare()944945 assert p.headers['Content-Length'] == length946947 def test_nonhttp_schemes_dont_check_URLs(self):948 test_urls = (949 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',950 'file:///etc/passwd',951 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',952 )953 for test_url in test_urls:954 req = requests.Request('GET', test_url)955 preq = req.prepare()956 assert test_url == preq.url957958 def test_auth_is_stripped_on_redirect_off_host(self):959 r = requests.get(960 httpbin('redirect-to'),961 params={'url': 'http://www.google.co.uk'},962 auth=('user', 'pass'),963 )964 assert r.history[0].request.headers['Authorization']965 assert not r.request.headers.get('Authorization', '')966967 def test_auth_is_retained_for_redirect_on_host(self):968 r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))969 h1 = r.history[0].request.headers['Authorization']970 h2 = r.request.headers['Authorization']971972 assert h1 == h2973974 def test_manual_redirect_with_partial_body_read(self):975 s = requests.Session()976 r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)977 assert r1.is_redirect978 rg = s.resolve_redirects(r1, r1.request, stream=True)979980 # read only the first eight bytes of the response body,981 # then follow the redirect982 r1.iter_content(8)983 r2 = next(rg)984 assert r2.is_redirect985986 # read all of the response via iter_content,987 # then follow the redirect988 for _ in r2.iter_content():989 pass990 r3 = next(rg)991 assert not r3.is_redirect992993 def _patch_adapter_gzipped_redirect(self, session, url):994 adapter = session.get_adapter(url=url)995 org_build_response = adapter.build_response996 self._patched_response = False997998 def build_response(*args, **kwargs):999 resp = org_build_response(*args, **kwargs)1000 if not self._patched_response:1001 resp.raw.headers['content-encoding'] = 'gzip'1002 self._patched_response = True1003 return resp10041005 adapter.build_response = build_response10061007 def test_redirect_with_wrong_gzipped_header(self):1008 s = requests.Session()1009 url = httpbin('redirect/1')1010 self._patch_adapter_gzipped_redirect(s, url)1011 s.get(url)10121013 def test_basic_auth_str_is_always_native(self):1014 s = _basic_auth_str("test", "test")1015 assert isinstance(s, builtin_str)1016 assert s == "Basic dGVzdDp0ZXN0"10171018 def test_requests_history_is_saved(self):1019 r = requests.get(httpbin('redirect/5'))1020 total = r.history[-1].history1021 i = 01022 for item in r.history:1023 assert item.history == total[0:i]1024 i = i + 110251026 def test_json_param_post_content_type_works(self):1027 r = requests.post(1028 httpbin('post'),1029 json={'life': 42}1030 )1031 assert r.status_code == 2001032 assert 'application/json' in r.request.headers['Content-Type']1033 assert {'life': 42} == r.json()['json']103410351036class TestContentEncodingDetection(unittest.TestCase):10371038 def test_none(self):1039 encodings = requests.utils.get_encodings_from_content('')1040 assert not len(encodings)10411042 def test_html_charset(self):1043 """HTML5 meta charset attribute"""1044 content = '<meta charset="UTF-8">'1045 encodings = requests.utils.get_encodings_from_content(content)1046 assert len(encodings) == 11047 assert encodings[0] == 'UTF-8'10481049 def test_html4_pragma(self):1050 """HTML4 pragma directive"""1051 content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">'1052 encodings = requests.utils.get_encodings_from_content(content)1053 assert len(encodings) == 11054 assert encodings[0] == 'UTF-8'10551056 def test_xhtml_pragma(self):1057 """XHTML 1.x served with text/html MIME type"""1058 content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />'1059 encodings = requests.utils.get_encodings_from_content(content)1060 assert len(encodings) == 11061 assert encodings[0] == 'UTF-8'10621063 def test_xml(self):1064 """XHTML 1.x served as XML"""1065 content = '<?xml version="1.0" encoding="UTF-8"?>'1066 encodings = requests.utils.get_encodings_from_content(content)1067 assert len(encodings) == 11068 assert encodings[0] == 'UTF-8'10691070 def test_precedence(self):1071 content = '''1072 <?xml version="1.0" encoding="XML"?>1073 <meta charset="HTML5">1074 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />1075 '''.strip()1076 encodings = requests.utils.get_encodings_from_content(content)1077 assert encodings == ['HTML5', 'HTML4', 'XML']107810791080class TestCaseInsensitiveDict(unittest.TestCase):10811082 def test_mapping_init(self):1083 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1084 assert len(cid) == 21085 assert 'foo' in cid1086 assert 'bar' in cid10871088 def test_iterable_init(self):1089 cid = CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')])1090 assert len(cid) == 21091 assert 'foo' in cid1092 assert 'bar' in cid10931094 def test_kwargs_init(self):1095 cid = CaseInsensitiveDict(FOO='foo', BAr='bar')1096 assert len(cid) == 21097 assert 'foo' in cid1098 assert 'bar' in cid10991100 def test_docstring_example(self):1101 cid = CaseInsensitiveDict()1102 cid['Accept'] = 'application/json'1103 assert cid['aCCEPT'] == 'application/json'1104 assert list(cid) == ['Accept']11051106 def test_len(self):1107 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1108 cid['A'] = 'a'1109 assert len(cid) == 211101111 def test_getitem(self):1112 cid = CaseInsensitiveDict({'Spam': 'blueval'})1113 assert cid['spam'] == 'blueval'1114 assert cid['SPAM'] == 'blueval'11151116 def test_fixes_649(self):1117 """__setitem__ should behave case-insensitively."""1118 cid = CaseInsensitiveDict()1119 cid['spam'] = 'oneval'1120 cid['Spam'] = 'twoval'1121 cid['sPAM'] = 'redval'1122 cid['SPAM'] = 'blueval'1123 assert cid['spam'] == 'blueval'1124 assert cid['SPAM'] == 'blueval'1125 assert list(cid.keys()) == ['SPAM']11261127 def test_delitem(self):1128 cid = CaseInsensitiveDict()1129 cid['Spam'] = 'someval'1130 del cid['sPam']1131 assert 'spam' not in cid1132 assert len(cid) == 011331134 def test_contains(self):1135 cid = CaseInsensitiveDict()1136 cid['Spam'] = 'someval'1137 assert 'Spam' in cid1138 assert 'spam' in cid1139 assert 'SPAM' in cid1140 assert 'sPam' in cid1141 assert 'notspam' not in cid11421143 def test_get(self):1144 cid = CaseInsensitiveDict()1145 cid['spam'] = 'oneval'1146 cid['SPAM'] = 'blueval'1147 assert cid.get('spam') == 'blueval'1148 assert cid.get('SPAM') == 'blueval'1149 assert cid.get('sPam') == 'blueval'1150 assert cid.get('notspam', 'default') == 'default'11511152 def test_update(self):1153 cid = CaseInsensitiveDict()1154 cid['spam'] = 'blueval'1155 cid.update({'sPam': 'notblueval'})1156 assert cid['spam'] == 'notblueval'1157 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1158 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1159 assert len(cid) == 21160 assert cid['foo'] == 'anotherfoo'1161 assert cid['bar'] == 'anotherbar'11621163 def test_update_retains_unchanged(self):1164 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1165 cid.update({'foo': 'newfoo'})1166 assert cid['bar'] == 'bar'11671168 def test_iter(self):1169 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1170 keys = frozenset(['Spam', 'Eggs'])1171 assert frozenset(iter(cid)) == keys11721173 def test_equality(self):1174 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1175 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1176 assert cid == othercid1177 del othercid['spam']1178 assert cid != othercid1179 assert cid == {'spam': 'blueval', 'eggs': 'redval'}11801181 def test_setdefault(self):1182 cid = CaseInsensitiveDict({'Spam': 'blueval'})1183 assert cid.setdefault('spam', 'notblueval') == 'blueval'1184 assert cid.setdefault('notspam', 'notblueval') == 'notblueval'11851186 def test_lower_items(self):1187 cid = CaseInsensitiveDict({1188 'Accept': 'application/json',1189 'user-Agent': 'requests',1190 })1191 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1192 lowerkeyset = frozenset(['accept', 'user-agent'])1193 assert keyset == lowerkeyset11941195 def test_preserve_key_case(self):1196 cid = CaseInsensitiveDict({1197 'Accept': 'application/json',1198 'user-Agent': 'requests',1199 })1200 keyset = frozenset(['Accept', 'user-Agent'])1201 assert frozenset(i[0] for i in cid.items()) == keyset1202 assert frozenset(cid.keys()) == keyset1203 assert frozenset(cid) == keyset12041205 def test_preserve_last_key_case(self):1206 cid = CaseInsensitiveDict({1207 'Accept': 'application/json',1208 'user-Agent': 'requests',1209 })1210 cid.update({'ACCEPT': 'application/json'})1211 cid['USER-AGENT'] = 'requests'1212 keyset = frozenset(['ACCEPT', 'USER-AGENT'])1213 assert frozenset(i[0] for i in cid.items()) == keyset1214 assert frozenset(cid.keys()) == keyset1215 assert frozenset(cid) == keyset121612171218class UtilsTestCase(unittest.TestCase):12191220 def test_super_len_io_streams(self):1221 """ Ensures that we properly deal with different kinds of IO streams. """1222 # uses StringIO or io.StringIO (see import above)1223 from io import BytesIO1224 from requests.utils import super_len12251226 assert super_len(StringIO.StringIO()) == 01227 assert super_len(1228 StringIO.StringIO('with so much drama in the LBC')) == 2912291230 assert super_len(BytesIO()) == 01231 assert super_len(1232 BytesIO(b"it's kinda hard bein' snoop d-o-double-g")) == 4012331234 try:1235 import cStringIO1236 except ImportError:1237 pass1238 else:1239 assert super_len(1240 cStringIO.StringIO('but some how, some way...')) == 2512411242 def test_get_environ_proxies_ip_ranges(self):1243 """Ensures that IP addresses are correctly matches with ranges1244 in no_proxy variable."""1245 from requests.utils import get_environ_proxies1246 os.environ['no_proxy'] = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"1247 assert get_environ_proxies('http://192.168.0.1:5000/') == {}1248 assert get_environ_proxies('http://192.168.0.1/') == {}1249 assert get_environ_proxies('http://172.16.1.1/') == {}1250 assert get_environ_proxies('http://172.16.1.1:5000/') == {}1251 assert get_environ_proxies('http://192.168.1.1:5000/') != {}1252 assert get_environ_proxies('http://192.168.1.1/') != {}12531254 def test_get_environ_proxies(self):1255 """Ensures that IP addresses are correctly matches with ranges1256 in no_proxy variable."""1257 from requests.utils import get_environ_proxies1258 os.environ['no_proxy'] = "127.0.0.1,localhost.localdomain,192.168.0.0/24,172.16.1.1"1259 assert get_environ_proxies(1260 'http://localhost.localdomain:5000/v1.0/') == {}1261 assert get_environ_proxies('http://www.requests.com/') != {}12621263 def test_is_ipv4_address(self):1264 from requests.utils import is_ipv4_address1265 assert is_ipv4_address('8.8.8.8')1266 assert not is_ipv4_address('8.8.8.8.8')1267 assert not is_ipv4_address('localhost.localdomain')12681269 def test_is_valid_cidr(self):1270 from requests.utils import is_valid_cidr1271 assert not is_valid_cidr('8.8.8.8')1272 assert is_valid_cidr('192.168.1.0/24')12731274 def test_dotted_netmask(self):1275 from requests.utils import dotted_netmask1276 assert dotted_netmask(8) == '255.0.0.0'1277 assert dotted_netmask(24) == '255.255.255.0'1278 assert dotted_netmask(25) == '255.255.255.128'12791280 def test_address_in_network(self):1281 from requests.utils import address_in_network1282 assert address_in_network('192.168.1.1', '192.168.1.0/24')1283 assert not address_in_network('172.16.0.1', '192.168.1.0/24')12841285 def test_get_auth_from_url(self):1286 """Ensures that username and password in well-encoded URI as per1287 RFC 3986 are correclty extracted."""1288 from requests.utils import get_auth_from_url1289 from requests.compat import quote1290 percent_encoding_test_chars = "%!*'();:@&=+$,/?#[] "1291 url_address = "request.com/url.html#test"1292 url = "http://" + quote(1293 percent_encoding_test_chars, '') + ':' + quote(1294 percent_encoding_test_chars, '') + '@' + url_address1295 (username, password) = get_auth_from_url(url)1296 assert username == percent_encoding_test_chars1297 assert password == percent_encoding_test_chars129812991300class TestMorselToCookieExpires(unittest.TestCase):13011302 """Tests for morsel_to_cookie when morsel contains expires."""13031304 def test_expires_valid_str(self):1305 """Test case where we convert expires from string time."""13061307 morsel = Morsel()1308 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1309 cookie = morsel_to_cookie(morsel)1310 assert cookie.expires == 113111312 def test_expires_invalid_int(self):1313 """Test case where an invalid type is passed for expires."""13141315 morsel = Morsel()1316 morsel['expires'] = 1001317 with pytest.raises(TypeError):1318 morsel_to_cookie(morsel)13191320 def test_expires_invalid_str(self):1321 """Test case where an invalid string is input."""13221323 morsel = Morsel()1324 morsel['expires'] = 'woops'1325 with pytest.raises(ValueError):1326 morsel_to_cookie(morsel)13271328 def test_expires_none(self):1329 """Test case where expires is None."""13301331 morsel = Morsel()1332 morsel['expires'] = None1333 cookie = morsel_to_cookie(morsel)1334 assert cookie.expires is None133513361337class TestMorselToCookieMaxAge(unittest.TestCase):13381339 """Tests for morsel_to_cookie when morsel contains max-age."""13401341 def test_max_age_valid_int(self):1342 """Test case where a valid max age in seconds is passed."""13431344 morsel = Morsel()1345 morsel['max-age'] = 601346 cookie = morsel_to_cookie(morsel)1347 assert isinstance(cookie.expires, int)13481349 def test_max_age_invalid_str(self):1350 """Test case where a invalid max age is passed."""13511352 morsel = Morsel()1353 morsel['max-age'] = 'woops'1354 with pytest.raises(TypeError):1355 morsel_to_cookie(morsel)135613571358class TestTimeout:1359 def test_stream_timeout(self):1360 try:1361 requests.get(httpbin('delay/10'), timeout=2.0)1362 except requests.exceptions.Timeout as e:1363 assert 'Read timed out' in e.args[0].args[0]13641365 def test_invalid_timeout(self):1366 with pytest.raises(ValueError) as e:1367 requests.get(httpbin('get'), timeout=(3, 4, 5))1368 assert '(connect, read)' in str(e)13691370 with pytest.raises(ValueError) as e:1371 requests.get(httpbin('get'), timeout="foo")1372 assert 'must be an int or float' in str(e)13731374 def test_none_timeout(self):1375 """ Check that you can set None as a valid timeout value.13761377 To actually test this behavior, we'd want to check that setting the1378 timeout to None actually lets the request block past the system default1379 timeout. However, this would make the test suite unbearably slow.1380 Instead we verify that setting the timeout to None does not prevent the1381 request from succeeding.1382 """1383 r = requests.get(httpbin('get'), timeout=None)1384 assert r.status_code == 20013851386 def test_read_timeout(self):1387 try:1388 requests.get(httpbin('delay/10'), timeout=(None, 0.1))1389 assert False, "The recv() request should time out."1390 except ReadTimeout:1391 pass13921393 def test_connect_timeout(self):1394 try:1395 requests.get(TARPIT, timeout=(0.1, None))1396 assert False, "The connect() request should time out."1397 except ConnectTimeout as e:1398 assert isinstance(e, ConnectionError)1399 assert isinstance(e, Timeout)14001401 def test_total_timeout_connect(self):1402 try:1403 requests.get(TARPIT, timeout=(0.1, 0.1))1404 assert False, "The connect() request should time out."1405 except ConnectTimeout:1406 pass14071408 def test_encoded_methods(self):1409 """See: https://github.com/kennethreitz/requests/issues/2316"""1410 r = requests.request(b'GET', httpbin('get'))1411 assert r.ok141214131414SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))141514161417class RedirectSession(SessionRedirectMixin):1418 def __init__(self, order_of_redirects):1419 self.redirects = order_of_redirects1420 self.calls = []1421 self.max_redirects = 301422 self.cookies = {}1423 self.trust_env = False14241425 def send(self, *args, **kwargs):1426 self.calls.append(SendCall(args, kwargs))1427 return self.build_response()14281429 def build_response(self):1430 request = self.calls[-1].args[0]1431 r = requests.Response()14321433 try:1434 r.status_code = int(self.redirects.pop(0))1435 except IndexError:1436 r.status_code = 20014371438 r.headers = CaseInsensitiveDict({'Location': '/'})1439 r.raw = self._build_raw()1440 r.request = request1441 return r14421443 def _build_raw(self):1444 string = StringIO.StringIO('')1445 setattr(string, 'release_conn', lambda *args: args)1446 return string144714481449class TestRedirects:1450 default_keyword_args = {1451 'stream': False,1452 'verify': True,1453 'cert': None,1454 'timeout': None,1455 'allow_redirects': False,1456 'proxies': {},1457 }14581459 def test_requests_are_updated_each_time(self):1460 session = RedirectSession([303, 307])1461 prep = requests.Request('POST', httpbin('post')).prepare()1462 r0 = session.send(prep)1463 assert r0.request.method == 'POST'1464 assert session.calls[-1] == SendCall((r0.request,), {})1465 redirect_generator = session.resolve_redirects(r0, prep)1466 for response in redirect_generator:1467 assert response.request.method == 'GET'1468 send_call = SendCall((response.request,),1469 TestRedirects.default_keyword_args)1470 assert session.calls[-1] == send_call1471147214731474@pytest.fixture1475def list_of_tuples():1476 return [1477 (('a', 'b'), ('c', 'd')),1478 (('c', 'd'), ('a', 'b')),1479 (('a', 'b'), ('c', 'd'), ('e', 'f')),1480 ]148114821483def test_data_argument_accepts_tuples(list_of_tuples):1484 """1485 Ensure that the data argument will accept tuples of strings1486 and properly encode them.1487 """1488 for data in list_of_tuples:1489 p = PreparedRequest()1490 p.prepare(1491 method='GET',1492 url='http://www.example.com',1493 data=data,1494 hooks=default_hooks()1495 )1496 assert p.body == urlencode(data)149714981499def assert_copy(p, p_copy):1500 for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):1501 assert getattr(p, attr) == getattr(p_copy, attr)150215031504def test_prepared_request_empty_copy():1505 p = PreparedRequest()1506 assert_copy(p, p.copy())150715081509def test_prepared_request_no_cookies_copy():1510 p = PreparedRequest()1511 p.prepare(1512 method='GET',1513 url='http://www.example.com',1514 data='foo=bar',1515 hooks=default_hooks()1516 )1517 assert_copy(p, p.copy())151815191520def test_prepared_request_complete_copy():1521 p = PreparedRequest()1522 p.prepare(1523 method='GET',1524 url='http://www.example.com',1525 data='foo=bar',1526 hooks=default_hooks(),1527 cookies={'foo': 'bar'}1528 )1529 assert_copy(p, p.copy())153015311532def test_prepare_unicode_url():1533 p = PreparedRequest()1534 p.prepare(1535 method='GET',1536 url=u('http://www.example.com/üniçø∂é'),1537 hooks=[]1538 )1539 assert_copy(p, p.copy())154015411542def test_urllib3_retries():1543 from requests.packages.urllib3.util import Retry1544 s = requests.Session()1545 s.mount('http://', HTTPAdapter(max_retries=Retry(1546 total=2, status_forcelist=[500]1547 )))15481549 with pytest.raises(RetryError):1550 s.get(httpbin('status/500'))15511552if __name__ == '__main__':1553 unittest.main()