test_requests.py
This file
Path
tests/test_requests.py
2,176 lines · 74.3 KiB · Python
Last changed by
Merge pull request #3673 from klimenko-forks/auth-unicodeCory Benfieldbefore adoptionb9f1c44
History of this fileTake it
Added tests module.Dmitry Dygalobefore adoption18b26d2
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 warningsAdded tests module.Dmitry Dygalobefore adoption18b26d2
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)Added tests module.Dmitry Dygalobefore adoption18b26d2
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)Added tests module.Dmitry Dygalobefore adoption18b26d2
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_environAdded tests module.Dmitry Dygalobefore adoption18b26d2
lines 36–38why, one step back3637# Requests to this URL should always fail with a connection timeout (nothing38# listening on that port)syntax changesKenneth Reitzbefore adoptionbbadf47
line 39why, one step back39TARPIT = 'http://10.255.255.1'Added tests module.Dmitry Dygalobefore adoption18b26d2
line 40why, one step back40Test 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 = FalseAdded tests module.Dmitry Dygalobefore adoption18b26d2
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 = False5354Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 55–67why, 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.post67syntax changesKenneth Reitzbefore adoptionbbadf47
lines 68–69why, one step back68 @pytest.mark.parametrize(69 'exception, url', (Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 70–74why, one step back70 (MissingSchema, 'hiwpefhipowhefopw'),71 (InvalidSchema, 'localhost:3128'),72 (InvalidSchema, 'localhost.localdomain:3128/'),73 (InvalidSchema, '10.122.1.1:3128/'),74 (InvalidURL, 'http://'),syntax changesKenneth Reitzbefore adoptionbbadf47
line 75why, one step back75 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 76–93why, one step back76 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'103Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 104–116why, 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'116syntax changesKenneth Reitzbefore adoptionbbadf47
lines 117–118why, one step back117 @pytest.mark.parametrize(118 'url, expected', (Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 119–120why, one step back119 ('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')syntax changesKenneth Reitzbefore adoptionbbadf47
line 121why, one step back121 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 122–142why, one step back122 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/'147Added tests module.Dmitry Dygalobefore adoption18b26d2
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')187Added tests module.Dmitry Dygalobefore adoption18b26d2
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.headers294Added tests module.Dmitry Dygalobefore adoption18b26d2
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'Added tests module.Dmitry Dygalobefore adoption18b26d2
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')451Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 452–454why, one step back452 @pytest.mark.parametrize('key', ('User-agent', 'user-agent'))453 def test_user_agent_transfers(self, httpbin, key):454syntax changesKenneth Reitzbefore adoptionbbadf47
line 455why, one step back455 heads = {key: 'Mozilla/5.0 (github.com/kennethreitz/requests)'}Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 456–483why, one step back456457 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–497why, one step back484 'username, password', (485 ('user', 'pass'),486 (u'имя'.encode('utf-8'), u'пароль'.encode('utf-8')),487 ))488 def test_set_basicauth(self, httpbin, username, password):489 auth = (username, password)490 url = httpbin('get')491492 r = requests.Request('GET', url, auth=auth)493 p = r.prepare()494495 assert p.headers['Authorization'] == _basic_auth_str(username, password)496497 @pytest.mark.parametrize(Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 498–504why, one step back498 'url, exception', (499 # Connecting to an unknown domain should raise a ConnectionError500 ('http://doesnotexist.google.com', ConnectionError),501 # Connecting to an invalid port should raise a ConnectionError502 ('http://localhost:1', ConnectionError),503 # Inputing a URL that cannot be parsed should raise an InvalidURL error504 ('http://fe80::5054:ff:fe5a:fc0', InvalidURL)syntax changesKenneth Reitzbefore adoptionbbadf47
line 505why, one step back505 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 506–508why, one step back506 def test_errors(self, url, exception):507 with pytest.raises(exception):508 requests.get(url, timeout=1)Merge pull request #3059 from alexanderad/proxy-connection-errorsKenneth Reitzbefore adoption03ed671
lines 509–513why, one step back509510 def test_proxy_error(self):511 # any proxy related error (address resolution, no route to host, etc) should result in a ProxyError512 with pytest.raises(ProxyError):513 requests.get('http://localhost:1', proxies={'http': 'non-resolvable-address'})Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 514–632why, one step back514515 def test_basicauth_with_netrc(self, httpbin):516 auth = ('user', 'pass')517 wrong_auth = ('wronguser', 'wrongpass')518 url = httpbin('basic-auth', 'user', 'pass')519520 old_auth = requests.sessions.get_netrc_auth521522 try:523 def get_netrc_auth_mock(url):524 return auth525 requests.sessions.get_netrc_auth = get_netrc_auth_mock526527 # Should use netrc and work.528 r = requests.get(url)529 assert r.status_code == 200530531 # Given auth should override and fail.532 r = requests.get(url, auth=wrong_auth)533 assert r.status_code == 401534535 s = requests.session()536537 # Should use netrc and work.538 r = s.get(url)539 assert r.status_code == 200540541 # Given auth should override and fail.542 s.auth = wrong_auth543 r = s.get(url)544 assert r.status_code == 401545 finally:546 requests.sessions.get_netrc_auth = old_auth547548 def test_DIGEST_HTTP_200_OK_GET(self, httpbin):549550 auth = HTTPDigestAuth('user', 'pass')551 url = httpbin('digest-auth', 'auth', 'user', 'pass')552553 r = requests.get(url, auth=auth)554 assert r.status_code == 200555556 r = requests.get(url)557 assert r.status_code == 401558559 s = requests.session()560 s.auth = HTTPDigestAuth('user', 'pass')561 r = s.get(url)562 assert r.status_code == 200563564 def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):565 url = httpbin('digest-auth', 'auth', 'user', 'pass')566 auth = HTTPDigestAuth('user', 'pass')567 r = requests.get(url)568 assert r.cookies['fake'] == 'fake_value'569570 r = requests.get(url, auth=auth)571 assert r.status_code == 200572573 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):574 url = httpbin('digest-auth', 'auth', 'user', 'pass')575 auth = HTTPDigestAuth('user', 'pass')576 s = requests.Session()577 s.get(url, auth=auth)578 assert s.cookies['fake'] == 'fake_value'579580 def test_DIGEST_STREAM(self, httpbin):581582 auth = HTTPDigestAuth('user', 'pass')583 url = httpbin('digest-auth', 'auth', 'user', 'pass')584585 r = requests.get(url, auth=auth, stream=True)586 assert r.raw.read() != b''587588 r = requests.get(url, auth=auth, stream=False)589 assert r.raw.read() == b''590591 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):592593 auth = HTTPDigestAuth('user', 'wrongpass')594 url = httpbin('digest-auth', 'auth', 'user', 'pass')595596 r = requests.get(url, auth=auth)597 assert r.status_code == 401598599 r = requests.get(url)600 assert r.status_code == 401601602 s = requests.session()603 s.auth = auth604 r = s.get(url)605 assert r.status_code == 401606607 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):608609 auth = HTTPDigestAuth('user', 'pass')610 url = httpbin('digest-auth', 'auth', 'user', 'pass')611612 r = requests.get(url, auth=auth)613 assert '"auth"' in r.request.headers['Authorization']614615 def test_POSTBIN_GET_POST_FILES(self, httpbin):616617 url = httpbin('post')618 requests.post(url).raise_for_status()619620 post1 = requests.post(url, data={'some': 'data'})621 assert post1.status_code == 200622623 with open('requirements.txt') as f:624 post2 = requests.post(url, files={'some': f})625 assert post2.status_code == 200626627 post4 = requests.post(url, data='[{"some": "json"}]')628 assert post4.status_code == 200629630 with pytest.raises(ValueError):631 requests.post(url, files=['bad file data'])632Merge pull request #3082 from tzickel/masterIan Cordascobefore adoptione65d6fc
lines 633–674why, one step back633 def test_POSTBIN_SEEKED_OBJECT_WITH_NO_ITER(self, httpbin):634635 class TestStream(object):636 def __init__(self, data):637 self.data = data.encode()638 self.length = len(self.data)639 self.index = 0640641 def __len__(self):642 return self.length643644 def read(self, size=None):645 if size:646 ret = self.data[self.index:self.index + size]647 self.index += size648 else:649 ret = self.data[self.index:]650 self.index = self.length651 return ret652653 def tell(self):654 return self.index655656 def seek(self, offset, where=0):657 if where == 0:658 self.index = offset659 elif where == 1:660 self.index += offset661 elif where == 2:662 self.index = self.length + offset663664 test = TestStream('test')665 post1 = requests.post(httpbin('post'), data=test)666 assert post1.status_code == 200667 assert post1.json()['data'] == 'test'668669 test = TestStream('test')670 test.seek(2)671 post2 = requests.post(httpbin('post'), data=test)672 assert post2.status_code == 200673 assert post2.json()['data'] == 'st'674Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 675–683why, one step back675 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):676677 url = httpbin('post')678 requests.post(url).raise_for_status()679680 post1 = requests.post(url, data={'some': 'data'})681 assert post1.status_code == 200682683 with open('requirements.txt') as f:Merge pull request #3428 from nateprewitt/pep8_fixesKenneth Reitzbefore adoption4285bac
line 684why, one step back684 post2 = requests.post(url, data={'some': 'data'}, files={'some': f})Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 685–692why, one step back685 assert post2.status_code == 200686687 post4 = requests.post(url, data='[{"some": "json"}]')688 assert post4.status_code == 200689690 with pytest.raises(ValueError):691 requests.post(url, files=['bad file data'])692Merge pull request #3652 from gardiac2002/masterIan Cordascobefore adoption9deb603
lines 693–717why, one step back693 def test_post_with_custom_mapping(self, httpbin):694 class CustomMapping(collections.MutableMapping):695 def __init__(self, *args, **kwargs):696 self.data = dict(*args, **kwargs)697698 def __delitem__(self, key):699 del self.data[key]700701 def __getitem__(self, key):702 return self.data[key]703704 def __setitem__(self, key, value):705 self.data[key] = value706707 def __iter__(self):708 return iter(self.data)709710 def __len__(self):711 return len(self.data)712713 data = CustomMapping({'some': 'data'})714 url = httpbin('post')715 found_json = requests.post(url, data=data).json().get('form')716 assert found_json == {'some': 'data'}717Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 718–740why, one step back718 def test_conflicting_post_params(self, httpbin):719 url = httpbin('post')720 with open('requirements.txt') as f:721 pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")722 pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")723724 def test_request_ok_set(self, httpbin):725 r = requests.get(httpbin('status', '404'))726 assert not r.ok727728 def test_status_raising(self, httpbin):729 r = requests.get(httpbin('status', '404'))730 with pytest.raises(requests.exceptions.HTTPError):731 r.raise_for_status()732733 r = requests.get(httpbin('status', '500'))734 assert not r.ok735736 def test_decompress_gzip(self, httpbin):737 r = requests.get(httpbin('gzip'))738 r.content.decode('ascii')739740 @pytest.mark.parametrize(syntax changesKenneth Reitzbefore adoptionbbadf47
line 741why, one step back741 'url, params', (Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 742–746why, one step back742 ('/get', {'foo': 'føø'}),743 ('/get', {'føø': 'føø'}),744 ('/get', {'føø': 'føø'}),745 ('/get', {'foo': 'foo'}),746 ('ø', {'foo': 'foo'}),syntax changesKenneth Reitzbefore adoptionbbadf47
line 747why, one step back747 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 748–758why, one step back748 def test_unicode_get(self, httpbin, url, params):749 requests.get(httpbin(url), params=params)750751 def test_unicode_header_name(self, httpbin):752 requests.put(753 httpbin('put'),754 headers={str('Content-Type'): 'application/octet-stream'},755 data='\xff') # compat.str is unicode.756757 def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):758 requests.get(httpbin_secure('status', '301'), verify=httpbin_ca_bundle)Test security warnings (#3289)John Vandenbergbefore adoption400d27f
lines 759–779why, one step back759760 def test_https_warnings(self, httpbin_secure, httpbin_ca_bundle):761 """warnings are emitted with requests.get"""762 if HAS_MODERN_SSL or HAS_PYOPENSSL:763 warnings_expected = ('SubjectAltNameWarning', )764 else:765 warnings_expected = ('SNIMissingWarning',766 'InsecurePlatformWarning',767 'SubjectAltNameWarning', )768769 with pytest.warns(None) as warning_records:770 warnings.simplefilter('always')771 requests.get(httpbin_secure('status', '200'),772 verify=httpbin_ca_bundle)773774 warning_records = [item for item in warning_records775 if item.category.__name__ != 'ResourceWarning']776777 warnings_category = tuple(778 item.category.__name__ for item in warning_records)779 assert warnings_category == warnings_expectedAdded tests module.Dmitry Dygalobefore adoption18b26d2
lines 780–799why, one step back780781 def test_urlencoded_get_query_multivalued_param(self, httpbin):782783 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))784 assert r.status_code == 200785 assert r.url == httpbin('get?test=foo&test=baz')786787 def test_different_encodings_dont_break_post(self, httpbin):788 r = requests.post(httpbin('post'),789 data={'stuff': json.dumps({'a': 123})},790 params={'blah': 'asdf1234'},791 files={'file': ('test_requests.py', open(__file__, 'rb'))})792 assert r.status_code == 200793794 @pytest.mark.parametrize(795 'data', (796 {'stuff': u('ëlïxr')},797 {'stuff': u('ëlïxr').encode('utf-8')},798 {'stuff': 'elixr'},799 {'stuff': 'elixr'.encode('utf-8')},syntax changesKenneth Reitzbefore adoptionbbadf47
line 800why, one step back800 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 801–808why, one step back801 def test_unicode_multipart_post(self, httpbin, data):802 r = requests.post(httpbin('post'),803 data=data,804 files={'file': ('test_requests.py', open(__file__, 'rb'))})805 assert r.status_code == 200806807 def test_unicode_multipart_post_fieldnames(self, httpbin):808 filename = os.path.splitext(__file__)[0] + '.py'syntax changesKenneth Reitzbefore adoptionbbadf47
lines 809–812why, one step back809 r = requests.Request(810 method='POST', url=httpbin('post'),811 data={'stuff'.encode('utf-8'): 'elixr'},812 files={'file': ('test_requests.py', open(filename, 'rb'))})Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 813–825why, one step back813 prep = r.prepare()814 assert b'name="stuff"' in prep.body815 assert b'name="b\'stuff\'"' not in prep.body816817 def test_unicode_method_name(self, httpbin):818 files = {'file': open(__file__, 'rb')}819 r = requests.request(820 method=u('POST'), url=httpbin('post'), files=files)821 assert r.status_code == 200822823 def test_unicode_method_name_with_request_object(self, httpbin):824 files = {'file': open(__file__, 'rb')}825 s = requests.Session()syntax changesKenneth Reitzbefore adoptionbbadf47
line 826why, one step back826 req = requests.Request(u('POST'), httpbin('post'), files=files)Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 827–828why, one step back827 prep = s.prepare_request(req)828 assert isinstance(prep.method, builtin_str)syntax changesKenneth Reitzbefore adoptionbbadf47
line 829why, one step back829 assert prep.method == 'POST'Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 830–833why, one step back830831 resp = s.send(prep)832 assert resp.status_code == 200833Merge pull request #3108 from kevinburke/flip-conditionalIan Cordascobefore adoptionbbeb000
lines 834–841why, one step back834 def test_non_prepared_request_error(self):835 s = requests.Session()836 req = requests.Request(u('POST'), '/')837838 with pytest.raises(ValueError) as e:839 s.send(req)840 assert str(e.value) == 'You can only send PreparedRequests.'841Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 842–845why, one step back842 def test_custom_content_type(self, httpbin):843 r = requests.post(844 httpbin('post'),845 data={'stuff': json.dumps({'a': 123})},syntax changesKenneth Reitzbefore adoptionbbadf47
lines 846–849why, one step back846 files={847 'file1': ('test_requests.py', open(__file__, 'rb')),848 'file2': ('test_requests', open(__file__, 'rb'),849 'text/py-content-type')})Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 850–919why, one step back850 assert r.status_code == 200851 assert b"text/py-content-type" in r.request.body852853 def test_hook_receives_request_arguments(self, httpbin):854 def hook(resp, **kwargs):855 assert resp is not None856 assert kwargs != {}857858 s = requests.Session()859 r = requests.Request('GET', httpbin(), hooks={'response': hook})860 prep = s.prepare_request(r)861 s.send(prep)862863 def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):864 hook = lambda x, *args, **kwargs: x865 s = requests.Session()866 s.hooks['response'].append(hook)867 r = requests.Request('GET', httpbin())868 prep = s.prepare_request(r)869 assert prep.hooks['response'] != []870 assert prep.hooks['response'] == [hook]871872 def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):873 hook1 = lambda x, *args, **kwargs: x874 hook2 = lambda x, *args, **kwargs: x875 assert hook1 is not hook2876 s = requests.Session()877 s.hooks['response'].append(hook2)878 r = requests.Request('GET', httpbin(), hooks={'response': [hook1]})879 prep = s.prepare_request(r)880 assert prep.hooks['response'] == [hook1]881882 def test_prepared_request_hook(self, httpbin):883 def hook(resp, **kwargs):884 resp.hook_working = True885 return resp886887 req = requests.Request('GET', httpbin(), hooks={'response': hook})888 prep = req.prepare()889890 s = requests.Session()891 s.proxies = getproxies()892 resp = s.send(prep)893894 assert hasattr(resp, 'hook_working')895896 def test_prepared_from_session(self, httpbin):897 class DummyAuth(requests.auth.AuthBase):898 def __call__(self, r):899 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'900 return r901902 req = requests.Request('GET', httpbin('headers'))903 assert not req.auth904905 s = requests.Session()906 s.auth = DummyAuth()907908 prep = s.prepare_request(req)909 resp = s.send(prep)910911 assert resp.json()['headers'][912 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'913914 def test_prepare_request_with_bytestring_url(self):915 req = requests.Request('GET', b'https://httpbin.org/')916 s = requests.Session()917 prep = s.prepare_request(req)918 assert prep.url == "https://httpbin.org/"919Merge pull request #3606 from bbamsch/httpbinTestFixCory Benfieldbefore adoption022e23c
line 920why, one step back920 def test_request_with_bytestring_host(self, httpbin):Merge pull request #3598 from bbamsch/bytestringHostFixCory Benfieldbefore adoption5eabcb7
lines 921–923why, one step back921 s = requests.Session()922 resp = s.request(923 'GET',Merge pull request #3606 from bbamsch/httpbinTestFixCory Benfieldbefore adoption022e23c
line 924why, one step back924 httpbin('cookies/set?cookie=value'),Merge pull request #3598 from bbamsch/bytestringHostFixCory Benfieldbefore adoption5eabcb7
lines 925–929why, one step back925 allow_redirects=False,926 headers={'Host': b'httpbin.org'}927 )928 assert resp.cookies.get('cookie') == 'value'929Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 930–1058why, one step back930 def test_links(self):931 r = requests.Response()932 r.headers = {933 'cache-control': 'public, max-age=60, s-maxage=60',934 'connection': 'keep-alive',935 'content-encoding': 'gzip',936 'content-type': 'application/json; charset=utf-8',937 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',938 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',939 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',940 'link': ('<https://api.github.com/users/kennethreitz/repos?'941 'page=2&per_page=10>; rel="next", <https://api.github.'942 'com/users/kennethreitz/repos?page=7&per_page=10>; '943 ' rel="last"'),944 'server': 'GitHub.com',945 'status': '200 OK',946 'vary': 'Accept',947 'x-content-type-options': 'nosniff',948 'x-github-media-type': 'github.beta',949 'x-ratelimit-limit': '60',950 'x-ratelimit-remaining': '57'951 }952 assert r.links['next']['rel'] == 'next'953954 def test_cookie_parameters(self):955 key = 'some_cookie'956 value = 'some_value'957 secure = True958 domain = 'test.com'959 rest = {'HttpOnly': True}960961 jar = requests.cookies.RequestsCookieJar()962 jar.set(key, value, secure=secure, domain=domain, rest=rest)963964 assert len(jar) == 1965 assert 'some_cookie' in jar966967 cookie = list(jar)[0]968 assert cookie.secure == secure969 assert cookie.domain == domain970 assert cookie._rest['HttpOnly'] == rest['HttpOnly']971972 def test_cookie_as_dict_keeps_len(self):973 key = 'some_cookie'974 value = 'some_value'975976 key1 = 'some_cookie1'977 value1 = 'some_value1'978979 jar = requests.cookies.RequestsCookieJar()980 jar.set(key, value)981 jar.set(key1, value1)982983 d1 = dict(jar)984 d2 = dict(jar.iteritems())985 d3 = dict(jar.items())986987 assert len(jar) == 2988 assert len(d1) == 2989 assert len(d2) == 2990 assert len(d3) == 2991992 def test_cookie_as_dict_keeps_items(self):993 key = 'some_cookie'994 value = 'some_value'995996 key1 = 'some_cookie1'997 value1 = 'some_value1'998999 jar = requests.cookies.RequestsCookieJar()1000 jar.set(key, value)1001 jar.set(key1, value1)10021003 d1 = dict(jar)1004 d2 = dict(jar.iteritems())1005 d3 = dict(jar.items())10061007 assert d1['some_cookie'] == 'some_value'1008 assert d2['some_cookie'] == 'some_value'1009 assert d3['some_cookie1'] == 'some_value1'10101011 def test_cookie_as_dict_keys(self):1012 key = 'some_cookie'1013 value = 'some_value'10141015 key1 = 'some_cookie1'1016 value1 = 'some_value1'10171018 jar = requests.cookies.RequestsCookieJar()1019 jar.set(key, value)1020 jar.set(key1, value1)10211022 keys = jar.keys()1023 assert keys == list(keys)1024 # make sure one can use keys multiple times1025 assert list(keys) == list(keys)10261027 def test_cookie_as_dict_values(self):1028 key = 'some_cookie'1029 value = 'some_value'10301031 key1 = 'some_cookie1'1032 value1 = 'some_value1'10331034 jar = requests.cookies.RequestsCookieJar()1035 jar.set(key, value)1036 jar.set(key1, value1)10371038 values = jar.values()1039 assert values == list(values)1040 # make sure one can use values multiple times1041 assert list(values) == list(values)10421043 def test_cookie_as_dict_items(self):1044 key = 'some_cookie'1045 value = 'some_value'10461047 key1 = 'some_cookie1'1048 value1 = 'some_value1'10491050 jar = requests.cookies.RequestsCookieJar()1051 jar.set(key, value)1052 jar.set(key1, value1)10531054 items = jar.items()1055 assert items == list(items)1056 # make sure one can use items multiple times1057 assert list(items) == list(items)1058Merge pull request #3032 from davidsoncasey/masterCory Benfieldbefore adoption4f378b0
lines 1059–1090why, one step back1059 def test_cookie_duplicate_names_different_domains(self):1060 key = 'some_cookie'1061 value = 'some_value'1062 domain1 = 'test1.com'1063 domain2 = 'test2.com'10641065 jar = requests.cookies.RequestsCookieJar()1066 jar.set(key, value, domain=domain1)1067 jar.set(key, value, domain=domain2)1068 assert key in jar1069 items = jar.items()1070 assert len(items) == 210711072 # Verify that CookieConflictError is raised if domain is not specified1073 with pytest.raises(requests.cookies.CookieConflictError):1074 jar.get(key)10751076 # Verify that CookieConflictError is not raised if domain is specified1077 cookie = jar.get(key, domain=domain1)1078 assert cookie == value10791080 def test_cookie_duplicate_names_raises_cookie_conflict_error(self):1081 key = 'some_cookie'1082 value = 'some_value'1083 path = 'some_path'10841085 jar = requests.cookies.RequestsCookieJar()1086 jar.set(key, value, path=path)1087 jar.set(key, value)1088 with pytest.raises(requests.cookies.CookieConflictError):1089 jar.get(key)1090Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 1091–1093why, one step back1091 def test_time_elapsed_blank(self, httpbin):1092 r = requests.get(httpbin('get'))1093 td = r.elapsedMerge pull request #3428 from nateprewitt/pep8_fixesKenneth Reitzbefore adoption4285bac
line 1094why, one step back1094 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6)Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 1095–1109why, one step back1095 assert total_seconds > 0.010961097 def test_response_is_iterable(self):1098 r = requests.Response()1099 io = StringIO.StringIO('abc')1100 read_ = io.read11011102 def read_mock(amt, decode_content=None):1103 return read_(amt)1104 setattr(io, 'read', read_mock)1105 r.raw = io1106 assert next(iter(r))1107 io.close()11081109 def test_response_decode_unicode(self):Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456
line 1110why, one step back1110 """When called with decode_unicode, Response.iter_content should alwaysAdded tests module.Dmitry Dygalobefore adoption18b26d2
lines 1111–1127why, one step back1111 return unicode.1112 """1113 r = requests.Response()1114 r._content_consumed = True1115 r._content = b'the content'1116 r.encoding = 'ascii'11171118 chunks = r.iter_content(decode_unicode=True)1119 assert all(isinstance(chunk, str) for chunk in chunks)11201121 # also for streaming1122 r = requests.Response()1123 r.raw = io.BytesIO(b'the content')1124 r.encoding = 'ascii'1125 chunks = r.iter_content(decode_unicode=True)1126 assert all(isinstance(chunk, str) for chunk in chunks)1127Support responses like `HTTP/1.1 404 Unicode chars` (#3385)Andrii Kostenkobefore adoption7700eca
lines 1128–1134why, one step back1128 def test_response_reason_unicode(self):1129 # check for unicode HTTP status1130 r = requests.Response()1131 r.url = u'unicode URL'1132 r.reason = u'Komponenttia ei löydy'.encode('utf-8')1133 r.status_code = 4041134 r.encoding = NoneMerge pull request #3428 from nateprewitt/pep8_fixesKenneth Reitzbefore adoption4285bac
line 1135why, one step back1135 assert not r.ok # old behaviour - crashes hereSupport responses like `HTTP/1.1 404 Unicode chars` (#3385)Andrii Kostenkobefore adoption7700eca
line 1136why, one step back1136Merge pull request #3554 from nateprewitt/3538_fallback_to_ISO_8591_1Ian Cordascobefore adoption87f9693
lines 1137–1140why, one step back1137 def test_response_reason_unicode_fallback(self):1138 # check raise_status falls back to ISO-8859-11139 r = requests.Response()1140 r.url = 'some url'Merge pull request #3576 from nateprewitt/3557_revert_and_fix_encodingIan Cordascobefore adoptionddf7df9
lines 1141–1142why, one step back1141 reason = u'Komponenttia ei löydy'1142 r.reason = reason.encode('latin-1')Merge pull request #3554 from nateprewitt/3538_fallback_to_ISO_8591_1Ian Cordascobefore adoption87f9693
lines 1143–1146why, one step back1143 r.status_code = 5001144 r.encoding = None1145 with pytest.raises(requests.exceptions.HTTPError) as e:1146 r.raise_for_status()Merge pull request #3576 from nateprewitt/3557_revert_and_fix_encodingIan Cordascobefore adoptionddf7df9
line 1147why, one step back1147 assert reason in e.value.args[0]Merge pull request #3554 from nateprewitt/3538_fallback_to_ISO_8591_1Ian Cordascobefore adoption87f9693
line 1148why, one step back1148Allow None value for chunk_size again (#3368)Joy Zhengbefore adoption0bcf634
lines 1149–1150why, one step back1149 def test_response_chunk_size_type(self):1150 """Ensure that chunk_size is passed as None or an integer, otherwiseMerge pull request #3365 from nateprewitt/3364_chunking_is_intCory Benfieldbefore adoption36453b9
lines 1151–1156why, one step back1151 raise a TypeError.1152 """1153 r = requests.Response()1154 r.raw = io.BytesIO(b'the content')1155 chunks = r.iter_content(1)1156 assert all(len(chunk) == 1 for chunk in chunks)Allow None value for chunk_size again (#3368)Joy Zhengbefore adoption0bcf634
lines 1157–1161why, one step back11571158 r = requests.Response()1159 r.raw = io.BytesIO(b'the content')1160 chunks = r.iter_content(None)1161 assert list(chunks) == [b'the content']Merge pull request #3365 from nateprewitt/3364_chunking_is_intCory Benfieldbefore adoption36453b9
lines 1162–1167why, one step back11621163 r = requests.Response()1164 r.raw = io.BytesIO(b'the content')1165 with pytest.raises(TypeError):1166 chunks = r.iter_content("1024")1167Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 1168–1179why, one step back1168 def test_request_and_response_are_pickleable(self, httpbin):1169 r = requests.get(httpbin('get'))11701171 # verify we can pickle the original request1172 assert pickle.loads(pickle.dumps(r.request))11731174 # verify we can pickle the response and that we have access to1175 # the original request.1176 pr = pickle.loads(pickle.dumps(r))1177 assert r.request.url == pr.request.url1178 assert r.request.headers == pr.request.headers1179Merge pull request #3489 from nateprewitt/1558_pickling_prepared_requestCory Benfieldbefore adoptiond24da4a
lines 1180–1225why, one step back1180 def test_prepared_request_is_pickleable(self, httpbin):1181 p = requests.Request('GET', httpbin('get')).prepare()11821183 # Verify PreparedRequest can be pickled and unpickled1184 r = pickle.loads(pickle.dumps(p))1185 assert r.url == p.url1186 assert r.headers == p.headers1187 assert r.body == p.body11881189 # Verify unpickled PreparedRequest sends properly1190 s = requests.Session()1191 resp = s.send(r)1192 assert resp.status_code == 20011931194 def test_prepared_request_with_file_is_pickleable(self, httpbin):1195 files = {'file': open(__file__, 'rb')}1196 r = requests.Request('POST', httpbin('post'), files=files)1197 p = r.prepare()11981199 # Verify PreparedRequest can be pickled and unpickled1200 r = pickle.loads(pickle.dumps(p))1201 assert r.url == p.url1202 assert r.headers == p.headers1203 assert r.body == p.body12041205 # Verify unpickled PreparedRequest sends properly1206 s = requests.Session()1207 resp = s.send(r)1208 assert resp.status_code == 20012091210 def test_prepared_request_with_hook_is_pickleable(self, httpbin):1211 r = requests.Request('GET', httpbin('get'), hooks=default_hooks())1212 p = r.prepare()12131214 # Verify PreparedRequest can be pickled1215 r = pickle.loads(pickle.dumps(p))1216 assert r.url == p.url1217 assert r.headers == p.headers1218 assert r.body == p.body1219 assert r.hooks == p.hooks12201221 # Verify unpickled PreparedRequest sends properly1222 s = requests.Session()1223 resp = s.send(r)1224 assert resp.status_code == 2001225Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 1226–1251why, one step back1226 def test_cannot_send_unprepared_requests(self, httpbin):1227 r = requests.Request(url=httpbin())1228 with pytest.raises(ValueError):1229 requests.Session().send(r)12301231 def test_http_error(self):1232 error = requests.exceptions.HTTPError()1233 assert not error.response1234 response = requests.Response()1235 error = requests.exceptions.HTTPError(response=response)1236 assert error.response == response1237 error = requests.exceptions.HTTPError('message', response=response)1238 assert str(error) == 'message'1239 assert error.response == response12401241 def test_session_pickling(self, httpbin):1242 r = requests.Request('GET', httpbin('get'))1243 s = requests.Session()12441245 s = pickle.loads(pickle.dumps(s))1246 s.proxies = getproxies()12471248 r = s.send(r.prepare())1249 assert r.status_code == 20012501251 def test_fixes_1329(self, httpbin):Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456
line 1252why, one step back1252 """Ensure that header updates are done case-insensitively."""Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 1253–1337why, one step back1253 s = requests.Session()1254 s.headers.update({'ACCEPT': 'BOGUS'})1255 s.headers.update({'accept': 'application/json'})1256 r = s.get(httpbin('get'))1257 headers = r.request.headers1258 assert headers['accept'] == 'application/json'1259 assert headers['Accept'] == 'application/json'1260 assert headers['ACCEPT'] == 'application/json'12611262 def test_uppercase_scheme_redirect(self, httpbin):1263 parts = urlparse(httpbin('html'))1264 url = "HTTP://" + parts.netloc + parts.path1265 r = requests.get(httpbin('redirect-to'), params={'url': url})1266 assert r.status_code == 2001267 assert r.url.lower() == url.lower()12681269 def test_transport_adapter_ordering(self):1270 s = requests.Session()1271 order = ['https://', 'http://']1272 assert order == list(s.adapters)1273 s.mount('http://git', HTTPAdapter())1274 s.mount('http://github', HTTPAdapter())1275 s.mount('http://github.com', HTTPAdapter())1276 s.mount('http://github.com/about/', HTTPAdapter())1277 order = [1278 'http://github.com/about/',1279 'http://github.com',1280 'http://github',1281 'http://git',1282 'https://',1283 'http://',1284 ]1285 assert order == list(s.adapters)1286 s.mount('http://gittip', HTTPAdapter())1287 s.mount('http://gittip.com', HTTPAdapter())1288 s.mount('http://gittip.com/about/', HTTPAdapter())1289 order = [1290 'http://github.com/about/',1291 'http://gittip.com/about/',1292 'http://github.com',1293 'http://gittip.com',1294 'http://github',1295 'http://gittip',1296 'http://git',1297 'https://',1298 'http://',1299 ]1300 assert order == list(s.adapters)1301 s2 = requests.Session()1302 s2.adapters = {'http://': HTTPAdapter()}1303 s2.mount('https://', HTTPAdapter())1304 assert 'http://' in s2.adapters1305 assert 'https://' in s2.adapters13061307 def test_header_remove_is_case_insensitive(self, httpbin):1308 # From issue #13211309 s = requests.Session()1310 s.headers['foo'] = 'bar'1311 r = s.get(httpbin('get'), headers={'FOO': None})1312 assert 'foo' not in r.request.headers13131314 def test_params_are_merged_case_sensitive(self, httpbin):1315 s = requests.Session()1316 s.params['foo'] = 'bar'1317 r = s.get(httpbin('get'), params={'FOO': 'bar'})1318 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}13191320 def test_long_authinfo_in_url(self):1321 url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(1322 'E8A3BE87-9E3F-4620-8858-95478E385B5B',1323 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',1324 'exactly-------------sixty-----------three------------characters',1325 )1326 r = requests.Request('GET', url).prepare()1327 assert r.url == url13281329 def test_header_keys_are_native(self, httpbin):1330 headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}1331 r = requests.Request('GET', httpbin('get'), headers=headers)1332 p = r.prepare()13331334 # This is testing that they are builtin strings. A bit weird, but there1335 # we go.1336 assert 'unicode' in p.headers.keys()1337 assert 'byte' in p.headers.keys()Merge pull request #3366 from nateprewitt/2947-no-returns-in-headerCory Benfieldbefore adoptionbd9e8f2
line 1338why, one step back1338Merge pull request #3390 from nateprewitt/3386_header_value_typeCory Benfieldbefore adoption425962c
line 1339why, one step back1339 def test_header_validation(self, httpbin):Merge pull request #3366 from nateprewitt/2947-no-returns-in-headerCory Benfieldbefore adoptionbd9e8f2
lines 1340–1341why, one step back1340 """Ensure prepare_headers regex isn't flagging valid header contents."""1341 headers_ok = {'foo': 'bar baz qux',Merge pull request #3390 from nateprewitt/3386_header_value_typeCory Benfieldbefore adoption425962c
line 1342why, one step back1342 'bar': u'fbbq'.encode('utf8'),Merge pull request #3366 from nateprewitt/2947-no-returns-in-headerCory Benfieldbefore adoptionbd9e8f2
line 1343why, one step back1343 'baz': '',Merge pull request #3390 from nateprewitt/3386_header_value_typeCory Benfieldbefore adoption425962c
line 1344why, one step back1344 'qux': '1'}Merge pull request #3366 from nateprewitt/2947-no-returns-in-headerCory Benfieldbefore adoptionbd9e8f2
lines 1345–1346why, one step back1345 r = requests.get(httpbin('get'), headers=headers_ok)1346 assert r.request.headers['foo'] == headers_ok['foo']Merge pull request #3390 from nateprewitt/3386_header_value_typeCory Benfieldbefore adoption425962c
lines 1347–1352why, one step back13471348 def test_header_value_not_str(self, httpbin):1349 """Ensure the header value is of type string or bytes as1350 per discussion in GH issue #33861351 """1352 headers_int = {'foo': 3}Merge pull request #3428 from nateprewitt/pep8_fixesKenneth Reitzbefore adoption4285bac
line 1353why, one step back1353 headers_dict = {'bar': {'foo': 'bar'}}Merge pull request #3390 from nateprewitt/3386_header_value_typeCory Benfieldbefore adoption425962c
lines 1354–1364why, one step back1354 headers_list = {'baz': ['foo', 'bar']}13551356 # Test for int1357 with pytest.raises(InvalidHeader):1358 r = requests.get(httpbin('get'), headers=headers_int)1359 # Test for dict1360 with pytest.raises(InvalidHeader):1361 r = requests.get(httpbin('get'), headers=headers_dict)1362 # Test for list1363 with pytest.raises(InvalidHeader):1364 r = requests.get(httpbin('get'), headers=headers_list)Merge pull request #3366 from nateprewitt/2947-no-returns-in-headerCory Benfieldbefore adoptionbd9e8f2
lines 1365–1396why, one step back13651366 def test_header_no_return_chars(self, httpbin):1367 """Ensure that a header containing return character sequences raise an1368 exception. Otherwise, multiple headers are created from single string.1369 """1370 headers_ret = {'foo': 'bar\r\nbaz: qux'}1371 headers_lf = {'foo': 'bar\nbaz: qux'}1372 headers_cr = {'foo': 'bar\rbaz: qux'}13731374 # Test for newline1375 with pytest.raises(InvalidHeader):1376 r = requests.get(httpbin('get'), headers=headers_ret)1377 # Test for line feed1378 with pytest.raises(InvalidHeader):1379 r = requests.get(httpbin('get'), headers=headers_lf)1380 # Test for carriage return1381 with pytest.raises(InvalidHeader):1382 r = requests.get(httpbin('get'), headers=headers_cr)13831384 def test_header_no_leading_space(self, httpbin):1385 """Ensure headers containing leading whitespace raise1386 InvalidHeader Error before sending.1387 """1388 headers_space = {'foo': ' bar'}1389 headers_tab = {'foo': ' bar'}13901391 # Test for whitespace1392 with pytest.raises(InvalidHeader):1393 r = requests.get(httpbin('get'), headers=headers_space)1394 # Test for tab1395 with pytest.raises(InvalidHeader):1396 r = requests.get(httpbin('get'), headers=headers_tab)Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 1397–1432why, one step back13971398 @pytest.mark.parametrize('files', ('foo', b'foo', bytearray(b'foo')))1399 def test_can_send_objects_with_files(self, httpbin, files):1400 data = {'a': 'this is a string'}1401 files = {'b': files}1402 r = requests.Request('POST', httpbin('post'), data=data, files=files)1403 p = r.prepare()1404 assert 'multipart/form-data' in p.headers['Content-Type']14051406 def test_can_send_file_object_with_non_string_filename(self, httpbin):1407 f = io.BytesIO()1408 f.name = 21409 r = requests.Request('POST', httpbin('post'), files={'f': f})1410 p = r.prepare()14111412 assert 'multipart/form-data' in p.headers['Content-Type']14131414 def test_autoset_header_values_are_native(self, httpbin):1415 data = 'this is a string'1416 length = '16'1417 req = requests.Request('POST', httpbin('post'), data=data)1418 p = req.prepare()14191420 assert p.headers['Content-Length'] == length14211422 def test_nonhttp_schemes_dont_check_URLs(self):1423 test_urls = (1424 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',1425 'file:///etc/passwd',1426 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',1427 )1428 for test_url in test_urls:1429 req = requests.Request('GET', test_url)1430 preq = req.prepare()1431 assert test_url == preq.url1432Merge pull request #3236 from eriol/xfail-testKenneth Reitzbefore adoption771ecd7
line 1433why, one step back1433 @pytest.mark.xfail(raises=ConnectionError)Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 1434–1467why, one step back1434 def test_auth_is_stripped_on_redirect_off_host(self, httpbin):1435 r = requests.get(1436 httpbin('redirect-to'),1437 params={'url': 'http://www.google.co.uk'},1438 auth=('user', 'pass'),1439 )1440 assert r.history[0].request.headers['Authorization']1441 assert not r.request.headers.get('Authorization', '')14421443 def test_auth_is_retained_for_redirect_on_host(self, httpbin):1444 r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))1445 h1 = r.history[0].request.headers['Authorization']1446 h2 = r.request.headers['Authorization']14471448 assert h1 == h214491450 def test_manual_redirect_with_partial_body_read(self, httpbin):1451 s = requests.Session()1452 r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)1453 assert r1.is_redirect1454 rg = s.resolve_redirects(r1, r1.request, stream=True)14551456 # read only the first eight bytes of the response body,1457 # then follow the redirect1458 r1.iter_content(8)1459 r2 = next(rg)1460 assert r2.is_redirect14611462 # read all of the response via iter_content,1463 # then follow the redirect1464 for _ in r2.iter_content():1465 pass1466 r3 = next(rg)1467 assert not r3.is_redirectMerge pull request #3655 from nateprewitt/tzickel_post_redirect_w_streamableCory Benfieldbefore adoptionf72684e
lines 1468–1568why, one step back14681469 def test_prepare_body_position_non_stream(self):1470 data = b'the data'1471 s = requests.Session()1472 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1473 assert prep._body_position is None14741475 def test_rewind_body(self):1476 data = io.BytesIO(b'the data')1477 s = requests.Session()1478 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1479 assert prep._body_position == 01480 assert prep.body.read() == b'the data'14811482 # the data has all been read1483 assert prep.body.read() == b''14841485 # rewind it back1486 requests.utils.rewind_body(prep)1487 assert prep.body.read() == b'the data'14881489 def test_rewind_partially_read_body(self):1490 data = io.BytesIO(b'the data')1491 s = requests.Session()1492 data.read(4) # read some data1493 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1494 assert prep._body_position == 41495 assert prep.body.read() == b'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'data'15031504 def test_rewind_body_no_seek(self):1505 class BadFileObj:1506 def __init__(self, data):1507 self.data = data15081509 def tell(self):1510 return 015111512 def __iter__(self):1513 return15141515 data = BadFileObj('the data')1516 s = requests.Session()1517 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1518 assert prep._body_position == 015191520 with pytest.raises(UnrewindableBodyError) as e:1521 requests.utils.rewind_body(prep)15221523 assert 'Unable to rewind request body' in str(e)15241525 def test_rewind_body_failed_seek(self):1526 class BadFileObj:1527 def __init__(self, data):1528 self.data = data15291530 def tell(self):1531 return 015321533 def seek(self, pos):1534 raise OSError()15351536 def __iter__(self):1537 return15381539 data = BadFileObj('the data')1540 s = requests.Session()1541 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1542 assert prep._body_position == 015431544 with pytest.raises(UnrewindableBodyError) as e:1545 requests.utils.rewind_body(prep)15461547 assert 'error occured when rewinding request body' in str(e)15481549 def test_rewind_body_failed_tell(self):1550 class BadFileObj:1551 def __init__(self, data):1552 self.data = data15531554 def tell(self):1555 raise OSError()15561557 def __iter__(self):1558 return15591560 data = BadFileObj('the data')1561 s = requests.Session()1562 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1563 assert prep._body_position is not None15641565 with pytest.raises(UnrewindableBodyError) as e:1566 requests.utils.rewind_body(prep)15671568 assert 'Unable to rewind request body' in str(e)Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 1569–1589why, one step back15691570 def _patch_adapter_gzipped_redirect(self, session, url):1571 adapter = session.get_adapter(url=url)1572 org_build_response = adapter.build_response1573 self._patched_response = False15741575 def build_response(*args, **kwargs):1576 resp = org_build_response(*args, **kwargs)1577 if not self._patched_response:1578 resp.raw.headers['content-encoding'] = 'gzip'1579 self._patched_response = True1580 return resp15811582 adapter.build_response = build_response15831584 def test_redirect_with_wrong_gzipped_header(self, httpbin):1585 s = requests.Session()1586 url = httpbin('redirect/1')1587 self._patch_adapter_gzipped_redirect(s, url)1588 s.get(url)1589Merge pull request #3673 from klimenko-forks/auth-unicodeCory Benfieldbefore adoptionb9f1c44
lines 1590–1596why, one step back1590 @pytest.mark.parametrize(1591 'username, password, auth_str', (1592 ('test', 'test', 'Basic dGVzdDp0ZXN0'),1593 (u'имя'.encode('utf-8'), u'пароль'.encode('utf-8'), 'Basic 0LjQvNGPOtC/0LDRgNC+0LvRjA=='),1594 ))1595 def test_basic_auth_str_is_always_native(self, username, password, auth_str):1596 s = _basic_auth_str(username, password)Added tests module.Dmitry Dygalobefore adoption18b26d2
line 1597why, one step back1597 assert isinstance(s, builtin_str)Merge pull request #3673 from klimenko-forks/auth-unicodeCory Benfieldbefore adoptionb9f1c44
line 1598why, one step back1598 assert s == auth_strAdded tests module.Dmitry Dygalobefore adoption18b26d2
lines 1599–1649why, one step back15991600 def test_requests_history_is_saved(self, httpbin):1601 r = requests.get(httpbin('redirect/5'))1602 total = r.history[-1].history1603 i = 01604 for item in r.history:1605 assert item.history == total[0:i]1606 i += 116071608 def test_json_param_post_content_type_works(self, httpbin):1609 r = requests.post(1610 httpbin('post'),1611 json={'life': 42}1612 )1613 assert r.status_code == 2001614 assert 'application/json' in r.request.headers['Content-Type']1615 assert {'life': 42} == r.json()['json']16161617 def test_json_param_post_should_not_override_data_param(self, httpbin):1618 r = requests.Request(method='POST', url=httpbin('post'),1619 data={'stuff': 'elixr'},1620 json={'music': 'flute'})1621 prep = r.prepare()1622 assert 'stuff=elixr' == prep.body16231624 def test_response_iter_lines(self, httpbin):1625 r = requests.get(httpbin('stream/4'), stream=True)1626 assert r.status_code == 20016271628 it = r.iter_lines()1629 next(it)1630 assert len(list(it)) == 316311632 def test_unconsumed_session_response_closes_connection(self, httpbin):1633 s = requests.session()16341635 with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1636 pass16371638 assert response._content_consumed is False1639 assert response.raw.closed16401641 @pytest.mark.xfail1642 def test_response_iter_lines_reentrant(self, httpbin):1643 """Response.iter_lines() is not reentrant safe"""1644 r = requests.get(httpbin('stream/4'), stream=True)1645 assert r.status_code == 20016461647 next(r.iter_lines())1648 assert len(list(r.iter_lines())) == 31649Merge pull request #3091 from bodgit/proxyIan Cordascobefore adoption60aee14
lines 1650–1660why, one step back1650 def test_session_close_proxy_clear(self, mocker):1651 proxies = {1652 'one': mocker.Mock(),1653 'two': mocker.Mock(),1654 }1655 session = requests.Session()1656 mocker.patch.dict(session.adapters['http://'].proxy_manager, proxies)1657 session.close()1658 proxies['one'].clear.assert_called_once_with()1659 proxies['two'].clear.assert_called_once_with()1660Merge pull request #3660 from pawelmhm/proxy_empty_passCory Benfieldbefore adoptionbf19750
lines 1661–1670why, one step back1661 def test_proxy_auth(self, httpbin):1662 adapter = HTTPAdapter()1663 headers = adapter.proxy_headers("http://user:pass@httpbin.org")1664 assert headers == {'Proxy-Authorization': 'Basic dXNlcjpwYXNz'}16651666 def test_proxy_auth_empty_pass(self, httpbin):1667 adapter = HTTPAdapter()1668 headers = adapter.proxy_headers("http://user:@httpbin.org")1669 assert headers == {'Proxy-Authorization': 'Basic dXNlcjo='}1670Merge pull request #3179 from messense/messense-patch-1Cory Benfieldbefore adoption8770410
lines 1671–1681why, one step back1671 def test_response_json_when_content_is_None(self, httpbin):1672 r = requests.get(httpbin('/status/204'))1673 # Make sure r.content is None1674 r.status_code = 01675 r._content = False1676 r._content_consumed = False16771678 assert r.content is None1679 with pytest.raises(ValueError):1680 r.json()1681Merge pull request #3510 from nateprewitt/add_close_passthroughCory Benfieldbefore adoptiond3567aa
lines 1682–1690why, one step back1682 def test_response_without_release_conn(self):1683 """Test `close` call for non-urllib3-like raw objects.1684 Should work when `release_conn` attr doesn't exist on `response.raw`.1685 """1686 resp = requests.Response()1687 resp.raw = StringIO.StringIO('test')1688 assert not resp.raw.closed1689 resp.close()1690 assert resp.raw.closedAdded tests module.Dmitry Dygalobefore adoption18b26d2
lines 1691–1698why, one step back16911692class TestCaseInsensitiveDict:16931694 @pytest.mark.parametrize(1695 'cid', (1696 CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}),1697 CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')]),1698 CaseInsensitiveDict(FOO='foo', BAr='bar'),syntax changesKenneth Reitzbefore adoptionbbadf47
line 1699why, one step back1699 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 1700–1848why, one step back1700 def test_init(self, cid):1701 assert len(cid) == 21702 assert 'foo' in cid1703 assert 'bar' in cid17041705 def test_docstring_example(self):1706 cid = CaseInsensitiveDict()1707 cid['Accept'] = 'application/json'1708 assert cid['aCCEPT'] == 'application/json'1709 assert list(cid) == ['Accept']17101711 def test_len(self):1712 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1713 cid['A'] = 'a'1714 assert len(cid) == 217151716 def test_getitem(self):1717 cid = CaseInsensitiveDict({'Spam': 'blueval'})1718 assert cid['spam'] == 'blueval'1719 assert cid['SPAM'] == 'blueval'17201721 def test_fixes_649(self):1722 """__setitem__ should behave case-insensitively."""1723 cid = CaseInsensitiveDict()1724 cid['spam'] = 'oneval'1725 cid['Spam'] = 'twoval'1726 cid['sPAM'] = 'redval'1727 cid['SPAM'] = 'blueval'1728 assert cid['spam'] == 'blueval'1729 assert cid['SPAM'] == 'blueval'1730 assert list(cid.keys()) == ['SPAM']17311732 def test_delitem(self):1733 cid = CaseInsensitiveDict()1734 cid['Spam'] = 'someval'1735 del cid['sPam']1736 assert 'spam' not in cid1737 assert len(cid) == 017381739 def test_contains(self):1740 cid = CaseInsensitiveDict()1741 cid['Spam'] = 'someval'1742 assert 'Spam' in cid1743 assert 'spam' in cid1744 assert 'SPAM' in cid1745 assert 'sPam' in cid1746 assert 'notspam' not in cid17471748 def test_get(self):1749 cid = CaseInsensitiveDict()1750 cid['spam'] = 'oneval'1751 cid['SPAM'] = 'blueval'1752 assert cid.get('spam') == 'blueval'1753 assert cid.get('SPAM') == 'blueval'1754 assert cid.get('sPam') == 'blueval'1755 assert cid.get('notspam', 'default') == 'default'17561757 def test_update(self):1758 cid = CaseInsensitiveDict()1759 cid['spam'] = 'blueval'1760 cid.update({'sPam': 'notblueval'})1761 assert cid['spam'] == 'notblueval'1762 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1763 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1764 assert len(cid) == 21765 assert cid['foo'] == 'anotherfoo'1766 assert cid['bar'] == 'anotherbar'17671768 def test_update_retains_unchanged(self):1769 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1770 cid.update({'foo': 'newfoo'})1771 assert cid['bar'] == 'bar'17721773 def test_iter(self):1774 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1775 keys = frozenset(['Spam', 'Eggs'])1776 assert frozenset(iter(cid)) == keys17771778 def test_equality(self):1779 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1780 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1781 assert cid == othercid1782 del othercid['spam']1783 assert cid != othercid1784 assert cid == {'spam': 'blueval', 'eggs': 'redval'}1785 assert cid != object()17861787 def test_setdefault(self):1788 cid = CaseInsensitiveDict({'Spam': 'blueval'})1789 assert cid.setdefault('spam', 'notblueval') == 'blueval'1790 assert cid.setdefault('notspam', 'notblueval') == 'notblueval'17911792 def test_lower_items(self):1793 cid = CaseInsensitiveDict({1794 'Accept': 'application/json',1795 'user-Agent': 'requests',1796 })1797 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1798 lowerkeyset = frozenset(['accept', 'user-agent'])1799 assert keyset == lowerkeyset18001801 def test_preserve_key_case(self):1802 cid = CaseInsensitiveDict({1803 'Accept': 'application/json',1804 'user-Agent': 'requests',1805 })1806 keyset = frozenset(['Accept', 'user-Agent'])1807 assert frozenset(i[0] for i in cid.items()) == keyset1808 assert frozenset(cid.keys()) == keyset1809 assert frozenset(cid) == keyset18101811 def test_preserve_last_key_case(self):1812 cid = CaseInsensitiveDict({1813 'Accept': 'application/json',1814 'user-Agent': 'requests',1815 })1816 cid.update({'ACCEPT': 'application/json'})1817 cid['USER-AGENT'] = 'requests'1818 keyset = frozenset(['ACCEPT', 'USER-AGENT'])1819 assert frozenset(i[0] for i in cid.items()) == keyset1820 assert frozenset(cid.keys()) == keyset1821 assert frozenset(cid) == keyset18221823 def test_copy(self):1824 cid = CaseInsensitiveDict({1825 'Accept': 'application/json',1826 'user-Agent': 'requests',1827 })1828 cid_copy = cid.copy()1829 assert cid == cid_copy1830 cid['changed'] = True1831 assert cid != cid_copy183218331834class TestMorselToCookieExpires:1835 """Tests for morsel_to_cookie when morsel contains expires."""18361837 def test_expires_valid_str(self):1838 """Test case where we convert expires from string time."""18391840 morsel = Morsel()1841 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1842 cookie = morsel_to_cookie(morsel)1843 assert cookie.expires == 118441845 @pytest.mark.parametrize(1846 'value, exception', (1847 (100, TypeError),1848 ('woops', ValueError),syntax changesKenneth Reitzbefore adoptionbbadf47
line 1849why, one step back1849 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 1850–1897why, one step back1850 def test_expires_invalid_int(self, value, exception):1851 """Test case where an invalid type is passed for expires."""1852 morsel = Morsel()1853 morsel['expires'] = value1854 with pytest.raises(exception):1855 morsel_to_cookie(morsel)18561857 def test_expires_none(self):1858 """Test case where expires is None."""18591860 morsel = Morsel()1861 morsel['expires'] = None1862 cookie = morsel_to_cookie(morsel)1863 assert cookie.expires is None186418651866class TestMorselToCookieMaxAge:18671868 """Tests for morsel_to_cookie when morsel contains max-age."""18691870 def test_max_age_valid_int(self):1871 """Test case where a valid max age in seconds is passed."""18721873 morsel = Morsel()1874 morsel['max-age'] = 601875 cookie = morsel_to_cookie(morsel)1876 assert isinstance(cookie.expires, int)18771878 def test_max_age_invalid_str(self):1879 """Test case where a invalid max age is passed."""18801881 morsel = Morsel()1882 morsel['max-age'] = 'woops'1883 with pytest.raises(TypeError):1884 morsel_to_cookie(morsel)188518861887class TestTimeout:18881889 def test_stream_timeout(self, httpbin):1890 try:1891 requests.get(httpbin('delay/10'), timeout=2.0)1892 except requests.exceptions.Timeout as e:1893 assert 'Read timed out' in e.args[0].args[0]18941895 @pytest.mark.parametrize(1896 'timeout, error_text', (1897 ((3, 4, 5), '(connect, read)'),Fix tests for new urllib3 exception text.Cory Benfieldbefore adoption2d211d5
line 1898why, one step back1898 ('foo', 'must be an int, float or None'),syntax changesKenneth Reitzbefore adoptionbbadf47
line 1899why, one step back1899 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 1900–1905why, one step back1900 def test_invalid_timeout(self, httpbin, timeout, error_text):1901 with pytest.raises(ValueError) as e:1902 requests.get(httpbin('get'), timeout=timeout)1903 assert error_text in str(e)19041905 def test_none_timeout(self, httpbin):Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456
line 1906why, one step back1906 """Check that you can set None as a valid timeout value.Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 1907–1979why, one step back19071908 To actually test this behavior, we'd want to check that setting the1909 timeout to None actually lets the request block past the system default1910 timeout. However, this would make the test suite unbearably slow.1911 Instead we verify that setting the timeout to None does not prevent the1912 request from succeeding.1913 """1914 r = requests.get(httpbin('get'), timeout=None)1915 assert r.status_code == 20019161917 def test_read_timeout(self, httpbin):1918 try:1919 requests.get(httpbin('delay/10'), timeout=(None, 0.1))1920 pytest.fail('The recv() request should time out.')1921 except ReadTimeout:1922 pass19231924 def test_connect_timeout(self):1925 try:1926 requests.get(TARPIT, timeout=(0.1, None))1927 pytest.fail('The connect() request should time out.')1928 except ConnectTimeout as e:1929 assert isinstance(e, ConnectionError)1930 assert isinstance(e, Timeout)19311932 def test_total_timeout_connect(self):1933 try:1934 requests.get(TARPIT, timeout=(0.1, 0.1))1935 pytest.fail('The connect() request should time out.')1936 except ConnectTimeout:1937 pass19381939 def test_encoded_methods(self, httpbin):1940 """See: https://github.com/kennethreitz/requests/issues/2316"""1941 r = requests.request(b'GET', httpbin('get'))1942 assert r.ok194319441945SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))194619471948class RedirectSession(SessionRedirectMixin):1949 def __init__(self, order_of_redirects):1950 self.redirects = order_of_redirects1951 self.calls = []1952 self.max_redirects = 301953 self.cookies = {}1954 self.trust_env = False19551956 def send(self, *args, **kwargs):1957 self.calls.append(SendCall(args, kwargs))1958 return self.build_response()19591960 def build_response(self):1961 request = self.calls[-1].args[0]1962 r = requests.Response()19631964 try:1965 r.status_code = int(self.redirects.pop(0))1966 except IndexError:1967 r.status_code = 20019681969 r.headers = CaseInsensitiveDict({'Location': '/'})1970 r.raw = self._build_raw()1971 r.request = request1972 return r19731974 def _build_raw(self):1975 string = StringIO.StringIO('')1976 setattr(string, 'release_conn', lambda *args: args)1977 return string19781979Merge pull request #3178 from haikuginger/masterCory Benfieldbefore adoption49b69c4
lines 1980–1991why, one step back1980def test_json_encodes_as_bytes():1981 # urllib3 expects bodies as bytes-like objects1982 body = {"key": "value"}1983 p = PreparedRequest()1984 p.prepare(1985 method='GET',1986 url='https://www.example.com/',1987 json=body1988 )1989 assert isinstance(p.body, bytes)19901991Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 1992–2010why, one step back1992def test_requests_are_updated_each_time(httpbin):1993 session = RedirectSession([303, 307])1994 prep = requests.Request('POST', httpbin('post')).prepare()1995 r0 = session.send(prep)1996 assert r0.request.method == 'POST'1997 assert session.calls[-1] == SendCall((r0.request,), {})1998 redirect_generator = session.resolve_redirects(r0, prep)1999 default_keyword_args = {2000 'stream': False,The first 2,000 of 2,176 lines.