test_requests.py
This file
Path
test_requests.py
1,696 lines · 56.6 KiB · Python
Last changed by
Merge branch 'auth-digest-multi-thread' of https://github.com/exvito/requests into proposed/2.8.0Ian Cordascobefore adoption77d7e53
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 collections12import contextlib1314import io15import requests16import pytest17from requests.adapters import HTTPAdapter18from requests.auth import HTTPDigestAuth, _basic_auth_str19from requests.compat import (20 Morsel, cookielib, getproxies, str, urljoin, urlparse, is_py3, builtin_str)21from requests.cookies import cookiejar_from_dict, morsel_to_cookie22from requests.exceptions import (ConnectionError, ConnectTimeout,23 InvalidSchema, InvalidURL, MissingSchema,24 ReadTimeout, Timeout, RetryError)25from requests.models import PreparedRequest26from requests.structures import CaseInsensitiveDict27from requests.sessions import SessionRedirectMixin28from requests.models import urlencode29from requests.hooks import default_hooks3031try:32 import StringIO33except ImportError:34 import io as StringIO3536try:37 from multiprocessing.pool import ThreadPool38except ImportError:39 ThreadPool = None4041if is_py3:42 def u(s):43 return s44else:45 def u(s):46 return s.decode('unicode-escape')474849# Requests to this URL should always fail with a connection timeout (nothing50# listening on that port)51TARPIT = "http://10.255.255.1"52HTTPBIN = os.environ.get('HTTPBIN_URL', 'http://httpbin.org/')53# Issue #1483: Make sure the URL always has a trailing slash54HTTPBIN = HTTPBIN.rstrip('/') + '/'555657def httpbin(*suffix):58 """Returns url for HTTPBIN resource."""59 return urljoin(HTTPBIN, '/'.join(suffix))606162class RequestsTestCase(unittest.TestCase):6364 _multiprocess_can_split_ = True6566 def setUp(self):67 """Create simple data set with headers."""68 pass6970 def tearDown(self):71 """Teardown."""72 pass7374 def test_entry_points(self):7576 requests.session77 requests.session().get78 requests.session().head79 requests.get80 requests.head81 requests.put82 requests.patch83 requests.post8485 def test_invalid_url(self):86 with pytest.raises(MissingSchema):87 requests.get('hiwpefhipowhefopw')88 with pytest.raises(InvalidSchema):89 requests.get('localhost:3128')90 with pytest.raises(InvalidSchema):91 requests.get('localhost.localdomain:3128/')92 with pytest.raises(InvalidSchema):93 requests.get('10.122.1.1:3128/')94 with pytest.raises(InvalidURL):95 requests.get('http://')9697 def test_basic_building(self):98 req = requests.Request()99 req.url = 'http://kennethreitz.org/'100 req.data = {'life': '42'}101102 pr = req.prepare()103 assert pr.url == req.url104 assert pr.body == 'life=42'105106 def test_no_content_length(self):107 get_req = requests.Request('GET', httpbin('get')).prepare()108 assert 'Content-Length' not in get_req.headers109 head_req = requests.Request('HEAD', httpbin('head')).prepare()110 assert 'Content-Length' not in head_req.headers111112 def test_override_content_length(self):113 headers = {114 'Content-Length': 'not zero'115 }116 r = requests.Request('POST', httpbin('post'), headers=headers).prepare()117 assert 'Content-Length' in r.headers118 assert r.headers['Content-Length'] == 'not zero'119120 def test_path_is_not_double_encoded(self):121 request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()122123 assert request.path_url == '/get/test%20case'124125 def test_params_are_added_before_fragment(self):126 request = requests.Request('GET',127 "http://example.com/path#fragment", params={"a": "b"}).prepare()128 assert request.url == "http://example.com/path?a=b#fragment"129 request = requests.Request('GET',130 "http://example.com/path?key=value#fragment", params={"a": "b"}).prepare()131 assert request.url == "http://example.com/path?key=value&a=b#fragment"132133 def test_mixed_case_scheme_acceptable(self):134 s = requests.Session()135 s.proxies = getproxies()136 parts = urlparse(httpbin('get'))137 schemes = ['http://', 'HTTP://', 'hTTp://', 'HttP://',138 'https://', 'HTTPS://', 'hTTps://', 'HttPs://']139 for scheme in schemes:140 url = scheme + parts.netloc + parts.path141 r = requests.Request('GET', url)142 r = s.send(r.prepare())143 assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)144145 def test_HTTP_200_OK_GET_ALTERNATIVE(self):146 r = requests.Request('GET', httpbin('get'))147 s = requests.Session()148 s.proxies = getproxies()149150 r = s.send(r.prepare())151152 assert r.status_code == 200153154 def test_HTTP_302_ALLOW_REDIRECT_GET(self):155 r = requests.get(httpbin('redirect', '1'))156 assert r.status_code == 200157 assert r.history[0].status_code == 302158 assert r.history[0].is_redirect159160 # def test_HTTP_302_ALLOW_REDIRECT_POST(self):161 # r = requests.post(httpbin('status', '302'), data={'some': 'data'})162 # self.assertEqual(r.status_code, 200)163164 def test_HTTP_200_OK_GET_WITH_PARAMS(self):165 heads = {'User-agent': 'Mozilla/5.0'}166167 r = requests.get(httpbin('user-agent'), headers=heads)168169 assert heads['User-agent'] in r.text170 assert r.status_code == 200171172 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):173 heads = {'User-agent': 'Mozilla/5.0'}174175 r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)176 assert r.status_code == 200177178 def test_set_cookie_on_301(self):179 s = requests.session()180 url = httpbin('cookies/set?foo=bar')181 s.get(url)182 assert s.cookies['foo'] == 'bar'183184 def test_cookie_sent_on_redirect(self):185 s = requests.session()186 s.get(httpbin('cookies/set?foo=bar'))187 r = s.get(httpbin('redirect/1')) # redirects to httpbin('get')188 assert 'Cookie' in r.json()['headers']189190 def test_cookie_removed_on_expire(self):191 s = requests.session()192 s.get(httpbin('cookies/set?foo=bar'))193 assert s.cookies['foo'] == 'bar'194 s.get(195 httpbin('response-headers'),196 params={197 'Set-Cookie':198 'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'199 }200 )201 assert 'foo' not in s.cookies202203 def test_cookie_quote_wrapped(self):204 s = requests.session()205 s.get(httpbin('cookies/set?foo="bar:baz"'))206 assert s.cookies['foo'] == '"bar:baz"'207208 def test_cookie_persists_via_api(self):209 s = requests.session()210 r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})211 assert 'foo' in r.request.headers['Cookie']212 assert 'foo' in r.history[0].request.headers['Cookie']213214 def test_request_cookie_overrides_session_cookie(self):215 s = requests.session()216 s.cookies['foo'] = 'bar'217 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})218 assert r.json()['cookies']['foo'] == 'baz'219 # Session cookie should not be modified220 assert s.cookies['foo'] == 'bar'221222 def test_request_cookies_not_persisted(self):223 s = requests.session()224 s.get(httpbin('cookies'), cookies={'foo': 'baz'})225 # Sending a request with cookies should not add cookies to the session226 assert not s.cookies227228 def test_generic_cookiejar_works(self):229 cj = cookielib.CookieJar()230 cookiejar_from_dict({'foo': 'bar'}, cj)231 s = requests.session()232 s.cookies = cj233 r = s.get(httpbin('cookies'))234 # Make sure the cookie was sent235 assert r.json()['cookies']['foo'] == 'bar'236 # Make sure the session cj is still the custom one237 assert s.cookies is cj238239 def test_param_cookiejar_works(self):240 cj = cookielib.CookieJar()241 cookiejar_from_dict({'foo': 'bar'}, cj)242 s = requests.session()243 r = s.get(httpbin('cookies'), cookies=cj)244 # Make sure the cookie was sent245 assert r.json()['cookies']['foo'] == 'bar'246247 def test_requests_in_history_are_not_overridden(self):248 resp = requests.get(httpbin('redirect/3'))249 urls = [r.url for r in resp.history]250 req_urls = [r.request.url for r in resp.history]251 assert urls == req_urls252253 def test_history_is_always_a_list(self):254 """255 Show that even with redirects, Response.history is always a list.256 """257 resp = requests.get(httpbin('get'))258 assert isinstance(resp.history, list)259 resp = requests.get(httpbin('redirect/1'))260 assert isinstance(resp.history, list)261 assert not isinstance(resp.history, tuple)262263 def test_headers_on_session_with_None_are_not_sent(self):264 """Do not send headers in Session.headers with None values."""265 ses = requests.Session()266 ses.headers['Accept-Encoding'] = None267 req = requests.Request('GET', httpbin('get'))268 prep = ses.prepare_request(req)269 assert 'Accept-Encoding' not in prep.headers270271 def test_user_agent_transfers(self):272273 heads = {274 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'275 }276277 r = requests.get(httpbin('user-agent'), headers=heads)278 assert heads['User-agent'] in r.text279280 heads = {281 'user-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'282 }283284 r = requests.get(httpbin('user-agent'), headers=heads)285 assert heads['user-agent'] in r.text286287 def test_HTTP_200_OK_HEAD(self):288 r = requests.head(httpbin('get'))289 assert r.status_code == 200290291 def test_HTTP_200_OK_PUT(self):292 r = requests.put(httpbin('put'))293 assert r.status_code == 200294295 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):296 auth = ('user', 'pass')297 url = httpbin('basic-auth', 'user', 'pass')298299 r = requests.get(url, auth=auth)300 assert r.status_code == 200301302 r = requests.get(url)303 assert r.status_code == 401304305 s = requests.session()306 s.auth = auth307 r = s.get(url)308 assert r.status_code == 200309310 def test_connection_error_invalid_domain(self):311 """Connecting to an unknown domain should raise a ConnectionError"""312 with pytest.raises(ConnectionError):313 requests.get("http://doesnotexist.google.com")314315 def test_connection_error_invalid_port(self):316 """Connecting to an invalid port should raise a ConnectionError"""317 with pytest.raises(ConnectionError):318 requests.get("http://httpbin.org:1", timeout=1)319320 def test_LocationParseError(self):321 """Inputing a URL that cannot be parsed should raise an InvalidURL error"""322 with pytest.raises(InvalidURL):323 requests.get("http://fe80::5054:ff:fe5a:fc0")324325 def test_basicauth_with_netrc(self):326 auth = ('user', 'pass')327 wrong_auth = ('wronguser', 'wrongpass')328 url = httpbin('basic-auth', 'user', 'pass')329330 def get_netrc_auth_mock(url):331 return auth332 requests.sessions.get_netrc_auth = get_netrc_auth_mock333334 # Should use netrc and work.335 r = requests.get(url)336 assert r.status_code == 200337338 # Given auth should override and fail.339 r = requests.get(url, auth=wrong_auth)340 assert r.status_code == 401341342 s = requests.session()343344 # Should use netrc and work.345 r = s.get(url)346 assert r.status_code == 200347348 # Given auth should override and fail.349 s.auth = wrong_auth350 r = s.get(url)351 assert r.status_code == 401352353 def test_DIGEST_HTTP_200_OK_GET(self):354355 auth = HTTPDigestAuth('user', 'pass')356 url = httpbin('digest-auth', 'auth', 'user', 'pass')357358 r = requests.get(url, auth=auth)359 assert r.status_code == 200360361 r = requests.get(url)362 assert r.status_code == 401363364 s = requests.session()365 s.auth = HTTPDigestAuth('user', 'pass')366 r = s.get(url)367 assert r.status_code == 200368369 def test_DIGEST_AUTH_RETURNS_COOKIE(self):370 url = httpbin('digest-auth', 'auth', 'user', 'pass')371 auth = HTTPDigestAuth('user', 'pass')372 r = requests.get(url)373 assert r.cookies['fake'] == 'fake_value'374375 r = requests.get(url, auth=auth)376 assert r.status_code == 200377378 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self):379 url = httpbin('digest-auth', 'auth', 'user', 'pass')380 auth = HTTPDigestAuth('user', 'pass')381 s = requests.Session()382 s.get(url, auth=auth)383 assert s.cookies['fake'] == 'fake_value'384385 def test_DIGEST_STREAM(self):386387 auth = HTTPDigestAuth('user', 'pass')388 url = httpbin('digest-auth', 'auth', 'user', 'pass')389390 r = requests.get(url, auth=auth, stream=True)391 assert r.raw.read() != b''392393 r = requests.get(url, auth=auth, stream=False)394 assert r.raw.read() == b''395396 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self):397398 auth = HTTPDigestAuth('user', 'wrongpass')399 url = httpbin('digest-auth', 'auth', 'user', 'pass')400401 r = requests.get(url, auth=auth)402 assert r.status_code == 401403404 r = requests.get(url)405 assert r.status_code == 401406407 s = requests.session()408 s.auth = auth409 r = s.get(url)410 assert r.status_code == 401411412 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self):413414 auth = HTTPDigestAuth('user', 'pass')415 url = httpbin('digest-auth', 'auth', 'user', 'pass')416417 r = requests.get(url, auth=auth)418 assert '"auth"' in r.request.headers['Authorization']419420 def test_DIGESTAUTH_THREADED(self):421422 auth = HTTPDigestAuth('user', 'pass')423 url = httpbin('digest-auth', 'auth', 'user', 'pass')424 session = requests.Session()425 session.auth=auth426427 def do_request(i):428 r = session.get(url)429 assert '"auth"' in r.request.headers['Authorization']430 return 1431 if ThreadPool is not None:432 pool = ThreadPool(processes=50)433 pool.map(do_request, range(100))434435 def test_POSTBIN_GET_POST_FILES(self):436437 url = httpbin('post')438 post1 = requests.post(url).raise_for_status()439440 post1 = requests.post(url, data={'some': 'data'})441 assert post1.status_code == 200442443 with open('requirements.txt') as f:444 post2 = requests.post(url, files={'some': f})445 assert post2.status_code == 200446447 post4 = requests.post(url, data='[{"some": "json"}]')448 assert post4.status_code == 200449450 with pytest.raises(ValueError):451 requests.post(url, files=['bad file data'])452453 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self):454455 url = httpbin('post')456 post1 = requests.post(url).raise_for_status()457458 post1 = requests.post(url, data={'some': 'data'})459 assert post1.status_code == 200460461 with open('requirements.txt') as f:462 post2 = requests.post(url,463 data={'some': 'data'}, files={'some': f})464 assert post2.status_code == 200465466 post4 = requests.post(url, data='[{"some": "json"}]')467 assert post4.status_code == 200468469 with pytest.raises(ValueError):470 requests.post(url, files=['bad file data'])471472 def test_conflicting_post_params(self):473 url = httpbin('post')474 with open('requirements.txt') as f:475 pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")476 pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")477478 def test_request_ok_set(self):479 r = requests.get(httpbin('status', '404'))480 assert not r.ok481482 def test_status_raising(self):483 r = requests.get(httpbin('status', '404'))484 with pytest.raises(requests.exceptions.HTTPError):485 r.raise_for_status()486487 r = requests.get(httpbin('status', '500'))488 assert not r.ok489490 def test_decompress_gzip(self):491 r = requests.get(httpbin('gzip'))492 r.content.decode('ascii')493494 def test_unicode_get(self):495 url = httpbin('/get')496 requests.get(url, params={'foo': 'føø'})497 requests.get(url, params={'føø': 'føø'})498 requests.get(url, params={'føø': 'føø'})499 requests.get(url, params={'foo': 'foo'})500 requests.get(httpbin('ø'), params={'foo': 'foo'})501502 def test_unicode_header_name(self):503 requests.put(504 httpbin('put'),505 headers={str('Content-Type'): 'application/octet-stream'},506 data='\xff') # compat.str is unicode.507508 def test_pyopenssl_redirect(self):509 requests.get('https://httpbin.org/status/301')510511 def test_urlencoded_get_query_multivalued_param(self):512513 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))514 assert r.status_code == 200515 assert r.url == httpbin('get?test=foo&test=baz')516517 def test_different_encodings_dont_break_post(self):518 r = requests.post(httpbin('post'),519 data={'stuff': json.dumps({'a': 123})},520 params={'blah': 'asdf1234'},521 files={'file': ('test_requests.py', open(__file__, 'rb'))})522 assert r.status_code == 200523524 def test_unicode_multipart_post(self):525 r = requests.post(httpbin('post'),526 data={'stuff': u('ëlïxr')},527 files={'file': ('test_requests.py', open(__file__, 'rb'))})528 assert r.status_code == 200529530 r = requests.post(httpbin('post'),531 data={'stuff': u('ëlïxr').encode('utf-8')},532 files={'file': ('test_requests.py', open(__file__, 'rb'))})533 assert r.status_code == 200534535 r = requests.post(httpbin('post'),536 data={'stuff': 'elixr'},537 files={'file': ('test_requests.py', open(__file__, 'rb'))})538 assert r.status_code == 200539540 r = requests.post(httpbin('post'),541 data={'stuff': 'elixr'.encode('utf-8')},542 files={'file': ('test_requests.py', open(__file__, 'rb'))})543 assert r.status_code == 200544545 def test_unicode_multipart_post_fieldnames(self):546 filename = os.path.splitext(__file__)[0] + '.py'547 r = requests.Request(method='POST',548 url=httpbin('post'),549 data={'stuff'.encode('utf-8'): 'elixr'},550 files={'file': ('test_requests.py',551 open(filename, 'rb'))})552 prep = r.prepare()553 assert b'name="stuff"' in prep.body554 assert b'name="b\'stuff\'"' not in prep.body555556 def test_unicode_method_name(self):557 files = {'file': open('test_requests.py', 'rb')}558 r = requests.request(559 method=u('POST'), url=httpbin('post'), files=files)560 assert r.status_code == 200561562 def test_custom_content_type(self):563 r = requests.post(564 httpbin('post'),565 data={'stuff': json.dumps({'a': 123})},566 files={'file1': ('test_requests.py', open(__file__, 'rb')),567 'file2': ('test_requests', open(__file__, 'rb'),568 'text/py-content-type')})569 assert r.status_code == 200570 assert b"text/py-content-type" in r.request.body571572 def test_hook_receives_request_arguments(self):573 def hook(resp, **kwargs):574 assert resp is not None575 assert kwargs != {}576577 requests.Request('GET', HTTPBIN, hooks={'response': hook})578579 def test_session_hooks_are_used_with_no_request_hooks(self):580 hook = lambda x, *args, **kwargs: x581 s = requests.Session()582 s.hooks['response'].append(hook)583 r = requests.Request('GET', HTTPBIN)584 prep = s.prepare_request(r)585 assert prep.hooks['response'] != []586 assert prep.hooks['response'] == [hook]587588 def test_session_hooks_are_overriden_by_request_hooks(self):589 hook1 = lambda x, *args, **kwargs: x590 hook2 = lambda x, *args, **kwargs: x591 assert hook1 is not hook2592 s = requests.Session()593 s.hooks['response'].append(hook2)594 r = requests.Request('GET', HTTPBIN, hooks={'response': [hook1]})595 prep = s.prepare_request(r)596 assert prep.hooks['response'] == [hook1]597598 def test_prepared_request_hook(self):599 def hook(resp, **kwargs):600 resp.hook_working = True601 return resp602603 req = requests.Request('GET', HTTPBIN, hooks={'response': hook})604 prep = req.prepare()605606 s = requests.Session()607 s.proxies = getproxies()608 resp = s.send(prep)609610 assert hasattr(resp, 'hook_working')611612 def test_prepared_from_session(self):613 class DummyAuth(requests.auth.AuthBase):614 def __call__(self, r):615 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'616 return r617618 req = requests.Request('GET', httpbin('headers'))619 assert not req.auth620621 s = requests.Session()622 s.auth = DummyAuth()623624 prep = s.prepare_request(req)625 resp = s.send(prep)626627 assert resp.json()['headers'][628 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'629630 def test_prepare_request_with_bytestring_url(self):631 req = requests.Request('GET', b'https://httpbin.org/')632 s = requests.Session()633 prep = s.prepare_request(req)634 assert prep.url == "https://httpbin.org/"635636 def test_links(self):637 r = requests.Response()638 r.headers = {639 'cache-control': 'public, max-age=60, s-maxage=60',640 'connection': 'keep-alive',641 'content-encoding': 'gzip',642 'content-type': 'application/json; charset=utf-8',643 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',644 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',645 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',646 'link': ('<https://api.github.com/users/kennethreitz/repos?'647 'page=2&per_page=10>; rel="next", <https://api.github.'648 'com/users/kennethreitz/repos?page=7&per_page=10>; '649 ' rel="last"'),650 'server': 'GitHub.com',651 'status': '200 OK',652 'vary': 'Accept',653 'x-content-type-options': 'nosniff',654 'x-github-media-type': 'github.beta',655 'x-ratelimit-limit': '60',656 'x-ratelimit-remaining': '57'657 }658 assert r.links['next']['rel'] == 'next'659660 def test_cookie_parameters(self):661 key = 'some_cookie'662 value = 'some_value'663 secure = True664 domain = 'test.com'665 rest = {'HttpOnly': True}666667 jar = requests.cookies.RequestsCookieJar()668 jar.set(key, value, secure=secure, domain=domain, rest=rest)669670 assert len(jar) == 1671 assert 'some_cookie' in jar672673 cookie = list(jar)[0]674 assert cookie.secure == secure675 assert cookie.domain == domain676 assert cookie._rest['HttpOnly'] == rest['HttpOnly']677678 def test_cookie_as_dict_keeps_len(self):679 key = 'some_cookie'680 value = 'some_value'681682 key1 = 'some_cookie1'683 value1 = 'some_value1'684685 jar = requests.cookies.RequestsCookieJar()686 jar.set(key, value)687 jar.set(key1, value1)688689 d1 = dict(jar)690 d2 = dict(jar.iteritems())691 d3 = dict(jar.items())692693 assert len(jar) == 2694 assert len(d1) == 2695 assert len(d2) == 2696 assert len(d3) == 2697698 def test_cookie_as_dict_keeps_items(self):699 key = 'some_cookie'700 value = 'some_value'701702 key1 = 'some_cookie1'703 value1 = 'some_value1'704705 jar = requests.cookies.RequestsCookieJar()706 jar.set(key, value)707 jar.set(key1, value1)708709 d1 = dict(jar)710 d2 = dict(jar.iteritems())711 d3 = dict(jar.items())712713 assert d1['some_cookie'] == 'some_value'714 assert d2['some_cookie'] == 'some_value'715 assert d3['some_cookie1'] == 'some_value1'716717 def test_cookie_as_dict_keys(self):718 key = 'some_cookie'719 value = 'some_value'720721 key1 = 'some_cookie1'722 value1 = 'some_value1'723724 jar = requests.cookies.RequestsCookieJar()725 jar.set(key, value)726 jar.set(key1, value1)727728 keys = jar.keys()729 assert keys == list(keys)730 # make sure one can use keys multiple times731 assert list(keys) == list(keys)732733 def test_cookie_as_dict_values(self):734 key = 'some_cookie'735 value = 'some_value'736737 key1 = 'some_cookie1'738 value1 = 'some_value1'739740 jar = requests.cookies.RequestsCookieJar()741 jar.set(key, value)742 jar.set(key1, value1)743744 values = jar.values()745 assert values == list(values)746 # make sure one can use values multiple times747 assert list(values) == list(values)748749 def test_cookie_as_dict_items(self):750 key = 'some_cookie'751 value = 'some_value'752753 key1 = 'some_cookie1'754 value1 = 'some_value1'755756 jar = requests.cookies.RequestsCookieJar()757 jar.set(key, value)758 jar.set(key1, value1)759760 items = jar.items()761 assert items == list(items)762 # make sure one can use items multiple times763 assert list(items) == list(items)764765 def test_time_elapsed_blank(self):766 r = requests.get(httpbin('get'))767 td = r.elapsed768 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)769 * 10**6) / 10**6)770 assert total_seconds > 0.0771772 def test_response_is_iterable(self):773 r = requests.Response()774 io = StringIO.StringIO('abc')775 read_ = io.read776777 def read_mock(amt, decode_content=None):778 return read_(amt)779 setattr(io, 'read', read_mock)780 r.raw = io781 assert next(iter(r))782 io.close()783784 def test_response_decode_unicode(self):785 """786 When called with decode_unicode, Response.iter_content should always787 return unicode.788 """789 r = requests.Response()790 r._content_consumed = True791 r._content = b'the content'792 r.encoding = 'ascii'793794 chunks = r.iter_content(decode_unicode=True)795 assert all(isinstance(chunk, str) for chunk in chunks)796797 # also for streaming798 r = requests.Response()799 r.raw = io.BytesIO(b'the content')800 r.encoding = 'ascii'801 chunks = r.iter_content(decode_unicode=True)802 assert all(isinstance(chunk, str) for chunk in chunks)803804 def test_request_and_response_are_pickleable(self):805 r = requests.get(httpbin('get'))806807 # verify we can pickle the original request808 assert pickle.loads(pickle.dumps(r.request))809810 # verify we can pickle the response and that we have access to811 # the original request.812 pr = pickle.loads(pickle.dumps(r))813 assert r.request.url == pr.request.url814 assert r.request.headers == pr.request.headers815816 def test_get_auth_from_url(self):817 url = 'http://user:pass@complex.url.com/path?query=yes'818 assert ('user', 'pass') == requests.utils.get_auth_from_url(url)819820 def test_get_auth_from_url_encoded_spaces(self):821 url = 'http://user:pass%20pass@complex.url.com/path?query=yes'822 assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)823824 def test_get_auth_from_url_not_encoded_spaces(self):825 url = 'http://user:pass pass@complex.url.com/path?query=yes'826 assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)827828 def test_get_auth_from_url_percent_chars(self):829 url = 'http://user%25user:pass@complex.url.com/path?query=yes'830 assert ('user%user', 'pass') == requests.utils.get_auth_from_url(url)831832 def test_get_auth_from_url_encoded_hashes(self):833 url = 'http://user:pass%23pass@complex.url.com/path?query=yes'834 assert ('user', 'pass#pass') == requests.utils.get_auth_from_url(url)835836 def test_cannot_send_unprepared_requests(self):837 r = requests.Request(url=HTTPBIN)838 with pytest.raises(ValueError):839 requests.Session().send(r)840841 def test_http_error(self):842 error = requests.exceptions.HTTPError()843 assert not error.response844 response = requests.Response()845 error = requests.exceptions.HTTPError(response=response)846 assert error.response == response847 error = requests.exceptions.HTTPError('message', response=response)848 assert str(error) == 'message'849 assert error.response == response850851 def test_session_pickling(self):852 r = requests.Request('GET', httpbin('get'))853 s = requests.Session()854855 s = pickle.loads(pickle.dumps(s))856 s.proxies = getproxies()857858 r = s.send(r.prepare())859 assert r.status_code == 200860861 def test_fixes_1329(self):862 """863 Ensure that header updates are done case-insensitively.864 """865 s = requests.Session()866 s.headers.update({'ACCEPT': 'BOGUS'})867 s.headers.update({'accept': 'application/json'})868 r = s.get(httpbin('get'))869 headers = r.request.headers870 assert headers['accept'] == 'application/json'871 assert headers['Accept'] == 'application/json'872 assert headers['ACCEPT'] == 'application/json'873874 def test_uppercase_scheme_redirect(self):875 parts = urlparse(httpbin('html'))876 url = "HTTP://" + parts.netloc + parts.path877 r = requests.get(httpbin('redirect-to'), params={'url': url})878 assert r.status_code == 200879 assert r.url.lower() == url.lower()880881 def test_transport_adapter_ordering(self):882 s = requests.Session()883 order = ['https://', 'http://']884 assert order == list(s.adapters)885 s.mount('http://git', HTTPAdapter())886 s.mount('http://github', HTTPAdapter())887 s.mount('http://github.com', HTTPAdapter())888 s.mount('http://github.com/about/', HTTPAdapter())889 order = [890 'http://github.com/about/',891 'http://github.com',892 'http://github',893 'http://git',894 'https://',895 'http://',896 ]897 assert order == list(s.adapters)898 s.mount('http://gittip', HTTPAdapter())899 s.mount('http://gittip.com', HTTPAdapter())900 s.mount('http://gittip.com/about/', HTTPAdapter())901 order = [902 'http://github.com/about/',903 'http://gittip.com/about/',904 'http://github.com',905 'http://gittip.com',906 'http://github',907 'http://gittip',908 'http://git',909 'https://',910 'http://',911 ]912 assert order == list(s.adapters)913 s2 = requests.Session()914 s2.adapters = {'http://': HTTPAdapter()}915 s2.mount('https://', HTTPAdapter())916 assert 'http://' in s2.adapters917 assert 'https://' in s2.adapters918919 def test_header_remove_is_case_insensitive(self):920 # From issue #1321921 s = requests.Session()922 s.headers['foo'] = 'bar'923 r = s.get(httpbin('get'), headers={'FOO': None})924 assert 'foo' not in r.request.headers925926 def test_params_are_merged_case_sensitive(self):927 s = requests.Session()928 s.params['foo'] = 'bar'929 r = s.get(httpbin('get'), params={'FOO': 'bar'})930 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}931932 def test_long_authinfo_in_url(self):933 url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(934 'E8A3BE87-9E3F-4620-8858-95478E385B5B',935 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',936 'exactly-------------sixty-----------three------------characters',937 )938 r = requests.Request('GET', url).prepare()939 assert r.url == url940941 def test_header_keys_are_native(self):942 headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}943 r = requests.Request('GET', httpbin('get'), headers=headers)944 p = r.prepare()945946 # This is testing that they are builtin strings. A bit weird, but there947 # we go.948 assert 'unicode' in p.headers.keys()949 assert 'byte' in p.headers.keys()950951 def test_can_send_nonstring_objects_with_files(self):952 data = {'a': 0.0}953 files = {'b': 'foo'}954 r = requests.Request('POST', httpbin('post'), data=data, files=files)955 p = r.prepare()956957 assert 'multipart/form-data' in p.headers['Content-Type']958959 def test_can_send_bytes_bytearray_objects_with_files(self):960 # Test bytes:961 data = {'a': 'this is a string'}962 files = {'b': b'foo'}963 r = requests.Request('POST', httpbin('post'), data=data, files=files)964 p = r.prepare()965 assert 'multipart/form-data' in p.headers['Content-Type']966 # Test bytearrays:967 files = {'b': bytearray(b'foo')}968 r = requests.Request('POST', httpbin('post'), data=data, files=files)969 p = r.prepare()970 assert 'multipart/form-data' in p.headers['Content-Type']971972 def test_can_send_file_object_with_non_string_filename(self):973 f = io.BytesIO()974 f.name = 2975 r = requests.Request('POST', httpbin('post'), files={'f': f})976 p = r.prepare()977978 assert 'multipart/form-data' in p.headers['Content-Type']979980 def test_autoset_header_values_are_native(self):981 data = 'this is a string'982 length = '16'983 req = requests.Request('POST', httpbin('post'), data=data)984 p = req.prepare()985986 assert p.headers['Content-Length'] == length987988 def test_nonhttp_schemes_dont_check_URLs(self):989 test_urls = (990 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',991 'file:///etc/passwd',992 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',993 )994 for test_url in test_urls:995 req = requests.Request('GET', test_url)996 preq = req.prepare()997 assert test_url == preq.url998999 def test_auth_is_stripped_on_redirect_off_host(self):1000 r = requests.get(1001 httpbin('redirect-to'),1002 params={'url': 'http://www.google.co.uk'},1003 auth=('user', 'pass'),1004 )1005 assert r.history[0].request.headers['Authorization']1006 assert not r.request.headers.get('Authorization', '')10071008 def test_auth_is_retained_for_redirect_on_host(self):1009 r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))1010 h1 = r.history[0].request.headers['Authorization']1011 h2 = r.request.headers['Authorization']10121013 assert h1 == h210141015 def test_manual_redirect_with_partial_body_read(self):1016 s = requests.Session()1017 r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)1018 assert r1.is_redirect1019 rg = s.resolve_redirects(r1, r1.request, stream=True)10201021 # read only the first eight bytes of the response body,1022 # then follow the redirect1023 r1.iter_content(8)1024 r2 = next(rg)1025 assert r2.is_redirect10261027 # read all of the response via iter_content,1028 # then follow the redirect1029 for _ in r2.iter_content():1030 pass1031 r3 = next(rg)1032 assert not r3.is_redirect10331034 def _patch_adapter_gzipped_redirect(self, session, url):1035 adapter = session.get_adapter(url=url)1036 org_build_response = adapter.build_response1037 self._patched_response = False10381039 def build_response(*args, **kwargs):1040 resp = org_build_response(*args, **kwargs)1041 if not self._patched_response:1042 resp.raw.headers['content-encoding'] = 'gzip'1043 self._patched_response = True1044 return resp10451046 adapter.build_response = build_response10471048 def test_redirect_with_wrong_gzipped_header(self):1049 s = requests.Session()1050 url = httpbin('redirect/1')1051 self._patch_adapter_gzipped_redirect(s, url)1052 s.get(url)10531054 def test_basic_auth_str_is_always_native(self):1055 s = _basic_auth_str("test", "test")1056 assert isinstance(s, builtin_str)1057 assert s == "Basic dGVzdDp0ZXN0"10581059 def test_requests_history_is_saved(self):1060 r = requests.get(httpbin('redirect/5'))1061 total = r.history[-1].history1062 i = 01063 for item in r.history:1064 assert item.history == total[0:i]1065 i = i + 110661067 def test_json_param_post_content_type_works(self):1068 r = requests.post(1069 httpbin('post'),1070 json={'life': 42}1071 )1072 assert r.status_code == 2001073 assert 'application/json' in r.request.headers['Content-Type']1074 assert {'life': 42} == r.json()['json']10751076 def test_response_iter_lines(self):1077 r = requests.get(httpbin('stream/4'), stream=True)1078 assert r.status_code == 20010791080 it = r.iter_lines()1081 next(it)1082 assert len(list(it)) == 310831084 def test_unconsumed_session_response_closes_connection(self):1085 s = requests.session()10861087 with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1088 pass10891090 self.assertFalse(response._content_consumed)1091 self.assertTrue(response.raw.closed)10921093 @pytest.mark.xfail1094 def test_response_iter_lines_reentrant(self):1095 """Response.iter_lines() is not reentrant safe"""1096 r = requests.get(httpbin('stream/4'), stream=True)1097 assert r.status_code == 20010981099 next(r.iter_lines())1100 assert len(list(r.iter_lines())) == 3110111021103class TestContentEncodingDetection(unittest.TestCase):11041105 def test_none(self):1106 encodings = requests.utils.get_encodings_from_content('')1107 assert not len(encodings)11081109 def test_html_charset(self):1110 """HTML5 meta charset attribute"""1111 content = '<meta charset="UTF-8">'1112 encodings = requests.utils.get_encodings_from_content(content)1113 assert len(encodings) == 11114 assert encodings[0] == 'UTF-8'11151116 def test_html4_pragma(self):1117 """HTML4 pragma directive"""1118 content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">'1119 encodings = requests.utils.get_encodings_from_content(content)1120 assert len(encodings) == 11121 assert encodings[0] == 'UTF-8'11221123 def test_xhtml_pragma(self):1124 """XHTML 1.x served with text/html MIME type"""1125 content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />'1126 encodings = requests.utils.get_encodings_from_content(content)1127 assert len(encodings) == 11128 assert encodings[0] == 'UTF-8'11291130 def test_xml(self):1131 """XHTML 1.x served as XML"""1132 content = '<?xml version="1.0" encoding="UTF-8"?>'1133 encodings = requests.utils.get_encodings_from_content(content)1134 assert len(encodings) == 11135 assert encodings[0] == 'UTF-8'11361137 def test_precedence(self):1138 content = '''1139 <?xml version="1.0" encoding="XML"?>1140 <meta charset="HTML5">1141 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />1142 '''.strip()1143 encodings = requests.utils.get_encodings_from_content(content)1144 assert encodings == ['HTML5', 'HTML4', 'XML']114511461147class TestCaseInsensitiveDict(unittest.TestCase):11481149 def test_mapping_init(self):1150 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1151 assert len(cid) == 21152 assert 'foo' in cid1153 assert 'bar' in cid11541155 def test_iterable_init(self):1156 cid = CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')])1157 assert len(cid) == 21158 assert 'foo' in cid1159 assert 'bar' in cid11601161 def test_kwargs_init(self):1162 cid = CaseInsensitiveDict(FOO='foo', BAr='bar')1163 assert len(cid) == 21164 assert 'foo' in cid1165 assert 'bar' in cid11661167 def test_docstring_example(self):1168 cid = CaseInsensitiveDict()1169 cid['Accept'] = 'application/json'1170 assert cid['aCCEPT'] == 'application/json'1171 assert list(cid) == ['Accept']11721173 def test_len(self):1174 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1175 cid['A'] = 'a'1176 assert len(cid) == 211771178 def test_getitem(self):1179 cid = CaseInsensitiveDict({'Spam': 'blueval'})1180 assert cid['spam'] == 'blueval'1181 assert cid['SPAM'] == 'blueval'11821183 def test_fixes_649(self):1184 """__setitem__ should behave case-insensitively."""1185 cid = CaseInsensitiveDict()1186 cid['spam'] = 'oneval'1187 cid['Spam'] = 'twoval'1188 cid['sPAM'] = 'redval'1189 cid['SPAM'] = 'blueval'1190 assert cid['spam'] == 'blueval'1191 assert cid['SPAM'] == 'blueval'1192 assert list(cid.keys()) == ['SPAM']11931194 def test_delitem(self):1195 cid = CaseInsensitiveDict()1196 cid['Spam'] = 'someval'1197 del cid['sPam']1198 assert 'spam' not in cid1199 assert len(cid) == 012001201 def test_contains(self):1202 cid = CaseInsensitiveDict()1203 cid['Spam'] = 'someval'1204 assert 'Spam' in cid1205 assert 'spam' in cid1206 assert 'SPAM' in cid1207 assert 'sPam' in cid1208 assert 'notspam' not in cid12091210 def test_get(self):1211 cid = CaseInsensitiveDict()1212 cid['spam'] = 'oneval'1213 cid['SPAM'] = 'blueval'1214 assert cid.get('spam') == 'blueval'1215 assert cid.get('SPAM') == 'blueval'1216 assert cid.get('sPam') == 'blueval'1217 assert cid.get('notspam', 'default') == 'default'12181219 def test_update(self):1220 cid = CaseInsensitiveDict()1221 cid['spam'] = 'blueval'1222 cid.update({'sPam': 'notblueval'})1223 assert cid['spam'] == 'notblueval'1224 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1225 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1226 assert len(cid) == 21227 assert cid['foo'] == 'anotherfoo'1228 assert cid['bar'] == 'anotherbar'12291230 def test_update_retains_unchanged(self):1231 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1232 cid.update({'foo': 'newfoo'})1233 assert cid['bar'] == 'bar'12341235 def test_iter(self):1236 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1237 keys = frozenset(['Spam', 'Eggs'])1238 assert frozenset(iter(cid)) == keys12391240 def test_equality(self):1241 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1242 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1243 assert cid == othercid1244 del othercid['spam']1245 assert cid != othercid1246 assert cid == {'spam': 'blueval', 'eggs': 'redval'}1247 assert cid != object()12481249 def test_setdefault(self):1250 cid = CaseInsensitiveDict({'Spam': 'blueval'})1251 assert cid.setdefault('spam', 'notblueval') == 'blueval'1252 assert cid.setdefault('notspam', 'notblueval') == 'notblueval'12531254 def test_lower_items(self):1255 cid = CaseInsensitiveDict({1256 'Accept': 'application/json',1257 'user-Agent': 'requests',1258 })1259 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1260 lowerkeyset = frozenset(['accept', 'user-agent'])1261 assert keyset == lowerkeyset12621263 def test_preserve_key_case(self):1264 cid = CaseInsensitiveDict({1265 'Accept': 'application/json',1266 'user-Agent': 'requests',1267 })1268 keyset = frozenset(['Accept', 'user-Agent'])1269 assert frozenset(i[0] for i in cid.items()) == keyset1270 assert frozenset(cid.keys()) == keyset1271 assert frozenset(cid) == keyset12721273 def test_preserve_last_key_case(self):1274 cid = CaseInsensitiveDict({1275 'Accept': 'application/json',1276 'user-Agent': 'requests',1277 })1278 cid.update({'ACCEPT': 'application/json'})1279 cid['USER-AGENT'] = 'requests'1280 keyset = frozenset(['ACCEPT', 'USER-AGENT'])1281 assert frozenset(i[0] for i in cid.items()) == keyset1282 assert frozenset(cid.keys()) == keyset1283 assert frozenset(cid) == keyset12841285 def test_copy(self):1286 cid = CaseInsensitiveDict({1287 'Accept': 'application/json',1288 'user-Agent': 'requests',1289 })1290 cid_copy = cid.copy()1291 assert cid == cid_copy1292 cid['changed'] = True1293 assert cid != cid_copy12941295 def test_repr(self):1296 cid = CaseInsensitiveDict({1297 'Accept': 'application/json',1298 'user-Agent': 'requests',1299 })1300 assert repr(cid) == "{'Accept': 'application/json', 'user-Agent': 'requests'}"130113021303class UtilsTestCase(unittest.TestCase):13041305 def test_super_len_io_streams(self):1306 """ Ensures that we properly deal with different kinds of IO streams. """1307 # uses StringIO or io.StringIO (see import above)1308 from io import BytesIO1309 from requests.utils import super_len13101311 assert super_len(StringIO.StringIO()) == 01312 assert super_len(1313 StringIO.StringIO('with so much drama in the LBC')) == 2913141315 assert super_len(BytesIO()) == 01316 assert super_len(1317 BytesIO(b"it's kinda hard bein' snoop d-o-double-g")) == 4013181319 try:1320 import cStringIO1321 except ImportError:1322 pass1323 else:1324 assert super_len(1325 cStringIO.StringIO('but some how, some way...')) == 2513261327 def test_get_environ_proxies_ip_ranges(self):1328 """Ensures that IP addresses are correctly matches with ranges1329 in no_proxy variable."""1330 from requests.utils import get_environ_proxies1331 os.environ['no_proxy'] = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"1332 assert get_environ_proxies('http://192.168.0.1:5000/') == {}1333 assert get_environ_proxies('http://192.168.0.1/') == {}1334 assert get_environ_proxies('http://172.16.1.1/') == {}1335 assert get_environ_proxies('http://172.16.1.1:5000/') == {}1336 assert get_environ_proxies('http://192.168.1.1:5000/') != {}1337 assert get_environ_proxies('http://192.168.1.1/') != {}13381339 def test_get_environ_proxies(self):1340 """Ensures that IP addresses are correctly matches with ranges1341 in no_proxy variable."""1342 from requests.utils import get_environ_proxies1343 os.environ['no_proxy'] = "127.0.0.1,localhost.localdomain,192.168.0.0/24,172.16.1.1"1344 assert get_environ_proxies(1345 'http://localhost.localdomain:5000/v1.0/') == {}1346 assert get_environ_proxies('http://www.requests.com/') != {}13471348 def test_guess_filename_when_int(self):1349 from requests.utils import guess_filename1350 assert None is guess_filename(1)13511352 def test_guess_filename_when_filename_is_an_int(self):1353 from requests.utils import guess_filename1354 fake = type('Fake', (object,), {'name': 1})()1355 assert None is guess_filename(fake)13561357 def test_guess_filename_with_file_like_obj(self):1358 from requests.utils import guess_filename1359 from requests import compat1360 fake = type('Fake', (object,), {'name': b'value'})()1361 guessed_name = guess_filename(fake)1362 assert b'value' == guessed_name1363 assert isinstance(guessed_name, compat.bytes)13641365 def test_guess_filename_with_unicode_name(self):1366 from requests.utils import guess_filename1367 from requests import compat1368 filename = b'value'.decode('utf-8')1369 fake = type('Fake', (object,), {'name': filename})()1370 guessed_name = guess_filename(fake)1371 assert filename == guessed_name1372 assert isinstance(guessed_name, compat.str)13731374 def test_is_ipv4_address(self):1375 from requests.utils import is_ipv4_address1376 assert is_ipv4_address('8.8.8.8')1377 assert not is_ipv4_address('8.8.8.8.8')1378 assert not is_ipv4_address('localhost.localdomain')13791380 def test_is_valid_cidr(self):1381 from requests.utils import is_valid_cidr1382 assert not is_valid_cidr('8.8.8.8')1383 assert is_valid_cidr('192.168.1.0/24')13841385 def test_dotted_netmask(self):1386 from requests.utils import dotted_netmask1387 assert dotted_netmask(8) == '255.0.0.0'1388 assert dotted_netmask(24) == '255.255.255.0'1389 assert dotted_netmask(25) == '255.255.255.128'13901391 def test_address_in_network(self):1392 from requests.utils import address_in_network1393 assert address_in_network('192.168.1.1', '192.168.1.0/24')1394 assert not address_in_network('172.16.0.1', '192.168.1.0/24')13951396 def test_get_auth_from_url(self):1397 """Ensures that username and password in well-encoded URI as per1398 RFC 3986 are correclty extracted."""1399 from requests.utils import get_auth_from_url1400 from requests.compat import quote1401 percent_encoding_test_chars = "%!*'();:@&=+$,/?#[] "1402 url_address = "request.com/url.html#test"1403 url = "http://" + quote(1404 percent_encoding_test_chars, '') + ':' + quote(1405 percent_encoding_test_chars, '') + '@' + url_address1406 (username, password) = get_auth_from_url(url)1407 assert username == percent_encoding_test_chars1408 assert password == percent_encoding_test_chars14091410 def test_requote_uri_with_unquoted_percents(self):1411 """Ensure we handle unquoted percent signs in redirects.14121413 See: https://github.com/kennethreitz/requests/issues/23561414 """1415 from requests.utils import requote_uri1416 bad_uri = 'http://example.com/fiz?buz=%ppicture'1417 quoted = 'http://example.com/fiz?buz=%25ppicture'1418 assert quoted == requote_uri(bad_uri)14191420 def test_requote_uri_properly_requotes(self):1421 """Ensure requoting doesn't break expectations."""1422 from requests.utils import requote_uri1423 quoted = 'http://example.com/fiz?buz=%25ppicture'1424 assert quoted == requote_uri(quoted)142514261427class TestMorselToCookieExpires(unittest.TestCase):14281429 """Tests for morsel_to_cookie when morsel contains expires."""14301431 def test_expires_valid_str(self):1432 """Test case where we convert expires from string time."""14331434 morsel = Morsel()1435 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1436 cookie = morsel_to_cookie(morsel)1437 assert cookie.expires == 114381439 def test_expires_invalid_int(self):1440 """Test case where an invalid type is passed for expires."""14411442 morsel = Morsel()1443 morsel['expires'] = 1001444 with pytest.raises(TypeError):1445 morsel_to_cookie(morsel)14461447 def test_expires_invalid_str(self):1448 """Test case where an invalid string is input."""14491450 morsel = Morsel()1451 morsel['expires'] = 'woops'1452 with pytest.raises(ValueError):1453 morsel_to_cookie(morsel)14541455 def test_expires_none(self):1456 """Test case where expires is None."""14571458 morsel = Morsel()1459 morsel['expires'] = None1460 cookie = morsel_to_cookie(morsel)1461 assert cookie.expires is None146214631464class TestMorselToCookieMaxAge(unittest.TestCase):14651466 """Tests for morsel_to_cookie when morsel contains max-age."""14671468 def test_max_age_valid_int(self):1469 """Test case where a valid max age in seconds is passed."""14701471 morsel = Morsel()1472 morsel['max-age'] = 601473 cookie = morsel_to_cookie(morsel)1474 assert isinstance(cookie.expires, int)14751476 def test_max_age_invalid_str(self):1477 """Test case where a invalid max age is passed."""14781479 morsel = Morsel()1480 morsel['max-age'] = 'woops'1481 with pytest.raises(TypeError):1482 morsel_to_cookie(morsel)148314841485class TestTimeout:1486 def test_stream_timeout(self):1487 try:1488 requests.get(httpbin('delay/10'), timeout=2.0)1489 except requests.exceptions.Timeout as e:1490 assert 'Read timed out' in e.args[0].args[0]14911492 def test_invalid_timeout(self):1493 with pytest.raises(ValueError) as e:1494 requests.get(httpbin('get'), timeout=(3, 4, 5))1495 assert '(connect, read)' in str(e)14961497 with pytest.raises(ValueError) as e:1498 requests.get(httpbin('get'), timeout="foo")1499 assert 'must be an int or float' in str(e)15001501 def test_none_timeout(self):1502 """ Check that you can set None as a valid timeout value.15031504 To actually test this behavior, we'd want to check that setting the1505 timeout to None actually lets the request block past the system default1506 timeout. However, this would make the test suite unbearably slow.1507 Instead we verify that setting the timeout to None does not prevent the1508 request from succeeding.1509 """1510 r = requests.get(httpbin('get'), timeout=None)1511 assert r.status_code == 20015121513 def test_read_timeout(self):1514 try:1515 requests.get(httpbin('delay/10'), timeout=(None, 0.1))1516 assert False, "The recv() request should time out."1517 except ReadTimeout:1518 pass15191520 def test_connect_timeout(self):1521 try:1522 requests.get(TARPIT, timeout=(0.1, None))1523 assert False, "The connect() request should time out."1524 except ConnectTimeout as e:1525 assert isinstance(e, ConnectionError)1526 assert isinstance(e, Timeout)15271528 def test_total_timeout_connect(self):1529 try:1530 requests.get(TARPIT, timeout=(0.1, 0.1))1531 assert False, "The connect() request should time out."1532 except ConnectTimeout:1533 pass15341535 def test_encoded_methods(self):1536 """See: https://github.com/kennethreitz/requests/issues/2316"""1537 r = requests.request(b'GET', httpbin('get'))1538 assert r.ok153915401541SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))154215431544class RedirectSession(SessionRedirectMixin):1545 def __init__(self, order_of_redirects):1546 self.redirects = order_of_redirects1547 self.calls = []1548 self.max_redirects = 301549 self.cookies = {}1550 self.trust_env = False15511552 def send(self, *args, **kwargs):1553 self.calls.append(SendCall(args, kwargs))1554 return self.build_response()15551556 def build_response(self):1557 request = self.calls[-1].args[0]1558 r = requests.Response()15591560 try:1561 r.status_code = int(self.redirects.pop(0))1562 except IndexError:1563 r.status_code = 20015641565 r.headers = CaseInsensitiveDict({'Location': '/'})1566 r.raw = self._build_raw()1567 r.request = request1568 return r15691570 def _build_raw(self):1571 string = StringIO.StringIO('')1572 setattr(string, 'release_conn', lambda *args: args)1573 return string157415751576class TestRedirects:1577 default_keyword_args = {1578 'stream': False,1579 'verify': True,1580 'cert': None,1581 'timeout': None,1582 'allow_redirects': False,1583 'proxies': {},1584 }15851586 def test_requests_are_updated_each_time(self):1587 session = RedirectSession([303, 307])1588 prep = requests.Request('POST', httpbin('post')).prepare()1589 r0 = session.send(prep)1590 assert r0.request.method == 'POST'1591 assert session.calls[-1] == SendCall((r0.request,), {})1592 redirect_generator = session.resolve_redirects(r0, prep)1593 for response in redirect_generator:1594 assert response.request.method == 'GET'1595 send_call = SendCall((response.request,),1596 TestRedirects.default_keyword_args)1597 assert session.calls[-1] == send_call1598159916001601@pytest.fixture1602def list_of_tuples():1603 return [1604 (('a', 'b'), ('c', 'd')),1605 (('c', 'd'), ('a', 'b')),1606 (('a', 'b'), ('c', 'd'), ('e', 'f')),1607 ]160816091610def test_data_argument_accepts_tuples(list_of_tuples):1611 """1612 Ensure that the data argument will accept tuples of strings1613 and properly encode them.1614 """1615 for data in list_of_tuples:1616 p = PreparedRequest()1617 p.prepare(1618 method='GET',1619 url='http://www.example.com',1620 data=data,1621 hooks=default_hooks()1622 )1623 assert p.body == urlencode(data)162416251626def assert_copy(p, p_copy):1627 for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):1628 assert getattr(p, attr) == getattr(p_copy, attr)162916301631def test_prepared_request_empty_copy():1632 p = PreparedRequest()1633 assert_copy(p, p.copy())163416351636def test_prepared_request_no_cookies_copy():1637 p = PreparedRequest()1638 p.prepare(1639 method='GET',1640 url='http://www.example.com',1641 data='foo=bar',1642 hooks=default_hooks()1643 )1644 assert_copy(p, p.copy())164516461647def test_prepared_request_complete_copy():1648 p = PreparedRequest()1649 p.prepare(1650 method='GET',1651 url='http://www.example.com',1652 data='foo=bar',1653 hooks=default_hooks(),1654 cookies={'foo': 'bar'}1655 )1656 assert_copy(p, p.copy())165716581659def test_prepare_unicode_url():1660 p = PreparedRequest()1661 p.prepare(1662 method='GET',1663 url=u('http://www.example.com/üniçø∂é'),1664 )1665 assert_copy(p, p.copy())166616671668def test_urllib3_retries():1669 from requests.packages.urllib3.util import Retry1670 s = requests.Session()1671 s.mount('http://', HTTPAdapter(max_retries=Retry(1672 total=2, status_forcelist=[500]1673 )))16741675 with pytest.raises(RetryError):1676 s.get(httpbin('status/500'))167716781679def test_urllib3_pool_connection_closed():1680 s = requests.Session()1681 s.mount('http://', HTTPAdapter(pool_connections=0, pool_maxsize=0))16821683 try:1684 s.get(httpbin('status/200'))1685 except ConnectionError as e:1686 assert u"HTTPConnectionPool(host='httpbin.org', port=80): Pool is closed." in str(e.message)16871688def test_vendor_aliases():1689 from requests.packages import urllib31690 from requests.packages import chardet16911692 with pytest.raises(ImportError):1693 from requests.packages import webbrowser16941695if __name__ == '__main__':1696 unittest.main()