test_requests.py
This file
Path
test_requests.py
1,519 lines · 50.6 KiB · Python
Last changed by
allow unicode URLs on Python 2MinRKbefore adoptionca2ebc5
History of this fileTake it
The walk stopped after 200 commits: lines older than 4401620 point at it.
add history to the docsKenneth Reitzbefore adoption4401620
lines 1–9why, one step back1#!/usr/bin/env python2# -*- coding: utf-8 -*-34"""Tests for Requests."""56from __future__ import division7import json8import os9import pickleMerge pull request #1772 from mdbecker/make_morsel_to_cookie_more_pythonicKenneth Reitzbefore adoption9fc0701
line 10why, one step back10import unittestMerge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptionb2c801f
line 11why, one step back11import collectionsadd history to the docsKenneth Reitzbefore adoption4401620
line 12why, one step back12Merge pull request #1937 from jaraco/masterKenneth Reitzbefore adoption569cd23
line 13why, one step back13import ioadd history to the docsKenneth Reitzbefore adoption4401620
lines 14–16why, one step back14import requests15import pytest16from requests.adapters import HTTPAdapterMerge pull request #2076 from Lukasa/basicKenneth Reitzbefore adoption3ee781b
line 17why, one step back17from requests.auth import HTTPDigestAuth, _basic_auth_strMerge pull request #1772 from mdbecker/make_morsel_to_cookie_more_pythonicKenneth Reitzbefore adoption9fc0701
line 18why, one step back18from requests.compat import (Merge pull request #2076 from Lukasa/basicKenneth Reitzbefore adoption3ee781b
line 19why, one step back19 Morsel, cookielib, getproxies, str, urljoin, urlparse, is_py3, builtin_str)Merge pull request #1772 from mdbecker/make_morsel_to_cookie_more_pythonicKenneth Reitzbefore adoption9fc0701
line 20why, one step back20from requests.cookies import cookiejar_from_dict, morsel_to_cookieMerge pull request #2222 from blueyed/fix-MissingScheme-for-hostportCory Benfieldbefore adoption1a44a99
lines 21–23why, one step back21from requests.exceptions import (ConnectionError, ConnectTimeout,22 InvalidSchema, InvalidURL, MissingSchema,23 ReadTimeout, Timeout)Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
line 24why, one step back24from requests.models import PreparedRequestadd history to the docsKenneth Reitzbefore adoption4401620
line 25why, one step back25from requests.structures import CaseInsensitiveDictMerge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptionb2c801f
line 26why, one step back26from requests.sessions import SessionRedirectMixinMerge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
line 27why, one step back27from requests.models import urlencodeMerge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptionb2c801f
line 28why, one step back28from requests.hooks import default_hooksadd history to the docsKenneth Reitzbefore adoption4401620
lines 29–34why, one step back2930try:31 import StringIO32except ImportError:33 import io as StringIO34Merge pull request #2065 from mgeisler/toxKenneth Reitzbefore adoptionddd748e
lines 35–42why, one step back35if is_py3:36 def u(s):37 return s38else:39 def u(s):40 return s.decode('unicode-escape')4142Merge pull request #2176 from kevinburke/connectKenneth Reitzbefore adoption32e403a
lines 43–45why, one step back43# Requests to this URL should always fail with a connection timeout (nothing44# listening on that port)45TARPIT = "http://10.255.255.1"add history to the docsKenneth Reitzbefore adoption4401620
lines 46–79why, one step back46HTTPBIN = os.environ.get('HTTPBIN_URL', 'http://httpbin.org/')47# Issue #1483: Make sure the URL always has a trailing slash48HTTPBIN = HTTPBIN.rstrip('/') + '/'495051def httpbin(*suffix):52 """Returns url for HTTPBIN resource."""53 return urljoin(HTTPBIN, '/'.join(suffix))545556class RequestsTestCase(unittest.TestCase):5758 _multiprocess_can_split_ = True5960 def setUp(self):61 """Create simple data set with headers."""62 pass6364 def tearDown(self):65 """Teardown."""66 pass6768 def test_entry_points(self):6970 requests.session71 requests.session().get72 requests.session().head73 requests.get74 requests.head75 requests.put76 requests.patch77 requests.post7879 def test_invalid_url(self):Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 80–81why, one step back80 with pytest.raises(MissingSchema):81 requests.get('hiwpefhipowhefopw')Merge pull request #2222 from blueyed/fix-MissingScheme-for-hostportCory Benfieldbefore adoption1a44a99
lines 82–87why, one step back82 with pytest.raises(InvalidSchema):83 requests.get('localhost:3128')84 with pytest.raises(InvalidSchema):85 requests.get('localhost.localdomain:3128/')86 with pytest.raises(InvalidSchema):87 requests.get('10.122.1.1:3128/')Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 88–89why, one step back88 with pytest.raises(InvalidURL):89 requests.get('http://')add history to the docsKenneth Reitzbefore adoption4401620
lines 90–101why, one step back9091 def test_basic_building(self):92 req = requests.Request()93 req.url = 'http://kennethreitz.org/'94 req.data = {'life': '42'}9596 pr = req.prepare()97 assert pr.url == req.url98 assert pr.body == 'life=42'99100 def test_no_content_length(self):101 get_req = requests.Request('GET', httpbin('get')).prepare()Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 102why, one step back102 assert 'Content-Length' not in get_req.headersadd history to the docsKenneth Reitzbefore adoption4401620
line 103why, one step back103 head_req = requests.Request('HEAD', httpbin('head')).prepare()Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 104why, one step back104 assert 'Content-Length' not in head_req.headersadd history to the docsKenneth Reitzbefore adoption4401620
lines 105–108why, one step back105106 def test_path_is_not_double_encoded(self):107 request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()108Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 109why, one step back109 assert request.path_url == '/get/test%20case'add history to the docsKenneth Reitzbefore adoption4401620
lines 110–113why, one step back110111 def test_params_are_added_before_fragment(self):112 request = requests.Request('GET',113 "http://example.com/path#fragment", params={"a": "b"}).prepare()Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 114why, one step back114 assert request.url == "http://example.com/path?a=b#fragment"add history to the docsKenneth Reitzbefore adoption4401620
lines 115–116why, one step back115 request = requests.Request('GET',116 "http://example.com/path?key=value#fragment", params={"a": "b"}).prepare()Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 117why, one step back117 assert request.url == "http://example.com/path?key=value&a=b#fragment"add history to the docsKenneth Reitzbefore adoption4401620
lines 118–128why, one step back118119 def test_mixed_case_scheme_acceptable(self):120 s = requests.Session()121 s.proxies = getproxies()122 parts = urlparse(httpbin('get'))123 schemes = ['http://', 'HTTP://', 'hTTp://', 'HttP://',124 'https://', 'HTTPS://', 'hTTps://', 'HttPs://']125 for scheme in schemes:126 url = scheme + parts.netloc + parts.path127 r = requests.Request('GET', url)128 r = s.send(r.prepare())Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 129why, one step back129 assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)add history to the docsKenneth Reitzbefore adoption4401620
lines 130–137why, one step back130131 def test_HTTP_200_OK_GET_ALTERNATIVE(self):132 r = requests.Request('GET', httpbin('get'))133 s = requests.Session()134 s.proxies = getproxies()135136 r = s.send(r.prepare())137Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 138why, one step back138 assert r.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
lines 139–141why, one step back139140 def test_HTTP_302_ALLOW_REDIRECT_GET(self):141 r = requests.get(httpbin('redirect', '1'))Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 142why, one step back142 assert r.status_code == 200Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona3cd2f3
lines 143–144why, one step back143 assert r.history[0].status_code == 302144 assert r.history[0].is_redirectadd history to the docsKenneth Reitzbefore adoption4401620
lines 145–154why, one step back145146 # def test_HTTP_302_ALLOW_REDIRECT_POST(self):147 # r = requests.post(httpbin('status', '302'), data={'some': 'data'})148 # self.assertEqual(r.status_code, 200)149150 def test_HTTP_200_OK_GET_WITH_PARAMS(self):151 heads = {'User-agent': 'Mozilla/5.0'}152153 r = requests.get(httpbin('user-agent'), headers=heads)154Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 155–156why, one step back155 assert heads['User-agent'] in r.text156 assert r.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
lines 157–161why, one step back157158 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):159 heads = {'User-agent': 'Mozilla/5.0'}160161 r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 162why, one step back162 assert r.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
lines 163–166why, one step back163164 def test_set_cookie_on_301(self):165 s = requests.session()166 url = httpbin('cookies/set?foo=bar')Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
line 167why, one step back167 s.get(url)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 168why, one step back168 assert s.cookies['foo'] == 'bar'add history to the docsKenneth Reitzbefore adoption4401620
lines 169–173why, one step back169170 def test_cookie_sent_on_redirect(self):171 s = requests.session()172 s.get(httpbin('cookies/set?foo=bar'))173 r = s.get(httpbin('redirect/1')) # redirects to httpbin('get')Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 174why, one step back174 assert 'Cookie' in r.json()['headers']add history to the docsKenneth Reitzbefore adoption4401620
lines 175–178why, one step back175176 def test_cookie_removed_on_expire(self):177 s = requests.session()178 s.get(httpbin('cookies/set?foo=bar'))Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 179why, one step back179 assert s.cookies['foo'] == 'bar'add history to the docsKenneth Reitzbefore adoption4401620
lines 180–191why, one step back180 s.get(181 httpbin('response-headers'),182 params={183 'Set-Cookie':184 'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'185 }186 )187 assert 'foo' not in s.cookies188189 def test_cookie_quote_wrapped(self):190 s = requests.session()191 s.get(httpbin('cookies/set?foo="bar:baz"'))Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 192why, one step back192 assert s.cookies['foo'] == '"bar:baz"'add history to the docsKenneth Reitzbefore adoption4401620
line 193why, one step back193Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption011f6da
lines 194–195why, one step back194 def test_cookie_persists_via_api(self):195 s = requests.session()Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption57c4684
line 196why, one step back196 r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 197–198why, one step back197 assert 'foo' in r.request.headers['Cookie']198 assert 'foo' in r.history[0].request.headers['Cookie']Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption011f6da
line 199why, one step back199add history to the docsKenneth Reitzbefore adoption4401620
lines 200–207why, one step back200 def test_request_cookie_overrides_session_cookie(self):201 s = requests.session()202 s.cookies['foo'] = 'bar'203 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})204 assert r.json()['cookies']['foo'] == 'baz'205 # Session cookie should not be modified206 assert s.cookies['foo'] == 'bar'207Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption57c4684
lines 208–213why, one step back208 def test_request_cookies_not_persisted(self):209 s = requests.session()210 s.get(httpbin('cookies'), cookies={'foo': 'baz'})211 # Sending a request with cookies should not add cookies to the session212 assert not s.cookies213add history to the docsKenneth Reitzbefore adoption4401620
lines 214–223why, one step back214 def test_generic_cookiejar_works(self):215 cj = cookielib.CookieJar()216 cookiejar_from_dict({'foo': 'bar'}, cj)217 s = requests.session()218 s.cookies = cj219 r = s.get(httpbin('cookies'))220 # Make sure the cookie was sent221 assert r.json()['cookies']['foo'] == 'bar'222 # Make sure the session cj is still the custom one223 assert s.cookies is cjMerge pull request #1862 from sybeck2k/masterKenneth Reitzbefore adoption0465d34
line 224why, one step back224Merge pull request #1713 from daftshady/masterKenneth Reitzbefore adoption8b88549
lines 225–226why, one step back225 def test_param_cookiejar_works(self):226 cj = cookielib.CookieJar()Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
line 227why, one step back227 cookiejar_from_dict({'foo': 'bar'}, cj)Merge pull request #1713 from daftshady/masterKenneth Reitzbefore adoption8b88549
lines 228–231why, one step back228 s = requests.session()229 r = s.get(httpbin('cookies'), cookies=cj)230 # Make sure the cookie was sent231 assert r.json()['cookies']['foo'] == 'bar'add history to the docsKenneth Reitzbefore adoption4401620
lines 232–236why, one step back232233 def test_requests_in_history_are_not_overridden(self):234 resp = requests.get(httpbin('redirect/3'))235 urls = [r.url for r in resp.history]236 req_urls = [r.request.url for r in resp.history]Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 237why, one step back237 assert urls == req_urlsadd history to the docsKenneth Reitzbefore adoption4401620
line 238why, one step back238Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptionb2c801f
lines 239–248why, one step back239 def test_history_is_always_a_list(self):240 """241 Show that even with redirects, Response.history is always a list.242 """243 resp = requests.get(httpbin('get'))244 assert isinstance(resp.history, list)245 resp = requests.get(httpbin('redirect/1'))246 assert isinstance(resp.history, list)247 assert not isinstance(resp.history, tuple)248Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona3cd2f3
lines 249–256why, one step back249 def test_headers_on_session_with_None_are_not_sent(self):250 """Do not send headers in Session.headers with None values."""251 ses = requests.Session()252 ses.headers['Accept-Encoding'] = None253 req = requests.Request('GET', 'http://httpbin.org/get')254 prep = ses.prepare_request(req)255 assert 'Accept-Encoding' not in prep.headers256add history to the docsKenneth Reitzbefore adoption4401620
lines 257–263why, one step back257 def test_user_agent_transfers(self):258259 heads = {260 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'261 }262263 r = requests.get(httpbin('user-agent'), headers=heads)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 264why, one step back264 assert heads['User-agent'] in r.textadd history to the docsKenneth Reitzbefore adoption4401620
lines 265–270why, one step back265266 heads = {267 'user-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'268 }269270 r = requests.get(httpbin('user-agent'), headers=heads)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 271why, one step back271 assert heads['user-agent'] in r.textadd history to the docsKenneth Reitzbefore adoption4401620
lines 272–274why, one step back272273 def test_HTTP_200_OK_HEAD(self):274 r = requests.head(httpbin('get'))Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 275why, one step back275 assert r.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
lines 276–278why, one step back276277 def test_HTTP_200_OK_PUT(self):278 r = requests.put(httpbin('put'))Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 279why, one step back279 assert r.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
lines 280–285why, one step back280281 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):282 auth = ('user', 'pass')283 url = httpbin('basic-auth', 'user', 'pass')284285 r = requests.get(url, auth=auth)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 286why, one step back286 assert r.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
lines 287–288why, one step back287288 r = requests.get(url)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 289why, one step back289 assert r.status_code == 401add history to the docsKenneth Reitzbefore adoption4401620
lines 290–293why, one step back290291 s = requests.session()292 s.auth = auth293 r = s.get(url)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 294why, one step back294 assert r.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
line 295why, one step back295Merge pull request #2193 from sigmavirus24/bug/2192Kenneth Reitzbefore adoption1324ca1
lines 296–303why, one step back296 def test_connection_error(self):297 """Connecting to an unknown domain should raise a ConnectionError"""298 with pytest.raises(ConnectionError):299 requests.get("http://fooobarbangbazbing.httpbin.org")300301 with pytest.raises(ConnectionError):302 requests.get("http://httpbin.org:1")303add history to the docsKenneth Reitzbefore adoption4401620
lines 304–314why, one step back304 def test_basicauth_with_netrc(self):305 auth = ('user', 'pass')306 wrong_auth = ('wronguser', 'wrongpass')307 url = httpbin('basic-auth', 'user', 'pass')308309 def get_netrc_auth_mock(url):310 return auth311 requests.sessions.get_netrc_auth = get_netrc_auth_mock312313 # Should use netrc and work.314 r = requests.get(url)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 315why, one step back315 assert r.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
lines 316–318why, one step back316317 # Given auth should override and fail.318 r = requests.get(url, auth=wrong_auth)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 319why, one step back319 assert r.status_code == 401add history to the docsKenneth Reitzbefore adoption4401620
lines 320–324why, one step back320321 s = requests.session()322323 # Should use netrc and work.324 r = s.get(url)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 325why, one step back325 assert r.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
lines 326–329why, one step back326327 # Given auth should override and fail.328 s.auth = wrong_auth329 r = s.get(url)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 330why, one step back330 assert r.status_code == 401add history to the docsKenneth Reitzbefore adoption4401620
lines 331–337why, one step back331332 def test_DIGEST_HTTP_200_OK_GET(self):333334 auth = HTTPDigestAuth('user', 'pass')335 url = httpbin('digest-auth', 'auth', 'user', 'pass')336337 r = requests.get(url, auth=auth)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 338why, one step back338 assert r.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
lines 339–340why, one step back339340 r = requests.get(url)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 341why, one step back341 assert r.status_code == 401add history to the docsKenneth Reitzbefore adoption4401620
lines 342–345why, one step back342343 s = requests.session()344 s.auth = HTTPDigestAuth('user', 'pass')345 r = s.get(url)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 346why, one step back346 assert r.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
lines 347–369why, one step back347348 def test_DIGEST_AUTH_RETURNS_COOKIE(self):349 url = httpbin('digest-auth', 'auth', 'user', 'pass')350 auth = HTTPDigestAuth('user', 'pass')351 r = requests.get(url)352 assert r.cookies['fake'] == 'fake_value'353354 r = requests.get(url, auth=auth)355 assert r.status_code == 200356357 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self):358 url = httpbin('digest-auth', 'auth', 'user', 'pass')359 auth = HTTPDigestAuth('user', 'pass')360 s = requests.Session()361 s.get(url, auth=auth)362 assert s.cookies['fake'] == 'fake_value'363364 def test_DIGEST_STREAM(self):365366 auth = HTTPDigestAuth('user', 'pass')367 url = httpbin('digest-auth', 'auth', 'user', 'pass')368369 r = requests.get(url, auth=auth, stream=True)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 370why, one step back370 assert r.raw.read() != b''add history to the docsKenneth Reitzbefore adoption4401620
lines 371–372why, one step back371372 r = requests.get(url, auth=auth, stream=False)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 373why, one step back373 assert r.raw.read() == b''add history to the docsKenneth Reitzbefore adoption4401620
lines 374–380why, one step back374375 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self):376377 auth = HTTPDigestAuth('user', 'wrongpass')378 url = httpbin('digest-auth', 'auth', 'user', 'pass')379380 r = requests.get(url, auth=auth)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 381why, one step back381 assert r.status_code == 401add history to the docsKenneth Reitzbefore adoption4401620
lines 382–383why, one step back382383 r = requests.get(url)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 384why, one step back384 assert r.status_code == 401add history to the docsKenneth Reitzbefore adoption4401620
lines 385–388why, one step back385386 s = requests.session()387 s.auth = auth388 r = s.get(url)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 389why, one step back389 assert r.status_code == 401add history to the docsKenneth Reitzbefore adoption4401620
line 390why, one step back390Merge pull request #1766 from Lukasa/qopKenneth Reitzbefore adoptiona030a58
lines 391–398why, one step back391 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self):392393 auth = HTTPDigestAuth('user', 'pass')394 url = httpbin('digest-auth', 'auth', 'user', 'pass')395396 r = requests.get(url, auth=auth)397 assert '"auth"' in r.request.headers['Authorization']398add history to the docsKenneth Reitzbefore adoption4401620
lines 399–404why, one step back399 def test_POSTBIN_GET_POST_FILES(self):400401 url = httpbin('post')402 post1 = requests.post(url).raise_for_status()403404 post1 = requests.post(url, data={'some': 'data'})Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 405why, one step back405 assert post1.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
lines 406–408why, one step back406407 with open('requirements.txt') as f:408 post2 = requests.post(url, files={'some': f})Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 409why, one step back409 assert post2.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
lines 410–411why, one step back410411 post4 = requests.post(url, data='[{"some": "json"}]')Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 412why, one step back412 assert post4.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
line 413why, one step back413Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 414why, one step back414 with pytest.raises(ValueError):Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
line 415why, one step back415 requests.post(url, files=['bad file data'])add history to the docsKenneth Reitzbefore adoption4401620
lines 416–422why, one step back416417 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self):418419 url = httpbin('post')420 post1 = requests.post(url).raise_for_status()421422 post1 = requests.post(url, data={'some': 'data'})Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 423why, one step back423 assert post1.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
lines 424–425why, one step back424425 with open('requirements.txt') as f:Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
lines 426–427why, one step back426 post2 = requests.post(url,427 data={'some': 'data'}, files={'some': f})Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 428why, one step back428 assert post2.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
lines 429–430why, one step back429430 post4 = requests.post(url, data='[{"some": "json"}]')Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 431why, one step back431 assert post4.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
line 432why, one step back432Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 433why, one step back433 with pytest.raises(ValueError):Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
line 434why, one step back434 requests.post(url, files=['bad file data'])add history to the docsKenneth Reitzbefore adoption4401620
lines 435–439why, one step back435436 def test_conflicting_post_params(self):437 url = httpbin('post')438 with open('requirements.txt') as f:439 pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")Merge pull request #2065 from mgeisler/toxKenneth Reitzbefore adoptionddd748e
line 440why, one step back440 pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")add history to the docsKenneth Reitzbefore adoption4401620
lines 441–443why, one step back441442 def test_request_ok_set(self):443 r = requests.get(httpbin('status', '404'))Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 444why, one step back444 assert not r.okadd history to the docsKenneth Reitzbefore adoption4401620
lines 445–447why, one step back445446 def test_status_raising(self):447 r = requests.get(httpbin('status', '404'))Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 448–449why, one step back448 with pytest.raises(requests.exceptions.HTTPError):449 r.raise_for_status()add history to the docsKenneth Reitzbefore adoption4401620
lines 450–451why, one step back450451 r = requests.get(httpbin('status', '500'))Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 452why, one step back452 assert not r.okadd history to the docsKenneth Reitzbefore adoption4401620
lines 453–466why, one step back453454 def test_decompress_gzip(self):455 r = requests.get(httpbin('gzip'))456 r.content.decode('ascii')457458 def test_unicode_get(self):459 url = httpbin('/get')460 requests.get(url, params={'foo': 'føø'})461 requests.get(url, params={'føø': 'føø'})462 requests.get(url, params={'føø': 'føø'})463 requests.get(url, params={'foo': 'foo'})464 requests.get(httpbin('ø'), params={'foo': 'foo'})465466 def test_unicode_header_name(self):Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
lines 467–470why, one step back467 requests.put(468 httpbin('put'),469 headers={str('Content-Type'): 'application/octet-stream'},470 data='\xff') # compat.str is unicode.add history to the docsKenneth Reitzbefore adoption4401620
line 471why, one step back471Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
lines 472–474why, one step back472 def test_pyopenssl_redirect(self):473 requests.get('https://httpbin.org/status/301')474add history to the docsKenneth Reitzbefore adoption4401620
lines 475–477why, one step back475 def test_urlencoded_get_query_multivalued_param(self):476477 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 478–479why, one step back478 assert r.status_code == 200479 assert r.url == httpbin('get?test=foo&test=baz')add history to the docsKenneth Reitzbefore adoption4401620
lines 480–482why, one step back480481 def test_different_encodings_dont_break_post(self):482 r = requests.post(httpbin('post'),Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
lines 483–485why, one step back483 data={'stuff': json.dumps({'a': 123})},484 params={'blah': 'asdf1234'},485 files={'file': ('test_requests.py', open(__file__, 'rb'))})Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 486why, one step back486 assert r.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
lines 487–489why, one step back487488 def test_unicode_multipart_post(self):489 r = requests.post(httpbin('post'),Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
lines 490–491why, one step back490 data={'stuff': u('ëlïxr')},491 files={'file': ('test_requests.py', open(__file__, 'rb'))})Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 492why, one step back492 assert r.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
lines 493–494why, one step back493494 r = requests.post(httpbin('post'),Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
lines 495–496why, one step back495 data={'stuff': u('ëlïxr').encode('utf-8')},496 files={'file': ('test_requests.py', open(__file__, 'rb'))})Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 497why, one step back497 assert r.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
lines 498–499why, one step back498499 r = requests.post(httpbin('post'),Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
lines 500–501why, one step back500 data={'stuff': 'elixr'},501 files={'file': ('test_requests.py', open(__file__, 'rb'))})Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 502why, one step back502 assert r.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
lines 503–504why, one step back503504 r = requests.post(httpbin('post'),Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
lines 505–506why, one step back505 data={'stuff': 'elixr'.encode('utf-8')},506 files={'file': ('test_requests.py', open(__file__, 'rb'))})Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 507why, one step back507 assert r.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
lines 508–516why, one step back508509 def test_unicode_multipart_post_fieldnames(self):510 filename = os.path.splitext(__file__)[0] + '.py'511 r = requests.Request(method='POST',512 url=httpbin('post'),513 data={'stuff'.encode('utf-8'): 'elixr'},514 files={'file': ('test_requests.py',515 open(filename, 'rb'))})516 prep = r.prepare()Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 517–518why, one step back517 assert b'name="stuff"' in prep.body518 assert b'name="b\'stuff\'"' not in prep.bodyMerge pull request #1733 from ionrock/pickleable-responsesKenneth Reitzbefore adoptionaf921c7
line 519why, one step back519Merge pull request #1724 from daftshady/dev3Kenneth Reitzbefore adoption7ccbcd2
lines 520–521why, one step back520 def test_unicode_method_name(self):521 files = {'file': open('test_requests.py', 'rb')}Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
lines 522–523why, one step back522 r = requests.request(523 method=u('POST'), url=httpbin('post'), files=files)Merge pull request #1724 from daftshady/dev3Kenneth Reitzbefore adoption7ccbcd2
line 524why, one step back524 assert r.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
lines 525–526why, one step back525526 def test_custom_content_type(self):Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
lines 527–532why, one step back527 r = requests.post(528 httpbin('post'),529 data={'stuff': json.dumps({'a': 123})},530 files={'file1': ('test_requests.py', open(__file__, 'rb')),531 'file2': ('test_requests', open(__file__, 'rb'),532 'text/py-content-type')})Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 533–534why, one step back533 assert r.status_code == 200534 assert b"text/py-content-type" in r.request.bodyadd history to the docsKenneth Reitzbefore adoption4401620
lines 535–542why, one step back535536 def test_hook_receives_request_arguments(self):537 def hook(resp, **kwargs):538 assert resp is not None539 assert kwargs != {}540541 requests.Request('GET', HTTPBIN, hooks={'response': hook})542Merge pull request #1657 from sigmavirus24/fix-session-hooksKenneth Reitzbefore adoption5c91545
lines 543–561why, one step back543 def test_session_hooks_are_used_with_no_request_hooks(self):544 hook = lambda x, *args, **kwargs: x545 s = requests.Session()546 s.hooks['response'].append(hook)547 r = requests.Request('GET', HTTPBIN)548 prep = s.prepare_request(r)549 assert prep.hooks['response'] != []550 assert prep.hooks['response'] == [hook]551552 def test_session_hooks_are_overriden_by_request_hooks(self):553 hook1 = lambda x, *args, **kwargs: x554 hook2 = lambda x, *args, **kwargs: x555 assert hook1 is not hook2556 s = requests.Session()557 s.hooks['response'].append(hook2)558 r = requests.Request('GET', HTTPBIN, hooks={'response': [hook1]})559 prep = s.prepare_request(r)560 assert prep.hooks['response'] == [hook1]561add history to the docsKenneth Reitzbefore adoption4401620
lines 562–573why, one step back562 def test_prepared_request_hook(self):563 def hook(resp, **kwargs):564 resp.hook_working = True565 return resp566567 req = requests.Request('GET', HTTPBIN, hooks={'response': hook})568 prep = req.prepare()569570 s = requests.Session()571 s.proxies = getproxies()572 resp = s.send(prep)573Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 574why, one step back574 assert hasattr(resp, 'hook_working')add history to the docsKenneth Reitzbefore adoption4401620
lines 575–582why, one step back575576 def test_prepared_from_session(self):577 class DummyAuth(requests.auth.AuthBase):578 def __call__(self, r):579 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'580 return r581582 req = requests.Request('GET', httpbin('headers'))Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 583why, one step back583 assert not req.authadd history to the docsKenneth Reitzbefore adoption4401620
lines 584–590why, one step back584585 s = requests.Session()586 s.auth = DummyAuth()587588 prep = s.prepare_request(req)589 resp = s.send(prep)590Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
lines 591–592why, one step back591 assert resp.json()['headers'][592 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'add history to the docsKenneth Reitzbefore adoption4401620
line 593why, one step back593Merge pull request #2238 from buttscicles/byte-urlsKenneth Reitzbefore adoptione74791d
lines 594–599why, one step back594 def test_prepare_request_with_bytestring_url(self):595 req = requests.Request('GET', b'https://httpbin.org/')596 s = requests.Session()597 prep = s.prepare_request(req)598 assert prep.url == "https://httpbin.org/"599add history to the docsKenneth Reitzbefore adoption4401620
lines 600–621why, one step back600 def test_links(self):601 r = requests.Response()602 r.headers = {603 'cache-control': 'public, max-age=60, s-maxage=60',604 'connection': 'keep-alive',605 'content-encoding': 'gzip',606 'content-type': 'application/json; charset=utf-8',607 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',608 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',609 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',610 'link': ('<https://api.github.com/users/kennethreitz/repos?'611 'page=2&per_page=10>; rel="next", <https://api.github.'612 'com/users/kennethreitz/repos?page=7&per_page=10>; '613 ' rel="last"'),614 'server': 'GitHub.com',615 'status': '200 OK',616 'vary': 'Accept',617 'x-content-type-options': 'nosniff',618 'x-github-media-type': 'github.beta',619 'x-ratelimit-limit': '60',620 'x-ratelimit-remaining': '57'621 }Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 622why, one step back622 assert r.links['next']['rel'] == 'next'add history to the docsKenneth Reitzbefore adoption4401620
lines 623–633why, one step back623624 def test_cookie_parameters(self):625 key = 'some_cookie'626 value = 'some_value'627 secure = True628 domain = 'test.com'629 rest = {'HttpOnly': True}630631 jar = requests.cookies.RequestsCookieJar()632 jar.set(key, value, secure=secure, domain=domain, rest=rest)633Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 634–635why, one step back634 assert len(jar) == 1635 assert 'some_cookie' in jaradd history to the docsKenneth Reitzbefore adoption4401620
lines 636–637why, one step back636637 cookie = list(jar)[0]Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 638–640why, one step back638 assert cookie.secure == secure639 assert cookie.domain == domain640 assert cookie._rest['HttpOnly'] == rest['HttpOnly']add history to the docsKenneth Reitzbefore adoption4401620
line 641why, one step back641Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233
lines 642–728why, one step back642 def test_cookie_as_dict_keeps_len(self):643 key = 'some_cookie'644 value = 'some_value'645646 key1 = 'some_cookie1'647 value1 = 'some_value1'648649 jar = requests.cookies.RequestsCookieJar()650 jar.set(key, value)651 jar.set(key1, value1)652653 d1 = dict(jar)654 d2 = dict(jar.iteritems())655 d3 = dict(jar.items())656657 assert len(jar) == 2658 assert len(d1) == 2659 assert len(d2) == 2660 assert len(d3) == 2661662 def test_cookie_as_dict_keeps_items(self):663 key = 'some_cookie'664 value = 'some_value'665666 key1 = 'some_cookie1'667 value1 = 'some_value1'668669 jar = requests.cookies.RequestsCookieJar()670 jar.set(key, value)671 jar.set(key1, value1)672673 d1 = dict(jar)674 d2 = dict(jar.iteritems())675 d3 = dict(jar.items())676677 assert d1['some_cookie'] == 'some_value'678 assert d2['some_cookie'] == 'some_value'679 assert d3['some_cookie1'] == 'some_value1'680681 def test_cookie_as_dict_keys(self):682 key = 'some_cookie'683 value = 'some_value'684685 key1 = 'some_cookie1'686 value1 = 'some_value1'687688 jar = requests.cookies.RequestsCookieJar()689 jar.set(key, value)690 jar.set(key1, value1)691692 keys = jar.keys()693 assert keys == list(keys)694 # make sure one can use keys multiple times695 assert list(keys) == list(keys)696697 def test_cookie_as_dict_values(self):698 key = 'some_cookie'699 value = 'some_value'700701 key1 = 'some_cookie1'702 value1 = 'some_value1'703704 jar = requests.cookies.RequestsCookieJar()705 jar.set(key, value)706 jar.set(key1, value1)707708 values = jar.values()709 assert values == list(values)710 # make sure one can use values multiple times711 assert list(values) == list(values)712713 def test_cookie_as_dict_items(self):714 key = 'some_cookie'715 value = 'some_value'716717 key1 = 'some_cookie1'718 value1 = 'some_value1'719720 jar = requests.cookies.RequestsCookieJar()721 jar.set(key, value)722 jar.set(key1, value1)723724 items = jar.items()725 assert items == list(items)726 # make sure one can use items multiple times727 assert list(items) == list(items)728add history to the docsKenneth Reitzbefore adoption4401620
lines 729–733why, one step back729 def test_time_elapsed_blank(self):730 r = requests.get(httpbin('get'))731 td = r.elapsed732 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)733 * 10**6) / 10**6)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 734why, one step back734 assert total_seconds > 0.0add history to the docsKenneth Reitzbefore adoption4401620
lines 735–744why, one step back735736 def test_response_is_iterable(self):737 r = requests.Response()738 io = StringIO.StringIO('abc')739 read_ = io.read740741 def read_mock(amt, decode_content=None):742 return read_(amt)743 setattr(io, 'read', read_mock)744 r.raw = ioMerge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 745why, one step back745 assert next(iter(r))add history to the docsKenneth Reitzbefore adoption4401620
line 746why, one step back746 io.close()Merge pull request #2148 from romanlevin/handle-socket-error-in-iter_contentKenneth Reitzbefore adoption3eb69be
line 747why, one step back747Merge pull request #1937 from jaraco/masterKenneth Reitzbefore adoption569cd23
lines 748–766why, one step back748 def test_response_decode_unicode(self):749 """750 When called with decode_unicode, Response.iter_content should always751 return unicode.752 """753 r = requests.Response()754 r._content_consumed = True755 r._content = b'the content'756 r.encoding = 'ascii'757758 chunks = r.iter_content(decode_unicode=True)759 assert all(isinstance(chunk, str) for chunk in chunks)760761 # also for streaming762 r = requests.Response()763 r.raw = io.BytesIO(b'the content')764 r.encoding = 'ascii'765 chunks = r.iter_content(decode_unicode=True)766 assert all(isinstance(chunk, str) for chunk in chunks)Merge pull request #1733 from ionrock/pickleable-responsesKenneth Reitzbefore adoptionaf921c7
lines 767–778why, one step back767768 def test_request_and_response_are_pickleable(self):769 r = requests.get(httpbin('get'))770771 # verify we can pickle the original request772 assert pickle.loads(pickle.dumps(r.request))773774 # verify we can pickle the response and that we have access to775 # the original request.776 pr = pickle.loads(pickle.dumps(r))777 assert r.request.url == pr.request.url778 assert r.request.headers == pr.request.headersadd history to the docsKenneth Reitzbefore adoption4401620
lines 779–781why, one step back779780 def test_get_auth_from_url(self):781 url = 'http://user:pass@complex.url.com/path?query=yes'Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 782why, one step back782 assert ('user', 'pass') == requests.utils.get_auth_from_url(url)add history to the docsKenneth Reitzbefore adoption4401620
line 783why, one step back783Merge pull request #1768 from Lukasa/credpctKenneth Reitzbefore adoption4bceb31
lines 784–792why, one step back784 def test_get_auth_from_url_encoded_spaces(self):785 url = 'http://user:pass%20pass@complex.url.com/path?query=yes'786 assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)787788 def test_get_auth_from_url_not_encoded_spaces(self):789 url = 'http://user:pass pass@complex.url.com/path?query=yes'790 assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)791792 def test_get_auth_from_url_percent_chars(self):Merge pull request #1862 from sybeck2k/masterKenneth Reitzbefore adoption0465d34
line 793why, one step back793 url = 'http://user%25user:pass@complex.url.com/path?query=yes'Merge pull request #1768 from Lukasa/credpctKenneth Reitzbefore adoption4bceb31
lines 794–795why, one step back794 assert ('user%user', 'pass') == requests.utils.get_auth_from_url(url)795Merge pull request #1862 from sybeck2k/masterKenneth Reitzbefore adoption0465d34
lines 796–799why, one step back796 def test_get_auth_from_url_encoded_hashes(self):797 url = 'http://user:pass%23pass@complex.url.com/path?query=yes'798 assert ('user', 'pass#pass') == requests.utils.get_auth_from_url(url)799add history to the docsKenneth Reitzbefore adoption4401620
lines 800–801why, one step back800 def test_cannot_send_unprepared_requests(self):801 r = requests.Request(url=HTTPBIN)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 802–803why, one step back802 with pytest.raises(ValueError):803 requests.Session().send(r)add history to the docsKenneth Reitzbefore adoption4401620
lines 804–806why, one step back804805 def test_http_error(self):806 error = requests.exceptions.HTTPError()Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 807why, one step back807 assert not error.responseadd history to the docsKenneth Reitzbefore adoption4401620
lines 808–809why, one step back808 response = requests.Response()809 error = requests.exceptions.HTTPError(response=response)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 810why, one step back810 assert error.response == responseadd history to the docsKenneth Reitzbefore adoption4401620
line 811why, one step back811 error = requests.exceptions.HTTPError('message', response=response)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 812–813why, one step back812 assert str(error) == 'message'813 assert error.response == responseadd history to the docsKenneth Reitzbefore adoption4401620
lines 814–822why, one step back814815 def test_session_pickling(self):816 r = requests.Request('GET', httpbin('get'))817 s = requests.Session()818819 s = pickle.loads(pickle.dumps(s))820 s.proxies = getproxies()821822 r = s.send(r.prepare())Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 823why, one step back823 assert r.status_code == 200add history to the docsKenneth Reitzbefore adoption4401620
lines 824–833why, one step back824825 def test_fixes_1329(self):826 """827 Ensure that header updates are done case-insensitively.828 """829 s = requests.Session()830 s.headers.update({'ACCEPT': 'BOGUS'})831 s.headers.update({'accept': 'application/json'})832 r = s.get(httpbin('get'))833 headers = r.request.headersMerge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 834–836why, one step back834 assert headers['accept'] == 'application/json'835 assert headers['Accept'] == 'application/json'836 assert headers['ACCEPT'] == 'application/json'add history to the docsKenneth Reitzbefore adoption4401620
lines 837–841why, one step back837838 def test_uppercase_scheme_redirect(self):839 parts = urlparse(httpbin('html'))840 url = "HTTP://" + parts.netloc + parts.path841 r = requests.get(httpbin('redirect-to'), params={'url': url})Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 842–843why, one step back842 assert r.status_code == 200843 assert r.url.lower() == url.lower()add history to the docsKenneth Reitzbefore adoption4401620
lines 844–847why, one step back844845 def test_transport_adapter_ordering(self):846 s = requests.Session()847 order = ['https://', 'http://']Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 848why, one step back848 assert order == list(s.adapters)add history to the docsKenneth Reitzbefore adoption4401620
lines 849–860why, one step back849 s.mount('http://git', HTTPAdapter())850 s.mount('http://github', HTTPAdapter())851 s.mount('http://github.com', HTTPAdapter())852 s.mount('http://github.com/about/', HTTPAdapter())853 order = [854 'http://github.com/about/',855 'http://github.com',856 'http://github',857 'http://git',858 'https://',859 'http://',860 ]Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 861why, one step back861 assert order == list(s.adapters)add history to the docsKenneth Reitzbefore adoption4401620
lines 862–875why, one step back862 s.mount('http://gittip', HTTPAdapter())863 s.mount('http://gittip.com', HTTPAdapter())864 s.mount('http://gittip.com/about/', HTTPAdapter())865 order = [866 'http://github.com/about/',867 'http://gittip.com/about/',868 'http://github.com',869 'http://gittip.com',870 'http://github',871 'http://gittip',872 'http://git',873 'https://',874 'http://',875 ]Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 876why, one step back876 assert order == list(s.adapters)add history to the docsKenneth Reitzbefore adoption4401620
lines 877–879why, one step back877 s2 = requests.Session()878 s2.adapters = {'http://': HTTPAdapter()}879 s2.mount('https://', HTTPAdapter())Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 880–881why, one step back880 assert 'http://' in s2.adapters881 assert 'https://' in s2.adaptersadd history to the docsKenneth Reitzbefore adoption4401620
lines 882–902why, one step back882883 def test_header_remove_is_case_insensitive(self):884 # From issue #1321885 s = requests.Session()886 s.headers['foo'] = 'bar'887 r = s.get(httpbin('get'), headers={'FOO': None})888 assert 'foo' not in r.request.headers889890 def test_params_are_merged_case_sensitive(self):891 s = requests.Session()892 s.params['foo'] = 'bar'893 r = s.get(httpbin('get'), params={'FOO': 'bar'})894 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}895896 def test_long_authinfo_in_url(self):897 url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(898 'E8A3BE87-9E3F-4620-8858-95478E385B5B',899 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',900 'exactly-------------sixty-----------three------------characters',901 )902 r = requests.Request('GET', url).prepare()Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 903why, one step back903 assert r.url == urladd history to the docsKenneth Reitzbefore adoption4401620
lines 904–905why, one step back904905 def test_header_keys_are_native(self):Merge pull request #2065 from mgeisler/toxKenneth Reitzbefore adoptionddd748e
line 906why, one step back906 headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}add history to the docsKenneth Reitzbefore adoption4401620
lines 907–911why, one step back907 r = requests.Request('GET', httpbin('get'), headers=headers)908 p = r.prepare()909910 # This is testing that they are builtin strings. A bit weird, but there911 # we go.Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 912–913why, one step back912 assert 'unicode' in p.headers.keys()913 assert 'byte' in p.headers.keys()add history to the docsKenneth Reitzbefore adoption4401620
lines 914–920why, one step back914915 def test_can_send_nonstring_objects_with_files(self):916 data = {'a': 0.0}917 files = {'b': 'foo'}918 r = requests.Request('POST', httpbin('post'), data=data, files=files)919 p = r.prepare()920Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 921why, one step back921 assert 'multipart/form-data' in p.headers['Content-Type']add history to the docsKenneth Reitzbefore adoption4401620
line 922why, one step back922Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption7b5c11f
lines 923–928why, one step back923 def test_autoset_header_values_are_native(self):924 data = 'this is a string'925 length = '16'926 req = requests.Request('POST', httpbin('post'), data=data)927 p = req.prepare()928Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 929why, one step back929 assert p.headers['Content-Length'] == lengthMerge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption7b5c11f
line 930why, one step back930Merge pull request #2223 from blueyed/doc-followup-2222Ian Cordascobefore adoption9b41308
line 931why, one step back931 def test_nonhttp_schemes_dont_check_URLs(self):Merge pull request #1717 from jvantuyl/masterKenneth Reitzbefore adoptionbcb10af
lines 932–941why, one step back932 test_urls = (933 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',934 'file:///etc/passwd',935 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',936 )937 for test_url in test_urls:938 req = requests.Request('GET', test_url)939 preq = req.prepare()940 assert test_url == preq.url941Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona3cd2f3
lines 942–949why, one step back942 def test_auth_is_stripped_on_redirect_off_host(self):943 r = requests.get(944 httpbin('redirect-to'),945 params={'url': 'http://www.google.co.uk'},946 auth=('user', 'pass'),947 )948 assert r.history[0].request.headers['Authorization']949 assert not r.request.headers.get('Authorization', '')Merge pull request #1717 from jvantuyl/masterKenneth Reitzbefore adoptionbcb10af
line 950why, one step back950Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona3cd2f3
lines 951–957why, one step back951 def test_auth_is_retained_for_redirect_on_host(self):952 r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))953 h1 = r.history[0].request.headers['Authorization']954 h2 = r.request.headers['Authorization']955956 assert h1 == h2957Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption343db40
lines 958–962why, one step back958 def test_manual_redirect_with_partial_body_read(self):959 s = requests.Session()960 r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)961 assert r1.is_redirect962 rg = s.resolve_redirects(r1, r1.request, stream=True)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona3cd2f3
line 963why, one step back963Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption343db40
lines 964–995why, one step back964 # read only the first eight bytes of the response body,965 # then follow the redirect966 r1.iter_content(8)967 r2 = next(rg)968 assert r2.is_redirect969970 # read all of the response via iter_content,971 # then follow the redirect972 for _ in r2.iter_content():973 pass974 r3 = next(rg)975 assert not r3.is_redirect976977 def _patch_adapter_gzipped_redirect(self, session, url):978 adapter = session.get_adapter(url=url)979 org_build_response = adapter.build_response980 self._patched_response = False981982 def build_response(*args, **kwargs):983 resp = org_build_response(*args, **kwargs)984 if not self._patched_response:985 resp.raw.headers['content-encoding'] = 'gzip'986 self._patched_response = True987 return resp988989 adapter.build_response = build_response990991 def test_redirect_with_wrong_gzipped_header(self):992 s = requests.Session()993 url = httpbin('redirect/1')994 self._patch_adapter_gzipped_redirect(s, url)995 s.get(url)Merge pull request #2076 from Lukasa/basicKenneth Reitzbefore adoption3ee781b
lines 996–1000why, one step back996997 def test_basic_auth_str_is_always_native(self):998 s = _basic_auth_str("test", "test")999 assert isinstance(s, builtin_str)1000 assert s == "Basic dGVzdDp0ZXN0"Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption343db40
line 1001why, one step back1001Merge pull request #2168 from ContinuousFunction/masterKenneth Reitzbefore adoptionaa6650a
lines 1002–1008why, one step back1002 def test_requests_history_is_saved(self):1003 r = requests.get('https://httpbin.org/redirect/5')1004 total = r.history[-1].history1005 i = 01006 for item in r.history:1007 assert item.history == total[0:i]1008 i=i+1Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption343db40
line 1009why, one step back1009Merge pull request #2258 from willingc/add-jsonKenneth Reitzbefore adoption1e79cf6
lines 1010–1018why, one step back1010 def test_json_param_post_content_type_works(self):1011 r = requests.post(1012 httpbin('post'),1013 json={'life': 42}1014 )1015 assert r.status_code == 2001016 assert 'application/json' in r.request.headers['Content-Type']1017 assert {'life': 42} == r.json()['json']1018Merge pull request #2168 from ContinuousFunction/masterKenneth Reitzbefore adoptionaa6650a
line 1019why, one step back1019add history to the docsKenneth Reitzbefore adoption4401620
lines 1020–1023why, one step back1020class TestContentEncodingDetection(unittest.TestCase):10211022 def test_none(self):1023 encodings = requests.utils.get_encodings_from_content('')Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 1024why, one step back1024 assert not len(encodings)add history to the docsKenneth Reitzbefore adoption4401620
lines 1025–1029why, one step back10251026 def test_html_charset(self):1027 """HTML5 meta charset attribute"""1028 content = '<meta charset="UTF-8">'1029 encodings = requests.utils.get_encodings_from_content(content)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 1030–1031why, one step back1030 assert len(encodings) == 11031 assert encodings[0] == 'UTF-8'add history to the docsKenneth Reitzbefore adoption4401620
lines 1032–1036why, one step back10321033 def test_html4_pragma(self):1034 """HTML4 pragma directive"""1035 content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">'1036 encodings = requests.utils.get_encodings_from_content(content)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 1037–1038why, one step back1037 assert len(encodings) == 11038 assert encodings[0] == 'UTF-8'add history to the docsKenneth Reitzbefore adoption4401620
lines 1039–1043why, one step back10391040 def test_xhtml_pragma(self):1041 """XHTML 1.x served with text/html MIME type"""1042 content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />'1043 encodings = requests.utils.get_encodings_from_content(content)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 1044–1045why, one step back1044 assert len(encodings) == 11045 assert encodings[0] == 'UTF-8'add history to the docsKenneth Reitzbefore adoption4401620
lines 1046–1050why, one step back10461047 def test_xml(self):1048 """XHTML 1.x served as XML"""1049 content = '<?xml version="1.0" encoding="UTF-8"?>'1050 encodings = requests.utils.get_encodings_from_content(content)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 1051–1052why, one step back1051 assert len(encodings) == 11052 assert encodings[0] == 'UTF-8'add history to the docsKenneth Reitzbefore adoption4401620
lines 1053–1060why, one step back10531054 def test_precedence(self):1055 content = '''1056 <?xml version="1.0" encoding="XML"?>1057 <meta charset="HTML5">1058 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />1059 '''.strip()1060 encodings = requests.utils.get_encodings_from_content(content)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 1061why, one step back1061 assert encodings == ['HTML5', 'HTML4', 'XML']add history to the docsKenneth Reitzbefore adoption4401620
lines 1062–1066why, one step back106210631064class TestCaseInsensitiveDict(unittest.TestCase):10651066 def test_mapping_init(self):Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
line 1067why, one step back1067 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 1068–1070why, one step back1068 assert len(cid) == 21069 assert 'foo' in cid1070 assert 'bar' in cidadd history to the docsKenneth Reitzbefore adoption4401620
lines 1071–1073why, one step back10711072 def test_iterable_init(self):1073 cid = CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')])Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 1074–1076why, one step back1074 assert len(cid) == 21075 assert 'foo' in cid1076 assert 'bar' in cidadd history to the docsKenneth Reitzbefore adoption4401620
lines 1077–1079why, one step back10771078 def test_kwargs_init(self):1079 cid = CaseInsensitiveDict(FOO='foo', BAr='bar')Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 1080–1082why, one step back1080 assert len(cid) == 21081 assert 'foo' in cid1082 assert 'bar' in cidadd history to the docsKenneth Reitzbefore adoption4401620
lines 1083–1086why, one step back10831084 def test_docstring_example(self):1085 cid = CaseInsensitiveDict()1086 cid['Accept'] = 'application/json'Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 1087–1088why, one step back1087 assert cid['aCCEPT'] == 'application/json'1088 assert list(cid) == ['Accept']add history to the docsKenneth Reitzbefore adoption4401620
lines 1089–1092why, one step back10891090 def test_len(self):1091 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1092 cid['A'] = 'a'Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 1093why, one step back1093 assert len(cid) == 2add history to the docsKenneth Reitzbefore adoption4401620
lines 1094–1096why, one step back10941095 def test_getitem(self):1096 cid = CaseInsensitiveDict({'Spam': 'blueval'})Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 1097–1098why, one step back1097 assert cid['spam'] == 'blueval'1098 assert cid['SPAM'] == 'blueval'add history to the docsKenneth Reitzbefore adoption4401620
lines 1099–1106why, one step back10991100 def test_fixes_649(self):1101 """__setitem__ should behave case-insensitively."""1102 cid = CaseInsensitiveDict()1103 cid['spam'] = 'oneval'1104 cid['Spam'] = 'twoval'1105 cid['sPAM'] = 'redval'1106 cid['SPAM'] = 'blueval'Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 1107–1109why, one step back1107 assert cid['spam'] == 'blueval'1108 assert cid['SPAM'] == 'blueval'1109 assert list(cid.keys()) == ['SPAM']add history to the docsKenneth Reitzbefore adoption4401620
lines 1110–1114why, one step back11101111 def test_delitem(self):1112 cid = CaseInsensitiveDict()1113 cid['Spam'] = 'someval'1114 del cid['sPam']Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 1115–1116why, one step back1115 assert 'spam' not in cid1116 assert len(cid) == 0add history to the docsKenneth Reitzbefore adoption4401620
lines 1117–1120why, one step back11171118 def test_contains(self):1119 cid = CaseInsensitiveDict()1120 cid['Spam'] = 'someval'Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 1121–1125why, one step back1121 assert 'Spam' in cid1122 assert 'spam' in cid1123 assert 'SPAM' in cid1124 assert 'sPam' in cid1125 assert 'notspam' not in cidadd history to the docsKenneth Reitzbefore adoption4401620
lines 1126–1130why, one step back11261127 def test_get(self):1128 cid = CaseInsensitiveDict()1129 cid['spam'] = 'oneval'1130 cid['SPAM'] = 'blueval'Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 1131–1134why, one step back1131 assert cid.get('spam') == 'blueval'1132 assert cid.get('SPAM') == 'blueval'1133 assert cid.get('sPam') == 'blueval'1134 assert cid.get('notspam', 'default') == 'default'add history to the docsKenneth Reitzbefore adoption4401620
lines 1135–1139why, one step back11351136 def test_update(self):1137 cid = CaseInsensitiveDict()1138 cid['spam'] = 'blueval'1139 cid.update({'sPam': 'notblueval'})Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 1140why, one step back1140 assert cid['spam'] == 'notblueval'Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
line 1141why, one step back1141 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})add history to the docsKenneth Reitzbefore adoption4401620
line 1142why, one step back1142 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 1143–1145why, one step back1143 assert len(cid) == 21144 assert cid['foo'] == 'anotherfoo'1145 assert cid['bar'] == 'anotherbar'add history to the docsKenneth Reitzbefore adoption4401620
lines 1146–1149why, one step back11461147 def test_update_retains_unchanged(self):1148 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1149 cid.update({'foo': 'newfoo'})Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 1150why, one step back1150 assert cid['bar'] == 'bar'add history to the docsKenneth Reitzbefore adoption4401620
lines 1151–1154why, one step back11511152 def test_iter(self):1153 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1154 keys = frozenset(['Spam', 'Eggs'])Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 1155why, one step back1155 assert frozenset(iter(cid)) == keysadd history to the docsKenneth Reitzbefore adoption4401620
lines 1156–1159why, one step back11561157 def test_equality(self):1158 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1159 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 1160why, one step back1160 assert cid == othercidadd history to the docsKenneth Reitzbefore adoption4401620
line 1161why, one step back1161 del othercid['spam']Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 1162–1163why, one step back1162 assert cid != othercid1163 assert cid == {'spam': 'blueval', 'eggs': 'redval'}add history to the docsKenneth Reitzbefore adoption4401620
lines 1164–1166why, one step back11641165 def test_setdefault(self):1166 cid = CaseInsensitiveDict({'Spam': 'blueval'})Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 1167–1168why, one step back1167 assert cid.setdefault('spam', 'notblueval') == 'blueval'1168 assert cid.setdefault('notspam', 'notblueval') == 'notblueval'add history to the docsKenneth Reitzbefore adoption4401620
lines 1169–1176why, one step back11691170 def test_lower_items(self):1171 cid = CaseInsensitiveDict({1172 'Accept': 'application/json',1173 'user-Agent': 'requests',1174 })1175 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1176 lowerkeyset = frozenset(['accept', 'user-agent'])Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 1177why, one step back1177 assert keyset == lowerkeysetadd history to the docsKenneth Reitzbefore adoption4401620
lines 1178–1184why, one step back11781179 def test_preserve_key_case(self):1180 cid = CaseInsensitiveDict({1181 'Accept': 'application/json',1182 'user-Agent': 'requests',1183 })1184 keyset = frozenset(['Accept', 'user-Agent'])Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 1185–1187why, one step back1185 assert frozenset(i[0] for i in cid.items()) == keyset1186 assert frozenset(cid.keys()) == keyset1187 assert frozenset(cid) == keysetadd history to the docsKenneth Reitzbefore adoption4401620
lines 1188–1196why, one step back11881189 def test_preserve_last_key_case(self):1190 cid = CaseInsensitiveDict({1191 'Accept': 'application/json',1192 'user-Agent': 'requests',1193 })1194 cid.update({'ACCEPT': 'application/json'})1195 cid['USER-AGENT'] = 'requests'1196 keyset = frozenset(['ACCEPT', 'USER-AGENT'])Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 1197–1199why, one step back1197 assert frozenset(i[0] for i in cid.items()) == keyset1198 assert frozenset(cid.keys()) == keyset1199 assert frozenset(cid) == keysetadd history to the docsKenneth Reitzbefore adoption4401620
line 1200why, one step back1200Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption011f6da
lines 1201–1209why, one step back12011202class UtilsTestCase(unittest.TestCase):12031204 def test_super_len_io_streams(self):1205 """ Ensures that we properly deal with different kinds of IO streams. """1206 # uses StringIO or io.StringIO (see import above)1207 from io import BytesIO1208 from requests.utils import super_len1209Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 1210why, one step back1210 assert super_len(StringIO.StringIO()) == 0Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
lines 1211–1212why, one step back1211 assert super_len(1212 StringIO.StringIO('with so much drama in the LBC')) == 29Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption011f6da
line 1213why, one step back1213Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 1214why, one step back1214 assert super_len(BytesIO()) == 0Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
lines 1215–1216why, one step back1215 assert super_len(1216 BytesIO(b"it's kinda hard bein' snoop d-o-double-g")) == 40Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption011f6da
lines 1217–1222why, one step back12171218 try:1219 import cStringIO1220 except ImportError:1221 pass1222 else:Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
lines 1223–1224why, one step back1223 assert super_len(1224 cStringIO.StringIO('but some how, some way...')) == 25Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption57c4684
lines 1225–1226why, one step back12251226 def test_get_environ_proxies_ip_ranges(self):Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
lines 1227–1228why, one step back1227 """Ensures that IP addresses are correctly matches with ranges1228 in no_proxy variable."""Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption57c4684
lines 1229–1238why, one step back1229 from requests.utils import get_environ_proxies1230 os.environ['no_proxy'] = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"1231 assert get_environ_proxies('http://192.168.0.1:5000/') == {}1232 assert get_environ_proxies('http://192.168.0.1/') == {}1233 assert get_environ_proxies('http://172.16.1.1/') == {}1234 assert get_environ_proxies('http://172.16.1.1:5000/') == {}1235 assert get_environ_proxies('http://192.168.1.1:5000/') != {}1236 assert get_environ_proxies('http://192.168.1.1/') != {}12371238 def test_get_environ_proxies(self):Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
lines 1239–1240why, one step back1239 """Ensures that IP addresses are correctly matches with ranges1240 in no_proxy variable."""Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption57c4684
lines 1241–1242why, one step back1241 from requests.utils import get_environ_proxies1242 os.environ['no_proxy'] = "127.0.0.1,localhost.localdomain,192.168.0.0/24,172.16.1.1"Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
lines 1243–1244why, one step back1243 assert get_environ_proxies(1244 'http://localhost.localdomain:5000/v1.0/') == {}Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption57c4684
lines 1245–1267why, one step back1245 assert get_environ_proxies('http://www.requests.com/') != {}12461247 def test_is_ipv4_address(self):1248 from requests.utils import is_ipv4_address1249 assert is_ipv4_address('8.8.8.8')1250 assert not is_ipv4_address('8.8.8.8.8')1251 assert not is_ipv4_address('localhost.localdomain')12521253 def test_is_valid_cidr(self):1254 from requests.utils import is_valid_cidr1255 assert not is_valid_cidr('8.8.8.8')1256 assert is_valid_cidr('192.168.1.0/24')12571258 def test_dotted_netmask(self):1259 from requests.utils import dotted_netmask1260 assert dotted_netmask(8) == '255.0.0.0'1261 assert dotted_netmask(24) == '255.255.255.0'1262 assert dotted_netmask(25) == '255.255.255.128'12631264 def test_address_in_network(self):1265 from requests.utils import address_in_network1266 assert address_in_network('192.168.1.1', '192.168.1.0/24')1267 assert not address_in_network('172.16.0.1', '192.168.1.0/24')Merge pull request #1772 from mdbecker/make_morsel_to_cookie_more_pythonicKenneth Reitzbefore adoption9fc0701
line 1268why, one step back1268Merge pull request #1862 from sybeck2k/masterKenneth Reitzbefore adoption0465d34
line 1269why, one step back1269 def test_get_auth_from_url(self):Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
lines 1270–1271why, one step back1270 """Ensures that username and password in well-encoded URI as per1271 RFC 3986 are correclty extracted."""Merge pull request #1862 from sybeck2k/masterKenneth Reitzbefore adoption0465d34
lines 1272–1275why, one step back1272 from requests.utils import get_auth_from_url1273 from requests.compat import quote1274 percent_encoding_test_chars = "%!*'();:@&=+$,/?#[] "1275 url_address = "request.com/url.html#test"Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
lines 1276–1278why, one step back1276 url = "http://" + quote(1277 percent_encoding_test_chars, '') + ':' + quote(1278 percent_encoding_test_chars, '') + '@' + url_addressMerge pull request #1862 from sybeck2k/masterKenneth Reitzbefore adoption0465d34
lines 1279–1281why, one step back1279 (username, password) = get_auth_from_url(url)1280 assert username == percent_encoding_test_chars1281 assert password == percent_encoding_test_charsMerge pull request #1772 from mdbecker/make_morsel_to_cookie_more_pythonicKenneth Reitzbefore adoption9fc0701
lines 1282–1339why, one step back128212831284class TestMorselToCookieExpires(unittest.TestCase):12851286 """Tests for morsel_to_cookie when morsel contains expires."""12871288 def test_expires_valid_str(self):1289 """Test case where we convert expires from string time."""12901291 morsel = Morsel()1292 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1293 cookie = morsel_to_cookie(morsel)1294 assert cookie.expires == 112951296 def test_expires_invalid_int(self):1297 """Test case where an invalid type is passed for expires."""12981299 morsel = Morsel()1300 morsel['expires'] = 1001301 with pytest.raises(TypeError):1302 morsel_to_cookie(morsel)13031304 def test_expires_invalid_str(self):1305 """Test case where an invalid string is input."""13061307 morsel = Morsel()1308 morsel['expires'] = 'woops'1309 with pytest.raises(ValueError):1310 morsel_to_cookie(morsel)13111312 def test_expires_none(self):1313 """Test case where expires is None."""13141315 morsel = Morsel()1316 morsel['expires'] = None1317 cookie = morsel_to_cookie(morsel)1318 assert cookie.expires is None131913201321class TestMorselToCookieMaxAge(unittest.TestCase):13221323 """Tests for morsel_to_cookie when morsel contains max-age."""13241325 def test_max_age_valid_int(self):1326 """Test case where a valid max age in seconds is passed."""13271328 morsel = Morsel()1329 morsel['max-age'] = 601330 cookie = morsel_to_cookie(morsel)1331 assert isinstance(cookie.expires, int)13321333 def test_max_age_invalid_str(self):1334 """Test case where a invalid max age is passed."""13351336 morsel = Morsel()1337 morsel['max-age'] = 'woops'1338 with pytest.raises(TypeError):1339 morsel_to_cookie(morsel)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona3cd2f3
lines 1340–1344why, one step back134013411342class TestTimeout:1343 def test_stream_timeout(self):1344 try:Merge pull request #2176 from kevinburke/connectKenneth Reitzbefore adoption32e403a
line 1345why, one step back1345 requests.get('https://httpbin.org/delay/10', timeout=2.0)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona3cd2f3
lines 1346–1347why, one step back1346 except requests.exceptions.Timeout as e:1347 assert 'Read timed out' in e.args[0].args[0]Merge pull request #2176 from kevinburke/connectKenneth Reitzbefore adoption32e403a
lines 1348–1390why, one step back13481349 def test_invalid_timeout(self):1350 with pytest.raises(ValueError) as e:1351 requests.get(httpbin('get'), timeout=(3, 4, 5))1352 assert '(connect, read)' in str(e)13531354 with pytest.raises(ValueError) as e:1355 requests.get(httpbin('get'), timeout="foo")1356 assert 'must be an int or float' in str(e)13571358 def test_none_timeout(self):1359 """ Check that you can set None as a valid timeout value.13601361 To actually test this behavior, we'd want to check that setting the1362 timeout to None actually lets the request block past the system default1363 timeout. However, this would make the test suite unbearably slow.1364 Instead we verify that setting the timeout to None does not prevent the1365 request from succeeding.1366 """1367 r = requests.get(httpbin('get'), timeout=None)1368 assert r.status_code == 20013691370 def test_read_timeout(self):1371 try:1372 requests.get(httpbin('delay/10'), timeout=(None, 0.1))1373 assert False, "The recv() request should time out."1374 except ReadTimeout:1375 pass13761377 def test_connect_timeout(self):1378 try:1379 requests.get(TARPIT, timeout=(0.1, None))1380 assert False, "The connect() request should time out."1381 except ConnectTimeout as e:1382 assert isinstance(e, ConnectionError)1383 assert isinstance(e, Timeout)13841385 def test_total_timeout_connect(self):1386 try:1387 requests.get(TARPIT, timeout=(0.1, 0.1))1388 assert False, "The connect() request should time out."1389 except ConnectTimeout:1390 passMerge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption57c4684
line 1391why, one step back1391Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptionb2c801f
lines 1392–1449why, one step back13921393SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))139413951396class RedirectSession(SessionRedirectMixin):1397 def __init__(self, order_of_redirects):1398 self.redirects = order_of_redirects1399 self.calls = []1400 self.max_redirects = 301401 self.cookies = {}1402 self.trust_env = False14031404 def send(self, *args, **kwargs):1405 self.calls.append(SendCall(args, kwargs))1406 return self.build_response()14071408 def build_response(self):1409 request = self.calls[-1].args[0]1410 r = requests.Response()14111412 try:1413 r.status_code = int(self.redirects.pop(0))1414 except IndexError:1415 r.status_code = 20014161417 r.headers = CaseInsensitiveDict({'Location': '/'})1418 r.raw = self._build_raw()1419 r.request = request1420 return r14211422 def _build_raw(self):1423 string = StringIO.StringIO('')1424 setattr(string, 'release_conn', lambda *args: args)1425 return string142614271428class TestRedirects:1429 default_keyword_args = {1430 'stream': False,1431 'verify': True,1432 'cert': None,1433 'timeout': None,1434 'allow_redirects': False,1435 'proxies': {},1436 }14371438 def test_requests_are_updated_each_time(self):1439 session = RedirectSession([303, 307])1440 prep = requests.Request('POST', 'http://httpbin.org/post').prepare()1441 r0 = session.send(prep)1442 assert r0.request.method == 'POST'1443 assert session.calls[-1] == SendCall((r0.request,), {})1444 redirect_generator = session.resolve_redirects(r0, prep)1445 for response in redirect_generator:1446 assert response.request.method == 'GET'1447 send_call = SendCall((response.request,),1448 TestRedirects.default_keyword_args)1449 assert session.calls[-1] == send_callMerge pull request #2168 from ContinuousFunction/masterKenneth Reitzbefore adoptionaa6650a
line 1450why, one step back1450Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptionb2c801f
lines 1451–1455why, one step back145114521453@pytest.fixture1454def list_of_tuples():1455 return [Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
lines 1456–1459why, one step back1456 (('a', 'b'), ('c', 'd')),1457 (('c', 'd'), ('a', 'b')),1458 (('a', 'b'), ('c', 'd'), ('e', 'f')),1459 ]Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptionb2c801f
lines 1460–1475why, one step back146014611462def test_data_argument_accepts_tuples(list_of_tuples):1463 """1464 Ensure that the data argument will accept tuples of strings1465 and properly encode them.1466 """1467 for data in list_of_tuples:1468 p = PreparedRequest()1469 p.prepare(1470 method='GET',1471 url='http://www.example.com',1472 data=data,1473 hooks=default_hooks()1474 )1475 assert p.body == urlencode(data)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption343db40
line 1476why, one step back1476Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
line 1477why, one step back1477Merge pull request #2078 from dgouldin/2077Kenneth Reitzbefore adoption75cd0a9
lines 1478–1481why, one step back1478def assert_copy(p, p_copy):1479 for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):1480 assert getattr(p, attr) == getattr(p_copy, attr)1481Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
line 1482why, one step back1482Merge pull request #2078 from dgouldin/2077Kenneth Reitzbefore adoption75cd0a9
lines 1483–1486why, one step back1483def test_prepared_request_empty_copy():1484 p = PreparedRequest()1485 assert_copy(p, p.copy())1486Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
line 1487why, one step back1487Merge pull request #2078 from dgouldin/2077Kenneth Reitzbefore adoption75cd0a9
lines 1488–1496why, one step back1488def test_prepared_request_no_cookies_copy():1489 p = PreparedRequest()1490 p.prepare(1491 method='GET',1492 url='http://www.example.com',1493 data='foo=bar',1494 hooks=default_hooks()1495 )1496 assert_copy(p, p.copy())Merge pull request #2088 from jeffknupp/masterKenneth Reitzbefore adoption743ce81
line 1497why, one step back1497Merge pull request #2078 from dgouldin/2077Kenneth Reitzbefore adoption75cd0a9
lines 1498–1508why, one step back14981499def test_prepared_request_complete_copy():1500 p = PreparedRequest()1501 p.prepare(1502 method='GET',1503 url='http://www.example.com',1504 data='foo=bar',1505 hooks=default_hooks(),1506 cookies={'foo': 'bar'}1507 )1508 assert_copy(p, p.copy())add history to the docsKenneth Reitzbefore adoption4401620
line 1509why, one step back1509allow unicode URLs on Python 2MinRKbefore adoptionca2ebc5
lines 1510–1517why, one step back1510def test_prepare_unicode_url():1511 p = PreparedRequest()1512 p.prepare(1513 method='GET',1514 url=u('http://www.example.com/üniçø∂é')1515 )1516 assert_copy(p, p.copy())1517add history to the docsKenneth Reitzbefore adoption4401620
lines 1518–1519why, one step back1518if __name__ == '__main__':1519 unittest.main()