tests.py 18 KB

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