tests.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. # -*- encoding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import time
  4. import warnings
  5. from datetime import datetime, timedelta
  6. from io import BytesIO
  7. from django.core.exceptions import SuspiciousOperation
  8. from django.core.handlers.wsgi import WSGIRequest, LimitedStream
  9. from django.http import HttpRequest, HttpResponse, parse_cookie, build_request_repr, UnreadablePostError
  10. from django.test.client import FakePayload
  11. from django.test.utils import override_settings, str_prefix
  12. from django.utils import unittest
  13. from django.utils.http import cookie_date, urlencode
  14. from django.utils.timezone import utc
  15. class RequestsTests(unittest.TestCase):
  16. def test_httprequest(self):
  17. request = HttpRequest()
  18. self.assertEqual(list(request.GET.keys()), [])
  19. self.assertEqual(list(request.POST.keys()), [])
  20. self.assertEqual(list(request.COOKIES.keys()), [])
  21. self.assertEqual(list(request.META.keys()), [])
  22. def test_httprequest_repr(self):
  23. request = HttpRequest()
  24. request.path = '/somepath/'
  25. request.GET = {'get-key': 'get-value'}
  26. request.POST = {'post-key': 'post-value'}
  27. request.COOKIES = {'post-key': 'post-value'}
  28. request.META = {'post-key': 'post-value'}
  29. self.assertEqual(repr(request), str_prefix("<HttpRequest\npath:/somepath/,\nGET:{%(_)s'get-key': %(_)s'get-value'},\nPOST:{%(_)s'post-key': %(_)s'post-value'},\nCOOKIES:{%(_)s'post-key': %(_)s'post-value'},\nMETA:{%(_)s'post-key': %(_)s'post-value'}>"))
  30. self.assertEqual(build_request_repr(request), repr(request))
  31. self.assertEqual(build_request_repr(request, path_override='/otherpath/', GET_override={'a': 'b'}, POST_override={'c': 'd'}, COOKIES_override={'e': 'f'}, META_override={'g': 'h'}),
  32. str_prefix("<HttpRequest\npath:/otherpath/,\nGET:{%(_)s'a': %(_)s'b'},\nPOST:{%(_)s'c': %(_)s'd'},\nCOOKIES:{%(_)s'e': %(_)s'f'},\nMETA:{%(_)s'g': %(_)s'h'}>"))
  33. def test_wsgirequest(self):
  34. request = WSGIRequest({'PATH_INFO': 'bogus', 'REQUEST_METHOD': 'bogus', 'wsgi.input': BytesIO(b'')})
  35. self.assertEqual(list(request.GET.keys()), [])
  36. self.assertEqual(list(request.POST.keys()), [])
  37. self.assertEqual(list(request.COOKIES.keys()), [])
  38. self.assertEqual(set(request.META.keys()), set(['PATH_INFO', 'REQUEST_METHOD', 'SCRIPT_NAME', 'wsgi.input']))
  39. self.assertEqual(request.META['PATH_INFO'], 'bogus')
  40. self.assertEqual(request.META['REQUEST_METHOD'], 'bogus')
  41. self.assertEqual(request.META['SCRIPT_NAME'], '')
  42. def test_wsgirequest_repr(self):
  43. request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')})
  44. request.GET = {'get-key': 'get-value'}
  45. request.POST = {'post-key': 'post-value'}
  46. request.COOKIES = {'post-key': 'post-value'}
  47. request.META = {'post-key': 'post-value'}
  48. self.assertEqual(repr(request), str_prefix("<WSGIRequest\npath:/somepath/,\nGET:{%(_)s'get-key': %(_)s'get-value'},\nPOST:{%(_)s'post-key': %(_)s'post-value'},\nCOOKIES:{%(_)s'post-key': %(_)s'post-value'},\nMETA:{%(_)s'post-key': %(_)s'post-value'}>"))
  49. self.assertEqual(build_request_repr(request), repr(request))
  50. self.assertEqual(build_request_repr(request, path_override='/otherpath/', GET_override={'a': 'b'}, POST_override={'c': 'd'}, COOKIES_override={'e': 'f'}, META_override={'g': 'h'}),
  51. str_prefix("<WSGIRequest\npath:/otherpath/,\nGET:{%(_)s'a': %(_)s'b'},\nPOST:{%(_)s'c': %(_)s'd'},\nCOOKIES:{%(_)s'e': %(_)s'f'},\nMETA:{%(_)s'g': %(_)s'h'}>"))
  52. def test_parse_cookie(self):
  53. self.assertEqual(parse_cookie('invalid@key=true'), {})
  54. def test_httprequest_location(self):
  55. request = HttpRequest()
  56. self.assertEqual(request.build_absolute_uri(location="https://www.example.com/asdf"),
  57. 'https://www.example.com/asdf')
  58. request.get_host = lambda: 'www.example.com'
  59. request.path = ''
  60. self.assertEqual(request.build_absolute_uri(location="/path/with:colons"),
  61. 'http://www.example.com/path/with:colons')
  62. @override_settings(USE_X_FORWARDED_HOST=False)
  63. def test_http_get_host(self):
  64. # Check if X_FORWARDED_HOST is provided.
  65. request = HttpRequest()
  66. request.META = {
  67. 'HTTP_X_FORWARDED_HOST': 'forward.com',
  68. 'HTTP_HOST': 'example.com',
  69. 'SERVER_NAME': 'internal.com',
  70. 'SERVER_PORT': 80,
  71. }
  72. # X_FORWARDED_HOST is ignored.
  73. self.assertEqual(request.get_host(), 'example.com')
  74. # Check if X_FORWARDED_HOST isn't provided.
  75. request = HttpRequest()
  76. request.META = {
  77. 'HTTP_HOST': 'example.com',
  78. 'SERVER_NAME': 'internal.com',
  79. 'SERVER_PORT': 80,
  80. }
  81. self.assertEqual(request.get_host(), 'example.com')
  82. # Check if HTTP_HOST isn't provided.
  83. request = HttpRequest()
  84. request.META = {
  85. 'SERVER_NAME': 'internal.com',
  86. 'SERVER_PORT': 80,
  87. }
  88. self.assertEqual(request.get_host(), 'internal.com')
  89. # Check if HTTP_HOST isn't provided, and we're on a nonstandard port
  90. request = HttpRequest()
  91. request.META = {
  92. 'SERVER_NAME': 'internal.com',
  93. 'SERVER_PORT': 8042,
  94. }
  95. self.assertEqual(request.get_host(), 'internal.com:8042')
  96. # Poisoned host headers are rejected as suspicious
  97. legit_hosts = [
  98. 'example.com',
  99. 'example.com:80',
  100. '12.34.56.78',
  101. '12.34.56.78:443',
  102. '[2001:19f0:feee::dead:beef:cafe]',
  103. '[2001:19f0:feee::dead:beef:cafe]:8080',
  104. 'xn--4ca9at.com', # Punnycode for öäü.com
  105. ]
  106. poisoned_hosts = [
  107. 'example.com@evil.tld',
  108. 'example.com:dr.frankenstein@evil.tld',
  109. 'example.com:dr.frankenstein@evil.tld:80',
  110. 'example.com:80/badpath',
  111. 'example.com: recovermypassword.com',
  112. ]
  113. for host in legit_hosts:
  114. request = HttpRequest()
  115. request.META = {
  116. 'HTTP_HOST': host,
  117. }
  118. request.get_host()
  119. for host in poisoned_hosts:
  120. with self.assertRaises(SuspiciousOperation):
  121. request = HttpRequest()
  122. request.META = {
  123. 'HTTP_HOST': host,
  124. }
  125. request.get_host()
  126. @override_settings(USE_X_FORWARDED_HOST=True)
  127. def test_http_get_host_with_x_forwarded_host(self):
  128. # Check if X_FORWARDED_HOST is provided.
  129. request = HttpRequest()
  130. request.META = {
  131. 'HTTP_X_FORWARDED_HOST': 'forward.com',
  132. 'HTTP_HOST': 'example.com',
  133. 'SERVER_NAME': 'internal.com',
  134. 'SERVER_PORT': 80,
  135. }
  136. # X_FORWARDED_HOST is obeyed.
  137. self.assertEqual(request.get_host(), 'forward.com')
  138. # Check if X_FORWARDED_HOST isn't provided.
  139. request = HttpRequest()
  140. request.META = {
  141. 'HTTP_HOST': 'example.com',
  142. 'SERVER_NAME': 'internal.com',
  143. 'SERVER_PORT': 80,
  144. }
  145. self.assertEqual(request.get_host(), 'example.com')
  146. # Check if HTTP_HOST isn't provided.
  147. request = HttpRequest()
  148. request.META = {
  149. 'SERVER_NAME': 'internal.com',
  150. 'SERVER_PORT': 80,
  151. }
  152. self.assertEqual(request.get_host(), 'internal.com')
  153. # Check if HTTP_HOST isn't provided, and we're on a nonstandard port
  154. request = HttpRequest()
  155. request.META = {
  156. 'SERVER_NAME': 'internal.com',
  157. 'SERVER_PORT': 8042,
  158. }
  159. self.assertEqual(request.get_host(), 'internal.com:8042')
  160. # Poisoned host headers are rejected as suspicious
  161. legit_hosts = [
  162. 'example.com',
  163. 'example.com:80',
  164. '12.34.56.78',
  165. '12.34.56.78:443',
  166. '[2001:19f0:feee::dead:beef:cafe]',
  167. '[2001:19f0:feee::dead:beef:cafe]:8080',
  168. 'xn--4ca9at.com', # Punnycode for öäü.com
  169. ]
  170. poisoned_hosts = [
  171. 'example.com@evil.tld',
  172. 'example.com:dr.frankenstein@evil.tld',
  173. 'example.com:dr.frankenstein@evil.tld:80',
  174. 'example.com:80/badpath',
  175. 'example.com: recovermypassword.com',
  176. ]
  177. for host in legit_hosts:
  178. request = HttpRequest()
  179. request.META = {
  180. 'HTTP_HOST': host,
  181. }
  182. request.get_host()
  183. for host in poisoned_hosts:
  184. with self.assertRaises(SuspiciousOperation):
  185. request = HttpRequest()
  186. request.META = {
  187. 'HTTP_HOST': host,
  188. }
  189. request.get_host()
  190. def test_near_expiration(self):
  191. "Cookie will expire when an near expiration time is provided"
  192. response = HttpResponse()
  193. # There is a timing weakness in this test; The
  194. # expected result for max-age requires that there be
  195. # a very slight difference between the evaluated expiration
  196. # time, and the time evaluated in set_cookie(). If this
  197. # difference doesn't exist, the cookie time will be
  198. # 1 second larger. To avoid the problem, put in a quick sleep,
  199. # which guarantees that there will be a time difference.
  200. expires = datetime.utcnow() + timedelta(seconds=10)
  201. time.sleep(0.001)
  202. response.set_cookie('datetime', expires=expires)
  203. datetime_cookie = response.cookies['datetime']
  204. self.assertEqual(datetime_cookie['max-age'], 10)
  205. def test_aware_expiration(self):
  206. "Cookie accepts an aware datetime as expiration time"
  207. response = HttpResponse()
  208. expires = (datetime.utcnow() + timedelta(seconds=10)).replace(tzinfo=utc)
  209. time.sleep(0.001)
  210. response.set_cookie('datetime', expires=expires)
  211. datetime_cookie = response.cookies['datetime']
  212. self.assertEqual(datetime_cookie['max-age'], 10)
  213. def test_far_expiration(self):
  214. "Cookie will expire when an distant expiration time is provided"
  215. response = HttpResponse()
  216. response.set_cookie('datetime', expires=datetime(2028, 1, 1, 4, 5, 6))
  217. datetime_cookie = response.cookies['datetime']
  218. self.assertEqual(datetime_cookie['expires'], 'Sat, 01-Jan-2028 04:05:06 GMT')
  219. def test_max_age_expiration(self):
  220. "Cookie will expire if max_age is provided"
  221. response = HttpResponse()
  222. response.set_cookie('max_age', max_age=10)
  223. max_age_cookie = response.cookies['max_age']
  224. self.assertEqual(max_age_cookie['max-age'], 10)
  225. self.assertEqual(max_age_cookie['expires'], cookie_date(time.time()+10))
  226. def test_httponly_cookie(self):
  227. response = HttpResponse()
  228. response.set_cookie('example', httponly=True)
  229. example_cookie = response.cookies['example']
  230. # A compat cookie may be in use -- check that it has worked
  231. # both as an output string, and using the cookie attributes
  232. self.assertTrue('; httponly' in str(example_cookie))
  233. self.assertTrue(example_cookie['httponly'])
  234. def test_limited_stream(self):
  235. # Read all of a limited stream
  236. stream = LimitedStream(BytesIO(b'test'), 2)
  237. self.assertEqual(stream.read(), b'te')
  238. # Reading again returns nothing.
  239. self.assertEqual(stream.read(), b'')
  240. # Read a number of characters greater than the stream has to offer
  241. stream = LimitedStream(BytesIO(b'test'), 2)
  242. self.assertEqual(stream.read(5), b'te')
  243. # Reading again returns nothing.
  244. self.assertEqual(stream.readline(5), b'')
  245. # Read sequentially from a stream
  246. stream = LimitedStream(BytesIO(b'12345678'), 8)
  247. self.assertEqual(stream.read(5), b'12345')
  248. self.assertEqual(stream.read(5), b'678')
  249. # Reading again returns nothing.
  250. self.assertEqual(stream.readline(5), b'')
  251. # Read lines from a stream
  252. stream = LimitedStream(BytesIO(b'1234\n5678\nabcd\nefgh\nijkl'), 24)
  253. # Read a full line, unconditionally
  254. self.assertEqual(stream.readline(), b'1234\n')
  255. # Read a number of characters less than a line
  256. self.assertEqual(stream.readline(2), b'56')
  257. # Read the rest of the partial line
  258. self.assertEqual(stream.readline(), b'78\n')
  259. # Read a full line, with a character limit greater than the line length
  260. self.assertEqual(stream.readline(6), b'abcd\n')
  261. # Read the next line, deliberately terminated at the line end
  262. self.assertEqual(stream.readline(4), b'efgh')
  263. # Read the next line... just the line end
  264. self.assertEqual(stream.readline(), b'\n')
  265. # Read everything else.
  266. self.assertEqual(stream.readline(), b'ijkl')
  267. # Regression for #15018
  268. # If a stream contains a newline, but the provided length
  269. # is less than the number of provided characters, the newline
  270. # doesn't reset the available character count
  271. stream = LimitedStream(BytesIO(b'1234\nabcdef'), 9)
  272. self.assertEqual(stream.readline(10), b'1234\n')
  273. self.assertEqual(stream.readline(3), b'abc')
  274. # Now expire the available characters
  275. self.assertEqual(stream.readline(3), b'd')
  276. # Reading again returns nothing.
  277. self.assertEqual(stream.readline(2), b'')
  278. # Same test, but with read, not readline.
  279. stream = LimitedStream(BytesIO(b'1234\nabcdef'), 9)
  280. self.assertEqual(stream.read(6), b'1234\na')
  281. self.assertEqual(stream.read(2), b'bc')
  282. self.assertEqual(stream.read(2), b'd')
  283. self.assertEqual(stream.read(2), b'')
  284. self.assertEqual(stream.read(), b'')
  285. def test_stream(self):
  286. payload = FakePayload('name=value')
  287. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  288. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  289. 'CONTENT_LENGTH': len(payload),
  290. 'wsgi.input': payload})
  291. self.assertEqual(request.read(), b'name=value')
  292. def test_read_after_value(self):
  293. """
  294. Reading from request is allowed after accessing request contents as
  295. POST or body.
  296. """
  297. payload = FakePayload('name=value')
  298. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  299. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  300. 'CONTENT_LENGTH': len(payload),
  301. 'wsgi.input': payload})
  302. self.assertEqual(request.POST, {'name': ['value']})
  303. self.assertEqual(request.body, b'name=value')
  304. self.assertEqual(request.read(), b'name=value')
  305. def test_value_after_read(self):
  306. """
  307. Construction of POST or body is not allowed after reading
  308. from request.
  309. """
  310. payload = FakePayload('name=value')
  311. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  312. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  313. 'CONTENT_LENGTH': len(payload),
  314. 'wsgi.input': payload})
  315. self.assertEqual(request.read(2), b'na')
  316. self.assertRaises(Exception, lambda: request.body)
  317. self.assertEqual(request.POST, {})
  318. def test_non_ascii_POST(self):
  319. payload = FakePayload(urlencode({'key': 'España'}))
  320. request = WSGIRequest({
  321. 'REQUEST_METHOD': 'POST',
  322. 'CONTENT_LENGTH': len(payload),
  323. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  324. 'wsgi.input': payload,
  325. })
  326. self.assertEqual(request.POST, {'key': ['España']})
  327. def test_alternate_charset_POST(self):
  328. """
  329. Test a POST with non-utf-8 payload encoding.
  330. """
  331. from django.utils.http import urllib_parse
  332. payload = FakePayload(urllib_parse.urlencode({'key': 'España'.encode('latin-1')}))
  333. request = WSGIRequest({
  334. 'REQUEST_METHOD': 'POST',
  335. 'CONTENT_LENGTH': len(payload),
  336. 'CONTENT_TYPE': 'application/x-www-form-urlencoded; charset=iso-8859-1',
  337. 'wsgi.input': payload,
  338. })
  339. self.assertEqual(request.POST, {'key': ['España']})
  340. def test_body_after_POST_multipart(self):
  341. """
  342. Reading body after parsing multipart is not allowed
  343. """
  344. # Because multipart is used for large amounts fo data i.e. file uploads,
  345. # we don't want the data held in memory twice, and we don't want to
  346. # silence the error by setting body = '' either.
  347. payload = FakePayload("\r\n".join([
  348. '--boundary',
  349. 'Content-Disposition: form-data; name="name"',
  350. '',
  351. 'value',
  352. '--boundary--'
  353. '']))
  354. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  355. 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary',
  356. 'CONTENT_LENGTH': len(payload),
  357. 'wsgi.input': payload})
  358. self.assertEqual(request.POST, {'name': ['value']})
  359. self.assertRaises(Exception, lambda: request.body)
  360. def test_POST_multipart_with_content_length_zero(self):
  361. """
  362. Multipart POST requests with Content-Length >= 0 are valid and need to be handled.
  363. """
  364. # According to:
  365. # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13
  366. # Every request.POST with Content-Length >= 0 is a valid request,
  367. # this test ensures that we handle Content-Length == 0.
  368. payload = FakePayload("\r\n".join([
  369. '--boundary',
  370. 'Content-Disposition: form-data; name="name"',
  371. '',
  372. 'value',
  373. '--boundary--'
  374. '']))
  375. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  376. 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary',
  377. 'CONTENT_LENGTH': 0,
  378. 'wsgi.input': payload})
  379. self.assertEqual(request.POST, {})
  380. def test_POST_binary_only(self):
  381. payload = b'\r\n\x01\x00\x00\x00ab\x00\x00\xcd\xcc,@'
  382. environ = {'REQUEST_METHOD': 'POST',
  383. 'CONTENT_TYPE': 'application/octet-stream',
  384. 'CONTENT_LENGTH': len(payload),
  385. 'wsgi.input': BytesIO(payload)}
  386. request = WSGIRequest(environ)
  387. self.assertEqual(request.POST, {})
  388. self.assertEqual(request.FILES, {})
  389. self.assertEqual(request.body, payload)
  390. # Same test without specifying content-type
  391. environ.update({'CONTENT_TYPE': '', 'wsgi.input': BytesIO(payload)})
  392. request = WSGIRequest(environ)
  393. self.assertEqual(request.POST, {})
  394. self.assertEqual(request.FILES, {})
  395. self.assertEqual(request.body, payload)
  396. def test_read_by_lines(self):
  397. payload = FakePayload('name=value')
  398. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  399. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  400. 'CONTENT_LENGTH': len(payload),
  401. 'wsgi.input': payload})
  402. self.assertEqual(list(request), [b'name=value'])
  403. def test_POST_after_body_read(self):
  404. """
  405. POST should be populated even if body is read first
  406. """
  407. payload = FakePayload('name=value')
  408. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  409. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  410. 'CONTENT_LENGTH': len(payload),
  411. 'wsgi.input': payload})
  412. raw_data = request.body
  413. self.assertEqual(request.POST, {'name': ['value']})
  414. def test_POST_after_body_read_and_stream_read(self):
  415. """
  416. POST should be populated even if body is read first, and then
  417. the stream is read second.
  418. """
  419. payload = FakePayload('name=value')
  420. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  421. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  422. 'CONTENT_LENGTH': len(payload),
  423. 'wsgi.input': payload})
  424. raw_data = request.body
  425. self.assertEqual(request.read(1), b'n')
  426. self.assertEqual(request.POST, {'name': ['value']})
  427. def test_POST_after_body_read_and_stream_read_multipart(self):
  428. """
  429. POST should be populated even if body is read first, and then
  430. the stream is read second. Using multipart/form-data instead of urlencoded.
  431. """
  432. payload = FakePayload("\r\n".join([
  433. '--boundary',
  434. 'Content-Disposition: form-data; name="name"',
  435. '',
  436. 'value',
  437. '--boundary--'
  438. '']))
  439. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  440. 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary',
  441. 'CONTENT_LENGTH': len(payload),
  442. 'wsgi.input': payload})
  443. raw_data = request.body
  444. # Consume enough data to mess up the parsing:
  445. self.assertEqual(request.read(13), b'--boundary\r\nC')
  446. self.assertEqual(request.POST, {'name': ['value']})
  447. def test_raw_post_data_returns_body(self):
  448. """
  449. HttpRequest.raw_post_body should be the same as HttpRequest.body
  450. """
  451. payload = FakePayload('Hello There!')
  452. request = WSGIRequest({
  453. 'REQUEST_METHOD': 'POST',
  454. 'CONTENT_LENGTH': len(payload),
  455. 'wsgi.input': payload,
  456. })
  457. with warnings.catch_warnings(record=True):
  458. self.assertEqual(request.body, request.raw_post_data)
  459. def test_POST_connection_error(self):
  460. """
  461. If wsgi.input.read() raises an exception while trying to read() the
  462. POST, the exception should be identifiable (not a generic IOError).
  463. """
  464. class ExplodingBytesIO(BytesIO):
  465. def read(self, len=0):
  466. raise IOError("kaboom!")
  467. payload = b'name=value'
  468. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  469. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  470. 'CONTENT_LENGTH': len(payload),
  471. 'wsgi.input': ExplodingBytesIO(payload)})
  472. with warnings.catch_warnings(record=True) as w:
  473. warnings.simplefilter("always")
  474. with self.assertRaises(UnreadablePostError):
  475. request.raw_post_data
  476. self.assertEqual(len(w), 1)