test_requests.py
This file
Path
test_requests.py
1,677 lines · 56.4 KiB · Python
Last changed by
Merge pull request #2741 from jasongrout/per-host-proxyCory Benfieldbefore adoption56ecdeb
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,21 builtin_str, OrderedDict22 )23from requests.cookies import cookiejar_from_dict, morsel_to_cookie24from requests.exceptions import (ConnectionError, ConnectTimeout,25 InvalidSchema, InvalidURL, MissingSchema,26 ReadTimeout, Timeout, RetryError)27from requests.models import PreparedRequest28from requests.structures import CaseInsensitiveDict29from requests.sessions import SessionRedirectMixin30from requests.models import urlencode31from requests.hooks import default_hooks3233try:34 import StringIO35except ImportError:36 import io as StringIO3738if is_py3:39 def u(s):40 return s41else:42 def u(s):43 return s.decode('unicode-escape')444546# Requests to this URL should always fail with a connection timeout (nothing47# listening on that port)48TARPIT = "http://10.255.255.1"49HTTPBIN = os.environ.get('HTTPBIN_URL', 'http://httpbin.org/')50# Issue #1483: Make sure the URL always has a trailing slash51HTTPBIN = HTTPBIN.rstrip('/') + '/'525354def httpbin(*suffix):55 """Returns url for HTTPBIN resource."""56 return urljoin(HTTPBIN, '/'.join(suffix))575859class RequestsTestCase(unittest.TestCase):6061 _multiprocess_can_split_ = True6263 def setUp(self):64 """Create simple data set with headers."""65 pass6667 def tearDown(self):68 """Teardown."""69 pass7071 def test_entry_points(self):7273 requests.session74 requests.session().get75 requests.session().head76 requests.get77 requests.head78 requests.put79 requests.patch80 requests.post8182 def test_invalid_url(self):83 with pytest.raises(MissingSchema):84 requests.get('hiwpefhipowhefopw')85 with pytest.raises(InvalidSchema):86 requests.get('localhost:3128')87 with pytest.raises(InvalidSchema):88 requests.get('localhost.localdomain:3128/')89 with pytest.raises(InvalidSchema):90 requests.get('10.122.1.1:3128/')91 with pytest.raises(InvalidURL):92 requests.get('http://')9394 def test_basic_building(self):95 req = requests.Request()96 req.url = 'http://kennethreitz.org/'97 req.data = {'life': '42'}9899 pr = req.prepare()100 assert pr.url == req.url101 assert pr.body == 'life=42'102103 def test_no_content_length(self):104 get_req = requests.Request('GET', httpbin('get')).prepare()105 assert 'Content-Length' not in get_req.headers106 head_req = requests.Request('HEAD', httpbin('head')).prepare()107 assert 'Content-Length' not in head_req.headers108109 def test_override_content_length(self):110 headers = {111 'Content-Length': 'not zero'112 }113 r = requests.Request('POST', httpbin('post'), headers=headers).prepare()114 assert 'Content-Length' in r.headers115 assert r.headers['Content-Length'] == 'not zero'116117 def test_path_is_not_double_encoded(self):118 request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()119120 assert request.path_url == '/get/test%20case'121122 def test_params_are_added_before_fragment(self):123 request = requests.Request('GET',124 "http://example.com/path#fragment", params={"a": "b"}).prepare()125 assert request.url == "http://example.com/path?a=b#fragment"126 request = requests.Request('GET',127 "http://example.com/path?key=value#fragment", params={"a": "b"}).prepare()128 assert request.url == "http://example.com/path?key=value&a=b#fragment"129130 def test_params_original_order_is_preserved_by_default(self):131 param_ordered_dict = OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))132 session = requests.Session()133 request = requests.Request('GET', 'http://example.com/', params=param_ordered_dict)134 prep = session.prepare_request(request)135 assert prep.url == 'http://example.com/?z=1&a=1&k=1&d=1'136137 def test_mixed_case_scheme_acceptable(self):138 s = requests.Session()139 s.proxies = getproxies()140 parts = urlparse(httpbin('get'))141 schemes = ['http://', 'HTTP://', 'hTTp://', 'HttP://',142 'https://', 'HTTPS://', 'hTTps://', 'HttPs://']143 for scheme in schemes:144 url = scheme + parts.netloc + parts.path145 r = requests.Request('GET', url)146 r = s.send(r.prepare())147 assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)148149 def test_HTTP_200_OK_GET_ALTERNATIVE(self):150 r = requests.Request('GET', httpbin('get'))151 s = requests.Session()152 s.proxies = getproxies()153154 r = s.send(r.prepare())155156 assert r.status_code == 200157158 def test_HTTP_302_ALLOW_REDIRECT_GET(self):159 r = requests.get(httpbin('redirect', '1'))160 assert r.status_code == 200161 assert r.history[0].status_code == 302162 assert r.history[0].is_redirect163164 # def test_HTTP_302_ALLOW_REDIRECT_POST(self):165 # r = requests.post(httpbin('status', '302'), data={'some': 'data'})166 # self.assertEqual(r.status_code, 200)167168 def test_HTTP_200_OK_GET_WITH_PARAMS(self):169 heads = {'User-agent': 'Mozilla/5.0'}170171 r = requests.get(httpbin('user-agent'), headers=heads)172173 assert heads['User-agent'] in r.text174 assert r.status_code == 200175176 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):177 heads = {'User-agent': 'Mozilla/5.0'}178179 r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)180 assert r.status_code == 200181182 def test_set_cookie_on_301(self):183 s = requests.session()184 url = httpbin('cookies/set?foo=bar')185 s.get(url)186 assert s.cookies['foo'] == 'bar'187188 def test_cookie_sent_on_redirect(self):189 s = requests.session()190 s.get(httpbin('cookies/set?foo=bar'))191 r = s.get(httpbin('redirect/1')) # redirects to httpbin('get')192 assert 'Cookie' in r.json()['headers']193194 def test_cookie_removed_on_expire(self):195 s = requests.session()196 s.get(httpbin('cookies/set?foo=bar'))197 assert s.cookies['foo'] == 'bar'198 s.get(199 httpbin('response-headers'),200 params={201 'Set-Cookie':202 'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'203 }204 )205 assert 'foo' not in s.cookies206207 def test_cookie_quote_wrapped(self):208 s = requests.session()209 s.get(httpbin('cookies/set?foo="bar:baz"'))210 assert s.cookies['foo'] == '"bar:baz"'211212 def test_cookie_persists_via_api(self):213 s = requests.session()214 r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})215 assert 'foo' in r.request.headers['Cookie']216 assert 'foo' in r.history[0].request.headers['Cookie']217218 def test_request_cookie_overrides_session_cookie(self):219 s = requests.session()220 s.cookies['foo'] = 'bar'221 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})222 assert r.json()['cookies']['foo'] == 'baz'223 # Session cookie should not be modified224 assert s.cookies['foo'] == 'bar'225226 def test_request_cookies_not_persisted(self):227 s = requests.session()228 s.get(httpbin('cookies'), cookies={'foo': 'baz'})229 # Sending a request with cookies should not add cookies to the session230 assert not s.cookies231232 def test_generic_cookiejar_works(self):233 cj = cookielib.CookieJar()234 cookiejar_from_dict({'foo': 'bar'}, cj)235 s = requests.session()236 s.cookies = cj237 r = s.get(httpbin('cookies'))238 # Make sure the cookie was sent239 assert r.json()['cookies']['foo'] == 'bar'240 # Make sure the session cj is still the custom one241 assert s.cookies is cj242243 def test_param_cookiejar_works(self):244 cj = cookielib.CookieJar()245 cookiejar_from_dict({'foo': 'bar'}, cj)246 s = requests.session()247 r = s.get(httpbin('cookies'), cookies=cj)248 # Make sure the cookie was sent249 assert r.json()['cookies']['foo'] == 'bar'250251 def test_requests_in_history_are_not_overridden(self):252 resp = requests.get(httpbin('redirect/3'))253 urls = [r.url for r in resp.history]254 req_urls = [r.request.url for r in resp.history]255 assert urls == req_urls256257 def test_history_is_always_a_list(self):258 """259 Show that even with redirects, Response.history is always a list.260 """261 resp = requests.get(httpbin('get'))262 assert isinstance(resp.history, list)263 resp = requests.get(httpbin('redirect/1'))264 assert isinstance(resp.history, list)265 assert not isinstance(resp.history, tuple)266267 def test_headers_on_session_with_None_are_not_sent(self):268 """Do not send headers in Session.headers with None values."""269 ses = requests.Session()270 ses.headers['Accept-Encoding'] = None271 req = requests.Request('GET', httpbin('get'))272 prep = ses.prepare_request(req)273 assert 'Accept-Encoding' not in prep.headers274275 def test_user_agent_transfers(self):276277 heads = {278 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'279 }280281 r = requests.get(httpbin('user-agent'), headers=heads)282 assert heads['User-agent'] in r.text283284 heads = {285 'user-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'286 }287288 r = requests.get(httpbin('user-agent'), headers=heads)289 assert heads['user-agent'] in r.text290291 def test_HTTP_200_OK_HEAD(self):292 r = requests.head(httpbin('get'))293 assert r.status_code == 200294295 def test_HTTP_200_OK_PUT(self):296 r = requests.put(httpbin('put'))297 assert r.status_code == 200298299 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):300 auth = ('user', 'pass')301 url = httpbin('basic-auth', 'user', 'pass')302303 r = requests.get(url, auth=auth)304 assert r.status_code == 200305306 r = requests.get(url)307 assert r.status_code == 401308309 s = requests.session()310 s.auth = auth311 r = s.get(url)312 assert r.status_code == 200313314 def test_connection_error_invalid_domain(self):315 """Connecting to an unknown domain should raise a ConnectionError"""316 with pytest.raises(ConnectionError):317 requests.get("http://doesnotexist.google.com")318319 def test_connection_error_invalid_port(self):320 """Connecting to an invalid port should raise a ConnectionError"""321 with pytest.raises(ConnectionError):322 requests.get("http://httpbin.org:1", timeout=1)323324 def test_LocationParseError(self):325 """Inputing a URL that cannot be parsed should raise an InvalidURL error"""326 with pytest.raises(InvalidURL):327 requests.get("http://fe80::5054:ff:fe5a:fc0")328329 def test_basicauth_with_netrc(self):330 auth = ('user', 'pass')331 wrong_auth = ('wronguser', 'wrongpass')332 url = httpbin('basic-auth', 'user', 'pass')333334 def get_netrc_auth_mock(url):335 return auth336 requests.sessions.get_netrc_auth = get_netrc_auth_mock337338 # Should use netrc and work.339 r = requests.get(url)340 assert r.status_code == 200341342 # Given auth should override and fail.343 r = requests.get(url, auth=wrong_auth)344 assert r.status_code == 401345346 s = requests.session()347348 # Should use netrc and work.349 r = s.get(url)350 assert r.status_code == 200351352 # Given auth should override and fail.353 s.auth = wrong_auth354 r = s.get(url)355 assert r.status_code == 401356357 def test_DIGEST_HTTP_200_OK_GET(self):358359 auth = HTTPDigestAuth('user', 'pass')360 url = httpbin('digest-auth', 'auth', 'user', 'pass')361362 r = requests.get(url, auth=auth)363 assert r.status_code == 200364365 r = requests.get(url)366 assert r.status_code == 401367368 s = requests.session()369 s.auth = HTTPDigestAuth('user', 'pass')370 r = s.get(url)371 assert r.status_code == 200372373 def test_DIGEST_AUTH_RETURNS_COOKIE(self):374 url = httpbin('digest-auth', 'auth', 'user', 'pass')375 auth = HTTPDigestAuth('user', 'pass')376 r = requests.get(url)377 assert r.cookies['fake'] == 'fake_value'378379 r = requests.get(url, auth=auth)380 assert r.status_code == 200381382 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self):383 url = httpbin('digest-auth', 'auth', 'user', 'pass')384 auth = HTTPDigestAuth('user', 'pass')385 s = requests.Session()386 s.get(url, auth=auth)387 assert s.cookies['fake'] == 'fake_value'388389 def test_DIGEST_STREAM(self):390391 auth = HTTPDigestAuth('user', 'pass')392 url = httpbin('digest-auth', 'auth', 'user', 'pass')393394 r = requests.get(url, auth=auth, stream=True)395 assert r.raw.read() != b''396397 r = requests.get(url, auth=auth, stream=False)398 assert r.raw.read() == b''399400 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self):401402 auth = HTTPDigestAuth('user', 'wrongpass')403 url = httpbin('digest-auth', 'auth', 'user', 'pass')404405 r = requests.get(url, auth=auth)406 assert r.status_code == 401407408 r = requests.get(url)409 assert r.status_code == 401410411 s = requests.session()412 s.auth = auth413 r = s.get(url)414 assert r.status_code == 401415416 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self):417418 auth = HTTPDigestAuth('user', 'pass')419 url = httpbin('digest-auth', 'auth', 'user', 'pass')420421 r = requests.get(url, auth=auth)422 assert '"auth"' in r.request.headers['Authorization']423424 def test_POSTBIN_GET_POST_FILES(self):425426 url = httpbin('post')427 post1 = requests.post(url).raise_for_status()428429 post1 = requests.post(url, data={'some': 'data'})430 assert post1.status_code == 200431432 with open('requirements.txt') as f:433 post2 = requests.post(url, files={'some': f})434 assert post2.status_code == 200435436 post4 = requests.post(url, data='[{"some": "json"}]')437 assert post4.status_code == 200438439 with pytest.raises(ValueError):440 requests.post(url, files=['bad file data'])441442 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self):443444 url = httpbin('post')445 post1 = requests.post(url).raise_for_status()446447 post1 = requests.post(url, data={'some': 'data'})448 assert post1.status_code == 200449450 with open('requirements.txt') as f:451 post2 = requests.post(url,452 data={'some': 'data'}, files={'some': f})453 assert post2.status_code == 200454455 post4 = requests.post(url, data='[{"some": "json"}]')456 assert post4.status_code == 200457458 with pytest.raises(ValueError):459 requests.post(url, files=['bad file data'])460461 def test_conflicting_post_params(self):462 url = httpbin('post')463 with open('requirements.txt') as f:464 pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")465 pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")466467 def test_request_ok_set(self):468 r = requests.get(httpbin('status', '404'))469 assert not r.ok470471 def test_status_raising(self):472 r = requests.get(httpbin('status', '404'))473 with pytest.raises(requests.exceptions.HTTPError):474 r.raise_for_status()475476 r = requests.get(httpbin('status', '500'))477 assert not r.ok478479 def test_decompress_gzip(self):480 r = requests.get(httpbin('gzip'))481 r.content.decode('ascii')482483 def test_unicode_get(self):484 url = httpbin('/get')485 requests.get(url, params={'foo': 'føø'})486 requests.get(url, params={'føø': 'føø'})487 requests.get(url, params={'føø': 'føø'})488 requests.get(url, params={'foo': 'foo'})489 requests.get(httpbin('ø'), params={'foo': 'foo'})490491 def test_unicode_header_name(self):492 requests.put(493 httpbin('put'),494 headers={str('Content-Type'): 'application/octet-stream'},495 data='\xff') # compat.str is unicode.496497 def test_pyopenssl_redirect(self):498 requests.get('https://httpbin.org/status/301')499500 def test_urlencoded_get_query_multivalued_param(self):501502 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))503 assert r.status_code == 200504 assert r.url == httpbin('get?test=foo&test=baz')505506 def test_different_encodings_dont_break_post(self):507 r = requests.post(httpbin('post'),508 data={'stuff': json.dumps({'a': 123})},509 params={'blah': 'asdf1234'},510 files={'file': ('test_requests.py', open(__file__, 'rb'))})511 assert r.status_code == 200512513 def test_unicode_multipart_post(self):514 r = requests.post(httpbin('post'),515 data={'stuff': u('ëlïxr')},516 files={'file': ('test_requests.py', open(__file__, 'rb'))})517 assert r.status_code == 200518519 r = requests.post(httpbin('post'),520 data={'stuff': u('ëlïxr').encode('utf-8')},521 files={'file': ('test_requests.py', open(__file__, 'rb'))})522 assert r.status_code == 200523524 r = requests.post(httpbin('post'),525 data={'stuff': 'elixr'},526 files={'file': ('test_requests.py', open(__file__, 'rb'))})527 assert r.status_code == 200528529 r = requests.post(httpbin('post'),530 data={'stuff': 'elixr'.encode('utf-8')},531 files={'file': ('test_requests.py', open(__file__, 'rb'))})532 assert r.status_code == 200533534 def test_unicode_multipart_post_fieldnames(self):535 filename = os.path.splitext(__file__)[0] + '.py'536 r = requests.Request(method='POST',537 url=httpbin('post'),538 data={'stuff'.encode('utf-8'): 'elixr'},539 files={'file': ('test_requests.py',540 open(filename, 'rb'))})541 prep = r.prepare()542 assert b'name="stuff"' in prep.body543 assert b'name="b\'stuff\'"' not in prep.body544545 def test_unicode_method_name(self):546 files = {'file': open('test_requests.py', 'rb')}547 r = requests.request(548 method=u('POST'), url=httpbin('post'), files=files)549 assert r.status_code == 200550551 def test_custom_content_type(self):552 r = requests.post(553 httpbin('post'),554 data={'stuff': json.dumps({'a': 123})},555 files={'file1': ('test_requests.py', open(__file__, 'rb')),556 'file2': ('test_requests', open(__file__, 'rb'),557 'text/py-content-type')})558 assert r.status_code == 200559 assert b"text/py-content-type" in r.request.body560561 def test_hook_receives_request_arguments(self):562 def hook(resp, **kwargs):563 assert resp is not None564 assert kwargs != {}565566 requests.Request('GET', HTTPBIN, hooks={'response': hook})567568 def test_session_hooks_are_used_with_no_request_hooks(self):569 hook = lambda x, *args, **kwargs: x570 s = requests.Session()571 s.hooks['response'].append(hook)572 r = requests.Request('GET', HTTPBIN)573 prep = s.prepare_request(r)574 assert prep.hooks['response'] != []575 assert prep.hooks['response'] == [hook]576577 def test_session_hooks_are_overriden_by_request_hooks(self):578 hook1 = lambda x, *args, **kwargs: x579 hook2 = lambda x, *args, **kwargs: x580 assert hook1 is not hook2581 s = requests.Session()582 s.hooks['response'].append(hook2)583 r = requests.Request('GET', HTTPBIN, hooks={'response': [hook1]})584 prep = s.prepare_request(r)585 assert prep.hooks['response'] == [hook1]586587 def test_prepared_request_hook(self):588 def hook(resp, **kwargs):589 resp.hook_working = True590 return resp591592 req = requests.Request('GET', HTTPBIN, hooks={'response': hook})593 prep = req.prepare()594595 s = requests.Session()596 s.proxies = getproxies()597 resp = s.send(prep)598599 assert hasattr(resp, 'hook_working')600601 def test_prepared_from_session(self):602 class DummyAuth(requests.auth.AuthBase):603 def __call__(self, r):604 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'605 return r606607 req = requests.Request('GET', httpbin('headers'))608 assert not req.auth609610 s = requests.Session()611 s.auth = DummyAuth()612613 prep = s.prepare_request(req)614 resp = s.send(prep)615616 assert resp.json()['headers'][617 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'618619 def test_prepare_request_with_bytestring_url(self):620 req = requests.Request('GET', b'https://httpbin.org/')621 s = requests.Session()622 prep = s.prepare_request(req)623 assert prep.url == "https://httpbin.org/"624625 def test_links(self):626 r = requests.Response()627 r.headers = {628 'cache-control': 'public, max-age=60, s-maxage=60',629 'connection': 'keep-alive',630 'content-encoding': 'gzip',631 'content-type': 'application/json; charset=utf-8',632 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',633 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',634 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',635 'link': ('<https://api.github.com/users/kennethreitz/repos?'636 'page=2&per_page=10>; rel="next", <https://api.github.'637 'com/users/kennethreitz/repos?page=7&per_page=10>; '638 ' rel="last"'),639 'server': 'GitHub.com',640 'status': '200 OK',641 'vary': 'Accept',642 'x-content-type-options': 'nosniff',643 'x-github-media-type': 'github.beta',644 'x-ratelimit-limit': '60',645 'x-ratelimit-remaining': '57'646 }647 assert r.links['next']['rel'] == 'next'648649 def test_cookie_parameters(self):650 key = 'some_cookie'651 value = 'some_value'652 secure = True653 domain = 'test.com'654 rest = {'HttpOnly': True}655656 jar = requests.cookies.RequestsCookieJar()657 jar.set(key, value, secure=secure, domain=domain, rest=rest)658659 assert len(jar) == 1660 assert 'some_cookie' in jar661662 cookie = list(jar)[0]663 assert cookie.secure == secure664 assert cookie.domain == domain665 assert cookie._rest['HttpOnly'] == rest['HttpOnly']666667 def test_cookie_as_dict_keeps_len(self):668 key = 'some_cookie'669 value = 'some_value'670671 key1 = 'some_cookie1'672 value1 = 'some_value1'673674 jar = requests.cookies.RequestsCookieJar()675 jar.set(key, value)676 jar.set(key1, value1)677678 d1 = dict(jar)679 d2 = dict(jar.iteritems())680 d3 = dict(jar.items())681682 assert len(jar) == 2683 assert len(d1) == 2684 assert len(d2) == 2685 assert len(d3) == 2686687 def test_cookie_as_dict_keeps_items(self):688 key = 'some_cookie'689 value = 'some_value'690691 key1 = 'some_cookie1'692 value1 = 'some_value1'693694 jar = requests.cookies.RequestsCookieJar()695 jar.set(key, value)696 jar.set(key1, value1)697698 d1 = dict(jar)699 d2 = dict(jar.iteritems())700 d3 = dict(jar.items())701702 assert d1['some_cookie'] == 'some_value'703 assert d2['some_cookie'] == 'some_value'704 assert d3['some_cookie1'] == 'some_value1'705706 def test_cookie_as_dict_keys(self):707 key = 'some_cookie'708 value = 'some_value'709710 key1 = 'some_cookie1'711 value1 = 'some_value1'712713 jar = requests.cookies.RequestsCookieJar()714 jar.set(key, value)715 jar.set(key1, value1)716717 keys = jar.keys()718 assert keys == list(keys)719 # make sure one can use keys multiple times720 assert list(keys) == list(keys)721722 def test_cookie_as_dict_values(self):723 key = 'some_cookie'724 value = 'some_value'725726 key1 = 'some_cookie1'727 value1 = 'some_value1'728729 jar = requests.cookies.RequestsCookieJar()730 jar.set(key, value)731 jar.set(key1, value1)732733 values = jar.values()734 assert values == list(values)735 # make sure one can use values multiple times736 assert list(values) == list(values)737738 def test_cookie_as_dict_items(self):739 key = 'some_cookie'740 value = 'some_value'741742 key1 = 'some_cookie1'743 value1 = 'some_value1'744745 jar = requests.cookies.RequestsCookieJar()746 jar.set(key, value)747 jar.set(key1, value1)748749 items = jar.items()750 assert items == list(items)751 # make sure one can use items multiple times752 assert list(items) == list(items)753754 def test_time_elapsed_blank(self):755 r = requests.get(httpbin('get'))756 td = r.elapsed757 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)758 * 10**6) / 10**6)759 assert total_seconds > 0.0760761 def test_response_is_iterable(self):762 r = requests.Response()763 io = StringIO.StringIO('abc')764 read_ = io.read765766 def read_mock(amt, decode_content=None):767 return read_(amt)768 setattr(io, 'read', read_mock)769 r.raw = io770 assert next(iter(r))771 io.close()772773 def test_response_decode_unicode(self):774 """775 When called with decode_unicode, Response.iter_content should always776 return unicode.777 """778 r = requests.Response()779 r._content_consumed = True780 r._content = b'the content'781 r.encoding = 'ascii'782783 chunks = r.iter_content(decode_unicode=True)784 assert all(isinstance(chunk, str) for chunk in chunks)785786 # also for streaming787 r = requests.Response()788 r.raw = io.BytesIO(b'the content')789 r.encoding = 'ascii'790 chunks = r.iter_content(decode_unicode=True)791 assert all(isinstance(chunk, str) for chunk in chunks)792793 def test_request_and_response_are_pickleable(self):794 r = requests.get(httpbin('get'))795796 # verify we can pickle the original request797 assert pickle.loads(pickle.dumps(r.request))798799 # verify we can pickle the response and that we have access to800 # the original request.801 pr = pickle.loads(pickle.dumps(r))802 assert r.request.url == pr.request.url803 assert r.request.headers == pr.request.headers804805 def test_get_auth_from_url(self):806 url = 'http://user:pass@complex.url.com/path?query=yes'807 assert ('user', 'pass') == requests.utils.get_auth_from_url(url)808809 def test_get_auth_from_url_encoded_spaces(self):810 url = 'http://user:pass%20pass@complex.url.com/path?query=yes'811 assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)812813 def test_get_auth_from_url_not_encoded_spaces(self):814 url = 'http://user:pass pass@complex.url.com/path?query=yes'815 assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)816817 def test_get_auth_from_url_percent_chars(self):818 url = 'http://user%25user:pass@complex.url.com/path?query=yes'819 assert ('user%user', 'pass') == requests.utils.get_auth_from_url(url)820821 def test_get_auth_from_url_encoded_hashes(self):822 url = 'http://user:pass%23pass@complex.url.com/path?query=yes'823 assert ('user', 'pass#pass') == requests.utils.get_auth_from_url(url)824825 def test_cannot_send_unprepared_requests(self):826 r = requests.Request(url=HTTPBIN)827 with pytest.raises(ValueError):828 requests.Session().send(r)829830 def test_http_error(self):831 error = requests.exceptions.HTTPError()832 assert not error.response833 response = requests.Response()834 error = requests.exceptions.HTTPError(response=response)835 assert error.response == response836 error = requests.exceptions.HTTPError('message', response=response)837 assert str(error) == 'message'838 assert error.response == response839840 def test_session_pickling(self):841 r = requests.Request('GET', httpbin('get'))842 s = requests.Session()843844 s = pickle.loads(pickle.dumps(s))845 s.proxies = getproxies()846847 r = s.send(r.prepare())848 assert r.status_code == 200849850 def test_fixes_1329(self):851 """852 Ensure that header updates are done case-insensitively.853 """854 s = requests.Session()855 s.headers.update({'ACCEPT': 'BOGUS'})856 s.headers.update({'accept': 'application/json'})857 r = s.get(httpbin('get'))858 headers = r.request.headers859 assert headers['accept'] == 'application/json'860 assert headers['Accept'] == 'application/json'861 assert headers['ACCEPT'] == 'application/json'862863 def test_uppercase_scheme_redirect(self):864 parts = urlparse(httpbin('html'))865 url = "HTTP://" + parts.netloc + parts.path866 r = requests.get(httpbin('redirect-to'), params={'url': url})867 assert r.status_code == 200868 assert r.url.lower() == url.lower()869870 def test_transport_adapter_ordering(self):871 s = requests.Session()872 order = ['https://', 'http://']873 assert order == list(s.adapters)874 s.mount('http://git', HTTPAdapter())875 s.mount('http://github', HTTPAdapter())876 s.mount('http://github.com', HTTPAdapter())877 s.mount('http://github.com/about/', HTTPAdapter())878 order = [879 'http://github.com/about/',880 'http://github.com',881 'http://github',882 'http://git',883 'https://',884 'http://',885 ]886 assert order == list(s.adapters)887 s.mount('http://gittip', HTTPAdapter())888 s.mount('http://gittip.com', HTTPAdapter())889 s.mount('http://gittip.com/about/', HTTPAdapter())890 order = [891 'http://github.com/about/',892 'http://gittip.com/about/',893 'http://github.com',894 'http://gittip.com',895 'http://github',896 'http://gittip',897 'http://git',898 'https://',899 'http://',900 ]901 assert order == list(s.adapters)902 s2 = requests.Session()903 s2.adapters = {'http://': HTTPAdapter()}904 s2.mount('https://', HTTPAdapter())905 assert 'http://' in s2.adapters906 assert 'https://' in s2.adapters907908 def test_header_remove_is_case_insensitive(self):909 # From issue #1321910 s = requests.Session()911 s.headers['foo'] = 'bar'912 r = s.get(httpbin('get'), headers={'FOO': None})913 assert 'foo' not in r.request.headers914915 def test_params_are_merged_case_sensitive(self):916 s = requests.Session()917 s.params['foo'] = 'bar'918 r = s.get(httpbin('get'), params={'FOO': 'bar'})919 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}920921 def test_long_authinfo_in_url(self):922 url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(923 'E8A3BE87-9E3F-4620-8858-95478E385B5B',924 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',925 'exactly-------------sixty-----------three------------characters',926 )927 r = requests.Request('GET', url).prepare()928 assert r.url == url929930 def test_header_keys_are_native(self):931 headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}932 r = requests.Request('GET', httpbin('get'), headers=headers)933 p = r.prepare()934935 # This is testing that they are builtin strings. A bit weird, but there936 # we go.937 assert 'unicode' in p.headers.keys()938 assert 'byte' in p.headers.keys()939940 def test_can_send_nonstring_objects_with_files(self):941 data = {'a': 0.0}942 files = {'b': 'foo'}943 r = requests.Request('POST', httpbin('post'), data=data, files=files)944 p = r.prepare()945946 assert 'multipart/form-data' in p.headers['Content-Type']947948 def test_can_send_bytes_bytearray_objects_with_files(self):949 # Test bytes:950 data = {'a': 'this is a string'}951 files = {'b': b'foo'}952 r = requests.Request('POST', httpbin('post'), data=data, files=files)953 p = r.prepare()954 assert 'multipart/form-data' in p.headers['Content-Type']955 # Test bytearrays:956 files = {'b': bytearray(b'foo')}957 r = requests.Request('POST', httpbin('post'), data=data, files=files)958 p = r.prepare()959 assert 'multipart/form-data' in p.headers['Content-Type']960961 def test_can_send_file_object_with_non_string_filename(self):962 f = io.BytesIO()963 f.name = 2964 r = requests.Request('POST', httpbin('post'), files={'f': f})965 p = r.prepare()966967 assert 'multipart/form-data' in p.headers['Content-Type']968969 def test_autoset_header_values_are_native(self):970 data = 'this is a string'971 length = '16'972 req = requests.Request('POST', httpbin('post'), data=data)973 p = req.prepare()974975 assert p.headers['Content-Length'] == length976977 def test_nonhttp_schemes_dont_check_URLs(self):978 test_urls = (979 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',980 'file:///etc/passwd',981 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',982 )983 for test_url in test_urls:984 req = requests.Request('GET', test_url)985 preq = req.prepare()986 assert test_url == preq.url987988 def test_auth_is_stripped_on_redirect_off_host(self):989 r = requests.get(990 httpbin('redirect-to'),991 params={'url': 'http://www.google.co.uk'},992 auth=('user', 'pass'),993 )994 assert r.history[0].request.headers['Authorization']995 assert not r.request.headers.get('Authorization', '')996997 def test_auth_is_retained_for_redirect_on_host(self):998 r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))999 h1 = r.history[0].request.headers['Authorization']1000 h2 = r.request.headers['Authorization']10011002 assert h1 == h210031004 def test_manual_redirect_with_partial_body_read(self):1005 s = requests.Session()1006 r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)1007 assert r1.is_redirect1008 rg = s.resolve_redirects(r1, r1.request, stream=True)10091010 # read only the first eight bytes of the response body,1011 # then follow the redirect1012 r1.iter_content(8)1013 r2 = next(rg)1014 assert r2.is_redirect10151016 # read all of the response via iter_content,1017 # then follow the redirect1018 for _ in r2.iter_content():1019 pass1020 r3 = next(rg)1021 assert not r3.is_redirect10221023 def _patch_adapter_gzipped_redirect(self, session, url):1024 adapter = session.get_adapter(url=url)1025 org_build_response = adapter.build_response1026 self._patched_response = False10271028 def build_response(*args, **kwargs):1029 resp = org_build_response(*args, **kwargs)1030 if not self._patched_response:1031 resp.raw.headers['content-encoding'] = 'gzip'1032 self._patched_response = True1033 return resp10341035 adapter.build_response = build_response10361037 def test_redirect_with_wrong_gzipped_header(self):1038 s = requests.Session()1039 url = httpbin('redirect/1')1040 self._patch_adapter_gzipped_redirect(s, url)1041 s.get(url)10421043 def test_basic_auth_str_is_always_native(self):1044 s = _basic_auth_str("test", "test")1045 assert isinstance(s, builtin_str)1046 assert s == "Basic dGVzdDp0ZXN0"10471048 def test_requests_history_is_saved(self):1049 r = requests.get(httpbin('redirect/5'))1050 total = r.history[-1].history1051 i = 01052 for item in r.history:1053 assert item.history == total[0:i]1054 i = i + 110551056 def test_json_param_post_content_type_works(self):1057 r = requests.post(1058 httpbin('post'),1059 json={'life': 42}1060 )1061 assert r.status_code == 2001062 assert 'application/json' in r.request.headers['Content-Type']1063 assert {'life': 42} == r.json()['json']10641065 def test_response_iter_lines(self):1066 r = requests.get(httpbin('stream/4'), stream=True)1067 assert r.status_code == 20010681069 it = r.iter_lines()1070 next(it)1071 assert len(list(it)) == 310721073 def test_unconsumed_session_response_closes_connection(self):1074 s = requests.session()10751076 with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1077 pass10781079 self.assertFalse(response._content_consumed)1080 self.assertTrue(response.raw.closed)10811082 @pytest.mark.xfail1083 def test_response_iter_lines_reentrant(self):1084 """Response.iter_lines() is not reentrant safe"""1085 r = requests.get(httpbin('stream/4'), stream=True)1086 assert r.status_code == 20010871088 next(r.iter_lines())1089 assert len(list(r.iter_lines())) == 3109010911092class TestContentEncodingDetection(unittest.TestCase):10931094 def test_none(self):1095 encodings = requests.utils.get_encodings_from_content('')1096 assert not len(encodings)10971098 def test_html_charset(self):1099 """HTML5 meta charset attribute"""1100 content = '<meta charset="UTF-8">'1101 encodings = requests.utils.get_encodings_from_content(content)1102 assert len(encodings) == 11103 assert encodings[0] == 'UTF-8'11041105 def test_html4_pragma(self):1106 """HTML4 pragma directive"""1107 content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">'1108 encodings = requests.utils.get_encodings_from_content(content)1109 assert len(encodings) == 11110 assert encodings[0] == 'UTF-8'11111112 def test_xhtml_pragma(self):1113 """XHTML 1.x served with text/html MIME type"""1114 content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />'1115 encodings = requests.utils.get_encodings_from_content(content)1116 assert len(encodings) == 11117 assert encodings[0] == 'UTF-8'11181119 def test_xml(self):1120 """XHTML 1.x served as XML"""1121 content = '<?xml version="1.0" encoding="UTF-8"?>'1122 encodings = requests.utils.get_encodings_from_content(content)1123 assert len(encodings) == 11124 assert encodings[0] == 'UTF-8'11251126 def test_precedence(self):1127 content = '''1128 <?xml version="1.0" encoding="XML"?>1129 <meta charset="HTML5">1130 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />1131 '''.strip()1132 encodings = requests.utils.get_encodings_from_content(content)1133 assert encodings == ['HTML5', 'HTML4', 'XML']113411351136class TestCaseInsensitiveDict(unittest.TestCase):11371138 def test_mapping_init(self):1139 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1140 assert len(cid) == 21141 assert 'foo' in cid1142 assert 'bar' in cid11431144 def test_iterable_init(self):1145 cid = CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')])1146 assert len(cid) == 21147 assert 'foo' in cid1148 assert 'bar' in cid11491150 def test_kwargs_init(self):1151 cid = CaseInsensitiveDict(FOO='foo', BAr='bar')1152 assert len(cid) == 21153 assert 'foo' in cid1154 assert 'bar' in cid11551156 def test_docstring_example(self):1157 cid = CaseInsensitiveDict()1158 cid['Accept'] = 'application/json'1159 assert cid['aCCEPT'] == 'application/json'1160 assert list(cid) == ['Accept']11611162 def test_len(self):1163 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1164 cid['A'] = 'a'1165 assert len(cid) == 211661167 def test_getitem(self):1168 cid = CaseInsensitiveDict({'Spam': 'blueval'})1169 assert cid['spam'] == 'blueval'1170 assert cid['SPAM'] == 'blueval'11711172 def test_fixes_649(self):1173 """__setitem__ should behave case-insensitively."""1174 cid = CaseInsensitiveDict()1175 cid['spam'] = 'oneval'1176 cid['Spam'] = 'twoval'1177 cid['sPAM'] = 'redval'1178 cid['SPAM'] = 'blueval'1179 assert cid['spam'] == 'blueval'1180 assert cid['SPAM'] == 'blueval'1181 assert list(cid.keys()) == ['SPAM']11821183 def test_delitem(self):1184 cid = CaseInsensitiveDict()1185 cid['Spam'] = 'someval'1186 del cid['sPam']1187 assert 'spam' not in cid1188 assert len(cid) == 011891190 def test_contains(self):1191 cid = CaseInsensitiveDict()1192 cid['Spam'] = 'someval'1193 assert 'Spam' in cid1194 assert 'spam' in cid1195 assert 'SPAM' in cid1196 assert 'sPam' in cid1197 assert 'notspam' not in cid11981199 def test_get(self):1200 cid = CaseInsensitiveDict()1201 cid['spam'] = 'oneval'1202 cid['SPAM'] = 'blueval'1203 assert cid.get('spam') == 'blueval'1204 assert cid.get('SPAM') == 'blueval'1205 assert cid.get('sPam') == 'blueval'1206 assert cid.get('notspam', 'default') == 'default'12071208 def test_update(self):1209 cid = CaseInsensitiveDict()1210 cid['spam'] = 'blueval'1211 cid.update({'sPam': 'notblueval'})1212 assert cid['spam'] == 'notblueval'1213 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1214 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1215 assert len(cid) == 21216 assert cid['foo'] == 'anotherfoo'1217 assert cid['bar'] == 'anotherbar'12181219 def test_update_retains_unchanged(self):1220 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1221 cid.update({'foo': 'newfoo'})1222 assert cid['bar'] == 'bar'12231224 def test_iter(self):1225 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1226 keys = frozenset(['Spam', 'Eggs'])1227 assert frozenset(iter(cid)) == keys12281229 def test_equality(self):1230 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1231 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1232 assert cid == othercid1233 del othercid['spam']1234 assert cid != othercid1235 assert cid == {'spam': 'blueval', 'eggs': 'redval'}1236 assert cid != object()12371238 def test_setdefault(self):1239 cid = CaseInsensitiveDict({'Spam': 'blueval'})1240 assert cid.setdefault('spam', 'notblueval') == 'blueval'1241 assert cid.setdefault('notspam', 'notblueval') == 'notblueval'12421243 def test_lower_items(self):1244 cid = CaseInsensitiveDict({1245 'Accept': 'application/json',1246 'user-Agent': 'requests',1247 })1248 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1249 lowerkeyset = frozenset(['accept', 'user-agent'])1250 assert keyset == lowerkeyset12511252 def test_preserve_key_case(self):1253 cid = CaseInsensitiveDict({1254 'Accept': 'application/json',1255 'user-Agent': 'requests',1256 })1257 keyset = frozenset(['Accept', 'user-Agent'])1258 assert frozenset(i[0] for i in cid.items()) == keyset1259 assert frozenset(cid.keys()) == keyset1260 assert frozenset(cid) == keyset12611262 def test_preserve_last_key_case(self):1263 cid = CaseInsensitiveDict({1264 'Accept': 'application/json',1265 'user-Agent': 'requests',1266 })1267 cid.update({'ACCEPT': 'application/json'})1268 cid['USER-AGENT'] = 'requests'1269 keyset = frozenset(['ACCEPT', 'USER-AGENT'])1270 assert frozenset(i[0] for i in cid.items()) == keyset1271 assert frozenset(cid.keys()) == keyset1272 assert frozenset(cid) == keyset12731274 def test_copy(self):1275 cid = CaseInsensitiveDict({1276 'Accept': 'application/json',1277 'user-Agent': 'requests',1278 })1279 cid_copy = cid.copy()1280 assert cid == cid_copy1281 cid['changed'] = True1282 assert cid != cid_copy128312841285class UtilsTestCase(unittest.TestCase):12861287 def test_super_len_io_streams(self):1288 """ Ensures that we properly deal with different kinds of IO streams. """1289 # uses StringIO or io.StringIO (see import above)1290 from io import BytesIO1291 from requests.utils import super_len12921293 assert super_len(StringIO.StringIO()) == 01294 assert super_len(1295 StringIO.StringIO('with so much drama in the LBC')) == 2912961297 assert super_len(BytesIO()) == 01298 assert super_len(1299 BytesIO(b"it's kinda hard bein' snoop d-o-double-g")) == 4013001301 try:1302 import cStringIO1303 except ImportError:1304 pass1305 else:1306 assert super_len(1307 cStringIO.StringIO('but some how, some way...')) == 2513081309 def test_get_environ_proxies_ip_ranges(self):1310 """Ensures that IP addresses are correctly matches with ranges1311 in no_proxy variable."""1312 from requests.utils import get_environ_proxies1313 os.environ['no_proxy'] = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"1314 assert get_environ_proxies('http://192.168.0.1:5000/') == {}1315 assert get_environ_proxies('http://192.168.0.1/') == {}1316 assert get_environ_proxies('http://172.16.1.1/') == {}1317 assert get_environ_proxies('http://172.16.1.1:5000/') == {}1318 assert get_environ_proxies('http://192.168.1.1:5000/') != {}1319 assert get_environ_proxies('http://192.168.1.1/') != {}13201321 def test_get_environ_proxies(self):1322 """Ensures that IP addresses are correctly matches with ranges1323 in no_proxy variable."""1324 from requests.utils import get_environ_proxies1325 os.environ['no_proxy'] = "127.0.0.1,localhost.localdomain,192.168.0.0/24,172.16.1.1"1326 assert get_environ_proxies(1327 'http://localhost.localdomain:5000/v1.0/') == {}1328 assert get_environ_proxies('http://www.requests.com/') != {}13291330 def test_select_proxies(self):1331 """Make sure we can select per-host proxies correctly."""1332 from requests.utils import select_proxy1333 proxies = {'http': 'http://http.proxy',1334 'http://some.host': 'http://some.host.proxy'}1335 assert select_proxy('hTTp://u:p@Some.Host/path', proxies) == 'http://some.host.proxy'1336 assert select_proxy('hTTp://u:p@Other.Host/path', proxies) == 'http://http.proxy'1337 assert select_proxy('hTTps://Other.Host', proxies) is None13381339 def test_guess_filename_when_int(self):1340 from requests.utils import guess_filename1341 assert None is guess_filename(1)13421343 def test_guess_filename_when_filename_is_an_int(self):1344 from requests.utils import guess_filename1345 fake = type('Fake', (object,), {'name': 1})()1346 assert None is guess_filename(fake)13471348 def test_guess_filename_with_file_like_obj(self):1349 from requests.utils import guess_filename1350 from requests import compat1351 fake = type('Fake', (object,), {'name': b'value'})()1352 guessed_name = guess_filename(fake)1353 assert b'value' == guessed_name1354 assert isinstance(guessed_name, compat.bytes)13551356 def test_guess_filename_with_unicode_name(self):1357 from requests.utils import guess_filename1358 from requests import compat1359 filename = b'value'.decode('utf-8')1360 fake = type('Fake', (object,), {'name': filename})()1361 guessed_name = guess_filename(fake)1362 assert filename == guessed_name1363 assert isinstance(guessed_name, compat.str)13641365 def test_is_ipv4_address(self):1366 from requests.utils import is_ipv4_address1367 assert is_ipv4_address('8.8.8.8')1368 assert not is_ipv4_address('8.8.8.8.8')1369 assert not is_ipv4_address('localhost.localdomain')13701371 def test_is_valid_cidr(self):1372 from requests.utils import is_valid_cidr1373 assert not is_valid_cidr('8.8.8.8')1374 assert is_valid_cidr('192.168.1.0/24')13751376 def test_dotted_netmask(self):1377 from requests.utils import dotted_netmask1378 assert dotted_netmask(8) == '255.0.0.0'1379 assert dotted_netmask(24) == '255.255.255.0'1380 assert dotted_netmask(25) == '255.255.255.128'13811382 def test_address_in_network(self):1383 from requests.utils import address_in_network1384 assert address_in_network('192.168.1.1', '192.168.1.0/24')1385 assert not address_in_network('172.16.0.1', '192.168.1.0/24')13861387 def test_get_auth_from_url(self):1388 """Ensures that username and password in well-encoded URI as per1389 RFC 3986 are correclty extracted."""1390 from requests.utils import get_auth_from_url1391 from requests.compat import quote1392 percent_encoding_test_chars = "%!*'();:@&=+$,/?#[] "1393 url_address = "request.com/url.html#test"1394 url = "http://" + quote(1395 percent_encoding_test_chars, '') + ':' + quote(1396 percent_encoding_test_chars, '') + '@' + url_address1397 (username, password) = get_auth_from_url(url)1398 assert username == percent_encoding_test_chars1399 assert password == percent_encoding_test_chars14001401 def test_requote_uri_with_unquoted_percents(self):1402 """Ensure we handle unquoted percent signs in redirects.14031404 See: https://github.com/kennethreitz/requests/issues/23561405 """1406 from requests.utils import requote_uri1407 bad_uri = 'http://example.com/fiz?buz=%ppicture'1408 quoted = 'http://example.com/fiz?buz=%25ppicture'1409 assert quoted == requote_uri(bad_uri)14101411 def test_requote_uri_properly_requotes(self):1412 """Ensure requoting doesn't break expectations."""1413 from requests.utils import requote_uri1414 quoted = 'http://example.com/fiz?buz=%25ppicture'1415 assert quoted == requote_uri(quoted)141614171418class TestMorselToCookieExpires(unittest.TestCase):14191420 """Tests for morsel_to_cookie when morsel contains expires."""14211422 def test_expires_valid_str(self):1423 """Test case where we convert expires from string time."""14241425 morsel = Morsel()1426 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1427 cookie = morsel_to_cookie(morsel)1428 assert cookie.expires == 114291430 def test_expires_invalid_int(self):1431 """Test case where an invalid type is passed for expires."""14321433 morsel = Morsel()1434 morsel['expires'] = 1001435 with pytest.raises(TypeError):1436 morsel_to_cookie(morsel)14371438 def test_expires_invalid_str(self):1439 """Test case where an invalid string is input."""14401441 morsel = Morsel()1442 morsel['expires'] = 'woops'1443 with pytest.raises(ValueError):1444 morsel_to_cookie(morsel)14451446 def test_expires_none(self):1447 """Test case where expires is None."""14481449 morsel = Morsel()1450 morsel['expires'] = None1451 cookie = morsel_to_cookie(morsel)1452 assert cookie.expires is None145314541455class TestMorselToCookieMaxAge(unittest.TestCase):14561457 """Tests for morsel_to_cookie when morsel contains max-age."""14581459 def test_max_age_valid_int(self):1460 """Test case where a valid max age in seconds is passed."""14611462 morsel = Morsel()1463 morsel['max-age'] = 601464 cookie = morsel_to_cookie(morsel)1465 assert isinstance(cookie.expires, int)14661467 def test_max_age_invalid_str(self):1468 """Test case where a invalid max age is passed."""14691470 morsel = Morsel()1471 morsel['max-age'] = 'woops'1472 with pytest.raises(TypeError):1473 morsel_to_cookie(morsel)147414751476class TestTimeout:1477 def test_stream_timeout(self):1478 try:1479 requests.get(httpbin('delay/10'), timeout=2.0)1480 except requests.exceptions.Timeout as e:1481 assert 'Read timed out' in e.args[0].args[0]14821483 def test_invalid_timeout(self):1484 with pytest.raises(ValueError) as e:1485 requests.get(httpbin('get'), timeout=(3, 4, 5))1486 assert '(connect, read)' in str(e)14871488 with pytest.raises(ValueError) as e:1489 requests.get(httpbin('get'), timeout="foo")1490 assert 'must be an int or float' in str(e)14911492 def test_none_timeout(self):1493 """ Check that you can set None as a valid timeout value.14941495 To actually test this behavior, we'd want to check that setting the1496 timeout to None actually lets the request block past the system default1497 timeout. However, this would make the test suite unbearably slow.1498 Instead we verify that setting the timeout to None does not prevent the1499 request from succeeding.1500 """1501 r = requests.get(httpbin('get'), timeout=None)1502 assert r.status_code == 20015031504 def test_read_timeout(self):1505 try:1506 requests.get(httpbin('delay/10'), timeout=(None, 0.1))1507 assert False, "The recv() request should time out."1508 except ReadTimeout:1509 pass15101511 def test_connect_timeout(self):1512 try:1513 requests.get(TARPIT, timeout=(0.1, None))1514 assert False, "The connect() request should time out."1515 except ConnectTimeout as e:1516 assert isinstance(e, ConnectionError)1517 assert isinstance(e, Timeout)15181519 def test_total_timeout_connect(self):1520 try:1521 requests.get(TARPIT, timeout=(0.1, 0.1))1522 assert False, "The connect() request should time out."1523 except ConnectTimeout:1524 pass15251526 def test_encoded_methods(self):1527 """See: https://github.com/kennethreitz/requests/issues/2316"""1528 r = requests.request(b'GET', httpbin('get'))1529 assert r.ok153015311532SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))153315341535class RedirectSession(SessionRedirectMixin):1536 def __init__(self, order_of_redirects):1537 self.redirects = order_of_redirects1538 self.calls = []1539 self.max_redirects = 301540 self.cookies = {}1541 self.trust_env = False15421543 def send(self, *args, **kwargs):1544 self.calls.append(SendCall(args, kwargs))1545 return self.build_response()15461547 def build_response(self):1548 request = self.calls[-1].args[0]1549 r = requests.Response()15501551 try:1552 r.status_code = int(self.redirects.pop(0))1553 except IndexError:1554 r.status_code = 20015551556 r.headers = CaseInsensitiveDict({'Location': '/'})1557 r.raw = self._build_raw()1558 r.request = request1559 return r15601561 def _build_raw(self):1562 string = StringIO.StringIO('')1563 setattr(string, 'release_conn', lambda *args: args)1564 return string156515661567class TestRedirects:1568 default_keyword_args = {1569 'stream': False,1570 'verify': True,1571 'cert': None,1572 'timeout': None,1573 'allow_redirects': False,1574 'proxies': {},1575 }15761577 def test_requests_are_updated_each_time(self):1578 session = RedirectSession([303, 307])1579 prep = requests.Request('POST', httpbin('post')).prepare()1580 r0 = session.send(prep)1581 assert r0.request.method == 'POST'1582 assert session.calls[-1] == SendCall((r0.request,), {})1583 redirect_generator = session.resolve_redirects(r0, prep)1584 for response in redirect_generator:1585 assert response.request.method == 'GET'1586 send_call = SendCall((response.request,),1587 TestRedirects.default_keyword_args)1588 assert session.calls[-1] == send_call1589159015911592@pytest.fixture1593def list_of_tuples():1594 return [1595 (('a', 'b'), ('c', 'd')),1596 (('c', 'd'), ('a', 'b')),1597 (('a', 'b'), ('c', 'd'), ('e', 'f')),1598 ]159916001601def test_data_argument_accepts_tuples(list_of_tuples):1602 """1603 Ensure that the data argument will accept tuples of strings1604 and properly encode them.1605 """1606 for data in list_of_tuples:1607 p = PreparedRequest()1608 p.prepare(1609 method='GET',1610 url='http://www.example.com',1611 data=data,1612 hooks=default_hooks()1613 )1614 assert p.body == urlencode(data)161516161617def assert_copy(p, p_copy):1618 for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):1619 assert getattr(p, attr) == getattr(p_copy, attr)162016211622def test_prepared_request_empty_copy():1623 p = PreparedRequest()1624 assert_copy(p, p.copy())162516261627def test_prepared_request_no_cookies_copy():1628 p = PreparedRequest()1629 p.prepare(1630 method='GET',1631 url='http://www.example.com',1632 data='foo=bar',1633 hooks=default_hooks()1634 )1635 assert_copy(p, p.copy())163616371638def test_prepared_request_complete_copy():1639 p = PreparedRequest()1640 p.prepare(1641 method='GET',1642 url='http://www.example.com',1643 data='foo=bar',1644 hooks=default_hooks(),1645 cookies={'foo': 'bar'}1646 )1647 assert_copy(p, p.copy())164816491650def test_prepare_unicode_url():1651 p = PreparedRequest()1652 p.prepare(1653 method='GET',1654 url=u('http://www.example.com/üniçø∂é'),1655 )1656 assert_copy(p, p.copy())165716581659def test_urllib3_retries():1660 from requests.packages.urllib3.util import Retry1661 s = requests.Session()1662 s.mount('http://', HTTPAdapter(max_retries=Retry(1663 total=2, status_forcelist=[500]1664 )))16651666 with pytest.raises(RetryError):1667 s.get(httpbin('status/500'))16681669def test_vendor_aliases():1670 from requests.packages import urllib31671 from requests.packages import chardet16721673 with pytest.raises(ImportError):1674 from requests.packages import webbrowser16751676if __name__ == '__main__':1677 unittest.main()