Skip to content
Myr

test_requests.py

This file

Path

tests/test_requests.py

2,354 lines · 81.3 KiB · Python

Last changed by

Merge pull request #3927 from bagerard/raise_IOError_invalid_certificate_filesCory Benfieldbefore adoption993cbf5

History of this file

Take it

The walk stopped after 200 commits: lines older than 6c9a0ef point at it.

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 1–11why, one step back
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-34"""Tests for Requests."""56from __future__ import division7import json8import os9import pickle10import collections11import contextlib

Test security warnings (#3289)John Vandenbergbefore adoption400d27f

line 12why, one step back
12import warnings

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 13–21why, one step back
13
14import 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

line 22why, one step back
22from requests.cookies import (

Merge pull request #3809 from JungWinter/masterCory Benfieldbefore adoptione2bd1f9

line 23why, one step back
23 cookiejar_from_dict, morsel_to_cookie)

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 24–26why, one step back
24from requests.exceptions import (
25 ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,26 MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects,

Merge pull request #3655 from nateprewitt/tzickel_post_redirect_w_streamableCory Benfieldbefore adoptionf72684e

line 27why, one step back
27 ProxyError, InvalidHeader, UnrewindableBodyError)

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 28–40why, one step back
28from requests.models import PreparedRequest
29from requests.structures import CaseInsensitiveDict30from requests.sessions import SessionRedirectMixin31from requests.models import urlencode32from requests.hooks import default_hooks3334from .compat import StringIO, u35from .utils import override_environ3637# Requests to this URL should always fail with a connection timeout (nothing38# listening on that port)39TARPIT = 'http://10.255.255.1'40

Test security warnings (#3289)John Vandenbergbefore adoption400d27f

lines 41–46why, one step back
41try:
42 from ssl import SSLContext43 del SSLContext44 HAS_MODERN_SSL = True45except ImportError:46 HAS_MODERN_SSL = False

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

line 47why, one step back
47

Test security warnings (#3289)John Vandenbergbefore adoption400d27f

lines 48–54why, one step back
48try:
49 requests.pyopenssl50 HAS_PYOPENSSL = True51except AttributeError:52 HAS_PYOPENSSL = False5354

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 55–93why, one step back
55class 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.headers93

Merge pull request #3545 from nateprewitt/new_prepare_content_lengthIan Cordascobefore adoption9407d69

lines 94–103why, one step back
94 @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'103

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 104–142why, one step back
104 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)142

Merge pull request #3697 from hussaintamboli/masterCory Benfieldbefore adoption1e198f9

lines 143–147why, one step back
143 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/'147

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 148–172why, one step back
148 @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_redirect172

Merge pull request #3655 from nateprewitt/tzickel_post_redirect_w_streamableCory Benfieldbefore adoptionf72684e

lines 173–187why, one step back
173 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')187

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 188–254why, one step back
188 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')211212 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_redirect254

Merge pull request #3493 from nateprewitt/3490_drop_headersIan Cordascobefore adoptionf5ff345

lines 255–294why, one step back
255 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.headers294

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 295–376why, one step back
295 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 back
377
378 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'

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 409–483why, one step back
409
410 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.headers431432 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')451452 @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 back
484 'username, password', (
485 ('user', 'pass'),486 (u'имя'.encode('utf-8'), u'пароль'.encode('utf-8')),

Merge pull request #3760 from sigmavirus24/deprecation-warningCory Benfieldbefore adoption4683f16

lines 487–488why, one step back
487 (42, 42),
488 (None, None),

Merge pull request #3673 from klimenko-forks/auth-unicodeCory Benfieldbefore adoptionb9f1c44

lines 489–497why, one step back
489 ))
490 def test_set_basicauth(self, httpbin, username, password):491 auth = (username, password)492 url = httpbin('get')493494 r = requests.Request('GET', url, auth=auth)495 p = r.prepare()496497 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 498–507why, one step back
498
499 def test_basicauth_encodes_byte_strings(self):500 """Ensure b'test' formats as the byte string "test" rather501 than the unicode string "b'test'" in Python 3.502 """503 auth = (b'\xc5\xafsername', b'test\xc6\xb6')504 r = requests.Request('GET', 'http://localhost', auth=auth)505 p = r.prepare()506507 assert p.headers['Authorization'] == 'Basic xa9zZXJuYW1lOnRlc3TGtg=='

Merge pull request #3673 from klimenko-forks/auth-unicodeCory Benfieldbefore adoptionb9f1c44

lines 508–509why, one step back
508
509 @pytest.mark.parametrize(

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 510–634why, one step back
510 'url, exception', (
511 # Connecting to an unknown domain should raise a ConnectionError512 ('http://doesnotexist.google.com', ConnectionError),513 # Connecting to an invalid port should raise a ConnectionError514 ('http://localhost:1', ConnectionError),515 # Inputing a URL that cannot be parsed should raise an InvalidURL error516 ('http://fe80::5054:ff:fe5a:fc0', InvalidURL)517 ))518 def test_errors(self, url, exception):519 with pytest.raises(exception):520 requests.get(url, timeout=1)521522 def test_proxy_error(self):523 # any proxy related error (address resolution, no route to host, etc) should result in a ProxyError524 with pytest.raises(ProxyError):525 requests.get('http://localhost:1', proxies={'http': 'non-resolvable-address'})526527 def test_basicauth_with_netrc(self, httpbin):528 auth = ('user', 'pass')529 wrong_auth = ('wronguser', 'wrongpass')530 url = httpbin('basic-auth', 'user', 'pass')531532 old_auth = requests.sessions.get_netrc_auth533534 try:535 def get_netrc_auth_mock(url):536 return auth537 requests.sessions.get_netrc_auth = get_netrc_auth_mock538539 # Should use netrc and work.540 r = requests.get(url)541 assert r.status_code == 200542543 # Given auth should override and fail.544 r = requests.get(url, auth=wrong_auth)545 assert r.status_code == 401546547 s = requests.session()548549 # Should use netrc and work.550 r = s.get(url)551 assert r.status_code == 200552553 # Given auth should override and fail.554 s.auth = wrong_auth555 r = s.get(url)556 assert r.status_code == 401557 finally:558 requests.sessions.get_netrc_auth = old_auth559560 def test_DIGEST_HTTP_200_OK_GET(self, httpbin):561562 auth = HTTPDigestAuth('user', 'pass')563 url = httpbin('digest-auth', 'auth', 'user', 'pass')564565 r = requests.get(url, auth=auth)566 assert r.status_code == 200567568 r = requests.get(url)569 assert r.status_code == 401570571 s = requests.session()572 s.auth = HTTPDigestAuth('user', 'pass')573 r = s.get(url)574 assert r.status_code == 200575576 def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):577 url = httpbin('digest-auth', 'auth', 'user', 'pass')578 auth = HTTPDigestAuth('user', 'pass')579 r = requests.get(url)580 assert r.cookies['fake'] == 'fake_value'581582 r = requests.get(url, auth=auth)583 assert r.status_code == 200584585 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):586 url = httpbin('digest-auth', 'auth', 'user', 'pass')587 auth = HTTPDigestAuth('user', 'pass')588 s = requests.Session()589 s.get(url, auth=auth)590 assert s.cookies['fake'] == 'fake_value'591592 def test_DIGEST_STREAM(self, httpbin):593594 auth = HTTPDigestAuth('user', 'pass')595 url = httpbin('digest-auth', 'auth', 'user', 'pass')596597 r = requests.get(url, auth=auth, stream=True)598 assert r.raw.read() != b''599600 r = requests.get(url, auth=auth, stream=False)601 assert r.raw.read() == b''602603 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):604605 auth = HTTPDigestAuth('user', 'wrongpass')606 url = httpbin('digest-auth', 'auth', 'user', 'pass')607608 r = requests.get(url, auth=auth)609 assert r.status_code == 401610611 r = requests.get(url)612 assert r.status_code == 401613614 s = requests.session()615 s.auth = auth616 r = s.get(url)617 assert r.status_code == 401618619 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):620621 auth = HTTPDigestAuth('user', 'pass')622 url = httpbin('digest-auth', 'auth', 'user', 'pass')623624 r = requests.get(url, auth=auth)625 assert '"auth"' in r.request.headers['Authorization']626627 def test_POSTBIN_GET_POST_FILES(self, httpbin):628629 url = httpbin('post')630 requests.post(url).raise_for_status()631632 post1 = requests.post(url, data={'some': 'data'})633 assert post1.status_code == 200634

fix broken testsKenneth Reitzbefore adoption97b5bc2

line 635why, one step back
635 with open('Pipfile') as f:

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 636–694why, one step back
636 post2 = requests.post(url, files={'some': f})
637 assert post2.status_code == 200638639 post4 = requests.post(url, data='[{"some": "json"}]')640 assert post4.status_code == 200641642 with pytest.raises(ValueError):643 requests.post(url, files=['bad file data'])644645 def test_POSTBIN_SEEKED_OBJECT_WITH_NO_ITER(self, httpbin):646647 class TestStream(object):648 def __init__(self, data):649 self.data = data.encode()650 self.length = len(self.data)651 self.index = 0652653 def __len__(self):654 return self.length655656 def read(self, size=None):657 if size:658 ret = self.data[self.index:self.index + size]659 self.index += size660 else:661 ret = self.data[self.index:]662 self.index = self.length663 return ret664665 def tell(self):666 return self.index667668 def seek(self, offset, where=0):669 if where == 0:670 self.index = offset671 elif where == 1:672 self.index += offset673 elif where == 2:674 self.index = self.length + offset675676 test = TestStream('test')677 post1 = requests.post(httpbin('post'), data=test)678 assert post1.status_code == 200679 assert post1.json()['data'] == 'test'680681 test = TestStream('test')682 test.seek(2)683 post2 = requests.post(httpbin('post'), data=test)684 assert post2.status_code == 200685 assert post2.json()['data'] == 'st'686687 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):688689 url = httpbin('post')690 requests.post(url).raise_for_status()691692 post1 = requests.post(url, data={'some': 'data'})693 assert post1.status_code == 200694

fix broken testsKenneth Reitzbefore adoption97b5bc2

line 695why, one step back
695 with open('Pipfile') as f:

Merge pull request #3428 from nateprewitt/pep8_fixesKenneth Reitzbefore adoption4285bac

line 696why, one step back
696 post2 = requests.post(url, data={'some': 'data'}, files={'some': f})

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 697–704why, one step back
697 assert post2.status_code == 200
698699 post4 = requests.post(url, data='[{"some": "json"}]')700 assert post4.status_code == 200701702 with pytest.raises(ValueError):703 requests.post(url, files=['bad file data'])704

Merge pull request #3652 from gardiac2002/masterIan Cordascobefore adoption9deb603

lines 705–729why, one step back
705 def test_post_with_custom_mapping(self, httpbin):
706 class CustomMapping(collections.MutableMapping):707 def __init__(self, *args, **kwargs):708 self.data = dict(*args, **kwargs)709710 def __delitem__(self, key):711 del self.data[key]712713 def __getitem__(self, key):714 return self.data[key]715716 def __setitem__(self, key, value):717 self.data[key] = value718719 def __iter__(self):720 return iter(self.data)721722 def __len__(self):723 return len(self.data)724725 data = CustomMapping({'some': 'data'})726 url = httpbin('post')727 found_json = requests.post(url, data=data).json().get('form')728 assert found_json == {'some': 'data'}729

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 730–731why, one step back
730 def test_conflicting_post_params(self, httpbin):
731 url = httpbin('post')

fix broken testsKenneth Reitzbefore adoption97b5bc2

line 732why, one step back
732 with open('Pipfile') as f:

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 733–770why, one step back
733 pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")
734 pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")735736 def test_request_ok_set(self, httpbin):737 r = requests.get(httpbin('status', '404'))738 assert not r.ok739740 def test_status_raising(self, httpbin):741 r = requests.get(httpbin('status', '404'))742 with pytest.raises(requests.exceptions.HTTPError):743 r.raise_for_status()744745 r = requests.get(httpbin('status', '500'))746 assert not r.ok747748 def test_decompress_gzip(self, httpbin):749 r = requests.get(httpbin('gzip'))750 r.content.decode('ascii')751752 @pytest.mark.parametrize(753 'url, params', (754 ('/get', {'foo': 'føø'}),755 ('/get', {'føø': 'føø'}),756 ('/get', {'føø': 'føø'}),757 ('/get', {'foo': 'foo'}),758 ('ø', {'foo': 'foo'}),759 ))760 def test_unicode_get(self, httpbin, url, params):761 requests.get(httpbin(url), params=params)762763 def test_unicode_header_name(self, httpbin):764 requests.put(765 httpbin('put'),766 headers={str('Content-Type'): 'application/octet-stream'},767 data='\xff') # compat.str is unicode.768769 def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):770 requests.get(httpbin_secure('status', '301'), verify=httpbin_ca_bundle)

Test security warnings (#3289)John Vandenbergbefore adoption400d27f

line 771why, one step back
771

Merge pull request #3927 from bagerard/raise_IOError_invalid_certificate_filesCory Benfieldbefore adoption993cbf5

lines 772–787why, one step back
772 def test_invalid_ca_certificate_path(self, httpbin_secure):
773 INVALID_PATH = '/garbage'774 with pytest.raises(IOError) as e:775 requests.get(httpbin_secure(), verify=INVALID_PATH)776 assert str(e.value) == 'Could not find a suitable TLS CA certificate bundle, invalid path: {0}'.format(INVALID_PATH)777778 def test_invalid_ssl_certificate_files(self, httpbin_secure):779 INVALID_PATH = '/garbage'780 with pytest.raises(IOError) as e:781 requests.get(httpbin_secure(), cert=INVALID_PATH)782 assert str(e.value) == 'Could not find the TLS certificate file, invalid path: {0}'.format(INVALID_PATH)783784 with pytest.raises(IOError) as e:785 requests.get(httpbin_secure(), cert=('.', INVALID_PATH))786 assert str(e.value) == 'Could not find the TLS key file, invalid path: {0}'.format(INVALID_PATH)787

Test security warnings (#3289)John Vandenbergbefore adoption400d27f

lines 788–807why, one step back
788 def test_https_warnings(self, httpbin_secure, httpbin_ca_bundle):
789 """warnings are emitted with requests.get"""790 if HAS_MODERN_SSL or HAS_PYOPENSSL:791 warnings_expected = ('SubjectAltNameWarning', )792 else:793 warnings_expected = ('SNIMissingWarning',794 'InsecurePlatformWarning',795 'SubjectAltNameWarning', )796797 with pytest.warns(None) as warning_records:798 warnings.simplefilter('always')799 requests.get(httpbin_secure('status', '200'),800 verify=httpbin_ca_bundle)801802 warning_records = [item for item in warning_records803 if item.category.__name__ != 'ResourceWarning']804805 warnings_category = tuple(806 item.category.__name__ for item in warning_records)807 assert warnings_category == warnings_expected

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 808–947why, one step back
808
809 def test_urlencoded_get_query_multivalued_param(self, httpbin):810811 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))812 assert r.status_code == 200813 assert r.url == httpbin('get?test=foo&test=baz')814815 def test_different_encodings_dont_break_post(self, httpbin):816 r = requests.post(httpbin('post'),817 data={'stuff': json.dumps({'a': 123})},818 params={'blah': 'asdf1234'},819 files={'file': ('test_requests.py', open(__file__, 'rb'))})820 assert r.status_code == 200821822 @pytest.mark.parametrize(823 'data', (824 {'stuff': u('ëlïxr')},825 {'stuff': u('ëlïxr').encode('utf-8')},826 {'stuff': 'elixr'},827 {'stuff': 'elixr'.encode('utf-8')},828 ))829 def test_unicode_multipart_post(self, httpbin, data):830 r = requests.post(httpbin('post'),831 data=data,832 files={'file': ('test_requests.py', open(__file__, 'rb'))})833 assert r.status_code == 200834835 def test_unicode_multipart_post_fieldnames(self, httpbin):836 filename = os.path.splitext(__file__)[0] + '.py'837 r = requests.Request(838 method='POST', url=httpbin('post'),839 data={'stuff'.encode('utf-8'): 'elixr'},840 files={'file': ('test_requests.py', open(filename, 'rb'))})841 prep = r.prepare()842 assert b'name="stuff"' in prep.body843 assert b'name="b\'stuff\'"' not in prep.body844845 def test_unicode_method_name(self, httpbin):846 files = {'file': open(__file__, 'rb')}847 r = requests.request(848 method=u('POST'), url=httpbin('post'), files=files)849 assert r.status_code == 200850851 def test_unicode_method_name_with_request_object(self, httpbin):852 files = {'file': open(__file__, 'rb')}853 s = requests.Session()854 req = requests.Request(u('POST'), httpbin('post'), files=files)855 prep = s.prepare_request(req)856 assert isinstance(prep.method, builtin_str)857 assert prep.method == 'POST'858859 resp = s.send(prep)860 assert resp.status_code == 200861862 def test_non_prepared_request_error(self):863 s = requests.Session()864 req = requests.Request(u('POST'), '/')865866 with pytest.raises(ValueError) as e:867 s.send(req)868 assert str(e.value) == 'You can only send PreparedRequests.'869870 def test_custom_content_type(self, httpbin):871 r = requests.post(872 httpbin('post'),873 data={'stuff': json.dumps({'a': 123})},874 files={875 'file1': ('test_requests.py', open(__file__, 'rb')),876 'file2': ('test_requests', open(__file__, 'rb'),877 'text/py-content-type')})878 assert r.status_code == 200879 assert b"text/py-content-type" in r.request.body880881 def test_hook_receives_request_arguments(self, httpbin):882 def hook(resp, **kwargs):883 assert resp is not None884 assert kwargs != {}885886 s = requests.Session()887 r = requests.Request('GET', httpbin(), hooks={'response': hook})888 prep = s.prepare_request(r)889 s.send(prep)890891 def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):892 hook = lambda x, *args, **kwargs: x893 s = requests.Session()894 s.hooks['response'].append(hook)895 r = requests.Request('GET', httpbin())896 prep = s.prepare_request(r)897 assert prep.hooks['response'] != []898 assert prep.hooks['response'] == [hook]899900 def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):901 hook1 = lambda x, *args, **kwargs: x902 hook2 = lambda x, *args, **kwargs: x903 assert hook1 is not hook2904 s = requests.Session()905 s.hooks['response'].append(hook2)906 r = requests.Request('GET', httpbin(), hooks={'response': [hook1]})907 prep = s.prepare_request(r)908 assert prep.hooks['response'] == [hook1]909910 def test_prepared_request_hook(self, httpbin):911 def hook(resp, **kwargs):912 resp.hook_working = True913 return resp914915 req = requests.Request('GET', httpbin(), hooks={'response': hook})916 prep = req.prepare()917918 s = requests.Session()919 s.proxies = getproxies()920 resp = s.send(prep)921922 assert hasattr(resp, 'hook_working')923924 def test_prepared_from_session(self, httpbin):925 class DummyAuth(requests.auth.AuthBase):926 def __call__(self, r):927 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'928 return r929930 req = requests.Request('GET', httpbin('headers'))931 assert not req.auth932933 s = requests.Session()934 s.auth = DummyAuth()935936 prep = s.prepare_request(req)937 resp = s.send(prep)938939 assert resp.json()['headers'][940 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'941942 def test_prepare_request_with_bytestring_url(self):943 req = requests.Request('GET', b'https://httpbin.org/')944 s = requests.Session()945 prep = s.prepare_request(req)946 assert prep.url == "https://httpbin.org/"947

Merge pull request #3606 from bbamsch/httpbinTestFixCory Benfieldbefore adoption022e23c

line 948why, one step back
948 def test_request_with_bytestring_host(self, httpbin):

Merge pull request #3598 from bbamsch/bytestringHostFixCory Benfieldbefore adoption5eabcb7

lines 949–951why, one step back
949 s = requests.Session()
950 resp = s.request(951 'GET',

Merge pull request #3606 from bbamsch/httpbinTestFixCory Benfieldbefore adoption022e23c

line 952why, one step back
952 httpbin('cookies/set?cookie=value'),

Merge pull request #3598 from bbamsch/bytestringHostFixCory Benfieldbefore adoption5eabcb7

lines 953–957why, one step back
953 allow_redirects=False,
954 headers={'Host': b'httpbin.org'}955 )956 assert resp.cookies.get('cookie') == 'value'957

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 958–1121why, one step back
958 def test_links(self):
959 r = requests.Response()960 r.headers = {961 'cache-control': 'public, max-age=60, s-maxage=60',962 'connection': 'keep-alive',963 'content-encoding': 'gzip',964 'content-type': 'application/json; charset=utf-8',965 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',966 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',967 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',968 'link': ('<https://api.github.com/users/kennethreitz/repos?'969 'page=2&per_page=10>; rel="next", <https://api.github.'970 'com/users/kennethreitz/repos?page=7&per_page=10>; '971 ' rel="last"'),972 'server': 'GitHub.com',973 'status': '200 OK',974 'vary': 'Accept',975 'x-content-type-options': 'nosniff',976 'x-github-media-type': 'github.beta',977 'x-ratelimit-limit': '60',978 'x-ratelimit-remaining': '57'979 }980 assert r.links['next']['rel'] == 'next'981982 def test_cookie_parameters(self):983 key = 'some_cookie'984 value = 'some_value'985 secure = True986 domain = 'test.com'987 rest = {'HttpOnly': True}988989 jar = requests.cookies.RequestsCookieJar()990 jar.set(key, value, secure=secure, domain=domain, rest=rest)991992 assert len(jar) == 1993 assert 'some_cookie' in jar994995 cookie = list(jar)[0]996 assert cookie.secure == secure997 assert cookie.domain == domain998 assert cookie._rest['HttpOnly'] == rest['HttpOnly']9991000 def test_cookie_as_dict_keeps_len(self):1001 key = 'some_cookie'1002 value = 'some_value'10031004 key1 = 'some_cookie1'1005 value1 = 'some_value1'10061007 jar = requests.cookies.RequestsCookieJar()1008 jar.set(key, value)1009 jar.set(key1, value1)10101011 d1 = dict(jar)1012 d2 = dict(jar.iteritems())1013 d3 = dict(jar.items())10141015 assert len(jar) == 21016 assert len(d1) == 21017 assert len(d2) == 21018 assert len(d3) == 210191020 def test_cookie_as_dict_keeps_items(self):1021 key = 'some_cookie'1022 value = 'some_value'10231024 key1 = 'some_cookie1'1025 value1 = 'some_value1'10261027 jar = requests.cookies.RequestsCookieJar()1028 jar.set(key, value)1029 jar.set(key1, value1)10301031 d1 = dict(jar)1032 d2 = dict(jar.iteritems())1033 d3 = dict(jar.items())10341035 assert d1['some_cookie'] == 'some_value'1036 assert d2['some_cookie'] == 'some_value'1037 assert d3['some_cookie1'] == 'some_value1'10381039 def test_cookie_as_dict_keys(self):1040 key = 'some_cookie'1041 value = 'some_value'10421043 key1 = 'some_cookie1'1044 value1 = 'some_value1'10451046 jar = requests.cookies.RequestsCookieJar()1047 jar.set(key, value)1048 jar.set(key1, value1)10491050 keys = jar.keys()1051 assert keys == list(keys)1052 # make sure one can use keys multiple times1053 assert list(keys) == list(keys)10541055 def test_cookie_as_dict_values(self):1056 key = 'some_cookie'1057 value = 'some_value'10581059 key1 = 'some_cookie1'1060 value1 = 'some_value1'10611062 jar = requests.cookies.RequestsCookieJar()1063 jar.set(key, value)1064 jar.set(key1, value1)10651066 values = jar.values()1067 assert values == list(values)1068 # make sure one can use values multiple times1069 assert list(values) == list(values)10701071 def test_cookie_as_dict_items(self):1072 key = 'some_cookie'1073 value = 'some_value'10741075 key1 = 'some_cookie1'1076 value1 = 'some_value1'10771078 jar = requests.cookies.RequestsCookieJar()1079 jar.set(key, value)1080 jar.set(key1, value1)10811082 items = jar.items()1083 assert items == list(items)1084 # make sure one can use items multiple times1085 assert list(items) == list(items)10861087 def test_cookie_duplicate_names_different_domains(self):1088 key = 'some_cookie'1089 value = 'some_value'1090 domain1 = 'test1.com'1091 domain2 = 'test2.com'10921093 jar = requests.cookies.RequestsCookieJar()1094 jar.set(key, value, domain=domain1)1095 jar.set(key, value, domain=domain2)1096 assert key in jar1097 items = jar.items()1098 assert len(items) == 210991100 # Verify that CookieConflictError is raised if domain is not specified1101 with pytest.raises(requests.cookies.CookieConflictError):1102 jar.get(key)11031104 # Verify that CookieConflictError is not raised if domain is specified1105 cookie = jar.get(key, domain=domain1)1106 assert cookie == value11071108 def test_cookie_duplicate_names_raises_cookie_conflict_error(self):1109 key = 'some_cookie'1110 value = 'some_value'1111 path = 'some_path'11121113 jar = requests.cookies.RequestsCookieJar()1114 jar.set(key, value, path=path)1115 jar.set(key, value)1116 with pytest.raises(requests.cookies.CookieConflictError):1117 jar.get(key)11181119 def test_time_elapsed_blank(self, httpbin):1120 r = requests.get(httpbin('get'))1121 td = r.elapsed

Merge pull request #3428 from nateprewitt/pep8_fixesKenneth Reitzbefore adoption4285bac

line 1122why, one step back
1122 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6)

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 1123–1124why, one step back
1123 assert total_seconds > 0.0
1124

Merge pull request #3718 from nsoranzo/masterCory Benfieldbefore adoption36c9c8c

lines 1125–1128why, one step back
1125 def test_empty_response_has_content_none(self):
1126 r = requests.Response()1127 assert r.content is None1128

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 1129–1141why, one step back
1129 def test_response_is_iterable(self):
1130 r = requests.Response()1131 io = StringIO.StringIO('abc')1132 read_ = io.read11331134 def read_mock(amt, decode_content=None):1135 return read_(amt)1136 setattr(io, 'read', read_mock)1137 r.raw = io1138 assert next(iter(r))1139 io.close()11401141 def test_response_decode_unicode(self):

Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456

line 1142why, one step back
1142 """When called with decode_unicode, Response.iter_content should always

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 1143–1159why, one step back
1143 return unicode.
1144 """1145 r = requests.Response()1146 r._content_consumed = True1147 r._content = b'the content'1148 r.encoding = 'ascii'11491150 chunks = r.iter_content(decode_unicode=True)1151 assert all(isinstance(chunk, str) for chunk in chunks)11521153 # also for streaming1154 r = requests.Response()1155 r.raw = io.BytesIO(b'the content')1156 r.encoding = 'ascii'1157 chunks = r.iter_content(decode_unicode=True)1158 assert all(isinstance(chunk, str) for chunk in chunks)1159

Support responses like `HTTP/1.1 404 Unicode chars` (#3385)Andrii Kostenkobefore adoption7700eca

lines 1160–1166why, one step back
1160 def test_response_reason_unicode(self):
1161 # check for unicode HTTP status1162 r = requests.Response()1163 r.url = u'unicode URL'1164 r.reason = u'Komponenttia ei löydy'.encode('utf-8')1165 r.status_code = 4041166 r.encoding = None

Merge pull request #3428 from nateprewitt/pep8_fixesKenneth Reitzbefore adoption4285bac

line 1167why, one step back
1167 assert not r.ok # old behaviour - crashes here

Support responses like `HTTP/1.1 404 Unicode chars` (#3385)Andrii Kostenkobefore adoption7700eca

line 1168why, one step back
1168

Merge pull request #3554 from nateprewitt/3538_fallback_to_ISO_8591_1Ian Cordascobefore adoption87f9693

lines 1169–1172why, one step back
1169 def test_response_reason_unicode_fallback(self):
1170 # check raise_status falls back to ISO-8859-11171 r = requests.Response()1172 r.url = 'some url'

Merge pull request #3576 from nateprewitt/3557_revert_and_fix_encodingIan Cordascobefore adoptionddf7df9

lines 1173–1174why, one step back
1173 reason = u'Komponenttia ei löydy'
1174 r.reason = reason.encode('latin-1')

Merge pull request #3554 from nateprewitt/3538_fallback_to_ISO_8591_1Ian Cordascobefore adoption87f9693

lines 1175–1178why, one step back
1175 r.status_code = 500
1176 r.encoding = None1177 with pytest.raises(requests.exceptions.HTTPError) as e:1178 r.raise_for_status()

Merge pull request #3576 from nateprewitt/3557_revert_and_fix_encodingIan Cordascobefore adoptionddf7df9

line 1179why, one step back
1179 assert reason in e.value.args[0]

Merge pull request #3554 from nateprewitt/3538_fallback_to_ISO_8591_1Ian Cordascobefore adoption87f9693

line 1180why, one step back
1180

Allow None value for chunk_size again (#3368)Joy Zhengbefore adoption0bcf634

lines 1181–1182why, one step back
1181 def test_response_chunk_size_type(self):
1182 """Ensure that chunk_size is passed as None or an integer, otherwise

Merge pull request #3365 from nateprewitt/3364_chunking_is_intCory Benfieldbefore adoption36453b9

lines 1183–1188why, one step back
1183 raise a TypeError.
1184 """1185 r = requests.Response()1186 r.raw = io.BytesIO(b'the content')1187 chunks = r.iter_content(1)1188 assert all(len(chunk) == 1 for chunk in chunks)

Allow None value for chunk_size again (#3368)Joy Zhengbefore adoption0bcf634

lines 1189–1193why, one step back
1189
1190 r = requests.Response()1191 r.raw = io.BytesIO(b'the content')1192 chunks = r.iter_content(None)1193 assert list(chunks) == [b'the content']

Merge pull request #3365 from nateprewitt/3364_chunking_is_intCory Benfieldbefore adoption36453b9

lines 1194–1199why, one step back
1194
1195 r = requests.Response()1196 r.raw = io.BytesIO(b'the content')1197 with pytest.raises(TypeError):1198 chunks = r.iter_content("1024")1199

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 1200–1211why, one step back
1200 def test_request_and_response_are_pickleable(self, httpbin):
1201 r = requests.get(httpbin('get'))12021203 # verify we can pickle the original request1204 assert pickle.loads(pickle.dumps(r.request))12051206 # verify we can pickle the response and that we have access to1207 # the original request.1208 pr = pickle.loads(pickle.dumps(r))1209 assert r.request.url == pr.request.url1210 assert r.request.headers == pr.request.headers1211

Merge pull request #3489 from nateprewitt/1558_pickling_prepared_requestCory Benfieldbefore adoptiond24da4a

lines 1212–1257why, one step back
1212 def test_prepared_request_is_pickleable(self, httpbin):
1213 p = requests.Request('GET', httpbin('get')).prepare()12141215 # Verify PreparedRequest can be pickled and unpickled1216 r = pickle.loads(pickle.dumps(p))1217 assert r.url == p.url1218 assert r.headers == p.headers1219 assert r.body == p.body12201221 # Verify unpickled PreparedRequest sends properly1222 s = requests.Session()1223 resp = s.send(r)1224 assert resp.status_code == 20012251226 def test_prepared_request_with_file_is_pickleable(self, httpbin):1227 files = {'file': open(__file__, 'rb')}1228 r = requests.Request('POST', httpbin('post'), files=files)1229 p = r.prepare()12301231 # Verify PreparedRequest can be pickled and unpickled1232 r = pickle.loads(pickle.dumps(p))1233 assert r.url == p.url1234 assert r.headers == p.headers1235 assert r.body == p.body12361237 # Verify unpickled PreparedRequest sends properly1238 s = requests.Session()1239 resp = s.send(r)1240 assert resp.status_code == 20012411242 def test_prepared_request_with_hook_is_pickleable(self, httpbin):1243 r = requests.Request('GET', httpbin('get'), hooks=default_hooks())1244 p = r.prepare()12451246 # Verify PreparedRequest can be pickled1247 r = pickle.loads(pickle.dumps(p))1248 assert r.url == p.url1249 assert r.headers == p.headers1250 assert r.body == p.body1251 assert r.hooks == p.hooks12521253 # Verify unpickled PreparedRequest sends properly1254 s = requests.Session()1255 resp = s.send(r)1256 assert resp.status_code == 2001257

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 1258–1283why, one step back
1258 def test_cannot_send_unprepared_requests(self, httpbin):
1259 r = requests.Request(url=httpbin())1260 with pytest.raises(ValueError):1261 requests.Session().send(r)12621263 def test_http_error(self):1264 error = requests.exceptions.HTTPError()1265 assert not error.response1266 response = requests.Response()1267 error = requests.exceptions.HTTPError(response=response)1268 assert error.response == response1269 error = requests.exceptions.HTTPError('message', response=response)1270 assert str(error) == 'message'1271 assert error.response == response12721273 def test_session_pickling(self, httpbin):1274 r = requests.Request('GET', httpbin('get'))1275 s = requests.Session()12761277 s = pickle.loads(pickle.dumps(s))1278 s.proxies = getproxies()12791280 r = s.send(r.prepare())1281 assert r.status_code == 20012821283 def test_fixes_1329(self, httpbin):

Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456

line 1284why, one step back
1284 """Ensure that header updates are done case-insensitively."""

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 1285–1369why, one step back
1285 s = requests.Session()
1286 s.headers.update({'ACCEPT': 'BOGUS'})1287 s.headers.update({'accept': 'application/json'})1288 r = s.get(httpbin('get'))1289 headers = r.request.headers1290 assert headers['accept'] == 'application/json'1291 assert headers['Accept'] == 'application/json'1292 assert headers['ACCEPT'] == 'application/json'12931294 def test_uppercase_scheme_redirect(self, httpbin):1295 parts = urlparse(httpbin('html'))1296 url = "HTTP://" + parts.netloc + parts.path1297 r = requests.get(httpbin('redirect-to'), params={'url': url})1298 assert r.status_code == 2001299 assert r.url.lower() == url.lower()13001301 def test_transport_adapter_ordering(self):1302 s = requests.Session()1303 order = ['https://', 'http://']1304 assert order == list(s.adapters)1305 s.mount('http://git', HTTPAdapter())1306 s.mount('http://github', HTTPAdapter())1307 s.mount('http://github.com', HTTPAdapter())1308 s.mount('http://github.com/about/', HTTPAdapter())1309 order = [1310 'http://github.com/about/',1311 'http://github.com',1312 'http://github',1313 'http://git',1314 'https://',1315 'http://',1316 ]1317 assert order == list(s.adapters)1318 s.mount('http://gittip', HTTPAdapter())1319 s.mount('http://gittip.com', HTTPAdapter())1320 s.mount('http://gittip.com/about/', HTTPAdapter())1321 order = [1322 'http://github.com/about/',1323 'http://gittip.com/about/',1324 'http://github.com',1325 'http://gittip.com',1326 'http://github',1327 'http://gittip',1328 'http://git',1329 'https://',1330 'http://',1331 ]1332 assert order == list(s.adapters)1333 s2 = requests.Session()1334 s2.adapters = {'http://': HTTPAdapter()}1335 s2.mount('https://', HTTPAdapter())1336 assert 'http://' in s2.adapters1337 assert 'https://' in s2.adapters13381339 def test_header_remove_is_case_insensitive(self, httpbin):1340 # From issue #13211341 s = requests.Session()1342 s.headers['foo'] = 'bar'1343 r = s.get(httpbin('get'), headers={'FOO': None})1344 assert 'foo' not in r.request.headers13451346 def test_params_are_merged_case_sensitive(self, httpbin):1347 s = requests.Session()1348 s.params['foo'] = 'bar'1349 r = s.get(httpbin('get'), params={'FOO': 'bar'})1350 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}13511352 def test_long_authinfo_in_url(self):1353 url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(1354 'E8A3BE87-9E3F-4620-8858-95478E385B5B',1355 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',1356 'exactly-------------sixty-----------three------------characters',1357 )1358 r = requests.Request('GET', url).prepare()1359 assert r.url == url13601361 def test_header_keys_are_native(self, httpbin):1362 headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}1363 r = requests.Request('GET', httpbin('get'), headers=headers)1364 p = r.prepare()13651366 # This is testing that they are builtin strings. A bit weird, but there1367 # we go.1368 assert 'unicode' in p.headers.keys()1369 assert 'byte' in p.headers.keys()

Merge pull request #3366 from nateprewitt/2947-no-returns-in-headerCory Benfieldbefore adoptionbd9e8f2

line 1370why, one step back
1370

Merge pull request #3390 from nateprewitt/3386_header_value_typeCory Benfieldbefore adoption425962c

line 1371why, one step back
1371 def test_header_validation(self, httpbin):

Merge pull request #3366 from nateprewitt/2947-no-returns-in-headerCory Benfieldbefore adoptionbd9e8f2

lines 1372–1373why, one step back
1372 """Ensure prepare_headers regex isn't flagging valid header contents."""
1373 headers_ok = {'foo': 'bar baz qux',

Merge pull request #3390 from nateprewitt/3386_header_value_typeCory Benfieldbefore adoption425962c

line 1374why, one step back
1374 'bar': u'fbbq'.encode('utf8'),

Merge pull request #3366 from nateprewitt/2947-no-returns-in-headerCory Benfieldbefore adoptionbd9e8f2

line 1375why, one step back
1375 'baz': '',

Merge pull request #3390 from nateprewitt/3386_header_value_typeCory Benfieldbefore adoption425962c

line 1376why, one step back
1376 'qux': '1'}

Merge pull request #3366 from nateprewitt/2947-no-returns-in-headerCory Benfieldbefore adoptionbd9e8f2

lines 1377–1378why, one step back
1377 r = requests.get(httpbin('get'), headers=headers_ok)
1378 assert r.request.headers['foo'] == headers_ok['foo']

Merge pull request #3390 from nateprewitt/3386_header_value_typeCory Benfieldbefore adoption425962c

lines 1379–1384why, one step back
1379
1380 def test_header_value_not_str(self, httpbin):1381 """Ensure the header value is of type string or bytes as1382 per discussion in GH issue #33861383 """1384 headers_int = {'foo': 3}

Merge pull request #3428 from nateprewitt/pep8_fixesKenneth Reitzbefore adoption4285bac

line 1385why, one step back
1385 headers_dict = {'bar': {'foo': 'bar'}}

Merge pull request #3390 from nateprewitt/3386_header_value_typeCory Benfieldbefore adoption425962c

lines 1386–1396why, one step back
1386 headers_list = {'baz': ['foo', 'bar']}
13871388 # Test for int1389 with pytest.raises(InvalidHeader):1390 r = requests.get(httpbin('get'), headers=headers_int)1391 # Test for dict1392 with pytest.raises(InvalidHeader):1393 r = requests.get(httpbin('get'), headers=headers_dict)1394 # Test for list1395 with pytest.raises(InvalidHeader):1396 r = requests.get(httpbin('get'), headers=headers_list)

Merge pull request #3366 from nateprewitt/2947-no-returns-in-headerCory Benfieldbefore adoptionbd9e8f2

lines 1397–1428why, one step back
1397
1398 def test_header_no_return_chars(self, httpbin):1399 """Ensure that a header containing return character sequences raise an1400 exception. Otherwise, multiple headers are created from single string.1401 """1402 headers_ret = {'foo': 'bar\r\nbaz: qux'}1403 headers_lf = {'foo': 'bar\nbaz: qux'}1404 headers_cr = {'foo': 'bar\rbaz: qux'}14051406 # Test for newline1407 with pytest.raises(InvalidHeader):1408 r = requests.get(httpbin('get'), headers=headers_ret)1409 # Test for line feed1410 with pytest.raises(InvalidHeader):1411 r = requests.get(httpbin('get'), headers=headers_lf)1412 # Test for carriage return1413 with pytest.raises(InvalidHeader):1414 r = requests.get(httpbin('get'), headers=headers_cr)14151416 def test_header_no_leading_space(self, httpbin):1417 """Ensure headers containing leading whitespace raise1418 InvalidHeader Error before sending.1419 """1420 headers_space = {'foo': ' bar'}1421 headers_tab = {'foo': ' bar'}14221423 # Test for whitespace1424 with pytest.raises(InvalidHeader):1425 r = requests.get(httpbin('get'), headers=headers_space)1426 # Test for tab1427 with pytest.raises(InvalidHeader):1428 r = requests.get(httpbin('get'), headers=headers_tab)

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 1429–1464why, one step back
1429
1430 @pytest.mark.parametrize('files', ('foo', b'foo', bytearray(b'foo')))1431 def test_can_send_objects_with_files(self, httpbin, files):1432 data = {'a': 'this is a string'}1433 files = {'b': files}1434 r = requests.Request('POST', httpbin('post'), data=data, files=files)1435 p = r.prepare()1436 assert 'multipart/form-data' in p.headers['Content-Type']14371438 def test_can_send_file_object_with_non_string_filename(self, httpbin):1439 f = io.BytesIO()1440 f.name = 21441 r = requests.Request('POST', httpbin('post'), files={'f': f})1442 p = r.prepare()14431444 assert 'multipart/form-data' in p.headers['Content-Type']14451446 def test_autoset_header_values_are_native(self, httpbin):1447 data = 'this is a string'1448 length = '16'1449 req = requests.Request('POST', httpbin('post'), data=data)1450 p = req.prepare()14511452 assert p.headers['Content-Length'] == length14531454 def test_nonhttp_schemes_dont_check_URLs(self):1455 test_urls = (1456 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',1457 'file:///etc/passwd',1458 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',1459 )1460 for test_url in test_urls:1461 req = requests.Request('GET', test_url)1462 preq = req.prepare()1463 assert test_url == preq.url1464

Merge pull request #3236 from eriol/xfail-testKenneth Reitzbefore adoption771ecd7

line 1465why, one step back
1465 @pytest.mark.xfail(raises=ConnectionError)

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 1466–1499why, one step back
1466 def test_auth_is_stripped_on_redirect_off_host(self, httpbin):
1467 r = requests.get(1468 httpbin('redirect-to'),1469 params={'url': 'http://www.google.co.uk'},1470 auth=('user', 'pass'),1471 )1472 assert r.history[0].request.headers['Authorization']1473 assert not r.request.headers.get('Authorization', '')14741475 def test_auth_is_retained_for_redirect_on_host(self, httpbin):1476 r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))1477 h1 = r.history[0].request.headers['Authorization']1478 h2 = r.request.headers['Authorization']14791480 assert h1 == h214811482 def test_manual_redirect_with_partial_body_read(self, httpbin):1483 s = requests.Session()1484 r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)1485 assert r1.is_redirect1486 rg = s.resolve_redirects(r1, r1.request, stream=True)14871488 # read only the first eight bytes of the response body,1489 # then follow the redirect1490 r1.iter_content(8)1491 r2 = next(rg)1492 assert r2.is_redirect14931494 # read all of the response via iter_content,1495 # then follow the redirect1496 for _ in r2.iter_content():1497 pass1498 r3 = next(rg)1499 assert not r3.is_redirect

Merge pull request #3655 from nateprewitt/tzickel_post_redirect_w_streamableCory Benfieldbefore adoptionf72684e

lines 1500–1564why, one step back
1500
1501 def test_prepare_body_position_non_stream(self):1502 data = b'the data'1503 s = requests.Session()1504 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1505 assert prep._body_position is None15061507 def test_rewind_body(self):1508 data = io.BytesIO(b'the data')1509 s = requests.Session()1510 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1511 assert prep._body_position == 01512 assert prep.body.read() == b'the data'15131514 # the data has all been read1515 assert prep.body.read() == b''15161517 # rewind it back1518 requests.utils.rewind_body(prep)1519 assert prep.body.read() == b'the data'15201521 def test_rewind_partially_read_body(self):1522 data = io.BytesIO(b'the data')1523 s = requests.Session()1524 data.read(4) # read some data1525 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1526 assert prep._body_position == 41527 assert prep.body.read() == b'data'15281529 # the data has all been read1530 assert prep.body.read() == b''15311532 # rewind it back1533 requests.utils.rewind_body(prep)1534 assert prep.body.read() == b'data'15351536 def test_rewind_body_no_seek(self):1537 class BadFileObj:1538 def __init__(self, data):1539 self.data = data15401541 def tell(self):1542 return 015431544 def __iter__(self):1545 return15461547 data = BadFileObj('the data')1548 s = requests.Session()1549 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1550 assert prep._body_position == 015511552 with pytest.raises(UnrewindableBodyError) as e:1553 requests.utils.rewind_body(prep)15541555 assert 'Unable to rewind request body' in str(e)15561557 def test_rewind_body_failed_seek(self):1558 class BadFileObj:1559 def __init__(self, data):1560 self.data = data15611562 def tell(self):1563 return 01564

Merge branch 'master' of github.com:kennethreitz/requestsKenneth Reitzbefore adoptionb60c5a5

line 1565why, one step back
1565 def seek(self, pos, whence=0):

Merge pull request #3655 from nateprewitt/tzickel_post_redirect_w_streamableCory Benfieldbefore adoptionf72684e

lines 1566–1578why, one step back
1566 raise OSError()
15671568 def __iter__(self):1569 return15701571 data = BadFileObj('the data')1572 s = requests.Session()1573 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1574 assert prep._body_position == 015751576 with pytest.raises(UnrewindableBodyError) as e:1577 requests.utils.rewind_body(prep)1578

Merge branch 'master' of github.com:kennethreitz/requestsKenneth Reitzbefore adoptionb60c5a5

line 1579why, one step back
1579 assert 'error occurred when rewinding request body' in str(e)

Merge pull request #3655 from nateprewitt/tzickel_post_redirect_w_streamableCory Benfieldbefore adoptionf72684e

lines 1580–1600why, one step back
1580
1581 def test_rewind_body_failed_tell(self):1582 class BadFileObj:1583 def __init__(self, data):1584 self.data = data15851586 def tell(self):1587 raise OSError()15881589 def __iter__(self):1590 return15911592 data = BadFileObj('the data')1593 s = requests.Session()1594 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1595 assert prep._body_position is not None15961597 with pytest.raises(UnrewindableBodyError) as e:1598 requests.utils.rewind_body(prep)15991600 assert 'Unable to rewind request body' in str(e)

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 1601–1621why, one step back
1601
1602 def _patch_adapter_gzipped_redirect(self, session, url):1603 adapter = session.get_adapter(url=url)1604 org_build_response = adapter.build_response1605 self._patched_response = False16061607 def build_response(*args, **kwargs):1608 resp = org_build_response(*args, **kwargs)1609 if not self._patched_response:1610 resp.raw.headers['content-encoding'] = 'gzip'1611 self._patched_response = True1612 return resp16131614 adapter.build_response = build_response16151616 def test_redirect_with_wrong_gzipped_header(self, httpbin):1617 s = requests.Session()1618 url = httpbin('redirect/1')1619 self._patch_adapter_gzipped_redirect(s, url)1620 s.get(url)1621

Merge pull request #3673 from klimenko-forks/auth-unicodeCory Benfieldbefore adoptionb9f1c44

lines 1622–1628why, one step back
1622 @pytest.mark.parametrize(
1623 'username, password, auth_str', (1624 ('test', 'test', 'Basic dGVzdDp0ZXN0'),1625 (u'имя'.encode('utf-8'), u'пароль'.encode('utf-8'), 'Basic 0LjQvNGPOtC/0LDRgNC+0LvRjA=='),1626 ))1627 def test_basic_auth_str_is_always_native(self, username, password, auth_str):1628 s = _basic_auth_str(username, password)

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

line 1629why, one step back
1629 assert isinstance(s, builtin_str)

Merge pull request #3673 from klimenko-forks/auth-unicodeCory Benfieldbefore adoptionb9f1c44

line 1630why, one step back
1630 assert s == auth_str

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 1631–1692why, one step back
1631
1632 def test_requests_history_is_saved(self, httpbin):1633 r = requests.get(httpbin('redirect/5'))1634 total = r.history[-1].history1635 i = 01636 for item in r.history:1637 assert item.history == total[0:i]1638 i += 116391640 def test_json_param_post_content_type_works(self, httpbin):1641 r = requests.post(1642 httpbin('post'),1643 json={'life': 42}1644 )1645 assert r.status_code == 2001646 assert 'application/json' in r.request.headers['Content-Type']1647 assert {'life': 42} == r.json()['json']16481649 def test_json_param_post_should_not_override_data_param(self, httpbin):1650 r = requests.Request(method='POST', url=httpbin('post'),1651 data={'stuff': 'elixr'},1652 json={'music': 'flute'})1653 prep = r.prepare()1654 assert 'stuff=elixr' == prep.body16551656 def test_response_iter_lines(self, httpbin):1657 r = requests.get(httpbin('stream/4'), stream=True)1658 assert r.status_code == 20016591660 it = r.iter_lines()1661 next(it)1662 assert len(list(it)) == 316631664 def test_unconsumed_session_response_closes_connection(self, httpbin):1665 s = requests.session()16661667 with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1668 pass16691670 assert response._content_consumed is False1671 assert response.raw.closed16721673 @pytest.mark.xfail1674 def test_response_iter_lines_reentrant(self, httpbin):1675 """Response.iter_lines() is not reentrant safe"""1676 r = requests.get(httpbin('stream/4'), stream=True)1677 assert r.status_code == 20016781679 next(r.iter_lines())1680 assert len(list(r.iter_lines())) == 316811682 def test_session_close_proxy_clear(self, mocker):1683 proxies = {1684 'one': mocker.Mock(),1685 'two': mocker.Mock(),1686 }1687 session = requests.Session()1688 mocker.patch.dict(session.adapters['http://'].proxy_manager, proxies)1689 session.close()1690 proxies['one'].clear.assert_called_once_with()1691 proxies['two'].clear.assert_called_once_with()1692

Merge pull request #3660 from pawelmhm/proxy_empty_passCory Benfieldbefore adoptionbf19750

lines 1693–1702why, one step back
1693 def test_proxy_auth(self, httpbin):
1694 adapter = HTTPAdapter()1695 headers = adapter.proxy_headers("http://user:pass@httpbin.org")1696 assert headers == {'Proxy-Authorization': 'Basic dXNlcjpwYXNz'}16971698 def test_proxy_auth_empty_pass(self, httpbin):1699 adapter = HTTPAdapter()1700 headers = adapter.proxy_headers("http://user:@httpbin.org")1701 assert headers == {'Proxy-Authorization': 'Basic dXNlcjo='}1702

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 1703–1713why, one step back
1703 def test_response_json_when_content_is_None(self, httpbin):
1704 r = requests.get(httpbin('/status/204'))1705 # Make sure r.content is None1706 r.status_code = 01707 r._content = False1708 r._content_consumed = False17091710 assert r.content is None1711 with pytest.raises(ValueError):1712 r.json()1713

Merge pull request #3510 from nateprewitt/add_close_passthroughCory Benfieldbefore adoptiond3567aa

lines 1714–1722why, one step back
1714 def test_response_without_release_conn(self):
1715 """Test `close` call for non-urllib3-like raw objects.1716 Should work when `release_conn` attr doesn't exist on `response.raw`.1717 """1718 resp = requests.Response()1719 resp.raw = StringIO.StringIO('test')1720 assert not resp.raw.closed1721 resp.close()1722 assert resp.raw.closed

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

line 1723why, one step back
1723

Merge pull request #3754 from nateprewitt/3066_auth_and_dataCory Benfieldbefore adoption11a86a5

lines 1724–1758why, one step back
1724 def test_empty_stream_with_auth_does_not_set_content_length_header(self, httpbin):
1725 """Ensure that a byte stream with size 0 will not set both a Content-Length1726 and Transfer-Encoding header.1727 """1728 auth = ('user', 'pass')1729 url = httpbin('post')1730 file_obj = io.BytesIO(b'')1731 r = requests.Request('POST', url, auth=auth, data=file_obj)1732 prepared_request = r.prepare()1733 assert 'Transfer-Encoding' in prepared_request.headers1734 assert 'Content-Length' not in prepared_request.headers17351736 def test_stream_with_auth_does_not_set_transfer_encoding_header(self, httpbin):1737 """Ensure that a byte stream with size > 0 will not set both a Content-Length1738 and Transfer-Encoding header.1739 """1740 auth = ('user', 'pass')1741 url = httpbin('post')1742 file_obj = io.BytesIO(b'test data')1743 r = requests.Request('POST', url, auth=auth, data=file_obj)1744 prepared_request = r.prepare()1745 assert 'Transfer-Encoding' not in prepared_request.headers1746 assert 'Content-Length' in prepared_request.headers17471748 def test_chunked_upload_does_not_set_content_length_header(self, httpbin):1749 """Ensure that requests with a generator body stream using1750 Transfer-Encoding: chunked, not a Content-Length header.1751 """1752 data = (i for i in [b'a', b'b', b'c'])1753 url = httpbin('post')1754 r = requests.Request('POST', url, data=data)1755 prepared_request = r.prepare()1756 assert 'Transfer-Encoding' in prepared_request.headers1757 assert 'Content-Length' not in prepared_request.headers1758

Merge pull request #3846 from jvanasco/feature-pluggable_handlingKenneth Reitzbefore adoption4533979

lines 1759–1801why, one step back
1759 def test_custom_redirect_mixin(self, httpbin):
1760 """Tests a custom mixin to overwrite ``get_redirect_target``.17611762 Ensures a subclassed ``requests.Session`` can handle a certain type of1763 malformed redirect responses.17641765 1. original request receives a proper response: 302 redirect1766 2. following the redirect, a malformed response is given:1767 status code = HTTP 2001768 location = alternate url1769 3. the custom session catches the edge case and follows the redirect1770 """1771 url_final = httpbin('html')1772 querystring_malformed = urlencode({'location': url_final})1773 url_redirect_malformed = httpbin('response-headers?%s' % querystring_malformed)1774 querystring_redirect = urlencode({'url': url_redirect_malformed})1775 url_redirect = httpbin('redirect-to?%s' % querystring_redirect)1776 urls_test = [url_redirect,1777 url_redirect_malformed,1778 url_final,1779 ]17801781 class CustomRedirectSession(requests.Session):1782 def get_redirect_target(self, resp):1783 # default behavior1784 if resp.is_redirect:1785 return resp.headers['location']1786 # edge case - check to see if 'location' is in headers anyways1787 location = resp.headers.get('location')1788 if location and (location != resp.url):1789 return location1790 return None17911792 session = CustomRedirectSession()1793 r = session.get(urls_test[0])1794 assert len(r.history) == 21795 assert r.status_code == 2001796 assert r.history[0].status_code == 3021797 assert r.history[0].is_redirect1798 assert r.history[1].status_code == 2001799 assert not r.history[1].is_redirect1800 assert r.url == urls_test[2]1801

Merge pull request #3754 from nateprewitt/3066_auth_and_dataCory Benfieldbefore adoption11a86a5

line 1802why, one step back
1802

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

lines 1803–2008why, one step back
1803class TestCaseInsensitiveDict:
18041805 @pytest.mark.parametrize(1806 'cid', (1807 CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}),1808 CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')]),1809 CaseInsensitiveDict(FOO='foo', BAr='bar'),1810 ))1811 def test_init(self, cid):1812 assert len(cid) == 21813 assert 'foo' in cid1814 assert 'bar' in cid18151816 def test_docstring_example(self):1817 cid = CaseInsensitiveDict()1818 cid['Accept'] = 'application/json'1819 assert cid['aCCEPT'] == 'application/json'1820 assert list(cid) == ['Accept']18211822 def test_len(self):1823 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1824 cid['A'] = 'a'1825 assert len(cid) == 218261827 def test_getitem(self):1828 cid = CaseInsensitiveDict({'Spam': 'blueval'})1829 assert cid['spam'] == 'blueval'1830 assert cid['SPAM'] == 'blueval'18311832 def test_fixes_649(self):1833 """__setitem__ should behave case-insensitively."""1834 cid = CaseInsensitiveDict()1835 cid['spam'] = 'oneval'1836 cid['Spam'] = 'twoval'1837 cid['sPAM'] = 'redval'1838 cid['SPAM'] = 'blueval'1839 assert cid['spam'] == 'blueval'1840 assert cid['SPAM'] == 'blueval'1841 assert list(cid.keys()) == ['SPAM']18421843 def test_delitem(self):1844 cid = CaseInsensitiveDict()1845 cid['Spam'] = 'someval'1846 del cid['sPam']1847 assert 'spam' not in cid1848 assert len(cid) == 018491850 def test_contains(self):1851 cid = CaseInsensitiveDict()1852 cid['Spam'] = 'someval'1853 assert 'Spam' in cid1854 assert 'spam' in cid1855 assert 'SPAM' in cid1856 assert 'sPam' in cid1857 assert 'notspam' not in cid18581859 def test_get(self):1860 cid = CaseInsensitiveDict()1861 cid['spam'] = 'oneval'1862 cid['SPAM'] = 'blueval'1863 assert cid.get('spam') == 'blueval'1864 assert cid.get('SPAM') == 'blueval'1865 assert cid.get('sPam') == 'blueval'1866 assert cid.get('notspam', 'default') == 'default'18671868 def test_update(self):1869 cid = CaseInsensitiveDict()1870 cid['spam'] = 'blueval'1871 cid.update({'sPam': 'notblueval'})1872 assert cid['spam'] == 'notblueval'1873 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1874 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1875 assert len(cid) == 21876 assert cid['foo'] == 'anotherfoo'1877 assert cid['bar'] == 'anotherbar'18781879 def test_update_retains_unchanged(self):1880 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1881 cid.update({'foo': 'newfoo'})1882 assert cid['bar'] == 'bar'18831884 def test_iter(self):1885 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1886 keys = frozenset(['Spam', 'Eggs'])1887 assert frozenset(iter(cid)) == keys18881889 def test_equality(self):1890 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1891 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1892 assert cid == othercid1893 del othercid['spam']1894 assert cid != othercid1895 assert cid == {'spam': 'blueval', 'eggs': 'redval'}1896 assert cid != object()18971898 def test_setdefault(self):1899 cid = CaseInsensitiveDict({'Spam': 'blueval'})1900 assert cid.setdefault('spam', 'notblueval') == 'blueval'1901 assert cid.setdefault('notspam', 'notblueval') == 'notblueval'19021903 def test_lower_items(self):1904 cid = CaseInsensitiveDict({1905 'Accept': 'application/json',1906 'user-Agent': 'requests',1907 })1908 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1909 lowerkeyset = frozenset(['accept', 'user-agent'])1910 assert keyset == lowerkeyset19111912 def test_preserve_key_case(self):1913 cid = CaseInsensitiveDict({1914 'Accept': 'application/json',1915 'user-Agent': 'requests',1916 })1917 keyset = frozenset(['Accept', 'user-Agent'])1918 assert frozenset(i[0] for i in cid.items()) == keyset1919 assert frozenset(cid.keys()) == keyset1920 assert frozenset(cid) == keyset19211922 def test_preserve_last_key_case(self):1923 cid = CaseInsensitiveDict({1924 'Accept': 'application/json',1925 'user-Agent': 'requests',1926 })1927 cid.update({'ACCEPT': 'application/json'})1928 cid['USER-AGENT'] = 'requests'1929 keyset = frozenset(['ACCEPT', 'USER-AGENT'])1930 assert frozenset(i[0] for i in cid.items()) == keyset1931 assert frozenset(cid.keys()) == keyset1932 assert frozenset(cid) == keyset19331934 def test_copy(self):1935 cid = CaseInsensitiveDict({1936 'Accept': 'application/json',1937 'user-Agent': 'requests',1938 })1939 cid_copy = cid.copy()1940 assert cid == cid_copy1941 cid['changed'] = True1942 assert cid != cid_copy194319441945class TestMorselToCookieExpires:1946 """Tests for morsel_to_cookie when morsel contains expires."""19471948 def test_expires_valid_str(self):1949 """Test case where we convert expires from string time."""19501951 morsel = Morsel()1952 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1953 cookie = morsel_to_cookie(morsel)1954 assert cookie.expires == 119551956 @pytest.mark.parametrize(1957 'value, exception', (1958 (100, TypeError),1959 ('woops', ValueError),1960 ))1961 def test_expires_invalid_int(self, value, exception):1962 """Test case where an invalid type is passed for expires."""1963 morsel = Morsel()1964 morsel['expires'] = value1965 with pytest.raises(exception):1966 morsel_to_cookie(morsel)19671968 def test_expires_none(self):1969 """Test case where expires is None."""19701971 morsel = Morsel()1972 morsel['expires'] = None1973 cookie = morsel_to_cookie(morsel)1974 assert cookie.expires is None197519761977class TestMorselToCookieMaxAge:19781979 """Tests for morsel_to_cookie when morsel contains max-age."""19801981 def test_max_age_valid_int(self):1982 """Test case where a valid max age in seconds is passed."""19831984 morsel = Morsel()1985 morsel['max-age'] = 601986 cookie = morsel_to_cookie(morsel)1987 assert isinstance(cookie.expires, int)19881989 def test_max_age_invalid_str(self):1990 """Test case where a invalid max age is passed."""19911992 morsel = Morsel()1993 morsel['max-age'] = 'woops'1994 with pytest.raises(TypeError):1995 morsel_to_cookie(morsel)199619971998class TestTimeout:19992000 def test_stream_timeout(self, httpbin):

The first 2,000 of 2,354 lines.