test_requests.py
This file
Path
tests/test_requests.py
2,295 lines · 78.7 KiB · Python
Last changed by
Merge pull request #3758 from nateprewitt/3753_allow_non_string_params_basic_authCory Benfieldbefore adoption449d748
History of this fileTake it
The walk stopped after 200 commits: lines older than 00c0a80 point at it.
Update README.rstKenneth Reitzbefore adoption00c0a80
lines 1–11why, one step back1#!/usr/bin/env python2# -*- coding: utf-8 -*-34"""Tests for Requests."""56from __future__ import division7import json8import os9import pickle10import collections11import contextlibTest security warnings (#3289)John Vandenbergbefore adoption400d27f
line 12why, one step back12import warningsUpdate README.rstKenneth Reitzbefore adoption00c0a80
lines 13–21why, one step back1314import io15import requests16import pytest17from requests.adapters import HTTPAdapter18from requests.auth import HTTPDigestAuth, _basic_auth_str19from requests.compat import (20 Morsel, cookielib, getproxies, str, urlparse,21 builtin_str, OrderedDict)Merge pull request #3591 from nateprewitt/3579_cookie_mergeCory Benfieldbefore adoption439451c
lines 22–23why, one step back22from requests.cookies import (23 cookiejar_from_dict, morsel_to_cookie, merge_cookies)Update README.rstKenneth Reitzbefore adoption00c0a80
lines 24–25why, one step back24from requests.exceptions import (25 ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,Merge pull request #3059 from alexanderad/proxy-connection-errorsKenneth Reitzbefore adoption03ed671
line 26why, one step back26 MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects,Merge pull request #3655 from nateprewitt/tzickel_post_redirect_w_streamableCory Benfieldbefore adoptionf72684e
line 27why, one step back27 ProxyError, InvalidHeader, UnrewindableBodyError)Update README.rstKenneth Reitzbefore adoption00c0a80
lines 28–34why, one step back28from requests.models import PreparedRequest29from requests.structures import CaseInsensitiveDict30from requests.sessions import SessionRedirectMixin31from requests.models import urlencode32from requests.hooks import default_hooks3334from .compat import StringIO, uMerge pull request #3185 from brettdh/3183-support-all-proxy-env-varIan Cordascobefore adoptioncd4e6b9
line 35why, one step back35from .utils import override_environUpdate README.rstKenneth Reitzbefore adoption00c0a80
lines 36–40why, one step back3637# Requests to this URL should always fail with a connection timeout (nothing38# listening on that port)39TARPIT = 'http://10.255.255.1'40Test security warnings (#3289)John Vandenbergbefore adoption400d27f
lines 41–46why, one step back41try:42 from ssl import SSLContext43 del SSLContext44 HAS_MODERN_SSL = True45except ImportError:46 HAS_MODERN_SSL = FalseUpdate README.rstKenneth Reitzbefore adoption00c0a80
line 47why, one step back47Test security warnings (#3289)John Vandenbergbefore adoption400d27f
lines 48–54why, one step back48try:49 requests.pyopenssl50 HAS_PYOPENSSL = True51except AttributeError:52 HAS_PYOPENSSL = False5354Update README.rstKenneth Reitzbefore adoption00c0a80
lines 55–93why, one step back55class TestRequests:5657 def test_entry_points(self):5859 requests.session60 requests.session().get61 requests.session().head62 requests.get63 requests.head64 requests.put65 requests.patch66 requests.post6768 @pytest.mark.parametrize(69 'exception, url', (70 (MissingSchema, 'hiwpefhipowhefopw'),71 (InvalidSchema, 'localhost:3128'),72 (InvalidSchema, 'localhost.localdomain:3128/'),73 (InvalidSchema, '10.122.1.1:3128/'),74 (InvalidURL, 'http://'),75 ))76 def test_invalid_url(self, exception, url):77 with pytest.raises(exception):78 requests.get(url)7980 def test_basic_building(self):81 req = requests.Request()82 req.url = 'http://kennethreitz.org/'83 req.data = {'life': '42'}8485 pr = req.prepare()86 assert pr.url == req.url87 assert pr.body == 'life=42'8889 @pytest.mark.parametrize('method', ('GET', 'HEAD'))90 def test_no_content_length(self, httpbin, method):91 req = requests.Request(method, httpbin(method.lower())).prepare()92 assert 'Content-Length' not in req.headers93Merge pull request #3545 from nateprewitt/new_prepare_content_lengthIan Cordascobefore adoption9407d69
lines 94–103why, one step back94 @pytest.mark.parametrize('method', ('POST', 'PUT', 'PATCH', 'OPTIONS'))95 def test_no_body_content_length(self, httpbin, method):96 req = requests.Request(method, httpbin(method.lower())).prepare()97 assert req.headers['Content-Length'] == '0'9899 @pytest.mark.parametrize('method', ('POST', 'PUT', 'PATCH', 'OPTIONS'))100 def test_empty_content_length(self, httpbin, method):101 req = requests.Request(method, httpbin(method.lower()), data='').prepare()102 assert req.headers['Content-Length'] == '0'103Update README.rstKenneth Reitzbefore adoption00c0a80
lines 104–142why, one step back104 def test_override_content_length(self, httpbin):105 headers = {106 'Content-Length': 'not zero'107 }108 r = requests.Request('POST', httpbin('post'), headers=headers).prepare()109 assert 'Content-Length' in r.headers110 assert r.headers['Content-Length'] == 'not zero'111112 def test_path_is_not_double_encoded(self):113 request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()114115 assert request.path_url == '/get/test%20case'116117 @pytest.mark.parametrize(118 'url, expected', (119 ('http://example.com/path#fragment', 'http://example.com/path?a=b#fragment'),120 ('http://example.com/path?key=value#fragment', 'http://example.com/path?key=value&a=b#fragment')121 ))122 def test_params_are_added_before_fragment(self, url, expected):123 request = requests.Request('GET', url, params={"a": "b"}).prepare()124 assert request.url == expected125126 def test_params_original_order_is_preserved_by_default(self):127 param_ordered_dict = OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))128 session = requests.Session()129 request = requests.Request('GET', 'http://example.com/', params=param_ordered_dict)130 prep = session.prepare_request(request)131 assert prep.url == 'http://example.com/?z=1&a=1&k=1&d=1'132133 def test_params_bytes_are_encoded(self):134 request = requests.Request('GET', 'http://example.com',135 params=b'test=foo').prepare()136 assert request.url == 'http://example.com/?test=foo'137138 def test_binary_put(self):139 request = requests.Request('PUT', 'http://example.com',140 data=u"ööö".encode("utf-8")).prepare()141 assert isinstance(request.body, bytes)142Merge pull request #3697 from hussaintamboli/masterCory Benfieldbefore adoption1e198f9
lines 143–147why, one step back143 def test_whitespaces_are_removed_from_url(self):144 # Test for issue #3696145 request = requests.Request('GET', ' http://example.com').prepare()146 assert request.url == 'http://example.com/'147Update README.rstKenneth Reitzbefore adoption00c0a80
lines 148–172why, one step back148 @pytest.mark.parametrize('scheme', ('http://', 'HTTP://', 'hTTp://', 'HttP://'))149 def test_mixed_case_scheme_acceptable(self, httpbin, scheme):150 s = requests.Session()151 s.proxies = getproxies()152 parts = urlparse(httpbin('get'))153 url = scheme + parts.netloc + parts.path154 r = requests.Request('GET', url)155 r = s.send(r.prepare())156 assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)157158 def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):159 r = requests.Request('GET', httpbin('get'))160 s = requests.Session()161 s.proxies = getproxies()162163 r = s.send(r.prepare())164165 assert r.status_code == 200166167 def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):168 r = requests.get(httpbin('redirect', '1'))169 assert r.status_code == 200170 assert r.history[0].status_code == 302171 assert r.history[0].is_redirect172Merge pull request #3655 from nateprewitt/tzickel_post_redirect_w_streamableCory Benfieldbefore adoptionf72684e
lines 173–187why, one step back173 def test_HTTP_307_ALLOW_REDIRECT_POST(self, httpbin):174 r = requests.post(httpbin('redirect-to'), data='test', params={'url': 'post', 'status_code': 307})175 assert r.status_code == 200176 assert r.history[0].status_code == 307177 assert r.history[0].is_redirect178 assert r.json()['data'] == 'test'179180 def test_HTTP_307_ALLOW_REDIRECT_POST_WITH_SEEKABLE(self, httpbin):181 byte_str = b'test'182 r = requests.post(httpbin('redirect-to'), data=io.BytesIO(byte_str), params={'url': 'post', 'status_code': 307})183 assert r.status_code == 200184 assert r.history[0].status_code == 307185 assert r.history[0].is_redirect186 assert r.json()['data'] == byte_str.decode('utf-8')187Update README.rstKenneth Reitzbefore adoption00c0a80
lines 188–211why, one step back188 def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):189 try:190 requests.get(httpbin('relative-redirect', '50'))191 except TooManyRedirects as e:192 url = httpbin('relative-redirect', '20')193 assert e.request.url == url194 assert e.response.url == url195 assert len(e.response.history) == 30196 else:197 pytest.fail('Expected redirect to raise TooManyRedirects but it did not')198199 def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):200 s = requests.session()201 s.max_redirects = 5202 try:203 s.get(httpbin('relative-redirect', '50'))204 except TooManyRedirects as e:205 url = httpbin('relative-redirect', '45')206 assert e.request.url == url207 assert e.response.url == url208 assert len(e.response.history) == 5209 else:210 pytest.fail('Expected custom max number of redirects to be respected but was not')211Merge pull request #3060 from benweatherman/masterIan Cordascobefore adoption3acf3a7
lines 212–254why, one step back212 def test_http_301_changes_post_to_get(self, httpbin):213 r = requests.post(httpbin('status', '301'))214 assert r.status_code == 200215 assert r.request.method == 'GET'216 assert r.history[0].status_code == 301217 assert r.history[0].is_redirect218219 def test_http_301_doesnt_change_head_to_get(self, httpbin):220 r = requests.head(httpbin('status', '301'), allow_redirects=True)221 print(r.content)222 assert r.status_code == 200223 assert r.request.method == 'HEAD'224 assert r.history[0].status_code == 301225 assert r.history[0].is_redirect226227 def test_http_302_changes_post_to_get(self, httpbin):228 r = requests.post(httpbin('status', '302'))229 assert r.status_code == 200230 assert r.request.method == 'GET'231 assert r.history[0].status_code == 302232 assert r.history[0].is_redirect233234 def test_http_302_doesnt_change_head_to_get(self, httpbin):235 r = requests.head(httpbin('status', '302'), allow_redirects=True)236 assert r.status_code == 200237 assert r.request.method == 'HEAD'238 assert r.history[0].status_code == 302239 assert r.history[0].is_redirect240241 def test_http_303_changes_post_to_get(self, httpbin):242 r = requests.post(httpbin('status', '303'))243 assert r.status_code == 200244 assert r.request.method == 'GET'245 assert r.history[0].status_code == 303246 assert r.history[0].is_redirect247248 def test_http_303_doesnt_change_head_to_get(self, httpbin):249 r = requests.head(httpbin('status', '303'), allow_redirects=True)250 assert r.status_code == 200251 assert r.request.method == 'HEAD'252 assert r.history[0].status_code == 303253 assert r.history[0].is_redirect254Merge pull request #3493 from nateprewitt/3490_drop_headersIan Cordascobefore adoptionf5ff345
lines 255–294why, one step back255 def test_header_and_body_removal_on_redirect(self, httpbin):256 purged_headers = ('Content-Length', 'Content-Type')257 ses = requests.Session()258 req = requests.Request('POST', httpbin('post'), data={'test': 'data'})259 prep = ses.prepare_request(req)260 resp = ses.send(prep)261262 # Mimic a redirect response263 resp.status_code = 302264 resp.headers['location'] = 'get'265266 # Run request through resolve_redirects267 next_resp = next(ses.resolve_redirects(resp, prep))268 assert next_resp.request.body is None269 for header in purged_headers:270 assert header not in next_resp.request.headers271272 def test_transfer_enc_removal_on_redirect(self, httpbin):273 purged_headers = ('Transfer-Encoding', 'Content-Type')274 ses = requests.Session()275 req = requests.Request('POST', httpbin('post'), data=(b'x' for x in range(1)))276 prep = ses.prepare_request(req)277 assert 'Transfer-Encoding' in prep.headers278279 # Create Response to avoid https://github.com/kevin1024/pytest-httpbin/issues/33280 resp = requests.Response()281 resp.raw = io.BytesIO(b'the content')282 resp.request = prep283 setattr(resp.raw, 'release_conn', lambda *args: args)284285 # Mimic a redirect response286 resp.status_code = 302287 resp.headers['location'] = httpbin('get')288289 # Run request through resolve_redirect290 next_resp = next(ses.resolve_redirects(resp, prep))291 assert next_resp.request.body is None292 for header in purged_headers:293 assert header not in next_resp.request.headers294Update README.rstKenneth Reitzbefore adoption00c0a80
lines 295–376why, one step back295 def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):296 heads = {'User-agent': 'Mozilla/5.0'}297298 r = requests.get(httpbin('user-agent'), headers=heads)299300 assert heads['User-agent'] in r.text301 assert r.status_code == 200302303 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):304 heads = {'User-agent': 'Mozilla/5.0'}305306 r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)307 assert r.status_code == 200308309 def test_set_cookie_on_301(self, httpbin):310 s = requests.session()311 url = httpbin('cookies/set?foo=bar')312 s.get(url)313 assert s.cookies['foo'] == 'bar'314315 def test_cookie_sent_on_redirect(self, httpbin):316 s = requests.session()317 s.get(httpbin('cookies/set?foo=bar'))318 r = s.get(httpbin('redirect/1')) # redirects to httpbin('get')319 assert 'Cookie' in r.json()['headers']320321 def test_cookie_removed_on_expire(self, httpbin):322 s = requests.session()323 s.get(httpbin('cookies/set?foo=bar'))324 assert s.cookies['foo'] == 'bar'325 s.get(326 httpbin('response-headers'),327 params={328 'Set-Cookie':329 'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'330 }331 )332 assert 'foo' not in s.cookies333334 def test_cookie_quote_wrapped(self, httpbin):335 s = requests.session()336 s.get(httpbin('cookies/set?foo="bar:baz"'))337 assert s.cookies['foo'] == '"bar:baz"'338339 def test_cookie_persists_via_api(self, httpbin):340 s = requests.session()341 r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})342 assert 'foo' in r.request.headers['Cookie']343 assert 'foo' in r.history[0].request.headers['Cookie']344345 def test_request_cookie_overrides_session_cookie(self, httpbin):346 s = requests.session()347 s.cookies['foo'] = 'bar'348 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})349 assert r.json()['cookies']['foo'] == 'baz'350 # Session cookie should not be modified351 assert s.cookies['foo'] == 'bar'352353 def test_request_cookies_not_persisted(self, httpbin):354 s = requests.session()355 s.get(httpbin('cookies'), cookies={'foo': 'baz'})356 # Sending a request with cookies should not add cookies to the session357 assert not s.cookies358359 def test_generic_cookiejar_works(self, httpbin):360 cj = cookielib.CookieJar()361 cookiejar_from_dict({'foo': 'bar'}, cj)362 s = requests.session()363 s.cookies = cj364 r = s.get(httpbin('cookies'))365 # Make sure the cookie was sent366 assert r.json()['cookies']['foo'] == 'bar'367 # Make sure the session cj is still the custom one368 assert s.cookies is cj369370 def test_param_cookiejar_works(self, httpbin):371 cj = cookielib.CookieJar()372 cookiejar_from_dict({'foo': 'bar'}, cj)373 s = requests.session()374 r = s.get(httpbin('cookies'), cookies=cj)375 # Make sure the cookie was sent376 assert r.json()['cookies']['foo'] == 'bar'Merge pull request #3591 from nateprewitt/3579_cookie_mergeCory Benfieldbefore adoption439451c
lines 377–408why, one step back377378 def test_cookielib_cookiejar_on_redirect(self, httpbin):379 """Tests resolve_redirect doesn't fail when merging cookies380 with non-RequestsCookieJar cookiejar.381382 See GH #3579383 """384 cj = cookiejar_from_dict({'foo': 'bar'}, cookielib.CookieJar())385 s = requests.Session()386 s.cookies = cookiejar_from_dict({'cookie': 'tasty'})387388 # Prepare request without using Session389 req = requests.Request('GET', httpbin('headers'), cookies=cj)390 prep_req = req.prepare()391392 # Send request and simulate redirect393 resp = s.send(prep_req)394 resp.status_code = 302395 resp.headers['location'] = httpbin('get')396 redirects = s.resolve_redirects(resp, prep_req)397 resp = next(redirects)398399 # Verify CookieJar isn't being converted to RequestsCookieJar400 assert isinstance(prep_req._cookies, cookielib.CookieJar)401 assert isinstance(resp.request._cookies, cookielib.CookieJar)402 assert not isinstance(resp.request._cookies, requests.cookies.RequestsCookieJar)403404 cookies = {}405 for c in resp.request._cookies:406 cookies[c.name] = c.value407 assert cookies['foo'] == 'bar'408 assert cookies['cookie'] == 'tasty'Update README.rstKenneth Reitzbefore adoption00c0a80
lines 409–431why, one step back409410 def test_requests_in_history_are_not_overridden(self, httpbin):411 resp = requests.get(httpbin('redirect/3'))412 urls = [r.url for r in resp.history]413 req_urls = [r.request.url for r in resp.history]414 assert urls == req_urls415416 def test_history_is_always_a_list(self, httpbin):417 """Show that even with redirects, Response.history is always a list."""418 resp = requests.get(httpbin('get'))419 assert isinstance(resp.history, list)420 resp = requests.get(httpbin('redirect/1'))421 assert isinstance(resp.history, list)422 assert not isinstance(resp.history, tuple)423424 def test_headers_on_session_with_None_are_not_sent(self, httpbin):425 """Do not send headers in Session.headers with None values."""426 ses = requests.Session()427 ses.headers['Accept-Encoding'] = None428 req = requests.Request('GET', httpbin('get'))429 prep = ses.prepare_request(req)430 assert 'Accept-Encoding' not in prep.headers431Merge pull request #3096 from piotrjurkiewicz/masterKenneth Reitzbefore adoptionce5e312
lines 432–451why, one step back432 def test_headers_preserve_order(self, httpbin):433 """Preserve order when headers provided as OrderedDict."""434 ses = requests.Session()435 ses.headers = OrderedDict()436 ses.headers['Accept-Encoding'] = 'identity'437 ses.headers['First'] = '1'438 ses.headers['Second'] = '2'439 headers = OrderedDict([('Third', '3'), ('Fourth', '4')])440 headers['Fifth'] = '5'441 headers['Second'] = '222'442 req = requests.Request('GET', httpbin('get'), headers=headers)443 prep = ses.prepare_request(req)444 items = list(prep.headers.items())445 assert items[0] == ('Accept-Encoding', 'identity')446 assert items[1] == ('First', '1')447 assert items[2] == ('Second', '222')448 assert items[3] == ('Third', '3')449 assert items[4] == ('Fourth', '4')450 assert items[5] == ('Fifth', '5')451Update README.rstKenneth Reitzbefore adoption00c0a80
lines 452–483why, one step back452 @pytest.mark.parametrize('key', ('User-agent', 'user-agent'))453 def test_user_agent_transfers(self, httpbin, key):454455 heads = {key: 'Mozilla/5.0 (github.com/kennethreitz/requests)'}456457 r = requests.get(httpbin('user-agent'), headers=heads)458 assert heads[key] in r.text459460 def test_HTTP_200_OK_HEAD(self, httpbin):461 r = requests.head(httpbin('get'))462 assert r.status_code == 200463464 def test_HTTP_200_OK_PUT(self, httpbin):465 r = requests.put(httpbin('put'))466 assert r.status_code == 200467468 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):469 auth = ('user', 'pass')470 url = httpbin('basic-auth', 'user', 'pass')471472 r = requests.get(url, auth=auth)473 assert r.status_code == 200474475 r = requests.get(url)476 assert r.status_code == 401477478 s = requests.session()479 s.auth = auth480 r = s.get(url)481 assert r.status_code == 200482483 @pytest.mark.parametrize(Merge pull request #3673 from klimenko-forks/auth-unicodeCory Benfieldbefore adoptionb9f1c44
lines 484–486why, one step back484 'username, password', (485 ('user', 'pass'),486 (u'имя'.encode('utf-8'), u'пароль'.encode('utf-8')),Merge pull request #3758 from nateprewitt/3753_allow_non_string_params_basic_authCory Benfieldbefore adoption449d748
line 487why, one step back487 (42, 42)Merge pull request #3673 from klimenko-forks/auth-unicodeCory Benfieldbefore adoptionb9f1c44
lines 488–496why, one step back488 ))489 def test_set_basicauth(self, httpbin, username, password):490 auth = (username, password)491 url = httpbin('get')492493 r = requests.Request('GET', url, auth=auth)494 p = r.prepare()495496 assert p.headers['Authorization'] == _basic_auth_str(username, password)Merge pull request #3758 from nateprewitt/3753_allow_non_string_params_basic_authCory Benfieldbefore adoption449d748
lines 497–506why, one step back497498 def test_basicauth_encodes_byte_strings(self):499 """Ensure b'test' formats as the byte string "test" rather500 than the unicode string "b'test'" in Python 3.501 """502 auth = (b'\xc5\xafsername', b'test\xc6\xb6')503 r = requests.Request('GET', 'http://localhost', auth=auth)504 p = r.prepare()505506 assert p.headers['Authorization'] == 'Basic xa9zZXJuYW1lOnRlc3TGtg=='Merge pull request #3673 from klimenko-forks/auth-unicodeCory Benfieldbefore adoptionb9f1c44
lines 507–508why, one step back507508 @pytest.mark.parametrize(Update README.rstKenneth Reitzbefore adoption00c0a80
lines 509–519why, one step back509 'url, exception', (510 # Connecting to an unknown domain should raise a ConnectionError511 ('http://doesnotexist.google.com', ConnectionError),512 # Connecting to an invalid port should raise a ConnectionError513 ('http://localhost:1', ConnectionError),514 # Inputing a URL that cannot be parsed should raise an InvalidURL error515 ('http://fe80::5054:ff:fe5a:fc0', InvalidURL)516 ))517 def test_errors(self, url, exception):518 with pytest.raises(exception):519 requests.get(url, timeout=1)Merge pull request #3059 from alexanderad/proxy-connection-errorsKenneth Reitzbefore adoption03ed671
lines 520–524why, one step back520521 def test_proxy_error(self):522 # any proxy related error (address resolution, no route to host, etc) should result in a ProxyError523 with pytest.raises(ProxyError):524 requests.get('http://localhost:1', proxies={'http': 'non-resolvable-address'})Update README.rstKenneth Reitzbefore adoption00c0a80
lines 525–643why, one step back525526 def test_basicauth_with_netrc(self, httpbin):527 auth = ('user', 'pass')528 wrong_auth = ('wronguser', 'wrongpass')529 url = httpbin('basic-auth', 'user', 'pass')530531 old_auth = requests.sessions.get_netrc_auth532533 try:534 def get_netrc_auth_mock(url):535 return auth536 requests.sessions.get_netrc_auth = get_netrc_auth_mock537538 # Should use netrc and work.539 r = requests.get(url)540 assert r.status_code == 200541542 # Given auth should override and fail.543 r = requests.get(url, auth=wrong_auth)544 assert r.status_code == 401545546 s = requests.session()547548 # Should use netrc and work.549 r = s.get(url)550 assert r.status_code == 200551552 # Given auth should override and fail.553 s.auth = wrong_auth554 r = s.get(url)555 assert r.status_code == 401556 finally:557 requests.sessions.get_netrc_auth = old_auth558559 def test_DIGEST_HTTP_200_OK_GET(self, httpbin):560561 auth = HTTPDigestAuth('user', 'pass')562 url = httpbin('digest-auth', 'auth', 'user', 'pass')563564 r = requests.get(url, auth=auth)565 assert r.status_code == 200566567 r = requests.get(url)568 assert r.status_code == 401569570 s = requests.session()571 s.auth = HTTPDigestAuth('user', 'pass')572 r = s.get(url)573 assert r.status_code == 200574575 def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):576 url = httpbin('digest-auth', 'auth', 'user', 'pass')577 auth = HTTPDigestAuth('user', 'pass')578 r = requests.get(url)579 assert r.cookies['fake'] == 'fake_value'580581 r = requests.get(url, auth=auth)582 assert r.status_code == 200583584 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):585 url = httpbin('digest-auth', 'auth', 'user', 'pass')586 auth = HTTPDigestAuth('user', 'pass')587 s = requests.Session()588 s.get(url, auth=auth)589 assert s.cookies['fake'] == 'fake_value'590591 def test_DIGEST_STREAM(self, httpbin):592593 auth = HTTPDigestAuth('user', 'pass')594 url = httpbin('digest-auth', 'auth', 'user', 'pass')595596 r = requests.get(url, auth=auth, stream=True)597 assert r.raw.read() != b''598599 r = requests.get(url, auth=auth, stream=False)600 assert r.raw.read() == b''601602 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):603604 auth = HTTPDigestAuth('user', 'wrongpass')605 url = httpbin('digest-auth', 'auth', 'user', 'pass')606607 r = requests.get(url, auth=auth)608 assert r.status_code == 401609610 r = requests.get(url)611 assert r.status_code == 401612613 s = requests.session()614 s.auth = auth615 r = s.get(url)616 assert r.status_code == 401617618 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):619620 auth = HTTPDigestAuth('user', 'pass')621 url = httpbin('digest-auth', 'auth', 'user', 'pass')622623 r = requests.get(url, auth=auth)624 assert '"auth"' in r.request.headers['Authorization']625626 def test_POSTBIN_GET_POST_FILES(self, httpbin):627628 url = httpbin('post')629 requests.post(url).raise_for_status()630631 post1 = requests.post(url, data={'some': 'data'})632 assert post1.status_code == 200633634 with open('requirements.txt') as f:635 post2 = requests.post(url, files={'some': f})636 assert post2.status_code == 200637638 post4 = requests.post(url, data='[{"some": "json"}]')639 assert post4.status_code == 200640641 with pytest.raises(ValueError):642 requests.post(url, files=['bad file data'])643Merge pull request #3082 from tzickel/masterIan Cordascobefore adoptione65d6fc
lines 644–685why, one step back644 def test_POSTBIN_SEEKED_OBJECT_WITH_NO_ITER(self, httpbin):645646 class TestStream(object):647 def __init__(self, data):648 self.data = data.encode()649 self.length = len(self.data)650 self.index = 0651652 def __len__(self):653 return self.length654655 def read(self, size=None):656 if size:657 ret = self.data[self.index:self.index + size]658 self.index += size659 else:660 ret = self.data[self.index:]661 self.index = self.length662 return ret663664 def tell(self):665 return self.index666667 def seek(self, offset, where=0):668 if where == 0:669 self.index = offset670 elif where == 1:671 self.index += offset672 elif where == 2:673 self.index = self.length + offset674675 test = TestStream('test')676 post1 = requests.post(httpbin('post'), data=test)677 assert post1.status_code == 200678 assert post1.json()['data'] == 'test'679680 test = TestStream('test')681 test.seek(2)682 post2 = requests.post(httpbin('post'), data=test)683 assert post2.status_code == 200684 assert post2.json()['data'] == 'st'685Update README.rstKenneth Reitzbefore adoption00c0a80
lines 686–694why, one step back686 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):687688 url = httpbin('post')689 requests.post(url).raise_for_status()690691 post1 = requests.post(url, data={'some': 'data'})692 assert post1.status_code == 200693694 with open('requirements.txt') as f:Merge pull request #3428 from nateprewitt/pep8_fixesKenneth Reitzbefore adoption4285bac
line 695why, one step back695 post2 = requests.post(url, data={'some': 'data'}, files={'some': f})Update README.rstKenneth Reitzbefore adoption00c0a80
lines 696–703why, one step back696 assert post2.status_code == 200697698 post4 = requests.post(url, data='[{"some": "json"}]')699 assert post4.status_code == 200700701 with pytest.raises(ValueError):702 requests.post(url, files=['bad file data'])703Merge pull request #3652 from gardiac2002/masterIan Cordascobefore adoption9deb603
lines 704–728why, one step back704 def test_post_with_custom_mapping(self, httpbin):705 class CustomMapping(collections.MutableMapping):706 def __init__(self, *args, **kwargs):707 self.data = dict(*args, **kwargs)708709 def __delitem__(self, key):710 del self.data[key]711712 def __getitem__(self, key):713 return self.data[key]714715 def __setitem__(self, key, value):716 self.data[key] = value717718 def __iter__(self):719 return iter(self.data)720721 def __len__(self):722 return len(self.data)723724 data = CustomMapping({'some': 'data'})725 url = httpbin('post')726 found_json = requests.post(url, data=data).json().get('form')727 assert found_json == {'some': 'data'}728Update README.rstKenneth Reitzbefore adoption00c0a80
lines 729–769why, one step back729 def test_conflicting_post_params(self, httpbin):730 url = httpbin('post')731 with open('requirements.txt') as f:732 pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")733 pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")734735 def test_request_ok_set(self, httpbin):736 r = requests.get(httpbin('status', '404'))737 assert not r.ok738739 def test_status_raising(self, httpbin):740 r = requests.get(httpbin('status', '404'))741 with pytest.raises(requests.exceptions.HTTPError):742 r.raise_for_status()743744 r = requests.get(httpbin('status', '500'))745 assert not r.ok746747 def test_decompress_gzip(self, httpbin):748 r = requests.get(httpbin('gzip'))749 r.content.decode('ascii')750751 @pytest.mark.parametrize(752 'url, params', (753 ('/get', {'foo': 'føø'}),754 ('/get', {'føø': 'føø'}),755 ('/get', {'føø': 'føø'}),756 ('/get', {'foo': 'foo'}),757 ('ø', {'foo': 'foo'}),758 ))759 def test_unicode_get(self, httpbin, url, params):760 requests.get(httpbin(url), params=params)761762 def test_unicode_header_name(self, httpbin):763 requests.put(764 httpbin('put'),765 headers={str('Content-Type'): 'application/octet-stream'},766 data='\xff') # compat.str is unicode.767768 def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):769 requests.get(httpbin_secure('status', '301'), verify=httpbin_ca_bundle)Test security warnings (#3289)John Vandenbergbefore adoption400d27f
lines 770–790why, one step back770771 def test_https_warnings(self, httpbin_secure, httpbin_ca_bundle):772 """warnings are emitted with requests.get"""773 if HAS_MODERN_SSL or HAS_PYOPENSSL:774 warnings_expected = ('SubjectAltNameWarning', )775 else:776 warnings_expected = ('SNIMissingWarning',777 'InsecurePlatformWarning',778 'SubjectAltNameWarning', )779780 with pytest.warns(None) as warning_records:781 warnings.simplefilter('always')782 requests.get(httpbin_secure('status', '200'),783 verify=httpbin_ca_bundle)784785 warning_records = [item for item in warning_records786 if item.category.__name__ != 'ResourceWarning']787788 warnings_category = tuple(789 item.category.__name__ for item in warning_records)790 assert warnings_category == warnings_expectedUpdate README.rstKenneth Reitzbefore adoption00c0a80
lines 791–844why, one step back791792 def test_urlencoded_get_query_multivalued_param(self, httpbin):793794 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))795 assert r.status_code == 200796 assert r.url == httpbin('get?test=foo&test=baz')797798 def test_different_encodings_dont_break_post(self, httpbin):799 r = requests.post(httpbin('post'),800 data={'stuff': json.dumps({'a': 123})},801 params={'blah': 'asdf1234'},802 files={'file': ('test_requests.py', open(__file__, 'rb'))})803 assert r.status_code == 200804805 @pytest.mark.parametrize(806 'data', (807 {'stuff': u('ëlïxr')},808 {'stuff': u('ëlïxr').encode('utf-8')},809 {'stuff': 'elixr'},810 {'stuff': 'elixr'.encode('utf-8')},811 ))812 def test_unicode_multipart_post(self, httpbin, data):813 r = requests.post(httpbin('post'),814 data=data,815 files={'file': ('test_requests.py', open(__file__, 'rb'))})816 assert r.status_code == 200817818 def test_unicode_multipart_post_fieldnames(self, httpbin):819 filename = os.path.splitext(__file__)[0] + '.py'820 r = requests.Request(821 method='POST', url=httpbin('post'),822 data={'stuff'.encode('utf-8'): 'elixr'},823 files={'file': ('test_requests.py', open(filename, 'rb'))})824 prep = r.prepare()825 assert b'name="stuff"' in prep.body826 assert b'name="b\'stuff\'"' not in prep.body827828 def test_unicode_method_name(self, httpbin):829 files = {'file': open(__file__, 'rb')}830 r = requests.request(831 method=u('POST'), url=httpbin('post'), files=files)832 assert r.status_code == 200833834 def test_unicode_method_name_with_request_object(self, httpbin):835 files = {'file': open(__file__, 'rb')}836 s = requests.Session()837 req = requests.Request(u('POST'), httpbin('post'), files=files)838 prep = s.prepare_request(req)839 assert isinstance(prep.method, builtin_str)840 assert prep.method == 'POST'841842 resp = s.send(prep)843 assert resp.status_code == 200844Merge pull request #3108 from kevinburke/flip-conditionalIan Cordascobefore adoptionbbeb000
lines 845–852why, one step back845 def test_non_prepared_request_error(self):846 s = requests.Session()847 req = requests.Request(u('POST'), '/')848849 with pytest.raises(ValueError) as e:850 s.send(req)851 assert str(e.value) == 'You can only send PreparedRequests.'852Update README.rstKenneth Reitzbefore adoption00c0a80
lines 853–930why, one step back853 def test_custom_content_type(self, httpbin):854 r = requests.post(855 httpbin('post'),856 data={'stuff': json.dumps({'a': 123})},857 files={858 'file1': ('test_requests.py', open(__file__, 'rb')),859 'file2': ('test_requests', open(__file__, 'rb'),860 'text/py-content-type')})861 assert r.status_code == 200862 assert b"text/py-content-type" in r.request.body863864 def test_hook_receives_request_arguments(self, httpbin):865 def hook(resp, **kwargs):866 assert resp is not None867 assert kwargs != {}868869 s = requests.Session()870 r = requests.Request('GET', httpbin(), hooks={'response': hook})871 prep = s.prepare_request(r)872 s.send(prep)873874 def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):875 hook = lambda x, *args, **kwargs: x876 s = requests.Session()877 s.hooks['response'].append(hook)878 r = requests.Request('GET', httpbin())879 prep = s.prepare_request(r)880 assert prep.hooks['response'] != []881 assert prep.hooks['response'] == [hook]882883 def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):884 hook1 = lambda x, *args, **kwargs: x885 hook2 = lambda x, *args, **kwargs: x886 assert hook1 is not hook2887 s = requests.Session()888 s.hooks['response'].append(hook2)889 r = requests.Request('GET', httpbin(), hooks={'response': [hook1]})890 prep = s.prepare_request(r)891 assert prep.hooks['response'] == [hook1]892893 def test_prepared_request_hook(self, httpbin):894 def hook(resp, **kwargs):895 resp.hook_working = True896 return resp897898 req = requests.Request('GET', httpbin(), hooks={'response': hook})899 prep = req.prepare()900901 s = requests.Session()902 s.proxies = getproxies()903 resp = s.send(prep)904905 assert hasattr(resp, 'hook_working')906907 def test_prepared_from_session(self, httpbin):908 class DummyAuth(requests.auth.AuthBase):909 def __call__(self, r):910 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'911 return r912913 req = requests.Request('GET', httpbin('headers'))914 assert not req.auth915916 s = requests.Session()917 s.auth = DummyAuth()918919 prep = s.prepare_request(req)920 resp = s.send(prep)921922 assert resp.json()['headers'][923 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'924925 def test_prepare_request_with_bytestring_url(self):926 req = requests.Request('GET', b'https://httpbin.org/')927 s = requests.Session()928 prep = s.prepare_request(req)929 assert prep.url == "https://httpbin.org/"930Merge pull request #3606 from bbamsch/httpbinTestFixCory Benfieldbefore adoption022e23c
line 931why, one step back931 def test_request_with_bytestring_host(self, httpbin):Merge pull request #3598 from bbamsch/bytestringHostFixCory Benfieldbefore adoption5eabcb7
lines 932–934why, one step back932 s = requests.Session()933 resp = s.request(934 'GET',Merge pull request #3606 from bbamsch/httpbinTestFixCory Benfieldbefore adoption022e23c
line 935why, one step back935 httpbin('cookies/set?cookie=value'),Merge pull request #3598 from bbamsch/bytestringHostFixCory Benfieldbefore adoption5eabcb7
lines 936–940why, one step back936 allow_redirects=False,937 headers={'Host': b'httpbin.org'}938 )939 assert resp.cookies.get('cookie') == 'value'940Update README.rstKenneth Reitzbefore adoption00c0a80
lines 941–1069why, one step back941 def test_links(self):942 r = requests.Response()943 r.headers = {944 'cache-control': 'public, max-age=60, s-maxage=60',945 'connection': 'keep-alive',946 'content-encoding': 'gzip',947 'content-type': 'application/json; charset=utf-8',948 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',949 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',950 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',951 'link': ('<https://api.github.com/users/kennethreitz/repos?'952 'page=2&per_page=10>; rel="next", <https://api.github.'953 'com/users/kennethreitz/repos?page=7&per_page=10>; '954 ' rel="last"'),955 'server': 'GitHub.com',956 'status': '200 OK',957 'vary': 'Accept',958 'x-content-type-options': 'nosniff',959 'x-github-media-type': 'github.beta',960 'x-ratelimit-limit': '60',961 'x-ratelimit-remaining': '57'962 }963 assert r.links['next']['rel'] == 'next'964965 def test_cookie_parameters(self):966 key = 'some_cookie'967 value = 'some_value'968 secure = True969 domain = 'test.com'970 rest = {'HttpOnly': True}971972 jar = requests.cookies.RequestsCookieJar()973 jar.set(key, value, secure=secure, domain=domain, rest=rest)974975 assert len(jar) == 1976 assert 'some_cookie' in jar977978 cookie = list(jar)[0]979 assert cookie.secure == secure980 assert cookie.domain == domain981 assert cookie._rest['HttpOnly'] == rest['HttpOnly']982983 def test_cookie_as_dict_keeps_len(self):984 key = 'some_cookie'985 value = 'some_value'986987 key1 = 'some_cookie1'988 value1 = 'some_value1'989990 jar = requests.cookies.RequestsCookieJar()991 jar.set(key, value)992 jar.set(key1, value1)993994 d1 = dict(jar)995 d2 = dict(jar.iteritems())996 d3 = dict(jar.items())997998 assert len(jar) == 2999 assert len(d1) == 21000 assert len(d2) == 21001 assert len(d3) == 210021003 def test_cookie_as_dict_keeps_items(self):1004 key = 'some_cookie'1005 value = 'some_value'10061007 key1 = 'some_cookie1'1008 value1 = 'some_value1'10091010 jar = requests.cookies.RequestsCookieJar()1011 jar.set(key, value)1012 jar.set(key1, value1)10131014 d1 = dict(jar)1015 d2 = dict(jar.iteritems())1016 d3 = dict(jar.items())10171018 assert d1['some_cookie'] == 'some_value'1019 assert d2['some_cookie'] == 'some_value'1020 assert d3['some_cookie1'] == 'some_value1'10211022 def test_cookie_as_dict_keys(self):1023 key = 'some_cookie'1024 value = 'some_value'10251026 key1 = 'some_cookie1'1027 value1 = 'some_value1'10281029 jar = requests.cookies.RequestsCookieJar()1030 jar.set(key, value)1031 jar.set(key1, value1)10321033 keys = jar.keys()1034 assert keys == list(keys)1035 # make sure one can use keys multiple times1036 assert list(keys) == list(keys)10371038 def test_cookie_as_dict_values(self):1039 key = 'some_cookie'1040 value = 'some_value'10411042 key1 = 'some_cookie1'1043 value1 = 'some_value1'10441045 jar = requests.cookies.RequestsCookieJar()1046 jar.set(key, value)1047 jar.set(key1, value1)10481049 values = jar.values()1050 assert values == list(values)1051 # make sure one can use values multiple times1052 assert list(values) == list(values)10531054 def test_cookie_as_dict_items(self):1055 key = 'some_cookie'1056 value = 'some_value'10571058 key1 = 'some_cookie1'1059 value1 = 'some_value1'10601061 jar = requests.cookies.RequestsCookieJar()1062 jar.set(key, value)1063 jar.set(key1, value1)10641065 items = jar.items()1066 assert items == list(items)1067 # make sure one can use items multiple times1068 assert list(items) == list(items)1069Merge pull request #3032 from davidsoncasey/masterCory Benfieldbefore adoption4f378b0
lines 1070–1101why, one step back1070 def test_cookie_duplicate_names_different_domains(self):1071 key = 'some_cookie'1072 value = 'some_value'1073 domain1 = 'test1.com'1074 domain2 = 'test2.com'10751076 jar = requests.cookies.RequestsCookieJar()1077 jar.set(key, value, domain=domain1)1078 jar.set(key, value, domain=domain2)1079 assert key in jar1080 items = jar.items()1081 assert len(items) == 210821083 # Verify that CookieConflictError is raised if domain is not specified1084 with pytest.raises(requests.cookies.CookieConflictError):1085 jar.get(key)10861087 # Verify that CookieConflictError is not raised if domain is specified1088 cookie = jar.get(key, domain=domain1)1089 assert cookie == value10901091 def test_cookie_duplicate_names_raises_cookie_conflict_error(self):1092 key = 'some_cookie'1093 value = 'some_value'1094 path = 'some_path'10951096 jar = requests.cookies.RequestsCookieJar()1097 jar.set(key, value, path=path)1098 jar.set(key, value)1099 with pytest.raises(requests.cookies.CookieConflictError):1100 jar.get(key)1101Update README.rstKenneth Reitzbefore adoption00c0a80
lines 1102–1104why, one step back1102 def test_time_elapsed_blank(self, httpbin):1103 r = requests.get(httpbin('get'))1104 td = r.elapsedMerge pull request #3428 from nateprewitt/pep8_fixesKenneth Reitzbefore adoption4285bac
line 1105why, one step back1105 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6)Update README.rstKenneth Reitzbefore adoption00c0a80
lines 1106–1107why, one step back1106 assert total_seconds > 0.01107Merge pull request #3718 from nsoranzo/masterCory Benfieldbefore adoption36c9c8c
lines 1108–1111why, one step back1108 def test_empty_response_has_content_none(self):1109 r = requests.Response()1110 assert r.content is None1111Update README.rstKenneth Reitzbefore adoption00c0a80
lines 1112–1124why, one step back1112 def test_response_is_iterable(self):1113 r = requests.Response()1114 io = StringIO.StringIO('abc')1115 read_ = io.read11161117 def read_mock(amt, decode_content=None):1118 return read_(amt)1119 setattr(io, 'read', read_mock)1120 r.raw = io1121 assert next(iter(r))1122 io.close()11231124 def test_response_decode_unicode(self):Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456
line 1125why, one step back1125 """When called with decode_unicode, Response.iter_content should alwaysUpdate README.rstKenneth Reitzbefore adoption00c0a80
lines 1126–1142why, one step back1126 return unicode.1127 """1128 r = requests.Response()1129 r._content_consumed = True1130 r._content = b'the content'1131 r.encoding = 'ascii'11321133 chunks = r.iter_content(decode_unicode=True)1134 assert all(isinstance(chunk, str) for chunk in chunks)11351136 # also for streaming1137 r = requests.Response()1138 r.raw = io.BytesIO(b'the content')1139 r.encoding = 'ascii'1140 chunks = r.iter_content(decode_unicode=True)1141 assert all(isinstance(chunk, str) for chunk in chunks)1142Support responses like `HTTP/1.1 404 Unicode chars` (#3385)Andrii Kostenkobefore adoption7700eca
lines 1143–1149why, one step back1143 def test_response_reason_unicode(self):1144 # check for unicode HTTP status1145 r = requests.Response()1146 r.url = u'unicode URL'1147 r.reason = u'Komponenttia ei löydy'.encode('utf-8')1148 r.status_code = 4041149 r.encoding = NoneMerge pull request #3428 from nateprewitt/pep8_fixesKenneth Reitzbefore adoption4285bac
line 1150why, one step back1150 assert not r.ok # old behaviour - crashes hereSupport responses like `HTTP/1.1 404 Unicode chars` (#3385)Andrii Kostenkobefore adoption7700eca
line 1151why, one step back1151Merge pull request #3554 from nateprewitt/3538_fallback_to_ISO_8591_1Ian Cordascobefore adoption87f9693
lines 1152–1155why, one step back1152 def test_response_reason_unicode_fallback(self):1153 # check raise_status falls back to ISO-8859-11154 r = requests.Response()1155 r.url = 'some url'Merge pull request #3576 from nateprewitt/3557_revert_and_fix_encodingIan Cordascobefore adoptionddf7df9
lines 1156–1157why, one step back1156 reason = u'Komponenttia ei löydy'1157 r.reason = reason.encode('latin-1')Merge pull request #3554 from nateprewitt/3538_fallback_to_ISO_8591_1Ian Cordascobefore adoption87f9693
lines 1158–1161why, one step back1158 r.status_code = 5001159 r.encoding = None1160 with pytest.raises(requests.exceptions.HTTPError) as e:1161 r.raise_for_status()Merge pull request #3576 from nateprewitt/3557_revert_and_fix_encodingIan Cordascobefore adoptionddf7df9
line 1162why, one step back1162 assert reason in e.value.args[0]Merge pull request #3554 from nateprewitt/3538_fallback_to_ISO_8591_1Ian Cordascobefore adoption87f9693
line 1163why, one step back1163Allow None value for chunk_size again (#3368)Joy Zhengbefore adoption0bcf634
lines 1164–1165why, one step back1164 def test_response_chunk_size_type(self):1165 """Ensure that chunk_size is passed as None or an integer, otherwiseMerge pull request #3365 from nateprewitt/3364_chunking_is_intCory Benfieldbefore adoption36453b9
lines 1166–1171why, one step back1166 raise a TypeError.1167 """1168 r = requests.Response()1169 r.raw = io.BytesIO(b'the content')1170 chunks = r.iter_content(1)1171 assert all(len(chunk) == 1 for chunk in chunks)Allow None value for chunk_size again (#3368)Joy Zhengbefore adoption0bcf634
lines 1172–1176why, one step back11721173 r = requests.Response()1174 r.raw = io.BytesIO(b'the content')1175 chunks = r.iter_content(None)1176 assert list(chunks) == [b'the content']Merge pull request #3365 from nateprewitt/3364_chunking_is_intCory Benfieldbefore adoption36453b9
lines 1177–1182why, one step back11771178 r = requests.Response()1179 r.raw = io.BytesIO(b'the content')1180 with pytest.raises(TypeError):1181 chunks = r.iter_content("1024")1182Update README.rstKenneth Reitzbefore adoption00c0a80
lines 1183–1194why, one step back1183 def test_request_and_response_are_pickleable(self, httpbin):1184 r = requests.get(httpbin('get'))11851186 # verify we can pickle the original request1187 assert pickle.loads(pickle.dumps(r.request))11881189 # verify we can pickle the response and that we have access to1190 # the original request.1191 pr = pickle.loads(pickle.dumps(r))1192 assert r.request.url == pr.request.url1193 assert r.request.headers == pr.request.headers1194Merge pull request #3489 from nateprewitt/1558_pickling_prepared_requestCory Benfieldbefore adoptiond24da4a
lines 1195–1240why, one step back1195 def test_prepared_request_is_pickleable(self, httpbin):1196 p = requests.Request('GET', httpbin('get')).prepare()11971198 # Verify PreparedRequest can be pickled and unpickled1199 r = pickle.loads(pickle.dumps(p))1200 assert r.url == p.url1201 assert r.headers == p.headers1202 assert r.body == p.body12031204 # Verify unpickled PreparedRequest sends properly1205 s = requests.Session()1206 resp = s.send(r)1207 assert resp.status_code == 20012081209 def test_prepared_request_with_file_is_pickleable(self, httpbin):1210 files = {'file': open(__file__, 'rb')}1211 r = requests.Request('POST', httpbin('post'), files=files)1212 p = r.prepare()12131214 # Verify PreparedRequest can be pickled and unpickled1215 r = pickle.loads(pickle.dumps(p))1216 assert r.url == p.url1217 assert r.headers == p.headers1218 assert r.body == p.body12191220 # Verify unpickled PreparedRequest sends properly1221 s = requests.Session()1222 resp = s.send(r)1223 assert resp.status_code == 20012241225 def test_prepared_request_with_hook_is_pickleable(self, httpbin):1226 r = requests.Request('GET', httpbin('get'), hooks=default_hooks())1227 p = r.prepare()12281229 # Verify PreparedRequest can be pickled1230 r = pickle.loads(pickle.dumps(p))1231 assert r.url == p.url1232 assert r.headers == p.headers1233 assert r.body == p.body1234 assert r.hooks == p.hooks12351236 # Verify unpickled PreparedRequest sends properly1237 s = requests.Session()1238 resp = s.send(r)1239 assert resp.status_code == 2001240Update README.rstKenneth Reitzbefore adoption00c0a80
lines 1241–1266why, one step back1241 def test_cannot_send_unprepared_requests(self, httpbin):1242 r = requests.Request(url=httpbin())1243 with pytest.raises(ValueError):1244 requests.Session().send(r)12451246 def test_http_error(self):1247 error = requests.exceptions.HTTPError()1248 assert not error.response1249 response = requests.Response()1250 error = requests.exceptions.HTTPError(response=response)1251 assert error.response == response1252 error = requests.exceptions.HTTPError('message', response=response)1253 assert str(error) == 'message'1254 assert error.response == response12551256 def test_session_pickling(self, httpbin):1257 r = requests.Request('GET', httpbin('get'))1258 s = requests.Session()12591260 s = pickle.loads(pickle.dumps(s))1261 s.proxies = getproxies()12621263 r = s.send(r.prepare())1264 assert r.status_code == 20012651266 def test_fixes_1329(self, httpbin):Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456
line 1267why, one step back1267 """Ensure that header updates are done case-insensitively."""Update README.rstKenneth Reitzbefore adoption00c0a80
lines 1268–1352why, one step back1268 s = requests.Session()1269 s.headers.update({'ACCEPT': 'BOGUS'})1270 s.headers.update({'accept': 'application/json'})1271 r = s.get(httpbin('get'))1272 headers = r.request.headers1273 assert headers['accept'] == 'application/json'1274 assert headers['Accept'] == 'application/json'1275 assert headers['ACCEPT'] == 'application/json'12761277 def test_uppercase_scheme_redirect(self, httpbin):1278 parts = urlparse(httpbin('html'))1279 url = "HTTP://" + parts.netloc + parts.path1280 r = requests.get(httpbin('redirect-to'), params={'url': url})1281 assert r.status_code == 2001282 assert r.url.lower() == url.lower()12831284 def test_transport_adapter_ordering(self):1285 s = requests.Session()1286 order = ['https://', 'http://']1287 assert order == list(s.adapters)1288 s.mount('http://git', HTTPAdapter())1289 s.mount('http://github', HTTPAdapter())1290 s.mount('http://github.com', HTTPAdapter())1291 s.mount('http://github.com/about/', HTTPAdapter())1292 order = [1293 'http://github.com/about/',1294 'http://github.com',1295 'http://github',1296 'http://git',1297 'https://',1298 'http://',1299 ]1300 assert order == list(s.adapters)1301 s.mount('http://gittip', HTTPAdapter())1302 s.mount('http://gittip.com', HTTPAdapter())1303 s.mount('http://gittip.com/about/', HTTPAdapter())1304 order = [1305 'http://github.com/about/',1306 'http://gittip.com/about/',1307 'http://github.com',1308 'http://gittip.com',1309 'http://github',1310 'http://gittip',1311 'http://git',1312 'https://',1313 'http://',1314 ]1315 assert order == list(s.adapters)1316 s2 = requests.Session()1317 s2.adapters = {'http://': HTTPAdapter()}1318 s2.mount('https://', HTTPAdapter())1319 assert 'http://' in s2.adapters1320 assert 'https://' in s2.adapters13211322 def test_header_remove_is_case_insensitive(self, httpbin):1323 # From issue #13211324 s = requests.Session()1325 s.headers['foo'] = 'bar'1326 r = s.get(httpbin('get'), headers={'FOO': None})1327 assert 'foo' not in r.request.headers13281329 def test_params_are_merged_case_sensitive(self, httpbin):1330 s = requests.Session()1331 s.params['foo'] = 'bar'1332 r = s.get(httpbin('get'), params={'FOO': 'bar'})1333 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}13341335 def test_long_authinfo_in_url(self):1336 url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(1337 'E8A3BE87-9E3F-4620-8858-95478E385B5B',1338 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',1339 'exactly-------------sixty-----------three------------characters',1340 )1341 r = requests.Request('GET', url).prepare()1342 assert r.url == url13431344 def test_header_keys_are_native(self, httpbin):1345 headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}1346 r = requests.Request('GET', httpbin('get'), headers=headers)1347 p = r.prepare()13481349 # This is testing that they are builtin strings. A bit weird, but there1350 # we go.1351 assert 'unicode' in p.headers.keys()1352 assert 'byte' in p.headers.keys()Merge pull request #3366 from nateprewitt/2947-no-returns-in-headerCory Benfieldbefore adoptionbd9e8f2
line 1353why, one step back1353Merge pull request #3390 from nateprewitt/3386_header_value_typeCory Benfieldbefore adoption425962c
line 1354why, one step back1354 def test_header_validation(self, httpbin):Merge pull request #3366 from nateprewitt/2947-no-returns-in-headerCory Benfieldbefore adoptionbd9e8f2
lines 1355–1356why, one step back1355 """Ensure prepare_headers regex isn't flagging valid header contents."""1356 headers_ok = {'foo': 'bar baz qux',Merge pull request #3390 from nateprewitt/3386_header_value_typeCory Benfieldbefore adoption425962c
line 1357why, one step back1357 'bar': u'fbbq'.encode('utf8'),Merge pull request #3366 from nateprewitt/2947-no-returns-in-headerCory Benfieldbefore adoptionbd9e8f2
line 1358why, one step back1358 'baz': '',Merge pull request #3390 from nateprewitt/3386_header_value_typeCory Benfieldbefore adoption425962c
line 1359why, one step back1359 'qux': '1'}Merge pull request #3366 from nateprewitt/2947-no-returns-in-headerCory Benfieldbefore adoptionbd9e8f2
lines 1360–1361why, one step back1360 r = requests.get(httpbin('get'), headers=headers_ok)1361 assert r.request.headers['foo'] == headers_ok['foo']Merge pull request #3390 from nateprewitt/3386_header_value_typeCory Benfieldbefore adoption425962c
lines 1362–1367why, one step back13621363 def test_header_value_not_str(self, httpbin):1364 """Ensure the header value is of type string or bytes as1365 per discussion in GH issue #33861366 """1367 headers_int = {'foo': 3}Merge pull request #3428 from nateprewitt/pep8_fixesKenneth Reitzbefore adoption4285bac
line 1368why, one step back1368 headers_dict = {'bar': {'foo': 'bar'}}Merge pull request #3390 from nateprewitt/3386_header_value_typeCory Benfieldbefore adoption425962c
lines 1369–1379why, one step back1369 headers_list = {'baz': ['foo', 'bar']}13701371 # Test for int1372 with pytest.raises(InvalidHeader):1373 r = requests.get(httpbin('get'), headers=headers_int)1374 # Test for dict1375 with pytest.raises(InvalidHeader):1376 r = requests.get(httpbin('get'), headers=headers_dict)1377 # Test for list1378 with pytest.raises(InvalidHeader):1379 r = requests.get(httpbin('get'), headers=headers_list)Merge pull request #3366 from nateprewitt/2947-no-returns-in-headerCory Benfieldbefore adoptionbd9e8f2
lines 1380–1411why, one step back13801381 def test_header_no_return_chars(self, httpbin):1382 """Ensure that a header containing return character sequences raise an1383 exception. Otherwise, multiple headers are created from single string.1384 """1385 headers_ret = {'foo': 'bar\r\nbaz: qux'}1386 headers_lf = {'foo': 'bar\nbaz: qux'}1387 headers_cr = {'foo': 'bar\rbaz: qux'}13881389 # Test for newline1390 with pytest.raises(InvalidHeader):1391 r = requests.get(httpbin('get'), headers=headers_ret)1392 # Test for line feed1393 with pytest.raises(InvalidHeader):1394 r = requests.get(httpbin('get'), headers=headers_lf)1395 # Test for carriage return1396 with pytest.raises(InvalidHeader):1397 r = requests.get(httpbin('get'), headers=headers_cr)13981399 def test_header_no_leading_space(self, httpbin):1400 """Ensure headers containing leading whitespace raise1401 InvalidHeader Error before sending.1402 """1403 headers_space = {'foo': ' bar'}1404 headers_tab = {'foo': ' bar'}14051406 # Test for whitespace1407 with pytest.raises(InvalidHeader):1408 r = requests.get(httpbin('get'), headers=headers_space)1409 # Test for tab1410 with pytest.raises(InvalidHeader):1411 r = requests.get(httpbin('get'), headers=headers_tab)Update README.rstKenneth Reitzbefore adoption00c0a80
lines 1412–1447why, one step back14121413 @pytest.mark.parametrize('files', ('foo', b'foo', bytearray(b'foo')))1414 def test_can_send_objects_with_files(self, httpbin, files):1415 data = {'a': 'this is a string'}1416 files = {'b': files}1417 r = requests.Request('POST', httpbin('post'), data=data, files=files)1418 p = r.prepare()1419 assert 'multipart/form-data' in p.headers['Content-Type']14201421 def test_can_send_file_object_with_non_string_filename(self, httpbin):1422 f = io.BytesIO()1423 f.name = 21424 r = requests.Request('POST', httpbin('post'), files={'f': f})1425 p = r.prepare()14261427 assert 'multipart/form-data' in p.headers['Content-Type']14281429 def test_autoset_header_values_are_native(self, httpbin):1430 data = 'this is a string'1431 length = '16'1432 req = requests.Request('POST', httpbin('post'), data=data)1433 p = req.prepare()14341435 assert p.headers['Content-Length'] == length14361437 def test_nonhttp_schemes_dont_check_URLs(self):1438 test_urls = (1439 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',1440 'file:///etc/passwd',1441 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',1442 )1443 for test_url in test_urls:1444 req = requests.Request('GET', test_url)1445 preq = req.prepare()1446 assert test_url == preq.url1447Merge pull request #3236 from eriol/xfail-testKenneth Reitzbefore adoption771ecd7
line 1448why, one step back1448 @pytest.mark.xfail(raises=ConnectionError)Update README.rstKenneth Reitzbefore adoption00c0a80
lines 1449–1482why, one step back1449 def test_auth_is_stripped_on_redirect_off_host(self, httpbin):1450 r = requests.get(1451 httpbin('redirect-to'),1452 params={'url': 'http://www.google.co.uk'},1453 auth=('user', 'pass'),1454 )1455 assert r.history[0].request.headers['Authorization']1456 assert not r.request.headers.get('Authorization', '')14571458 def test_auth_is_retained_for_redirect_on_host(self, httpbin):1459 r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))1460 h1 = r.history[0].request.headers['Authorization']1461 h2 = r.request.headers['Authorization']14621463 assert h1 == h214641465 def test_manual_redirect_with_partial_body_read(self, httpbin):1466 s = requests.Session()1467 r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)1468 assert r1.is_redirect1469 rg = s.resolve_redirects(r1, r1.request, stream=True)14701471 # read only the first eight bytes of the response body,1472 # then follow the redirect1473 r1.iter_content(8)1474 r2 = next(rg)1475 assert r2.is_redirect14761477 # read all of the response via iter_content,1478 # then follow the redirect1479 for _ in r2.iter_content():1480 pass1481 r3 = next(rg)1482 assert not r3.is_redirectMerge pull request #3655 from nateprewitt/tzickel_post_redirect_w_streamableCory Benfieldbefore adoptionf72684e
lines 1483–1583why, one step back14831484 def test_prepare_body_position_non_stream(self):1485 data = b'the data'1486 s = requests.Session()1487 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1488 assert prep._body_position is None14891490 def test_rewind_body(self):1491 data = io.BytesIO(b'the data')1492 s = requests.Session()1493 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1494 assert prep._body_position == 01495 assert prep.body.read() == b'the data'14961497 # the data has all been read1498 assert prep.body.read() == b''14991500 # rewind it back1501 requests.utils.rewind_body(prep)1502 assert prep.body.read() == b'the data'15031504 def test_rewind_partially_read_body(self):1505 data = io.BytesIO(b'the data')1506 s = requests.Session()1507 data.read(4) # read some data1508 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1509 assert prep._body_position == 41510 assert prep.body.read() == b'data'15111512 # the data has all been read1513 assert prep.body.read() == b''15141515 # rewind it back1516 requests.utils.rewind_body(prep)1517 assert prep.body.read() == b'data'15181519 def test_rewind_body_no_seek(self):1520 class BadFileObj:1521 def __init__(self, data):1522 self.data = data15231524 def tell(self):1525 return 015261527 def __iter__(self):1528 return15291530 data = BadFileObj('the data')1531 s = requests.Session()1532 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1533 assert prep._body_position == 015341535 with pytest.raises(UnrewindableBodyError) as e:1536 requests.utils.rewind_body(prep)15371538 assert 'Unable to rewind request body' in str(e)15391540 def test_rewind_body_failed_seek(self):1541 class BadFileObj:1542 def __init__(self, data):1543 self.data = data15441545 def tell(self):1546 return 015471548 def seek(self, pos):1549 raise OSError()15501551 def __iter__(self):1552 return15531554 data = BadFileObj('the data')1555 s = requests.Session()1556 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1557 assert prep._body_position == 015581559 with pytest.raises(UnrewindableBodyError) as e:1560 requests.utils.rewind_body(prep)15611562 assert 'error occured when rewinding request body' in str(e)15631564 def test_rewind_body_failed_tell(self):1565 class BadFileObj:1566 def __init__(self, data):1567 self.data = data15681569 def tell(self):1570 raise OSError()15711572 def __iter__(self):1573 return15741575 data = BadFileObj('the data')1576 s = requests.Session()1577 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1578 assert prep._body_position is not None15791580 with pytest.raises(UnrewindableBodyError) as e:1581 requests.utils.rewind_body(prep)15821583 assert 'Unable to rewind request body' in str(e)Update README.rstKenneth Reitzbefore adoption00c0a80
lines 1584–1604why, one step back15841585 def _patch_adapter_gzipped_redirect(self, session, url):1586 adapter = session.get_adapter(url=url)1587 org_build_response = adapter.build_response1588 self._patched_response = False15891590 def build_response(*args, **kwargs):1591 resp = org_build_response(*args, **kwargs)1592 if not self._patched_response:1593 resp.raw.headers['content-encoding'] = 'gzip'1594 self._patched_response = True1595 return resp15961597 adapter.build_response = build_response15981599 def test_redirect_with_wrong_gzipped_header(self, httpbin):1600 s = requests.Session()1601 url = httpbin('redirect/1')1602 self._patch_adapter_gzipped_redirect(s, url)1603 s.get(url)1604Merge pull request #3673 from klimenko-forks/auth-unicodeCory Benfieldbefore adoptionb9f1c44
lines 1605–1611why, one step back1605 @pytest.mark.parametrize(1606 'username, password, auth_str', (1607 ('test', 'test', 'Basic dGVzdDp0ZXN0'),1608 (u'имя'.encode('utf-8'), u'пароль'.encode('utf-8'), 'Basic 0LjQvNGPOtC/0LDRgNC+0LvRjA=='),1609 ))1610 def test_basic_auth_str_is_always_native(self, username, password, auth_str):1611 s = _basic_auth_str(username, password)Update README.rstKenneth Reitzbefore adoption00c0a80
line 1612why, one step back1612 assert isinstance(s, builtin_str)Merge pull request #3673 from klimenko-forks/auth-unicodeCory Benfieldbefore adoptionb9f1c44
line 1613why, one step back1613 assert s == auth_strUpdate README.rstKenneth Reitzbefore adoption00c0a80
lines 1614–1664why, one step back16141615 def test_requests_history_is_saved(self, httpbin):1616 r = requests.get(httpbin('redirect/5'))1617 total = r.history[-1].history1618 i = 01619 for item in r.history:1620 assert item.history == total[0:i]1621 i += 116221623 def test_json_param_post_content_type_works(self, httpbin):1624 r = requests.post(1625 httpbin('post'),1626 json={'life': 42}1627 )1628 assert r.status_code == 2001629 assert 'application/json' in r.request.headers['Content-Type']1630 assert {'life': 42} == r.json()['json']16311632 def test_json_param_post_should_not_override_data_param(self, httpbin):1633 r = requests.Request(method='POST', url=httpbin('post'),1634 data={'stuff': 'elixr'},1635 json={'music': 'flute'})1636 prep = r.prepare()1637 assert 'stuff=elixr' == prep.body16381639 def test_response_iter_lines(self, httpbin):1640 r = requests.get(httpbin('stream/4'), stream=True)1641 assert r.status_code == 20016421643 it = r.iter_lines()1644 next(it)1645 assert len(list(it)) == 316461647 def test_unconsumed_session_response_closes_connection(self, httpbin):1648 s = requests.session()16491650 with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1651 pass16521653 assert response._content_consumed is False1654 assert response.raw.closed16551656 @pytest.mark.xfail1657 def test_response_iter_lines_reentrant(self, httpbin):1658 """Response.iter_lines() is not reentrant safe"""1659 r = requests.get(httpbin('stream/4'), stream=True)1660 assert r.status_code == 20016611662 next(r.iter_lines())1663 assert len(list(r.iter_lines())) == 31664Merge pull request #3091 from bodgit/proxyIan Cordascobefore adoption60aee14
lines 1665–1675why, one step back1665 def test_session_close_proxy_clear(self, mocker):1666 proxies = {1667 'one': mocker.Mock(),1668 'two': mocker.Mock(),1669 }1670 session = requests.Session()1671 mocker.patch.dict(session.adapters['http://'].proxy_manager, proxies)1672 session.close()1673 proxies['one'].clear.assert_called_once_with()1674 proxies['two'].clear.assert_called_once_with()1675Merge pull request #3660 from pawelmhm/proxy_empty_passCory Benfieldbefore adoptionbf19750
lines 1676–1685why, one step back1676 def test_proxy_auth(self, httpbin):1677 adapter = HTTPAdapter()1678 headers = adapter.proxy_headers("http://user:pass@httpbin.org")1679 assert headers == {'Proxy-Authorization': 'Basic dXNlcjpwYXNz'}16801681 def test_proxy_auth_empty_pass(self, httpbin):1682 adapter = HTTPAdapter()1683 headers = adapter.proxy_headers("http://user:@httpbin.org")1684 assert headers == {'Proxy-Authorization': 'Basic dXNlcjo='}1685Merge pull request #3179 from messense/messense-patch-1Cory Benfieldbefore adoption8770410
lines 1686–1696why, one step back1686 def test_response_json_when_content_is_None(self, httpbin):1687 r = requests.get(httpbin('/status/204'))1688 # Make sure r.content is None1689 r.status_code = 01690 r._content = False1691 r._content_consumed = False16921693 assert r.content is None1694 with pytest.raises(ValueError):1695 r.json()1696Merge pull request #3510 from nateprewitt/add_close_passthroughCory Benfieldbefore adoptiond3567aa
lines 1697–1705why, one step back1697 def test_response_without_release_conn(self):1698 """Test `close` call for non-urllib3-like raw objects.1699 Should work when `release_conn` attr doesn't exist on `response.raw`.1700 """1701 resp = requests.Response()1702 resp.raw = StringIO.StringIO('test')1703 assert not resp.raw.closed1704 resp.close()1705 assert resp.raw.closedUpdate README.rstKenneth Reitzbefore adoption00c0a80
line 1706why, one step back1706Merge pull request #3754 from nateprewitt/3066_auth_and_dataCory Benfieldbefore adoption11a86a5
lines 1707–1742why, one step back1707 def test_empty_stream_with_auth_does_not_set_content_length_header(self, httpbin):1708 """Ensure that a byte stream with size 0 will not set both a Content-Length1709 and Transfer-Encoding header.1710 """1711 auth = ('user', 'pass')1712 url = httpbin('post')1713 file_obj = io.BytesIO(b'')1714 r = requests.Request('POST', url, auth=auth, data=file_obj)1715 prepared_request = r.prepare()1716 assert 'Transfer-Encoding' in prepared_request.headers1717 assert 'Content-Length' not in prepared_request.headers17181719 def test_stream_with_auth_does_not_set_transfer_encoding_header(self, httpbin):1720 """Ensure that a byte stream with size > 0 will not set both a Content-Length1721 and Transfer-Encoding header.1722 """1723 auth = ('user', 'pass')1724 url = httpbin('post')1725 file_obj = io.BytesIO(b'test data')1726 r = requests.Request('POST', url, auth=auth, data=file_obj)1727 prepared_request = r.prepare()1728 assert 'Transfer-Encoding' not in prepared_request.headers1729 assert 'Content-Length' in prepared_request.headers17301731 def test_chunked_upload_does_not_set_content_length_header(self, httpbin):1732 """Ensure that requests with a generator body stream using1733 Transfer-Encoding: chunked, not a Content-Length header.1734 """1735 data = (i for i in [b'a', b'b', b'c'])1736 url = httpbin('post')1737 r = requests.Request('POST', url, data=data)1738 prepared_request = r.prepare()1739 assert 'Transfer-Encoding' in prepared_request.headers1740 assert 'Content-Length' not in prepared_request.headers17411742Update README.rstKenneth Reitzbefore adoption00c0a80
lines 1743–1948why, one step back1743class TestCaseInsensitiveDict:17441745 @pytest.mark.parametrize(1746 'cid', (1747 CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}),1748 CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')]),1749 CaseInsensitiveDict(FOO='foo', BAr='bar'),1750 ))1751 def test_init(self, cid):1752 assert len(cid) == 21753 assert 'foo' in cid1754 assert 'bar' in cid17551756 def test_docstring_example(self):1757 cid = CaseInsensitiveDict()1758 cid['Accept'] = 'application/json'1759 assert cid['aCCEPT'] == 'application/json'1760 assert list(cid) == ['Accept']17611762 def test_len(self):1763 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1764 cid['A'] = 'a'1765 assert len(cid) == 217661767 def test_getitem(self):1768 cid = CaseInsensitiveDict({'Spam': 'blueval'})1769 assert cid['spam'] == 'blueval'1770 assert cid['SPAM'] == 'blueval'17711772 def test_fixes_649(self):1773 """__setitem__ should behave case-insensitively."""1774 cid = CaseInsensitiveDict()1775 cid['spam'] = 'oneval'1776 cid['Spam'] = 'twoval'1777 cid['sPAM'] = 'redval'1778 cid['SPAM'] = 'blueval'1779 assert cid['spam'] == 'blueval'1780 assert cid['SPAM'] == 'blueval'1781 assert list(cid.keys()) == ['SPAM']17821783 def test_delitem(self):1784 cid = CaseInsensitiveDict()1785 cid['Spam'] = 'someval'1786 del cid['sPam']1787 assert 'spam' not in cid1788 assert len(cid) == 017891790 def test_contains(self):1791 cid = CaseInsensitiveDict()1792 cid['Spam'] = 'someval'1793 assert 'Spam' in cid1794 assert 'spam' in cid1795 assert 'SPAM' in cid1796 assert 'sPam' in cid1797 assert 'notspam' not in cid17981799 def test_get(self):1800 cid = CaseInsensitiveDict()1801 cid['spam'] = 'oneval'1802 cid['SPAM'] = 'blueval'1803 assert cid.get('spam') == 'blueval'1804 assert cid.get('SPAM') == 'blueval'1805 assert cid.get('sPam') == 'blueval'1806 assert cid.get('notspam', 'default') == 'default'18071808 def test_update(self):1809 cid = CaseInsensitiveDict()1810 cid['spam'] = 'blueval'1811 cid.update({'sPam': 'notblueval'})1812 assert cid['spam'] == 'notblueval'1813 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1814 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1815 assert len(cid) == 21816 assert cid['foo'] == 'anotherfoo'1817 assert cid['bar'] == 'anotherbar'18181819 def test_update_retains_unchanged(self):1820 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1821 cid.update({'foo': 'newfoo'})1822 assert cid['bar'] == 'bar'18231824 def test_iter(self):1825 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1826 keys = frozenset(['Spam', 'Eggs'])1827 assert frozenset(iter(cid)) == keys18281829 def test_equality(self):1830 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1831 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1832 assert cid == othercid1833 del othercid['spam']1834 assert cid != othercid1835 assert cid == {'spam': 'blueval', 'eggs': 'redval'}1836 assert cid != object()18371838 def test_setdefault(self):1839 cid = CaseInsensitiveDict({'Spam': 'blueval'})1840 assert cid.setdefault('spam', 'notblueval') == 'blueval'1841 assert cid.setdefault('notspam', 'notblueval') == 'notblueval'18421843 def test_lower_items(self):1844 cid = CaseInsensitiveDict({1845 'Accept': 'application/json',1846 'user-Agent': 'requests',1847 })1848 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1849 lowerkeyset = frozenset(['accept', 'user-agent'])1850 assert keyset == lowerkeyset18511852 def test_preserve_key_case(self):1853 cid = CaseInsensitiveDict({1854 'Accept': 'application/json',1855 'user-Agent': 'requests',1856 })1857 keyset = frozenset(['Accept', 'user-Agent'])1858 assert frozenset(i[0] for i in cid.items()) == keyset1859 assert frozenset(cid.keys()) == keyset1860 assert frozenset(cid) == keyset18611862 def test_preserve_last_key_case(self):1863 cid = CaseInsensitiveDict({1864 'Accept': 'application/json',1865 'user-Agent': 'requests',1866 })1867 cid.update({'ACCEPT': 'application/json'})1868 cid['USER-AGENT'] = 'requests'1869 keyset = frozenset(['ACCEPT', 'USER-AGENT'])1870 assert frozenset(i[0] for i in cid.items()) == keyset1871 assert frozenset(cid.keys()) == keyset1872 assert frozenset(cid) == keyset18731874 def test_copy(self):1875 cid = CaseInsensitiveDict({1876 'Accept': 'application/json',1877 'user-Agent': 'requests',1878 })1879 cid_copy = cid.copy()1880 assert cid == cid_copy1881 cid['changed'] = True1882 assert cid != cid_copy188318841885class TestMorselToCookieExpires:1886 """Tests for morsel_to_cookie when morsel contains expires."""18871888 def test_expires_valid_str(self):1889 """Test case where we convert expires from string time."""18901891 morsel = Morsel()1892 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1893 cookie = morsel_to_cookie(morsel)1894 assert cookie.expires == 118951896 @pytest.mark.parametrize(1897 'value, exception', (1898 (100, TypeError),1899 ('woops', ValueError),1900 ))1901 def test_expires_invalid_int(self, value, exception):1902 """Test case where an invalid type is passed for expires."""1903 morsel = Morsel()1904 morsel['expires'] = value1905 with pytest.raises(exception):1906 morsel_to_cookie(morsel)19071908 def test_expires_none(self):1909 """Test case where expires is None."""19101911 morsel = Morsel()1912 morsel['expires'] = None1913 cookie = morsel_to_cookie(morsel)1914 assert cookie.expires is None191519161917class TestMorselToCookieMaxAge:19181919 """Tests for morsel_to_cookie when morsel contains max-age."""19201921 def test_max_age_valid_int(self):1922 """Test case where a valid max age in seconds is passed."""19231924 morsel = Morsel()1925 morsel['max-age'] = 601926 cookie = morsel_to_cookie(morsel)1927 assert isinstance(cookie.expires, int)19281929 def test_max_age_invalid_str(self):1930 """Test case where a invalid max age is passed."""19311932 morsel = Morsel()1933 morsel['max-age'] = 'woops'1934 with pytest.raises(TypeError):1935 morsel_to_cookie(morsel)193619371938class TestTimeout:19391940 def test_stream_timeout(self, httpbin):1941 try:1942 requests.get(httpbin('delay/10'), timeout=2.0)1943 except requests.exceptions.Timeout as e:1944 assert 'Read timed out' in e.args[0].args[0]19451946 @pytest.mark.parametrize(1947 'timeout, error_text', (1948 ((3, 4, 5), '(connect, read)'),Fix tests for new urllib3 exception text.Cory Benfieldbefore adoption2d211d5
line 1949why, one step back1949 ('foo', 'must be an int, float or None'),Update README.rstKenneth Reitzbefore adoption00c0a80
lines 1950–1956why, one step back1950 ))1951 def test_invalid_timeout(self, httpbin, timeout, error_text):1952 with pytest.raises(ValueError) as e:1953 requests.get(httpbin('get'), timeout=timeout)1954 assert error_text in str(e)19551956 def test_none_timeout(self, httpbin):Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456
line 1957why, one step back1957 """Check that you can set None as a valid timeout value.Update README.rstKenneth Reitzbefore adoption00c0a80
lines 1958–2030why, one step back19581959 To actually test this behavior, we'd want to check that setting the1960 timeout to None actually lets the request block past the system default1961 timeout. However, this would make the test suite unbearably slow.1962 Instead we verify that setting the timeout to None does not prevent the1963 request from succeeding.1964 """1965 r = requests.get(httpbin('get'), timeout=None)1966 assert r.status_code == 20019671968 def test_read_timeout(self, httpbin):1969 try:1970 requests.get(httpbin('delay/10'), timeout=(None, 0.1))1971 pytest.fail('The recv() request should time out.')1972 except ReadTimeout:1973 pass19741975 def test_connect_timeout(self):1976 try:1977 requests.get(TARPIT, timeout=(0.1, None))1978 pytest.fail('The connect() request should time out.')1979 except ConnectTimeout as e:1980 assert isinstance(e, ConnectionError)1981 assert isinstance(e, Timeout)19821983 def test_total_timeout_connect(self):1984 try:1985 requests.get(TARPIT, timeout=(0.1, 0.1))1986 pytest.fail('The connect() request should time out.')1987 except ConnectTimeout:1988 pass19891990 def test_encoded_methods(self, httpbin):1991 """See: https://github.com/kennethreitz/requests/issues/2316"""1992 r = requests.request(b'GET', httpbin('get'))1993 assert r.ok199419951996SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))199719981999class RedirectSession(SessionRedirectMixin):2000 def __init__(self, order_of_redirects):The first 2,000 of 2,295 lines.