test_requests.py
This file
Path
test_requests.py
1,668 lines · 55.9 KiB · Python
Last changed by
Merge pull request #2743 from sigmavirus24/fix-py26-testsCory Benfieldbefore adoptione579252
History of this fileTake it
The walk stopped after 200 commits: lines older than 2c262de point at it.
Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 1–11why, one step back1#!/usr/bin/env python2# -*- coding: utf-8 -*-34"""Tests for Requests."""56from __future__ import division7import json8import os9import pickle10import unittest11import collectionsMerge pull request #2610 from colindickson/masterCory Benfieldbefore adoptiondfdf371
line 12why, one step back12import contextlibMerge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 13–19why, one step back1314import io15import requests16import pytest17from requests.adapters import HTTPAdapter18from requests.auth import HTTPDigestAuth, _basic_auth_str19from requests.compat import (Merge pull request #2743 from sigmavirus24/fix-py26-testsCory Benfieldbefore adoptione579252
lines 20–22why, one step back20 Morsel, cookielib, getproxies, str, urljoin, urlparse, is_py3,21 builtin_str, OrderedDict22 )Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
line 23why, one step back23from requests.cookies import cookiejar_from_dict, morsel_to_cookieMerge pull request #2222 from blueyed/fix-MissingScheme-for-hostportCory Benfieldbefore adoption1a44a99
lines 24–25why, one step back24from requests.exceptions import (ConnectionError, ConnectTimeout,25 InvalidSchema, InvalidURL, MissingSchema,Merge pull request #2216 from sigmavirus24/retries-take-2Kenneth Reitzbefore adoption90857b8
line 26why, one step back26 ReadTimeout, Timeout, RetryError)Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 27–45why, one step back27from 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')4445Merge pull request #2176 from kevinburke/connectKenneth Reitzbefore adoption32e403a
lines 46–48why, one step back46# Requests to this URL should always fail with a connection timeout (nothing47# listening on that port)48TARPIT = "http://10.255.255.1"Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 49–84why, one step back49HTTPBIN = 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')Merge pull request #2222 from blueyed/fix-MissingScheme-for-hostportCory Benfieldbefore adoption1a44a99
lines 85–90why, one step back85 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/')Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 91–108why, one step back91 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.headers108Merge pull request #2332 from asnelzin/fix-2329Kenneth Reitzbefore adoption45ef1f8
lines 109–116why, one step back109 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'116Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 117–129why, one step back117 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"129Merge pull request #2706 from ak1r4/fix-merge-settingIan Cordascobefore adoption53ea231
line 130why, one step back130 def test_params_original_order_is_preserved_by_default(self):Merge pull request #2743 from sigmavirus24/fix-py26-testsCory Benfieldbefore adoptione579252
line 131why, one step back131 param_ordered_dict = OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))Merge pull request #2706 from ak1r4/fix-merge-settingIan Cordascobefore adoption53ea231
lines 132–136why, one step back132 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'136Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 137–270why, one step back137 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'] = NoneMerge pull request #2363 from sigmavirus24/fix-testsKenneth Reitzbefore adoption4e90aa7
line 271why, one step back271 req = requests.Request('GET', httpbin('get'))Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 272–313why, one step back272 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 == 200313Merge pull request #2436 from colindickson/masterCory Benfieldbefore adoption69b7c45
line 314why, one step back314 def test_connection_error_invalid_domain(self):Merge pull request #2193 from sigmavirus24/bug/2192Kenneth Reitzbefore adoption1324ca1
lines 315–316why, one step back315 """Connecting to an unknown domain should raise a ConnectionError"""316 with pytest.raises(ConnectionError):Merge pull request #2436 from colindickson/masterCory Benfieldbefore adoption69b7c45
line 317why, one step back317 requests.get("http://doesnotexist.google.com")Merge pull request #2193 from sigmavirus24/bug/2192Kenneth Reitzbefore adoption1324ca1
line 318why, one step back318Merge pull request #2436 from colindickson/masterCory Benfieldbefore adoption69b7c45
lines 319–320why, one step back319 def test_connection_error_invalid_port(self):320 """Connecting to an invalid port should raise a ConnectionError"""Merge pull request #2193 from sigmavirus24/bug/2192Kenneth Reitzbefore adoption1324ca1
line 321why, one step back321 with pytest.raises(ConnectionError):Merge pull request #2438 from colindickson/masterCory Benfieldbefore adoption426493f
line 322why, one step back322 requests.get("http://httpbin.org:1", timeout=1)Merge pull request #2193 from sigmavirus24/bug/2192Kenneth Reitzbefore adoption1324ca1
line 323why, one step back323Merge branch 'master' of https://github.com/ContinuousFunction/requests into pr/2344Ian Cordascobefore adoption386c589
lines 324–328why, one step back324 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")328Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 329–618why, one step back329 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'618Merge pull request #2238 from buttscicles/byte-urlsKenneth Reitzbefore adoptione74791d
lines 619–624why, one step back619 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/"624Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 625–771why, one step back625 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()Merge pull request #2148 from romanlevin/handle-socket-error-in-iter_contentKenneth Reitzbefore adoption3eb69be
line 772why, one step back772Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 773–947why, one step back773 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']947Merge pull request #2468 from scholer/masterIan Cordascobefore adoption61f4faa
lines 948–960why, one step back948 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']960Merge pull request #2379 from arthurdarcet/masterIan Cordascobefore adoptiona8205bb
lines 961–968why, one step back961 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']968Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 969–976why, one step back969 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'] == length976Merge pull request #2223 from blueyed/doc-followup-2222Ian Cordascobefore adoption9b41308
line 977why, one step back977 def test_nonhttp_schemes_dont_check_URLs(self):Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 978–1047why, one step back978 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"1047Merge pull request #2168 from ContinuousFunction/masterKenneth Reitzbefore adoptionaa6650a
line 1048why, one step back1048 def test_requests_history_is_saved(self):Merge pull request #2363 from sigmavirus24/fix-testsKenneth Reitzbefore adoption4e90aa7
line 1049why, one step back1049 r = requests.get(httpbin('redirect/5'))Merge pull request #2168 from ContinuousFunction/masterKenneth Reitzbefore adoptionaa6650a
lines 1050–1053why, one step back1050 total = r.history[-1].history1051 i = 01052 for item in r.history:1053 assert item.history == total[0:i]Merge pull request #2363 from sigmavirus24/fix-testsKenneth Reitzbefore adoption4e90aa7
line 1054why, one step back1054 i = i + 1Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
line 1055why, one step back1055Merge pull request #2258 from willingc/add-jsonKenneth Reitzbefore adoption1e79cf6
lines 1056–1064why, one step back1056 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']1064Merge pull request #2478 from plaes/iter-linesCory Benfieldbefore adoption14b653a
lines 1065–1071why, one step back1065 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)) == 3Merge pull request #2610 from colindickson/masterCory Benfieldbefore adoptiondfdf371
lines 1072–1078why, one step back10721073 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 pass1078Merge branch 'colindickson-master'Cory Benfieldbefore adoption8b5e457
lines 1079–1080why, one step back1079 self.assertFalse(response._content_consumed)1080 self.assertTrue(response.raw.closed)Merge pull request #2478 from plaes/iter-linesCory Benfieldbefore adoption14b653a
lines 1081–1090why, one step back10811082 @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())) == 31090Merge pull request #2168 from ContinuousFunction/masterKenneth Reitzbefore adoptionaa6650a
line 1091why, one step back1091Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 1092–1235why, one step back1092class 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'}Merge pull request #2666 from gvangool/extra_testsCory Benfieldbefore adoption2b26489
line 1236why, one step back1236 assert cid != object()Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 1237–1272why, one step back12371238 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) == keysetMerge pull request #2666 from gvangool/extra_testsCory Benfieldbefore adoption2b26489
lines 1273–1283why, one step back12731274 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_copy1283Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 1284–1329why, one step back12841285class 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/') != {}1329Merge pull request #2413 from sigmavirus24/bug/2411Kenneth Reitzbefore adoption3314eb9
lines 1330–1355why, one step back1330 def test_guess_filename_when_int(self):1331 from requests.utils import guess_filename1332 assert None is guess_filename(1)13331334 def test_guess_filename_when_filename_is_an_int(self):1335 from requests.utils import guess_filename1336 fake = type('Fake', (object,), {'name': 1})()1337 assert None is guess_filename(fake)13381339 def test_guess_filename_with_file_like_obj(self):1340 from requests.utils import guess_filename1341 from requests import compat1342 fake = type('Fake', (object,), {'name': b'value'})()1343 guessed_name = guess_filename(fake)1344 assert b'value' == guessed_name1345 assert isinstance(guessed_name, compat.bytes)13461347 def test_guess_filename_with_unicode_name(self):1348 from requests.utils import guess_filename1349 from requests import compat1350 filename = b'value'.decode('utf-8')1351 fake = type('Fake', (object,), {'name': filename})()1352 guessed_name = guess_filename(fake)1353 assert filename == guessed_name1354 assert isinstance(guessed_name, compat.str)1355Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 1356–1391why, one step back1356 def test_is_ipv4_address(self):1357 from requests.utils import is_ipv4_address1358 assert is_ipv4_address('8.8.8.8')1359 assert not is_ipv4_address('8.8.8.8.8')1360 assert not is_ipv4_address('localhost.localdomain')13611362 def test_is_valid_cidr(self):1363 from requests.utils import is_valid_cidr1364 assert not is_valid_cidr('8.8.8.8')1365 assert is_valid_cidr('192.168.1.0/24')13661367 def test_dotted_netmask(self):1368 from requests.utils import dotted_netmask1369 assert dotted_netmask(8) == '255.0.0.0'1370 assert dotted_netmask(24) == '255.255.255.0'1371 assert dotted_netmask(25) == '255.255.255.128'13721373 def test_address_in_network(self):1374 from requests.utils import address_in_network1375 assert address_in_network('192.168.1.1', '192.168.1.0/24')1376 assert not address_in_network('172.16.0.1', '192.168.1.0/24')13771378 def test_get_auth_from_url(self):1379 """Ensures that username and password in well-encoded URI as per1380 RFC 3986 are correclty extracted."""1381 from requests.utils import get_auth_from_url1382 from requests.compat import quote1383 percent_encoding_test_chars = "%!*'();:@&=+$,/?#[] "1384 url_address = "request.com/url.html#test"1385 url = "http://" + quote(1386 percent_encoding_test_chars, '') + ':' + quote(1387 percent_encoding_test_chars, '') + '@' + url_address1388 (username, password) = get_auth_from_url(url)1389 assert username == percent_encoding_test_chars1390 assert password == percent_encoding_test_chars1391Merge pull request #2393 from sigmavirus24/bug/2356Kenneth Reitzbefore adoptionb137472
lines 1392–1407why, one step back1392 def test_requote_uri_with_unquoted_percents(self):1393 """Ensure we handle unquoted percent signs in redirects.13941395 See: https://github.com/kennethreitz/requests/issues/23561396 """1397 from requests.utils import requote_uri1398 bad_uri = 'http://example.com/fiz?buz=%ppicture'1399 quoted = 'http://example.com/fiz?buz=%25ppicture'1400 assert quoted == requote_uri(bad_uri)14011402 def test_requote_uri_properly_requotes(self):1403 """Ensure requoting doesn't break expectations."""1404 from requests.utils import requote_uri1405 quoted = 'http://example.com/fiz?buz=%25ppicture'1406 assert quoted == requote_uri(quoted)1407Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 1408–1469why, one step back14081409class TestMorselToCookieExpires(unittest.TestCase):14101411 """Tests for morsel_to_cookie when morsel contains expires."""14121413 def test_expires_valid_str(self):1414 """Test case where we convert expires from string time."""14151416 morsel = Morsel()1417 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1418 cookie = morsel_to_cookie(morsel)1419 assert cookie.expires == 114201421 def test_expires_invalid_int(self):1422 """Test case where an invalid type is passed for expires."""14231424 morsel = Morsel()1425 morsel['expires'] = 1001426 with pytest.raises(TypeError):1427 morsel_to_cookie(morsel)14281429 def test_expires_invalid_str(self):1430 """Test case where an invalid string is input."""14311432 morsel = Morsel()1433 morsel['expires'] = 'woops'1434 with pytest.raises(ValueError):1435 morsel_to_cookie(morsel)14361437 def test_expires_none(self):1438 """Test case where expires is None."""14391440 morsel = Morsel()1441 morsel['expires'] = None1442 cookie = morsel_to_cookie(morsel)1443 assert cookie.expires is None144414451446class TestMorselToCookieMaxAge(unittest.TestCase):14471448 """Tests for morsel_to_cookie when morsel contains max-age."""14491450 def test_max_age_valid_int(self):1451 """Test case where a valid max age in seconds is passed."""14521453 morsel = Morsel()1454 morsel['max-age'] = 601455 cookie = morsel_to_cookie(morsel)1456 assert isinstance(cookie.expires, int)14571458 def test_max_age_invalid_str(self):1459 """Test case where a invalid max age is passed."""14601461 morsel = Morsel()1462 morsel['max-age'] = 'woops'1463 with pytest.raises(TypeError):1464 morsel_to_cookie(morsel)146514661467class TestTimeout:1468 def test_stream_timeout(self):1469 try:Merge pull request #2363 from sigmavirus24/fix-testsKenneth Reitzbefore adoption4e90aa7
line 1470why, one step back1470 requests.get(httpbin('delay/10'), timeout=2.0)Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 1471–1472why, one step back1471 except requests.exceptions.Timeout as e:1472 assert 'Read timed out' in e.args[0].args[0]Merge pull request #2176 from kevinburke/connectKenneth Reitzbefore adoption32e403a
lines 1473–1515why, one step back14731474 def test_invalid_timeout(self):1475 with pytest.raises(ValueError) as e:1476 requests.get(httpbin('get'), timeout=(3, 4, 5))1477 assert '(connect, read)' in str(e)14781479 with pytest.raises(ValueError) as e:1480 requests.get(httpbin('get'), timeout="foo")1481 assert 'must be an int or float' in str(e)14821483 def test_none_timeout(self):1484 """ Check that you can set None as a valid timeout value.14851486 To actually test this behavior, we'd want to check that setting the1487 timeout to None actually lets the request block past the system default1488 timeout. However, this would make the test suite unbearably slow.1489 Instead we verify that setting the timeout to None does not prevent the1490 request from succeeding.1491 """1492 r = requests.get(httpbin('get'), timeout=None)1493 assert r.status_code == 20014941495 def test_read_timeout(self):1496 try:1497 requests.get(httpbin('delay/10'), timeout=(None, 0.1))1498 assert False, "The recv() request should time out."1499 except ReadTimeout:1500 pass15011502 def test_connect_timeout(self):1503 try:1504 requests.get(TARPIT, timeout=(0.1, None))1505 assert False, "The connect() request should time out."1506 except ConnectTimeout as e:1507 assert isinstance(e, ConnectionError)1508 assert isinstance(e, Timeout)15091510 def test_total_timeout_connect(self):1511 try:1512 requests.get(TARPIT, timeout=(0.1, 0.1))1513 assert False, "The connect() request should time out."1514 except ConnectTimeout:1515 passMerge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
line 1516why, one step back1516Merge pull request #2317 from sigmavirus24/bug/2316Kenneth Reitzbefore adoption124c094
lines 1517–1521why, one step back1517 def test_encoded_methods(self):1518 """See: https://github.com/kennethreitz/requests/issues/2316"""1519 r = requests.request(b'GET', httpbin('get'))1520 assert r.ok1521Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 1522–1569why, one step back15221523SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))152415251526class RedirectSession(SessionRedirectMixin):1527 def __init__(self, order_of_redirects):1528 self.redirects = order_of_redirects1529 self.calls = []1530 self.max_redirects = 301531 self.cookies = {}1532 self.trust_env = False15331534 def send(self, *args, **kwargs):1535 self.calls.append(SendCall(args, kwargs))1536 return self.build_response()15371538 def build_response(self):1539 request = self.calls[-1].args[0]1540 r = requests.Response()15411542 try:1543 r.status_code = int(self.redirects.pop(0))1544 except IndexError:1545 r.status_code = 20015461547 r.headers = CaseInsensitiveDict({'Location': '/'})1548 r.raw = self._build_raw()1549 r.request = request1550 return r15511552 def _build_raw(self):1553 string = StringIO.StringIO('')1554 setattr(string, 'release_conn', lambda *args: args)1555 return string155615571558class TestRedirects:1559 default_keyword_args = {1560 'stream': False,1561 'verify': True,1562 'cert': None,1563 'timeout': None,1564 'allow_redirects': False,1565 'proxies': {},1566 }15671568 def test_requests_are_updated_each_time(self):1569 session = RedirectSession([303, 307])Merge pull request #2363 from sigmavirus24/fix-testsKenneth Reitzbefore adoption4e90aa7
line 1570why, one step back1570 prep = requests.Request('POST', httpbin('post')).prepare()Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 1571–1579why, one step back1571 r0 = session.send(prep)1572 assert r0.request.method == 'POST'1573 assert session.calls[-1] == SendCall((r0.request,), {})1574 redirect_generator = session.resolve_redirects(r0, prep)1575 for response in redirect_generator:1576 assert response.request.method == 'GET'1577 send_call = SendCall((response.request,),1578 TestRedirects.default_keyword_args)1579 assert session.calls[-1] == send_callMerge pull request #2168 from ContinuousFunction/masterKenneth Reitzbefore adoptionaa6650a
line 1580why, one step back1580Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 1581–1639why, one step back158115821583@pytest.fixture1584def list_of_tuples():1585 return [1586 (('a', 'b'), ('c', 'd')),1587 (('c', 'd'), ('a', 'b')),1588 (('a', 'b'), ('c', 'd'), ('e', 'f')),1589 ]159015911592def test_data_argument_accepts_tuples(list_of_tuples):1593 """1594 Ensure that the data argument will accept tuples of strings1595 and properly encode them.1596 """1597 for data in list_of_tuples:1598 p = PreparedRequest()1599 p.prepare(1600 method='GET',1601 url='http://www.example.com',1602 data=data,1603 hooks=default_hooks()1604 )1605 assert p.body == urlencode(data)160616071608def assert_copy(p, p_copy):1609 for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):1610 assert getattr(p, attr) == getattr(p_copy, attr)161116121613def test_prepared_request_empty_copy():1614 p = PreparedRequest()1615 assert_copy(p, p.copy())161616171618def test_prepared_request_no_cookies_copy():1619 p = PreparedRequest()1620 p.prepare(1621 method='GET',1622 url='http://www.example.com',1623 data='foo=bar',1624 hooks=default_hooks()1625 )1626 assert_copy(p, p.copy())162716281629def test_prepared_request_complete_copy():1630 p = PreparedRequest()1631 p.prepare(1632 method='GET',1633 url='http://www.example.com',1634 data='foo=bar',1635 hooks=default_hooks(),1636 cookies={'foo': 'bar'}1637 )1638 assert_copy(p, p.copy())1639Merge pull request #2216 from sigmavirus24/retries-take-2Kenneth Reitzbefore adoption90857b8
line 1640why, one step back1640Merge pull request #2267 from minrk/unicode-url-py2Kenneth Reitzbefore adoption4ec26da
lines 1641–1644why, one step back1641def test_prepare_unicode_url():1642 p = PreparedRequest()1643 p.prepare(1644 method='GET',Merge pull request #2306 from ssadler/fix-failing-test-test_prepare_unicode_urlIan Cordascobefore adoption091991b
line 1645why, one step back1645 url=u('http://www.example.com/üniçø∂é'),Merge pull request #2267 from minrk/unicode-url-py2Kenneth Reitzbefore adoption4ec26da
lines 1646–1647why, one step back1646 )1647 assert_copy(p, p.copy())Merge pull request #2216 from sigmavirus24/retries-take-2Kenneth Reitzbefore adoption90857b8
lines 1648–1652why, one step back164816491650def test_urllib3_retries():1651 from requests.packages.urllib3.util import Retry1652 s = requests.Session()Merge pull request #2363 from sigmavirus24/fix-testsKenneth Reitzbefore adoption4e90aa7
line 1653why, one step back1653 s.mount('http://', HTTPAdapter(max_retries=Retry(Merge pull request #2216 from sigmavirus24/retries-take-2Kenneth Reitzbefore adoption90857b8
lines 1654–1657why, one step back1654 total=2, status_forcelist=[500]1655 )))16561657 with pytest.raises(RetryError):Merge pull request #2363 from sigmavirus24/fix-testsKenneth Reitzbefore adoption4e90aa7
line 1658why, one step back1658 s.get(httpbin('status/500'))Merge pull request #2267 from minrk/unicode-url-py2Kenneth Reitzbefore adoption4ec26da
line 1659why, one step back1659Merge pull request #2466 from sigmavirus24/bug/2465Ian Cordascobefore adoption39e49e5
lines 1660–1666why, one step back1660def test_vendor_aliases():1661 from requests.packages import urllib31662 from requests.packages import chardet16631664 with pytest.raises(ImportError):1665 from requests.packages import webbrowser1666Merge pull request #2090 from ericfrederich/fix_308Kenneth Reitzbefore adoption2c262de
lines 1667–1668why, one step back1667if __name__ == '__main__':1668 unittest.main()