test_requests.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """Tests for Requests."""
  4. from __future__ import division
  5. import json
  6. import os
  7. import pickle
  8. import unittest
  9. import collections
  10. import io
  11. import requests
  12. import pytest
  13. from requests.adapters import HTTPAdapter
  14. from requests.auth import HTTPDigestAuth, _basic_auth_str
  15. from requests.compat import (
  16. Morsel, cookielib, getproxies, str, urljoin, urlparse, is_py3, builtin_str)
  17. from requests.cookies import cookiejar_from_dict, morsel_to_cookie
  18. from requests.exceptions import (ConnectionError, ConnectTimeout,
  19. InvalidSchema, InvalidURL, MissingSchema,
  20. ReadTimeout, Timeout, RetryError)
  21. from requests.models import PreparedRequest
  22. from requests.structures import CaseInsensitiveDict
  23. from requests.sessions import SessionRedirectMixin
  24. from requests.models import urlencode
  25. from requests.hooks import default_hooks
  26. try:
  27. import StringIO
  28. except ImportError:
  29. import io as StringIO
  30. if is_py3:
  31. def u(s):
  32. return s
  33. else:
  34. def u(s):
  35. return s.decode('unicode-escape')
  36. # Requests to this URL should always fail with a connection timeout (nothing
  37. # listening on that port)
  38. TARPIT = "http://10.255.255.1"
  39. HTTPBIN = os.environ.get('HTTPBIN_URL', 'http://httpbin.org/')
  40. # Issue #1483: Make sure the URL always has a trailing slash
  41. HTTPBIN = HTTPBIN.rstrip('/') + '/'
  42. def httpbin(*suffix):
  43. """Returns url for HTTPBIN resource."""
  44. return urljoin(HTTPBIN, '/'.join(suffix))
  45. class RequestsTestCase(unittest.TestCase):
  46. _multiprocess_can_split_ = True
  47. def setUp(self):
  48. """Create simple data set with headers."""
  49. pass
  50. def tearDown(self):
  51. """Teardown."""
  52. pass
  53. def test_entry_points(self):
  54. requests.session
  55. requests.session().get
  56. requests.session().head
  57. requests.get
  58. requests.head
  59. requests.put
  60. requests.patch
  61. requests.post
  62. def test_invalid_url(self):
  63. with pytest.raises(MissingSchema):
  64. requests.get('hiwpefhipowhefopw')
  65. with pytest.raises(InvalidSchema):
  66. requests.get('localhost:3128')
  67. with pytest.raises(InvalidSchema):
  68. requests.get('localhost.localdomain:3128/')
  69. with pytest.raises(InvalidSchema):
  70. requests.get('10.122.1.1:3128/')
  71. with pytest.raises(InvalidURL):
  72. requests.get('http://')
  73. def test_basic_building(self):
  74. req = requests.Request()
  75. req.url = 'http://kennethreitz.org/'
  76. req.data = {'life': '42'}
  77. pr = req.prepare()
  78. assert pr.url == req.url
  79. assert pr.body == 'life=42'
  80. def test_no_content_length(self):
  81. get_req = requests.Request('GET', httpbin('get')).prepare()
  82. assert 'Content-Length' not in get_req.headers
  83. head_req = requests.Request('HEAD', httpbin('head')).prepare()
  84. assert 'Content-Length' not in head_req.headers
  85. def test_override_content_length(self):
  86. headers = {
  87. 'Content-Length': 'not zero'
  88. }
  89. r = requests.Request('POST', httpbin('post'), headers=headers).prepare()
  90. assert 'Content-Length' in r.headers
  91. assert r.headers['Content-Length'] == 'not zero'
  92. def test_path_is_not_double_encoded(self):
  93. request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()
  94. assert request.path_url == '/get/test%20case'
  95. def test_params_are_added_before_fragment(self):
  96. request = requests.Request('GET',
  97. "http://example.com/path#fragment", params={"a": "b"}).prepare()
  98. assert request.url == "http://example.com/path?a=b#fragment"
  99. request = requests.Request('GET',
  100. "http://example.com/path?key=value#fragment", params={"a": "b"}).prepare()
  101. assert request.url == "http://example.com/path?key=value&a=b#fragment"
  102. def test_mixed_case_scheme_acceptable(self):
  103. s = requests.Session()
  104. s.proxies = getproxies()
  105. parts = urlparse(httpbin('get'))
  106. schemes = ['http://', 'HTTP://', 'hTTp://', 'HttP://',
  107. 'https://', 'HTTPS://', 'hTTps://', 'HttPs://']
  108. for scheme in schemes:
  109. url = scheme + parts.netloc + parts.path
  110. r = requests.Request('GET', url)
  111. r = s.send(r.prepare())
  112. assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)
  113. def test_HTTP_200_OK_GET_ALTERNATIVE(self):
  114. r = requests.Request('GET', httpbin('get'))
  115. s = requests.Session()
  116. s.proxies = getproxies()
  117. r = s.send(r.prepare())
  118. assert r.status_code == 200
  119. def test_HTTP_302_ALLOW_REDIRECT_GET(self):
  120. r = requests.get(httpbin('redirect', '1'))
  121. assert r.status_code == 200
  122. assert r.history[0].status_code == 302
  123. assert r.history[0].is_redirect
  124. # def test_HTTP_302_ALLOW_REDIRECT_POST(self):
  125. # r = requests.post(httpbin('status', '302'), data={'some': 'data'})
  126. # self.assertEqual(r.status_code, 200)
  127. def test_HTTP_200_OK_GET_WITH_PARAMS(self):
  128. heads = {'User-agent': 'Mozilla/5.0'}
  129. r = requests.get(httpbin('user-agent'), headers=heads)
  130. assert heads['User-agent'] in r.text
  131. assert r.status_code == 200
  132. def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):
  133. heads = {'User-agent': 'Mozilla/5.0'}
  134. r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)
  135. assert r.status_code == 200
  136. def test_set_cookie_on_301(self):
  137. s = requests.session()
  138. url = httpbin('cookies/set?foo=bar')
  139. s.get(url)
  140. assert s.cookies['foo'] == 'bar'
  141. def test_cookie_sent_on_redirect(self):
  142. s = requests.session()
  143. s.get(httpbin('cookies/set?foo=bar'))
  144. r = s.get(httpbin('redirect/1')) # redirects to httpbin('get')
  145. assert 'Cookie' in r.json()['headers']
  146. def test_cookie_removed_on_expire(self):
  147. s = requests.session()
  148. s.get(httpbin('cookies/set?foo=bar'))
  149. assert s.cookies['foo'] == 'bar'
  150. s.get(
  151. httpbin('response-headers'),
  152. params={
  153. 'Set-Cookie':
  154. 'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'
  155. }
  156. )
  157. assert 'foo' not in s.cookies
  158. def test_cookie_quote_wrapped(self):
  159. s = requests.session()
  160. s.get(httpbin('cookies/set?foo="bar:baz"'))
  161. assert s.cookies['foo'] == '"bar:baz"'
  162. def test_cookie_persists_via_api(self):
  163. s = requests.session()
  164. r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})
  165. assert 'foo' in r.request.headers['Cookie']
  166. assert 'foo' in r.history[0].request.headers['Cookie']
  167. def test_request_cookie_overrides_session_cookie(self):
  168. s = requests.session()
  169. s.cookies['foo'] = 'bar'
  170. r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})
  171. assert r.json()['cookies']['foo'] == 'baz'
  172. # Session cookie should not be modified
  173. assert s.cookies['foo'] == 'bar'
  174. def test_request_cookies_not_persisted(self):
  175. s = requests.session()
  176. s.get(httpbin('cookies'), cookies={'foo': 'baz'})
  177. # Sending a request with cookies should not add cookies to the session
  178. assert not s.cookies
  179. def test_generic_cookiejar_works(self):
  180. cj = cookielib.CookieJar()
  181. cookiejar_from_dict({'foo': 'bar'}, cj)
  182. s = requests.session()
  183. s.cookies = cj
  184. r = s.get(httpbin('cookies'))
  185. # Make sure the cookie was sent
  186. assert r.json()['cookies']['foo'] == 'bar'
  187. # Make sure the session cj is still the custom one
  188. assert s.cookies is cj
  189. def test_param_cookiejar_works(self):
  190. cj = cookielib.CookieJar()
  191. cookiejar_from_dict({'foo': 'bar'}, cj)
  192. s = requests.session()
  193. r = s.get(httpbin('cookies'), cookies=cj)
  194. # Make sure the cookie was sent
  195. assert r.json()['cookies']['foo'] == 'bar'
  196. def test_requests_in_history_are_not_overridden(self):
  197. resp = requests.get(httpbin('redirect/3'))
  198. urls = [r.url for r in resp.history]
  199. req_urls = [r.request.url for r in resp.history]
  200. assert urls == req_urls
  201. def test_history_is_always_a_list(self):
  202. """
  203. Show that even with redirects, Response.history is always a list.
  204. """
  205. resp = requests.get(httpbin('get'))
  206. assert isinstance(resp.history, list)
  207. resp = requests.get(httpbin('redirect/1'))
  208. assert isinstance(resp.history, list)
  209. assert not isinstance(resp.history, tuple)
  210. def test_headers_on_session_with_None_are_not_sent(self):
  211. """Do not send headers in Session.headers with None values."""
  212. ses = requests.Session()
  213. ses.headers['Accept-Encoding'] = None
  214. req = requests.Request('GET', httpbin('get'))
  215. prep = ses.prepare_request(req)
  216. assert 'Accept-Encoding' not in prep.headers
  217. def test_user_agent_transfers(self):
  218. heads = {
  219. 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'
  220. }
  221. r = requests.get(httpbin('user-agent'), headers=heads)
  222. assert heads['User-agent'] in r.text
  223. heads = {
  224. 'user-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'
  225. }
  226. r = requests.get(httpbin('user-agent'), headers=heads)
  227. assert heads['user-agent'] in r.text
  228. def test_HTTP_200_OK_HEAD(self):
  229. r = requests.head(httpbin('get'))
  230. assert r.status_code == 200
  231. def test_HTTP_200_OK_PUT(self):
  232. r = requests.put(httpbin('put'))
  233. assert r.status_code == 200
  234. def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):
  235. auth = ('user', 'pass')
  236. url = httpbin('basic-auth', 'user', 'pass')
  237. r = requests.get(url, auth=auth)
  238. assert r.status_code == 200
  239. r = requests.get(url)
  240. assert r.status_code == 401
  241. s = requests.session()
  242. s.auth = auth
  243. r = s.get(url)
  244. assert r.status_code == 200
  245. def test_connection_error(self):
  246. """Connecting to an unknown domain should raise a ConnectionError"""
  247. with pytest.raises(ConnectionError):
  248. requests.get("http://fooobarbangbazbing.httpbin.org")
  249. with pytest.raises(ConnectionError):
  250. requests.get("http://httpbin.org:1")
  251. def test_LocationParseError(self):
  252. """Inputing a URL that cannot be parsed should raise an InvalidURL error"""
  253. with pytest.raises(InvalidURL):
  254. requests.get("http://fe80::5054:ff:fe5a:fc0")
  255. def test_basicauth_with_netrc(self):
  256. auth = ('user', 'pass')
  257. wrong_auth = ('wronguser', 'wrongpass')
  258. url = httpbin('basic-auth', 'user', 'pass')
  259. def get_netrc_auth_mock(url):
  260. return auth
  261. requests.sessions.get_netrc_auth = get_netrc_auth_mock
  262. # Should use netrc and work.
  263. r = requests.get(url)
  264. assert r.status_code == 200
  265. # Given auth should override and fail.
  266. r = requests.get(url, auth=wrong_auth)
  267. assert r.status_code == 401
  268. s = requests.session()
  269. # Should use netrc and work.
  270. r = s.get(url)
  271. assert r.status_code == 200
  272. # Given auth should override and fail.
  273. s.auth = wrong_auth
  274. r = s.get(url)
  275. assert r.status_code == 401
  276. def test_DIGEST_HTTP_200_OK_GET(self):
  277. auth = HTTPDigestAuth('user', 'pass')
  278. url = httpbin('digest-auth', 'auth', 'user', 'pass')
  279. r = requests.get(url, auth=auth)
  280. assert r.status_code == 200
  281. r = requests.get(url)
  282. assert r.status_code == 401
  283. s = requests.session()
  284. s.auth = HTTPDigestAuth('user', 'pass')
  285. r = s.get(url)
  286. assert r.status_code == 200
  287. def test_DIGEST_AUTH_RETURNS_COOKIE(self):
  288. url = httpbin('digest-auth', 'auth', 'user', 'pass')
  289. auth = HTTPDigestAuth('user', 'pass')
  290. r = requests.get(url)
  291. assert r.cookies['fake'] == 'fake_value'
  292. r = requests.get(url, auth=auth)
  293. assert r.status_code == 200
  294. def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self):
  295. url = httpbin('digest-auth', 'auth', 'user', 'pass')
  296. auth = HTTPDigestAuth('user', 'pass')
  297. s = requests.Session()
  298. s.get(url, auth=auth)
  299. assert s.cookies['fake'] == 'fake_value'
  300. def test_DIGEST_STREAM(self):
  301. auth = HTTPDigestAuth('user', 'pass')
  302. url = httpbin('digest-auth', 'auth', 'user', 'pass')
  303. r = requests.get(url, auth=auth, stream=True)
  304. assert r.raw.read() != b''
  305. r = requests.get(url, auth=auth, stream=False)
  306. assert r.raw.read() == b''
  307. def test_DIGESTAUTH_WRONG_HTTP_401_GET(self):
  308. auth = HTTPDigestAuth('user', 'wrongpass')
  309. url = httpbin('digest-auth', 'auth', 'user', 'pass')
  310. r = requests.get(url, auth=auth)
  311. assert r.status_code == 401
  312. r = requests.get(url)
  313. assert r.status_code == 401
  314. s = requests.session()
  315. s.auth = auth
  316. r = s.get(url)
  317. assert r.status_code == 401
  318. def test_DIGESTAUTH_QUOTES_QOP_VALUE(self):
  319. auth = HTTPDigestAuth('user', 'pass')
  320. url = httpbin('digest-auth', 'auth', 'user', 'pass')
  321. r = requests.get(url, auth=auth)
  322. assert '"auth"' in r.request.headers['Authorization']
  323. def test_POSTBIN_GET_POST_FILES(self):
  324. url = httpbin('post')
  325. post1 = requests.post(url).raise_for_status()
  326. post1 = requests.post(url, data={'some': 'data'})
  327. assert post1.status_code == 200
  328. with open('requirements.txt') as f:
  329. post2 = requests.post(url, files={'some': f})
  330. assert post2.status_code == 200
  331. post4 = requests.post(url, data='[{"some": "json"}]')
  332. assert post4.status_code == 200
  333. with pytest.raises(ValueError):
  334. requests.post(url, files=['bad file data'])
  335. def test_POSTBIN_GET_POST_FILES_WITH_DATA(self):
  336. url = httpbin('post')
  337. post1 = requests.post(url).raise_for_status()
  338. post1 = requests.post(url, data={'some': 'data'})
  339. assert post1.status_code == 200
  340. with open('requirements.txt') as f:
  341. post2 = requests.post(url,
  342. data={'some': 'data'}, files={'some': f})
  343. assert post2.status_code == 200
  344. post4 = requests.post(url, data='[{"some": "json"}]')
  345. assert post4.status_code == 200
  346. with pytest.raises(ValueError):
  347. requests.post(url, files=['bad file data'])
  348. def test_conflicting_post_params(self):
  349. url = httpbin('post')
  350. with open('requirements.txt') as f:
  351. pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")
  352. pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")
  353. def test_request_ok_set(self):
  354. r = requests.get(httpbin('status', '404'))
  355. assert not r.ok
  356. def test_status_raising(self):
  357. r = requests.get(httpbin('status', '404'))
  358. with pytest.raises(requests.exceptions.HTTPError):
  359. r.raise_for_status()
  360. r = requests.get(httpbin('status', '500'))
  361. assert not r.ok
  362. def test_decompress_gzip(self):
  363. r = requests.get(httpbin('gzip'))
  364. r.content.decode('ascii')
  365. def test_unicode_get(self):
  366. url = httpbin('/get')
  367. requests.get(url, params={'foo': 'føø'})
  368. requests.get(url, params={'føø': 'føø'})
  369. requests.get(url, params={'føø': 'føø'})
  370. requests.get(url, params={'foo': 'foo'})
  371. requests.get(httpbin('ø'), params={'foo': 'foo'})
  372. def test_unicode_header_name(self):
  373. requests.put(
  374. httpbin('put'),
  375. headers={str('Content-Type'): 'application/octet-stream'},
  376. data='\xff') # compat.str is unicode.
  377. def test_pyopenssl_redirect(self):
  378. requests.get('https://httpbin.org/status/301')
  379. def test_urlencoded_get_query_multivalued_param(self):
  380. r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))
  381. assert r.status_code == 200
  382. assert r.url == httpbin('get?test=foo&test=baz')
  383. def test_different_encodings_dont_break_post(self):
  384. r = requests.post(httpbin('post'),
  385. data={'stuff': json.dumps({'a': 123})},
  386. params={'blah': 'asdf1234'},
  387. files={'file': ('test_requests.py', open(__file__, 'rb'))})
  388. assert r.status_code == 200
  389. def test_unicode_multipart_post(self):
  390. r = requests.post(httpbin('post'),
  391. data={'stuff': u('ëlïxr')},
  392. files={'file': ('test_requests.py', open(__file__, 'rb'))})
  393. assert r.status_code == 200
  394. r = requests.post(httpbin('post'),
  395. data={'stuff': u('ëlïxr').encode('utf-8')},
  396. files={'file': ('test_requests.py', open(__file__, 'rb'))})
  397. assert r.status_code == 200
  398. r = requests.post(httpbin('post'),
  399. data={'stuff': 'elixr'},
  400. files={'file': ('test_requests.py', open(__file__, 'rb'))})
  401. assert r.status_code == 200
  402. r = requests.post(httpbin('post'),
  403. data={'stuff': 'elixr'.encode('utf-8')},
  404. files={'file': ('test_requests.py', open(__file__, 'rb'))})
  405. assert r.status_code == 200
  406. def test_unicode_multipart_post_fieldnames(self):
  407. filename = os.path.splitext(__file__)[0] + '.py'
  408. r = requests.Request(method='POST',
  409. url=httpbin('post'),
  410. data={'stuff'.encode('utf-8'): 'elixr'},
  411. files={'file': ('test_requests.py',
  412. open(filename, 'rb'))})
  413. prep = r.prepare()
  414. assert b'name="stuff"' in prep.body
  415. assert b'name="b\'stuff\'"' not in prep.body
  416. def test_unicode_method_name(self):
  417. files = {'file': open('test_requests.py', 'rb')}
  418. r = requests.request(
  419. method=u('POST'), url=httpbin('post'), files=files)
  420. assert r.status_code == 200
  421. def test_custom_content_type(self):
  422. r = requests.post(
  423. httpbin('post'),
  424. data={'stuff': json.dumps({'a': 123})},
  425. files={'file1': ('test_requests.py', open(__file__, 'rb')),
  426. 'file2': ('test_requests', open(__file__, 'rb'),
  427. 'text/py-content-type')})
  428. assert r.status_code == 200
  429. assert b"text/py-content-type" in r.request.body
  430. def test_hook_receives_request_arguments(self):
  431. def hook(resp, **kwargs):
  432. assert resp is not None
  433. assert kwargs != {}
  434. requests.Request('GET', HTTPBIN, hooks={'response': hook})
  435. def test_session_hooks_are_used_with_no_request_hooks(self):
  436. hook = lambda x, *args, **kwargs: x
  437. s = requests.Session()
  438. s.hooks['response'].append(hook)
  439. r = requests.Request('GET', HTTPBIN)
  440. prep = s.prepare_request(r)
  441. assert prep.hooks['response'] != []
  442. assert prep.hooks['response'] == [hook]
  443. def test_session_hooks_are_overriden_by_request_hooks(self):
  444. hook1 = lambda x, *args, **kwargs: x
  445. hook2 = lambda x, *args, **kwargs: x
  446. assert hook1 is not hook2
  447. s = requests.Session()
  448. s.hooks['response'].append(hook2)
  449. r = requests.Request('GET', HTTPBIN, hooks={'response': [hook1]})
  450. prep = s.prepare_request(r)
  451. assert prep.hooks['response'] == [hook1]
  452. def test_prepared_request_hook(self):
  453. def hook(resp, **kwargs):
  454. resp.hook_working = True
  455. return resp
  456. req = requests.Request('GET', HTTPBIN, hooks={'response': hook})
  457. prep = req.prepare()
  458. s = requests.Session()
  459. s.proxies = getproxies()
  460. resp = s.send(prep)
  461. assert hasattr(resp, 'hook_working')
  462. def test_prepared_from_session(self):
  463. class DummyAuth(requests.auth.AuthBase):
  464. def __call__(self, r):
  465. r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'
  466. return r
  467. req = requests.Request('GET', httpbin('headers'))
  468. assert not req.auth
  469. s = requests.Session()
  470. s.auth = DummyAuth()
  471. prep = s.prepare_request(req)
  472. resp = s.send(prep)
  473. assert resp.json()['headers'][
  474. 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'
  475. def test_prepare_request_with_bytestring_url(self):
  476. req = requests.Request('GET', b'https://httpbin.org/')
  477. s = requests.Session()
  478. prep = s.prepare_request(req)
  479. assert prep.url == "https://httpbin.org/"
  480. def test_links(self):
  481. r = requests.Response()
  482. r.headers = {
  483. 'cache-control': 'public, max-age=60, s-maxage=60',
  484. 'connection': 'keep-alive',
  485. 'content-encoding': 'gzip',
  486. 'content-type': 'application/json; charset=utf-8',
  487. 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',
  488. 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',
  489. 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',
  490. 'link': ('<https://api.github.com/users/kennethreitz/repos?'
  491. 'page=2&per_page=10>; rel="next", <https://api.github.'
  492. 'com/users/kennethreitz/repos?page=7&per_page=10>; '
  493. ' rel="last"'),
  494. 'server': 'GitHub.com',
  495. 'status': '200 OK',
  496. 'vary': 'Accept',
  497. 'x-content-type-options': 'nosniff',
  498. 'x-github-media-type': 'github.beta',
  499. 'x-ratelimit-limit': '60',
  500. 'x-ratelimit-remaining': '57'
  501. }
  502. assert r.links['next']['rel'] == 'next'
  503. def test_cookie_parameters(self):
  504. key = 'some_cookie'
  505. value = 'some_value'
  506. secure = True
  507. domain = 'test.com'
  508. rest = {'HttpOnly': True}
  509. jar = requests.cookies.RequestsCookieJar()
  510. jar.set(key, value, secure=secure, domain=domain, rest=rest)
  511. assert len(jar) == 1
  512. assert 'some_cookie' in jar
  513. cookie = list(jar)[0]
  514. assert cookie.secure == secure
  515. assert cookie.domain == domain
  516. assert cookie._rest['HttpOnly'] == rest['HttpOnly']
  517. def test_cookie_as_dict_keeps_len(self):
  518. key = 'some_cookie'
  519. value = 'some_value'
  520. key1 = 'some_cookie1'
  521. value1 = 'some_value1'
  522. jar = requests.cookies.RequestsCookieJar()
  523. jar.set(key, value)
  524. jar.set(key1, value1)
  525. d1 = dict(jar)
  526. d2 = dict(jar.iteritems())
  527. d3 = dict(jar.items())
  528. assert len(jar) == 2
  529. assert len(d1) == 2
  530. assert len(d2) == 2
  531. assert len(d3) == 2
  532. def test_cookie_as_dict_keeps_items(self):
  533. key = 'some_cookie'
  534. value = 'some_value'
  535. key1 = 'some_cookie1'
  536. value1 = 'some_value1'
  537. jar = requests.cookies.RequestsCookieJar()
  538. jar.set(key, value)
  539. jar.set(key1, value1)
  540. d1 = dict(jar)
  541. d2 = dict(jar.iteritems())
  542. d3 = dict(jar.items())
  543. assert d1['some_cookie'] == 'some_value'
  544. assert d2['some_cookie'] == 'some_value'
  545. assert d3['some_cookie1'] == 'some_value1'
  546. def test_cookie_as_dict_keys(self):
  547. key = 'some_cookie'
  548. value = 'some_value'
  549. key1 = 'some_cookie1'
  550. value1 = 'some_value1'
  551. jar = requests.cookies.RequestsCookieJar()
  552. jar.set(key, value)
  553. jar.set(key1, value1)
  554. keys = jar.keys()
  555. assert keys == list(keys)
  556. # make sure one can use keys multiple times
  557. assert list(keys) == list(keys)
  558. def test_cookie_as_dict_values(self):
  559. key = 'some_cookie'
  560. value = 'some_value'
  561. key1 = 'some_cookie1'
  562. value1 = 'some_value1'
  563. jar = requests.cookies.RequestsCookieJar()
  564. jar.set(key, value)
  565. jar.set(key1, value1)
  566. values = jar.values()
  567. assert values == list(values)
  568. # make sure one can use values multiple times
  569. assert list(values) == list(values)
  570. def test_cookie_as_dict_items(self):
  571. key = 'some_cookie'
  572. value = 'some_value'
  573. key1 = 'some_cookie1'
  574. value1 = 'some_value1'
  575. jar = requests.cookies.RequestsCookieJar()
  576. jar.set(key, value)
  577. jar.set(key1, value1)
  578. items = jar.items()
  579. assert items == list(items)
  580. # make sure one can use items multiple times
  581. assert list(items) == list(items)
  582. def test_time_elapsed_blank(self):
  583. r = requests.get(httpbin('get'))
  584. td = r.elapsed
  585. total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)
  586. * 10**6) / 10**6)
  587. assert total_seconds > 0.0
  588. def test_response_is_iterable(self):
  589. r = requests.Response()
  590. io = StringIO.StringIO('abc')
  591. read_ = io.read
  592. def read_mock(amt, decode_content=None):
  593. return read_(amt)
  594. setattr(io, 'read', read_mock)
  595. r.raw = io
  596. assert next(iter(r))
  597. io.close()
  598. def test_response_decode_unicode(self):
  599. """
  600. When called with decode_unicode, Response.iter_content should always
  601. return unicode.
  602. """
  603. r = requests.Response()
  604. r._content_consumed = True
  605. r._content = b'the content'
  606. r.encoding = 'ascii'
  607. chunks = r.iter_content(decode_unicode=True)
  608. assert all(isinstance(chunk, str) for chunk in chunks)
  609. # also for streaming
  610. r = requests.Response()
  611. r.raw = io.BytesIO(b'the content')
  612. r.encoding = 'ascii'
  613. chunks = r.iter_content(decode_unicode=True)
  614. assert all(isinstance(chunk, str) for chunk in chunks)
  615. def test_request_and_response_are_pickleable(self):
  616. r = requests.get(httpbin('get'))
  617. # verify we can pickle the original request
  618. assert pickle.loads(pickle.dumps(r.request))
  619. # verify we can pickle the response and that we have access to
  620. # the original request.
  621. pr = pickle.loads(pickle.dumps(r))
  622. assert r.request.url == pr.request.url
  623. assert r.request.headers == pr.request.headers
  624. def test_get_auth_from_url(self):
  625. url = 'http://user:pass@complex.url.com/path?query=yes'
  626. assert ('user', 'pass') == requests.utils.get_auth_from_url(url)
  627. def test_get_auth_from_url_encoded_spaces(self):
  628. url = 'http://user:pass%20pass@complex.url.com/path?query=yes'
  629. assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)
  630. def test_get_auth_from_url_not_encoded_spaces(self):
  631. url = 'http://user:pass pass@complex.url.com/path?query=yes'
  632. assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)
  633. def test_get_auth_from_url_percent_chars(self):
  634. url = 'http://user%25user:pass@complex.url.com/path?query=yes'
  635. assert ('user%user', 'pass') == requests.utils.get_auth_from_url(url)
  636. def test_get_auth_from_url_encoded_hashes(self):
  637. url = 'http://user:pass%23pass@complex.url.com/path?query=yes'
  638. assert ('user', 'pass#pass') == requests.utils.get_auth_from_url(url)
  639. def test_cannot_send_unprepared_requests(self):
  640. r = requests.Request(url=HTTPBIN)
  641. with pytest.raises(ValueError):
  642. requests.Session().send(r)
  643. def test_http_error(self):
  644. error = requests.exceptions.HTTPError()
  645. assert not error.response
  646. response = requests.Response()
  647. error = requests.exceptions.HTTPError(response=response)
  648. assert error.response == response
  649. error = requests.exceptions.HTTPError('message', response=response)
  650. assert str(error) == 'message'
  651. assert error.response == response
  652. def test_session_pickling(self):
  653. r = requests.Request('GET', httpbin('get'))
  654. s = requests.Session()
  655. s = pickle.loads(pickle.dumps(s))
  656. s.proxies = getproxies()
  657. r = s.send(r.prepare())
  658. assert r.status_code == 200
  659. def test_fixes_1329(self):
  660. """
  661. Ensure that header updates are done case-insensitively.
  662. """
  663. s = requests.Session()
  664. s.headers.update({'ACCEPT': 'BOGUS'})
  665. s.headers.update({'accept': 'application/json'})
  666. r = s.get(httpbin('get'))
  667. headers = r.request.headers
  668. assert headers['accept'] == 'application/json'
  669. assert headers['Accept'] == 'application/json'
  670. assert headers['ACCEPT'] == 'application/json'
  671. def test_uppercase_scheme_redirect(self):
  672. parts = urlparse(httpbin('html'))
  673. url = "HTTP://" + parts.netloc + parts.path
  674. r = requests.get(httpbin('redirect-to'), params={'url': url})
  675. assert r.status_code == 200
  676. assert r.url.lower() == url.lower()
  677. def test_transport_adapter_ordering(self):
  678. s = requests.Session()
  679. order = ['https://', 'http://']
  680. assert order == list(s.adapters)
  681. s.mount('http://git', HTTPAdapter())
  682. s.mount('http://github', HTTPAdapter())
  683. s.mount('http://github.com', HTTPAdapter())
  684. s.mount('http://github.com/about/', HTTPAdapter())
  685. order = [
  686. 'http://github.com/about/',
  687. 'http://github.com',
  688. 'http://github',
  689. 'http://git',
  690. 'https://',
  691. 'http://',
  692. ]
  693. assert order == list(s.adapters)
  694. s.mount('http://gittip', HTTPAdapter())
  695. s.mount('http://gittip.com', HTTPAdapter())
  696. s.mount('http://gittip.com/about/', HTTPAdapter())
  697. order = [
  698. 'http://github.com/about/',
  699. 'http://gittip.com/about/',
  700. 'http://github.com',
  701. 'http://gittip.com',
  702. 'http://github',
  703. 'http://gittip',
  704. 'http://git',
  705. 'https://',
  706. 'http://',
  707. ]
  708. assert order == list(s.adapters)
  709. s2 = requests.Session()
  710. s2.adapters = {'http://': HTTPAdapter()}
  711. s2.mount('https://', HTTPAdapter())
  712. assert 'http://' in s2.adapters
  713. assert 'https://' in s2.adapters
  714. def test_header_remove_is_case_insensitive(self):
  715. # From issue #1321
  716. s = requests.Session()
  717. s.headers['foo'] = 'bar'
  718. r = s.get(httpbin('get'), headers={'FOO': None})
  719. assert 'foo' not in r.request.headers
  720. def test_params_are_merged_case_sensitive(self):
  721. s = requests.Session()
  722. s.params['foo'] = 'bar'
  723. r = s.get(httpbin('get'), params={'FOO': 'bar'})
  724. assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}
  725. def test_long_authinfo_in_url(self):
  726. url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(
  727. 'E8A3BE87-9E3F-4620-8858-95478E385B5B',
  728. 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',
  729. 'exactly-------------sixty-----------three------------characters',
  730. )
  731. r = requests.Request('GET', url).prepare()
  732. assert r.url == url
  733. def test_header_keys_are_native(self):
  734. headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}
  735. r = requests.Request('GET', httpbin('get'), headers=headers)
  736. p = r.prepare()
  737. # This is testing that they are builtin strings. A bit weird, but there
  738. # we go.
  739. assert 'unicode' in p.headers.keys()
  740. assert 'byte' in p.headers.keys()
  741. def test_can_send_nonstring_objects_with_files(self):
  742. data = {'a': 0.0}
  743. files = {'b': 'foo'}
  744. r = requests.Request('POST', httpbin('post'), data=data, files=files)
  745. p = r.prepare()
  746. assert 'multipart/form-data' in p.headers['Content-Type']
  747. def test_can_send_file_object_with_non_string_filename(self):
  748. f = io.BytesIO()
  749. f.name = 2
  750. r = requests.Request('POST', httpbin('post'), files={'f': f})
  751. p = r.prepare()
  752. assert 'multipart/form-data' in p.headers['Content-Type']
  753. def test_autoset_header_values_are_native(self):
  754. data = 'this is a string'
  755. length = '16'
  756. req = requests.Request('POST', httpbin('post'), data=data)
  757. p = req.prepare()
  758. assert p.headers['Content-Length'] == length
  759. def test_nonhttp_schemes_dont_check_URLs(self):
  760. test_urls = (
  761. 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',
  762. 'file:///etc/passwd',
  763. 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',
  764. )
  765. for test_url in test_urls:
  766. req = requests.Request('GET', test_url)
  767. preq = req.prepare()
  768. assert test_url == preq.url
  769. def test_auth_is_stripped_on_redirect_off_host(self):
  770. r = requests.get(
  771. httpbin('redirect-to'),
  772. params={'url': 'http://www.google.co.uk'},
  773. auth=('user', 'pass'),
  774. )
  775. assert r.history[0].request.headers['Authorization']
  776. assert not r.request.headers.get('Authorization', '')
  777. def test_auth_is_retained_for_redirect_on_host(self):
  778. r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))
  779. h1 = r.history[0].request.headers['Authorization']
  780. h2 = r.request.headers['Authorization']
  781. assert h1 == h2
  782. def test_manual_redirect_with_partial_body_read(self):
  783. s = requests.Session()
  784. r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)
  785. assert r1.is_redirect
  786. rg = s.resolve_redirects(r1, r1.request, stream=True)
  787. # read only the first eight bytes of the response body,
  788. # then follow the redirect
  789. r1.iter_content(8)
  790. r2 = next(rg)
  791. assert r2.is_redirect
  792. # read all of the response via iter_content,
  793. # then follow the redirect
  794. for _ in r2.iter_content():
  795. pass
  796. r3 = next(rg)
  797. assert not r3.is_redirect
  798. def _patch_adapter_gzipped_redirect(self, session, url):
  799. adapter = session.get_adapter(url=url)
  800. org_build_response = adapter.build_response
  801. self._patched_response = False
  802. def build_response(*args, **kwargs):
  803. resp = org_build_response(*args, **kwargs)
  804. if not self._patched_response:
  805. resp.raw.headers['content-encoding'] = 'gzip'
  806. self._patched_response = True
  807. return resp
  808. adapter.build_response = build_response
  809. def test_redirect_with_wrong_gzipped_header(self):
  810. s = requests.Session()
  811. url = httpbin('redirect/1')
  812. self._patch_adapter_gzipped_redirect(s, url)
  813. s.get(url)
  814. def test_basic_auth_str_is_always_native(self):
  815. s = _basic_auth_str("test", "test")
  816. assert isinstance(s, builtin_str)
  817. assert s == "Basic dGVzdDp0ZXN0"
  818. def test_requests_history_is_saved(self):
  819. r = requests.get(httpbin('redirect/5'))
  820. total = r.history[-1].history
  821. i = 0
  822. for item in r.history:
  823. assert item.history == total[0:i]
  824. i = i + 1
  825. def test_json_param_post_content_type_works(self):
  826. r = requests.post(
  827. httpbin('post'),
  828. json={'life': 42}
  829. )
  830. assert r.status_code == 200
  831. assert 'application/json' in r.request.headers['Content-Type']
  832. assert {'life': 42} == r.json()['json']
  833. class TestContentEncodingDetection(unittest.TestCase):
  834. def test_none(self):
  835. encodings = requests.utils.get_encodings_from_content('')
  836. assert not len(encodings)
  837. def test_html_charset(self):
  838. """HTML5 meta charset attribute"""
  839. content = '<meta charset="UTF-8">'
  840. encodings = requests.utils.get_encodings_from_content(content)
  841. assert len(encodings) == 1
  842. assert encodings[0] == 'UTF-8'
  843. def test_html4_pragma(self):
  844. """HTML4 pragma directive"""
  845. content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">'
  846. encodings = requests.utils.get_encodings_from_content(content)
  847. assert len(encodings) == 1
  848. assert encodings[0] == 'UTF-8'
  849. def test_xhtml_pragma(self):
  850. """XHTML 1.x served with text/html MIME type"""
  851. content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />'
  852. encodings = requests.utils.get_encodings_from_content(content)
  853. assert len(encodings) == 1
  854. assert encodings[0] == 'UTF-8'
  855. def test_xml(self):
  856. """XHTML 1.x served as XML"""
  857. content = '<?xml version="1.0" encoding="UTF-8"?>'
  858. encodings = requests.utils.get_encodings_from_content(content)
  859. assert len(encodings) == 1
  860. assert encodings[0] == 'UTF-8'
  861. def test_precedence(self):
  862. content = '''
  863. <?xml version="1.0" encoding="XML"?>
  864. <meta charset="HTML5">
  865. <meta http-equiv="Content-type" content="text/html;charset=HTML4" />
  866. '''.strip()
  867. encodings = requests.utils.get_encodings_from_content(content)
  868. assert encodings == ['HTML5', 'HTML4', 'XML']
  869. class TestCaseInsensitiveDict(unittest.TestCase):
  870. def test_mapping_init(self):
  871. cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})
  872. assert len(cid) == 2
  873. assert 'foo' in cid
  874. assert 'bar' in cid
  875. def test_iterable_init(self):
  876. cid = CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')])
  877. assert len(cid) == 2
  878. assert 'foo' in cid
  879. assert 'bar' in cid
  880. def test_kwargs_init(self):
  881. cid = CaseInsensitiveDict(FOO='foo', BAr='bar')
  882. assert len(cid) == 2
  883. assert 'foo' in cid
  884. assert 'bar' in cid
  885. def test_docstring_example(self):
  886. cid = CaseInsensitiveDict()
  887. cid['Accept'] = 'application/json'
  888. assert cid['aCCEPT'] == 'application/json'
  889. assert list(cid) == ['Accept']
  890. def test_len(self):
  891. cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})
  892. cid['A'] = 'a'
  893. assert len(cid) == 2
  894. def test_getitem(self):
  895. cid = CaseInsensitiveDict({'Spam': 'blueval'})
  896. assert cid['spam'] == 'blueval'
  897. assert cid['SPAM'] == 'blueval'
  898. def test_fixes_649(self):
  899. """__setitem__ should behave case-insensitively."""
  900. cid = CaseInsensitiveDict()
  901. cid['spam'] = 'oneval'
  902. cid['Spam'] = 'twoval'
  903. cid['sPAM'] = 'redval'
  904. cid['SPAM'] = 'blueval'
  905. assert cid['spam'] == 'blueval'
  906. assert cid['SPAM'] == 'blueval'
  907. assert list(cid.keys()) == ['SPAM']
  908. def test_delitem(self):
  909. cid = CaseInsensitiveDict()
  910. cid['Spam'] = 'someval'
  911. del cid['sPam']
  912. assert 'spam' not in cid
  913. assert len(cid) == 0
  914. def test_contains(self):
  915. cid = CaseInsensitiveDict()
  916. cid['Spam'] = 'someval'
  917. assert 'Spam' in cid
  918. assert 'spam' in cid
  919. assert 'SPAM' in cid
  920. assert 'sPam' in cid
  921. assert 'notspam' not in cid
  922. def test_get(self):
  923. cid = CaseInsensitiveDict()
  924. cid['spam'] = 'oneval'
  925. cid['SPAM'] = 'blueval'
  926. assert cid.get('spam') == 'blueval'
  927. assert cid.get('SPAM') == 'blueval'
  928. assert cid.get('sPam') == 'blueval'
  929. assert cid.get('notspam', 'default') == 'default'
  930. def test_update(self):
  931. cid = CaseInsensitiveDict()
  932. cid['spam'] = 'blueval'
  933. cid.update({'sPam': 'notblueval'})
  934. assert cid['spam'] == 'notblueval'
  935. cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})
  936. cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})
  937. assert len(cid) == 2
  938. assert cid['foo'] == 'anotherfoo'
  939. assert cid['bar'] == 'anotherbar'
  940. def test_update_retains_unchanged(self):
  941. cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})
  942. cid.update({'foo': 'newfoo'})
  943. assert cid['bar'] == 'bar'
  944. def test_iter(self):
  945. cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})
  946. keys = frozenset(['Spam', 'Eggs'])
  947. assert frozenset(iter(cid)) == keys
  948. def test_equality(self):
  949. cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})
  950. othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})
  951. assert cid == othercid
  952. del othercid['spam']
  953. assert cid != othercid
  954. assert cid == {'spam': 'blueval', 'eggs': 'redval'}
  955. def test_setdefault(self):
  956. cid = CaseInsensitiveDict({'Spam': 'blueval'})
  957. assert cid.setdefault('spam', 'notblueval') == 'blueval'
  958. assert cid.setdefault('notspam', 'notblueval') == 'notblueval'
  959. def test_lower_items(self):
  960. cid = CaseInsensitiveDict({
  961. 'Accept': 'application/json',
  962. 'user-Agent': 'requests',
  963. })
  964. keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())
  965. lowerkeyset = frozenset(['accept', 'user-agent'])
  966. assert keyset == lowerkeyset
  967. def test_preserve_key_case(self):
  968. cid = CaseInsensitiveDict({
  969. 'Accept': 'application/json',
  970. 'user-Agent': 'requests',
  971. })
  972. keyset = frozenset(['Accept', 'user-Agent'])
  973. assert frozenset(i[0] for i in cid.items()) == keyset
  974. assert frozenset(cid.keys()) == keyset
  975. assert frozenset(cid) == keyset
  976. def test_preserve_last_key_case(self):
  977. cid = CaseInsensitiveDict({
  978. 'Accept': 'application/json',
  979. 'user-Agent': 'requests',
  980. })
  981. cid.update({'ACCEPT': 'application/json'})
  982. cid['USER-AGENT'] = 'requests'
  983. keyset = frozenset(['ACCEPT', 'USER-AGENT'])
  984. assert frozenset(i[0] for i in cid.items()) == keyset
  985. assert frozenset(cid.keys()) == keyset
  986. assert frozenset(cid) == keyset
  987. class UtilsTestCase(unittest.TestCase):
  988. def test_super_len_io_streams(self):
  989. """ Ensures that we properly deal with different kinds of IO streams. """
  990. # uses StringIO or io.StringIO (see import above)
  991. from io import BytesIO
  992. from requests.utils import super_len
  993. assert super_len(StringIO.StringIO()) == 0
  994. assert super_len(
  995. StringIO.StringIO('with so much drama in the LBC')) == 29
  996. assert super_len(BytesIO()) == 0
  997. assert super_len(
  998. BytesIO(b"it's kinda hard bein' snoop d-o-double-g")) == 40
  999. try:
  1000. import cStringIO
  1001. except ImportError:
  1002. pass
  1003. else:
  1004. assert super_len(
  1005. cStringIO.StringIO('but some how, some way...')) == 25
  1006. def test_get_environ_proxies_ip_ranges(self):
  1007. """Ensures that IP addresses are correctly matches with ranges
  1008. in no_proxy variable."""
  1009. from requests.utils import get_environ_proxies
  1010. os.environ['no_proxy'] = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"
  1011. assert get_environ_proxies('http://192.168.0.1:5000/') == {}
  1012. assert get_environ_proxies('http://192.168.0.1/') == {}
  1013. assert get_environ_proxies('http://172.16.1.1/') == {}
  1014. assert get_environ_proxies('http://172.16.1.1:5000/') == {}
  1015. assert get_environ_proxies('http://192.168.1.1:5000/') != {}
  1016. assert get_environ_proxies('http://192.168.1.1/') != {}
  1017. def test_get_environ_proxies(self):
  1018. """Ensures that IP addresses are correctly matches with ranges
  1019. in no_proxy variable."""
  1020. from requests.utils import get_environ_proxies
  1021. os.environ['no_proxy'] = "127.0.0.1,localhost.localdomain,192.168.0.0/24,172.16.1.1"
  1022. assert get_environ_proxies(
  1023. 'http://localhost.localdomain:5000/v1.0/') == {}
  1024. assert get_environ_proxies('http://www.requests.com/') != {}
  1025. def test_is_ipv4_address(self):
  1026. from requests.utils import is_ipv4_address
  1027. assert is_ipv4_address('8.8.8.8')
  1028. assert not is_ipv4_address('8.8.8.8.8')
  1029. assert not is_ipv4_address('localhost.localdomain')
  1030. def test_is_valid_cidr(self):
  1031. from requests.utils import is_valid_cidr
  1032. assert not is_valid_cidr('8.8.8.8')
  1033. assert is_valid_cidr('192.168.1.0/24')
  1034. def test_dotted_netmask(self):
  1035. from requests.utils import dotted_netmask
  1036. assert dotted_netmask(8) == '255.0.0.0'
  1037. assert dotted_netmask(24) == '255.255.255.0'
  1038. assert dotted_netmask(25) == '255.255.255.128'
  1039. def test_address_in_network(self):
  1040. from requests.utils import address_in_network
  1041. assert address_in_network('192.168.1.1', '192.168.1.0/24')
  1042. assert not address_in_network('172.16.0.1', '192.168.1.0/24')
  1043. def test_get_auth_from_url(self):
  1044. """Ensures that username and password in well-encoded URI as per
  1045. RFC 3986 are correclty extracted."""
  1046. from requests.utils import get_auth_from_url
  1047. from requests.compat import quote
  1048. percent_encoding_test_chars = "%!*'();:@&=+$,/?#[] "
  1049. url_address = "request.com/url.html#test"
  1050. url = "http://" + quote(
  1051. percent_encoding_test_chars, '') + ':' + quote(
  1052. percent_encoding_test_chars, '') + '@' + url_address
  1053. (username, password) = get_auth_from_url(url)
  1054. assert username == percent_encoding_test_chars
  1055. assert password == percent_encoding_test_chars
  1056. class TestMorselToCookieExpires(unittest.TestCase):
  1057. """Tests for morsel_to_cookie when morsel contains expires."""
  1058. def test_expires_valid_str(self):
  1059. """Test case where we convert expires from string time."""
  1060. morsel = Morsel()
  1061. morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'
  1062. cookie = morsel_to_cookie(morsel)
  1063. assert cookie.expires == 1
  1064. def test_expires_invalid_int(self):
  1065. """Test case where an invalid type is passed for expires."""
  1066. morsel = Morsel()
  1067. morsel['expires'] = 100
  1068. with pytest.raises(TypeError):
  1069. morsel_to_cookie(morsel)
  1070. def test_expires_invalid_str(self):
  1071. """Test case where an invalid string is input."""
  1072. morsel = Morsel()
  1073. morsel['expires'] = 'woops'
  1074. with pytest.raises(ValueError):
  1075. morsel_to_cookie(morsel)
  1076. def test_expires_none(self):
  1077. """Test case where expires is None."""
  1078. morsel = Morsel()
  1079. morsel['expires'] = None
  1080. cookie = morsel_to_cookie(morsel)
  1081. assert cookie.expires is None
  1082. class TestMorselToCookieMaxAge(unittest.TestCase):
  1083. """Tests for morsel_to_cookie when morsel contains max-age."""
  1084. def test_max_age_valid_int(self):
  1085. """Test case where a valid max age in seconds is passed."""
  1086. morsel = Morsel()
  1087. morsel['max-age'] = 60
  1088. cookie = morsel_to_cookie(morsel)
  1089. assert isinstance(cookie.expires, int)
  1090. def test_max_age_invalid_str(self):
  1091. """Test case where a invalid max age is passed."""
  1092. morsel = Morsel()
  1093. morsel['max-age'] = 'woops'
  1094. with pytest.raises(TypeError):
  1095. morsel_to_cookie(morsel)
  1096. class TestTimeout:
  1097. def test_stream_timeout(self):
  1098. try:
  1099. requests.get(httpbin('delay/10'), timeout=2.0)
  1100. except requests.exceptions.Timeout as e:
  1101. assert 'Read timed out' in e.args[0].args[0]
  1102. def test_invalid_timeout(self):
  1103. with pytest.raises(ValueError) as e:
  1104. requests.get(httpbin('get'), timeout=(3, 4, 5))
  1105. assert '(connect, read)' in str(e)
  1106. with pytest.raises(ValueError) as e:
  1107. requests.get(httpbin('get'), timeout="foo")
  1108. assert 'must be an int or float' in str(e)
  1109. def test_none_timeout(self):
  1110. """ Check that you can set None as a valid timeout value.
  1111. To actually test this behavior, we'd want to check that setting the
  1112. timeout to None actually lets the request block past the system default
  1113. timeout. However, this would make the test suite unbearably slow.
  1114. Instead we verify that setting the timeout to None does not prevent the
  1115. request from succeeding.
  1116. """
  1117. r = requests.get(httpbin('get'), timeout=None)
  1118. assert r.status_code == 200
  1119. def test_read_timeout(self):
  1120. try:
  1121. requests.get(httpbin('delay/10'), timeout=(None, 0.1))
  1122. assert False, "The recv() request should time out."
  1123. except ReadTimeout:
  1124. pass
  1125. def test_connect_timeout(self):
  1126. try:
  1127. requests.get(TARPIT, timeout=(0.1, None))
  1128. assert False, "The connect() request should time out."
  1129. except ConnectTimeout as e:
  1130. assert isinstance(e, ConnectionError)
  1131. assert isinstance(e, Timeout)
  1132. def test_total_timeout_connect(self):
  1133. try:
  1134. requests.get(TARPIT, timeout=(0.1, 0.1))
  1135. assert False, "The connect() request should time out."
  1136. except ConnectTimeout:
  1137. pass
  1138. def test_encoded_methods(self):
  1139. """See: https://github.com/kennethreitz/requests/issues/2316"""
  1140. r = requests.request(b'GET', httpbin('get'))
  1141. assert r.ok
  1142. SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))
  1143. class RedirectSession(SessionRedirectMixin):
  1144. def __init__(self, order_of_redirects):
  1145. self.redirects = order_of_redirects
  1146. self.calls = []
  1147. self.max_redirects = 30
  1148. self.cookies = {}
  1149. self.trust_env = False
  1150. def send(self, *args, **kwargs):
  1151. self.calls.append(SendCall(args, kwargs))
  1152. return self.build_response()
  1153. def build_response(self):
  1154. request = self.calls[-1].args[0]
  1155. r = requests.Response()
  1156. try:
  1157. r.status_code = int(self.redirects.pop(0))
  1158. except IndexError:
  1159. r.status_code = 200
  1160. r.headers = CaseInsensitiveDict({'Location': '/'})
  1161. r.raw = self._build_raw()
  1162. r.request = request
  1163. return r
  1164. def _build_raw(self):
  1165. string = StringIO.StringIO('')
  1166. setattr(string, 'release_conn', lambda *args: args)
  1167. return string
  1168. class TestRedirects:
  1169. default_keyword_args = {
  1170. 'stream': False,
  1171. 'verify': True,
  1172. 'cert': None,
  1173. 'timeout': None,
  1174. 'allow_redirects': False,
  1175. 'proxies': {},
  1176. }
  1177. def test_requests_are_updated_each_time(self):
  1178. session = RedirectSession([303, 307])
  1179. prep = requests.Request('POST', httpbin('post')).prepare()
  1180. r0 = session.send(prep)
  1181. assert r0.request.method == 'POST'
  1182. assert session.calls[-1] == SendCall((r0.request,), {})
  1183. redirect_generator = session.resolve_redirects(r0, prep)
  1184. for response in redirect_generator:
  1185. assert response.request.method == 'GET'
  1186. send_call = SendCall((response.request,),
  1187. TestRedirects.default_keyword_args)
  1188. assert session.calls[-1] == send_call
  1189. @pytest.fixture
  1190. def list_of_tuples():
  1191. return [
  1192. (('a', 'b'), ('c', 'd')),
  1193. (('c', 'd'), ('a', 'b')),
  1194. (('a', 'b'), ('c', 'd'), ('e', 'f')),
  1195. ]
  1196. def test_data_argument_accepts_tuples(list_of_tuples):
  1197. """
  1198. Ensure that the data argument will accept tuples of strings
  1199. and properly encode them.
  1200. """
  1201. for data in list_of_tuples:
  1202. p = PreparedRequest()
  1203. p.prepare(
  1204. method='GET',
  1205. url='http://www.example.com',
  1206. data=data,
  1207. hooks=default_hooks()
  1208. )
  1209. assert p.body == urlencode(data)
  1210. def assert_copy(p, p_copy):
  1211. for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):
  1212. assert getattr(p, attr) == getattr(p_copy, attr)
  1213. def test_prepared_request_empty_copy():
  1214. p = PreparedRequest()
  1215. assert_copy(p, p.copy())
  1216. def test_prepared_request_no_cookies_copy():
  1217. p = PreparedRequest()
  1218. p.prepare(
  1219. method='GET',
  1220. url='http://www.example.com',
  1221. data='foo=bar',
  1222. hooks=default_hooks()
  1223. )
  1224. assert_copy(p, p.copy())
  1225. def test_prepared_request_complete_copy():
  1226. p = PreparedRequest()
  1227. p.prepare(
  1228. method='GET',
  1229. url='http://www.example.com',
  1230. data='foo=bar',
  1231. hooks=default_hooks(),
  1232. cookies={'foo': 'bar'}
  1233. )
  1234. assert_copy(p, p.copy())
  1235. def test_prepare_unicode_url():
  1236. p = PreparedRequest()
  1237. p.prepare(
  1238. method='GET',
  1239. url=u('http://www.example.com/üniçø∂é'),
  1240. hooks=[]
  1241. )
  1242. assert_copy(p, p.copy())
  1243. def test_urllib3_retries():
  1244. from requests.packages.urllib3.util import Retry
  1245. s = requests.Session()
  1246. s.mount('http://', HTTPAdapter(max_retries=Retry(
  1247. total=2, status_forcelist=[500]
  1248. )))
  1249. with pytest.raises(RetryError):
  1250. s.get(httpbin('status/500'))
  1251. if __name__ == '__main__':
  1252. unittest.main()