test_requests.py 55 KB

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