tests.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import gzip
  4. from io import BytesIO
  5. import random
  6. import re
  7. from unittest import skipIf
  8. import warnings
  9. from django.conf import settings
  10. from django.core import mail
  11. from django.db import (transaction, connections, DEFAULT_DB_ALIAS,
  12. IntegrityError)
  13. from django.http import HttpRequest, HttpResponse, StreamingHttpResponse
  14. from django.middleware.clickjacking import XFrameOptionsMiddleware
  15. from django.middleware.common import CommonMiddleware, BrokenLinkEmailsMiddleware
  16. from django.middleware.http import ConditionalGetMiddleware
  17. from django.middleware.gzip import GZipMiddleware
  18. from django.middleware.transaction import TransactionMiddleware
  19. from django.test import TransactionTestCase, TestCase, RequestFactory, override_settings
  20. from django.test.utils import IgnoreDeprecationWarningsMixin
  21. from django.utils import six
  22. from django.utils.encoding import force_str
  23. from django.utils.six.moves import xrange
  24. from .models import Band
  25. class CommonMiddlewareTest(TestCase):
  26. urls = 'middleware.urls'
  27. def _get_request(self, path):
  28. request = HttpRequest()
  29. request.META = {
  30. 'SERVER_NAME': 'testserver',
  31. 'SERVER_PORT': 80,
  32. }
  33. request.path = request.path_info = "/%s" % path
  34. return request
  35. @override_settings(APPEND_SLASH=True)
  36. def test_append_slash_have_slash(self):
  37. """
  38. Tests that URLs with slashes go unmolested.
  39. """
  40. request = self._get_request('slash/')
  41. self.assertEqual(CommonMiddleware().process_request(request), None)
  42. @override_settings(APPEND_SLASH=True)
  43. def test_append_slash_slashless_resource(self):
  44. """
  45. Tests that matches to explicit slashless URLs go unmolested.
  46. """
  47. request = self._get_request('noslash')
  48. self.assertEqual(CommonMiddleware().process_request(request), None)
  49. @override_settings(APPEND_SLASH=True)
  50. def test_append_slash_slashless_unknown(self):
  51. """
  52. Tests that APPEND_SLASH doesn't redirect to unknown resources.
  53. """
  54. request = self._get_request('unknown')
  55. self.assertEqual(CommonMiddleware().process_request(request), None)
  56. @override_settings(APPEND_SLASH=True)
  57. def test_append_slash_redirect(self):
  58. """
  59. Tests that APPEND_SLASH redirects slashless URLs to a valid pattern.
  60. """
  61. request = self._get_request('slash')
  62. r = CommonMiddleware().process_request(request)
  63. self.assertEqual(r.status_code, 301)
  64. self.assertEqual(r.url, 'http://testserver/slash/')
  65. @override_settings(APPEND_SLASH=True, DEBUG=True)
  66. def test_append_slash_no_redirect_on_POST_in_DEBUG(self):
  67. """
  68. Tests that while in debug mode, an exception is raised with a warning
  69. when a failed attempt is made to POST to an URL which would normally be
  70. redirected to a slashed version.
  71. """
  72. request = self._get_request('slash')
  73. request.method = 'POST'
  74. with six.assertRaisesRegex(self, RuntimeError, 'end in a slash'):
  75. CommonMiddleware().process_request(request)
  76. @override_settings(APPEND_SLASH=False)
  77. def test_append_slash_disabled(self):
  78. """
  79. Tests disabling append slash functionality.
  80. """
  81. request = self._get_request('slash')
  82. self.assertEqual(CommonMiddleware().process_request(request), None)
  83. @override_settings(APPEND_SLASH=True)
  84. def test_append_slash_quoted(self):
  85. """
  86. Tests that URLs which require quoting are redirected to their slash
  87. version ok.
  88. """
  89. request = self._get_request('needsquoting#')
  90. r = CommonMiddleware().process_request(request)
  91. self.assertEqual(r.status_code, 301)
  92. self.assertEqual(
  93. r.url,
  94. 'http://testserver/needsquoting%23/')
  95. @override_settings(APPEND_SLASH=False, PREPEND_WWW=True)
  96. def test_prepend_www(self):
  97. request = self._get_request('path/')
  98. r = CommonMiddleware().process_request(request)
  99. self.assertEqual(r.status_code, 301)
  100. self.assertEqual(
  101. r.url,
  102. 'http://www.testserver/path/')
  103. @override_settings(APPEND_SLASH=True, PREPEND_WWW=True)
  104. def test_prepend_www_append_slash_have_slash(self):
  105. request = self._get_request('slash/')
  106. r = CommonMiddleware().process_request(request)
  107. self.assertEqual(r.status_code, 301)
  108. self.assertEqual(r.url,
  109. 'http://www.testserver/slash/')
  110. @override_settings(APPEND_SLASH=True, PREPEND_WWW=True)
  111. def test_prepend_www_append_slash_slashless(self):
  112. request = self._get_request('slash')
  113. r = CommonMiddleware().process_request(request)
  114. self.assertEqual(r.status_code, 301)
  115. self.assertEqual(r.url,
  116. 'http://www.testserver/slash/')
  117. # The following tests examine expected behavior given a custom urlconf that
  118. # overrides the default one through the request object.
  119. @override_settings(APPEND_SLASH=True)
  120. def test_append_slash_have_slash_custom_urlconf(self):
  121. """
  122. Tests that URLs with slashes go unmolested.
  123. """
  124. request = self._get_request('customurlconf/slash/')
  125. request.urlconf = 'middleware.extra_urls'
  126. self.assertEqual(CommonMiddleware().process_request(request), None)
  127. @override_settings(APPEND_SLASH=True)
  128. def test_append_slash_slashless_resource_custom_urlconf(self):
  129. """
  130. Tests that matches to explicit slashless URLs go unmolested.
  131. """
  132. request = self._get_request('customurlconf/noslash')
  133. request.urlconf = 'middleware.extra_urls'
  134. self.assertEqual(CommonMiddleware().process_request(request), None)
  135. @override_settings(APPEND_SLASH=True)
  136. def test_append_slash_slashless_unknown_custom_urlconf(self):
  137. """
  138. Tests that APPEND_SLASH doesn't redirect to unknown resources.
  139. """
  140. request = self._get_request('customurlconf/unknown')
  141. request.urlconf = 'middleware.extra_urls'
  142. self.assertEqual(CommonMiddleware().process_request(request), None)
  143. @override_settings(APPEND_SLASH=True)
  144. def test_append_slash_redirect_custom_urlconf(self):
  145. """
  146. Tests that APPEND_SLASH redirects slashless URLs to a valid pattern.
  147. """
  148. request = self._get_request('customurlconf/slash')
  149. request.urlconf = 'middleware.extra_urls'
  150. r = CommonMiddleware().process_request(request)
  151. self.assertFalse(r is None,
  152. "CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf")
  153. self.assertEqual(r.status_code, 301)
  154. self.assertEqual(r.url, 'http://testserver/customurlconf/slash/')
  155. @override_settings(APPEND_SLASH=True, DEBUG=True)
  156. def test_append_slash_no_redirect_on_POST_in_DEBUG_custom_urlconf(self):
  157. """
  158. Tests that while in debug mode, an exception is raised with a warning
  159. when a failed attempt is made to POST to an URL which would normally be
  160. redirected to a slashed version.
  161. """
  162. request = self._get_request('customurlconf/slash')
  163. request.urlconf = 'middleware.extra_urls'
  164. request.method = 'POST'
  165. with six.assertRaisesRegex(self, RuntimeError, 'end in a slash'):
  166. CommonMiddleware().process_request(request)
  167. @override_settings(APPEND_SLASH=False)
  168. def test_append_slash_disabled_custom_urlconf(self):
  169. """
  170. Tests disabling append slash functionality.
  171. """
  172. request = self._get_request('customurlconf/slash')
  173. request.urlconf = 'middleware.extra_urls'
  174. self.assertEqual(CommonMiddleware().process_request(request), None)
  175. @override_settings(APPEND_SLASH=True)
  176. def test_append_slash_quoted_custom_urlconf(self):
  177. """
  178. Tests that URLs which require quoting are redirected to their slash
  179. version ok.
  180. """
  181. request = self._get_request('customurlconf/needsquoting#')
  182. request.urlconf = 'middleware.extra_urls'
  183. r = CommonMiddleware().process_request(request)
  184. self.assertFalse(r is None,
  185. "CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf")
  186. self.assertEqual(r.status_code, 301)
  187. self.assertEqual(
  188. r.url,
  189. 'http://testserver/customurlconf/needsquoting%23/')
  190. @override_settings(APPEND_SLASH=False, PREPEND_WWW=True)
  191. def test_prepend_www_custom_urlconf(self):
  192. request = self._get_request('customurlconf/path/')
  193. request.urlconf = 'middleware.extra_urls'
  194. r = CommonMiddleware().process_request(request)
  195. self.assertEqual(r.status_code, 301)
  196. self.assertEqual(
  197. r.url,
  198. 'http://www.testserver/customurlconf/path/')
  199. @override_settings(APPEND_SLASH=True, PREPEND_WWW=True)
  200. def test_prepend_www_append_slash_have_slash_custom_urlconf(self):
  201. request = self._get_request('customurlconf/slash/')
  202. request.urlconf = 'middleware.extra_urls'
  203. r = CommonMiddleware().process_request(request)
  204. self.assertEqual(r.status_code, 301)
  205. self.assertEqual(r.url,
  206. 'http://www.testserver/customurlconf/slash/')
  207. @override_settings(APPEND_SLASH=True, PREPEND_WWW=True)
  208. def test_prepend_www_append_slash_slashless_custom_urlconf(self):
  209. request = self._get_request('customurlconf/slash')
  210. request.urlconf = 'middleware.extra_urls'
  211. r = CommonMiddleware().process_request(request)
  212. self.assertEqual(r.status_code, 301)
  213. self.assertEqual(r.url,
  214. 'http://www.testserver/customurlconf/slash/')
  215. # Legacy tests for the 404 error reporting via email (to be removed in 1.8)
  216. @override_settings(IGNORABLE_404_URLS=(re.compile(r'foo'),),
  217. SEND_BROKEN_LINK_EMAILS=True,
  218. MANAGERS=('PHB@dilbert.com',))
  219. def test_404_error_reporting(self):
  220. request = self._get_request('regular_url/that/does/not/exist')
  221. request.META['HTTP_REFERER'] = '/another/url/'
  222. with warnings.catch_warnings():
  223. warnings.simplefilter("ignore", DeprecationWarning)
  224. response = self.client.get(request.path)
  225. CommonMiddleware().process_response(request, response)
  226. self.assertEqual(len(mail.outbox), 1)
  227. self.assertIn('Broken', mail.outbox[0].subject)
  228. @override_settings(IGNORABLE_404_URLS=(re.compile(r'foo'),),
  229. SEND_BROKEN_LINK_EMAILS=True,
  230. MANAGERS=('PHB@dilbert.com',))
  231. def test_404_error_reporting_no_referer(self):
  232. request = self._get_request('regular_url/that/does/not/exist')
  233. with warnings.catch_warnings():
  234. warnings.simplefilter("ignore", DeprecationWarning)
  235. response = self.client.get(request.path)
  236. CommonMiddleware().process_response(request, response)
  237. self.assertEqual(len(mail.outbox), 0)
  238. @override_settings(IGNORABLE_404_URLS=(re.compile(r'foo'),),
  239. SEND_BROKEN_LINK_EMAILS=True,
  240. MANAGERS=('PHB@dilbert.com',))
  241. def test_404_error_reporting_ignored_url(self):
  242. request = self._get_request('foo_url/that/does/not/exist/either')
  243. request.META['HTTP_REFERER'] = '/another/url/'
  244. with warnings.catch_warnings():
  245. warnings.simplefilter("ignore", DeprecationWarning)
  246. response = self.client.get(request.path)
  247. CommonMiddleware().process_response(request, response)
  248. self.assertEqual(len(mail.outbox), 0)
  249. # Other tests
  250. def test_non_ascii_query_string_does_not_crash(self):
  251. """Regression test for #15152"""
  252. request = self._get_request('slash')
  253. request.META['QUERY_STRING'] = force_str('drink=café')
  254. response = CommonMiddleware().process_request(request)
  255. self.assertEqual(response.status_code, 301)
  256. @override_settings(
  257. IGNORABLE_404_URLS=(re.compile(r'foo'),),
  258. MANAGERS=('PHB@dilbert.com',),
  259. )
  260. class BrokenLinkEmailsMiddlewareTest(TestCase):
  261. def setUp(self):
  262. self.req = HttpRequest()
  263. self.req.META = {
  264. 'SERVER_NAME': 'testserver',
  265. 'SERVER_PORT': 80,
  266. }
  267. self.req.path = self.req.path_info = 'regular_url/that/does/not/exist'
  268. self.resp = self.client.get(self.req.path)
  269. def test_404_error_reporting(self):
  270. self.req.META['HTTP_REFERER'] = '/another/url/'
  271. BrokenLinkEmailsMiddleware().process_response(self.req, self.resp)
  272. self.assertEqual(len(mail.outbox), 1)
  273. self.assertIn('Broken', mail.outbox[0].subject)
  274. def test_404_error_reporting_no_referer(self):
  275. BrokenLinkEmailsMiddleware().process_response(self.req, self.resp)
  276. self.assertEqual(len(mail.outbox), 0)
  277. def test_404_error_reporting_ignored_url(self):
  278. self.req.path = self.req.path_info = 'foo_url/that/does/not/exist'
  279. BrokenLinkEmailsMiddleware().process_response(self.req, self.resp)
  280. self.assertEqual(len(mail.outbox), 0)
  281. @skipIf(six.PY3, "HTTP_REFERER is str type on Python 3")
  282. def test_404_error_nonascii_referrer(self):
  283. # Such referer strings should not happen, but anyway, if it happens,
  284. # let's not crash
  285. self.req.META['HTTP_REFERER'] = b'http://testserver/c/\xd0\xbb\xd0\xb8/'
  286. BrokenLinkEmailsMiddleware().process_response(self.req, self.resp)
  287. self.assertEqual(len(mail.outbox), 1)
  288. def test_custom_request_checker(self):
  289. class SubclassedMiddleware(BrokenLinkEmailsMiddleware):
  290. ignored_user_agent_patterns = (re.compile(r'Spider.*'),
  291. re.compile(r'Robot.*'))
  292. def is_ignorable_request(self, request, uri, domain, referer):
  293. '''Check user-agent in addition to normal checks.'''
  294. if super(SubclassedMiddleware, self).is_ignorable_request(request, uri, domain, referer):
  295. return True
  296. user_agent = request.META['HTTP_USER_AGENT']
  297. return any(pattern.search(user_agent) for pattern in
  298. self.ignored_user_agent_patterns)
  299. self.req.META['HTTP_REFERER'] = '/another/url/'
  300. self.req.META['HTTP_USER_AGENT'] = 'Spider machine 3.4'
  301. SubclassedMiddleware().process_response(self.req, self.resp)
  302. self.assertEqual(len(mail.outbox), 0)
  303. self.req.META['HTTP_USER_AGENT'] = 'My user agent'
  304. SubclassedMiddleware().process_response(self.req, self.resp)
  305. self.assertEqual(len(mail.outbox), 1)
  306. class ConditionalGetMiddlewareTest(TestCase):
  307. urls = 'middleware.cond_get_urls'
  308. def setUp(self):
  309. self.req = HttpRequest()
  310. self.req.META = {
  311. 'SERVER_NAME': 'testserver',
  312. 'SERVER_PORT': 80,
  313. }
  314. self.req.path = self.req.path_info = "/"
  315. self.resp = self.client.get(self.req.path)
  316. # Tests for the Date header
  317. def test_date_header_added(self):
  318. self.assertFalse('Date' in self.resp)
  319. self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
  320. self.assertTrue('Date' in self.resp)
  321. # Tests for the Content-Length header
  322. def test_content_length_header_added(self):
  323. content_length = len(self.resp.content)
  324. self.assertFalse('Content-Length' in self.resp)
  325. self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
  326. self.assertTrue('Content-Length' in self.resp)
  327. self.assertEqual(int(self.resp['Content-Length']), content_length)
  328. def test_content_length_header_not_added(self):
  329. resp = StreamingHttpResponse('content')
  330. self.assertFalse('Content-Length' in resp)
  331. resp = ConditionalGetMiddleware().process_response(self.req, resp)
  332. self.assertFalse('Content-Length' in resp)
  333. def test_content_length_header_not_changed(self):
  334. bad_content_length = len(self.resp.content) + 10
  335. self.resp['Content-Length'] = bad_content_length
  336. self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
  337. self.assertEqual(int(self.resp['Content-Length']), bad_content_length)
  338. # Tests for the ETag header
  339. def test_if_none_match_and_no_etag(self):
  340. self.req.META['HTTP_IF_NONE_MATCH'] = 'spam'
  341. self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
  342. self.assertEqual(self.resp.status_code, 200)
  343. def test_no_if_none_match_and_etag(self):
  344. self.resp['ETag'] = 'eggs'
  345. self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
  346. self.assertEqual(self.resp.status_code, 200)
  347. def test_if_none_match_and_same_etag(self):
  348. self.req.META['HTTP_IF_NONE_MATCH'] = self.resp['ETag'] = 'spam'
  349. self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
  350. self.assertEqual(self.resp.status_code, 304)
  351. def test_if_none_match_and_different_etag(self):
  352. self.req.META['HTTP_IF_NONE_MATCH'] = 'spam'
  353. self.resp['ETag'] = 'eggs'
  354. self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
  355. self.assertEqual(self.resp.status_code, 200)
  356. @override_settings(USE_ETAGS=True)
  357. def test_etag(self):
  358. req = HttpRequest()
  359. res = HttpResponse('content')
  360. self.assertTrue(
  361. CommonMiddleware().process_response(req, res).has_header('ETag'))
  362. @override_settings(USE_ETAGS=True)
  363. def test_etag_streaming_response(self):
  364. req = HttpRequest()
  365. res = StreamingHttpResponse(['content'])
  366. res['ETag'] = 'tomatoes'
  367. self.assertEqual(
  368. CommonMiddleware().process_response(req, res).get('ETag'),
  369. 'tomatoes')
  370. @override_settings(USE_ETAGS=True)
  371. def test_no_etag_streaming_response(self):
  372. req = HttpRequest()
  373. res = StreamingHttpResponse(['content'])
  374. self.assertFalse(
  375. CommonMiddleware().process_response(req, res).has_header('ETag'))
  376. # Tests for the Last-Modified header
  377. def test_if_modified_since_and_no_last_modified(self):
  378. self.req.META['HTTP_IF_MODIFIED_SINCE'] = 'Sat, 12 Feb 2011 17:38:44 GMT'
  379. self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
  380. self.assertEqual(self.resp.status_code, 200)
  381. def test_no_if_modified_since_and_last_modified(self):
  382. self.resp['Last-Modified'] = 'Sat, 12 Feb 2011 17:38:44 GMT'
  383. self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
  384. self.assertEqual(self.resp.status_code, 200)
  385. def test_if_modified_since_and_same_last_modified(self):
  386. self.req.META['HTTP_IF_MODIFIED_SINCE'] = 'Sat, 12 Feb 2011 17:38:44 GMT'
  387. self.resp['Last-Modified'] = 'Sat, 12 Feb 2011 17:38:44 GMT'
  388. self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
  389. self.assertEqual(self.resp.status_code, 304)
  390. def test_if_modified_since_and_last_modified_in_the_past(self):
  391. self.req.META['HTTP_IF_MODIFIED_SINCE'] = 'Sat, 12 Feb 2011 17:38:44 GMT'
  392. self.resp['Last-Modified'] = 'Sat, 12 Feb 2011 17:35:44 GMT'
  393. self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
  394. self.assertEqual(self.resp.status_code, 304)
  395. def test_if_modified_since_and_last_modified_in_the_future(self):
  396. self.req.META['HTTP_IF_MODIFIED_SINCE'] = 'Sat, 12 Feb 2011 17:38:44 GMT'
  397. self.resp['Last-Modified'] = 'Sat, 12 Feb 2011 17:41:44 GMT'
  398. self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
  399. self.assertEqual(self.resp.status_code, 200)
  400. class XFrameOptionsMiddlewareTest(TestCase):
  401. """
  402. Tests for the X-Frame-Options clickjacking prevention middleware.
  403. """
  404. def test_same_origin(self):
  405. """
  406. Tests that the X_FRAME_OPTIONS setting can be set to SAMEORIGIN to
  407. have the middleware use that value for the HTTP header.
  408. """
  409. with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):
  410. r = XFrameOptionsMiddleware().process_response(HttpRequest(),
  411. HttpResponse())
  412. self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
  413. with override_settings(X_FRAME_OPTIONS='sameorigin'):
  414. r = XFrameOptionsMiddleware().process_response(HttpRequest(),
  415. HttpResponse())
  416. self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
  417. def test_deny(self):
  418. """
  419. Tests that the X_FRAME_OPTIONS setting can be set to DENY to
  420. have the middleware use that value for the HTTP header.
  421. """
  422. with override_settings(X_FRAME_OPTIONS='DENY'):
  423. r = XFrameOptionsMiddleware().process_response(HttpRequest(),
  424. HttpResponse())
  425. self.assertEqual(r['X-Frame-Options'], 'DENY')
  426. with override_settings(X_FRAME_OPTIONS='deny'):
  427. r = XFrameOptionsMiddleware().process_response(HttpRequest(),
  428. HttpResponse())
  429. self.assertEqual(r['X-Frame-Options'], 'DENY')
  430. def test_defaults_sameorigin(self):
  431. """
  432. Tests that if the X_FRAME_OPTIONS setting is not set then it defaults
  433. to SAMEORIGIN.
  434. """
  435. with override_settings(X_FRAME_OPTIONS=None):
  436. del settings.X_FRAME_OPTIONS # restored by override_settings
  437. r = XFrameOptionsMiddleware().process_response(HttpRequest(),
  438. HttpResponse())
  439. self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
  440. def test_dont_set_if_set(self):
  441. """
  442. Tests that if the X-Frame-Options header is already set then the
  443. middleware does not attempt to override it.
  444. """
  445. with override_settings(X_FRAME_OPTIONS='DENY'):
  446. response = HttpResponse()
  447. response['X-Frame-Options'] = 'SAMEORIGIN'
  448. r = XFrameOptionsMiddleware().process_response(HttpRequest(),
  449. response)
  450. self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
  451. with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):
  452. response = HttpResponse()
  453. response['X-Frame-Options'] = 'DENY'
  454. r = XFrameOptionsMiddleware().process_response(HttpRequest(),
  455. response)
  456. self.assertEqual(r['X-Frame-Options'], 'DENY')
  457. def test_response_exempt(self):
  458. """
  459. Tests that if the response has a xframe_options_exempt attribute set
  460. to False then it still sets the header, but if it's set to True then
  461. it does not.
  462. """
  463. with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):
  464. response = HttpResponse()
  465. response.xframe_options_exempt = False
  466. r = XFrameOptionsMiddleware().process_response(HttpRequest(),
  467. response)
  468. self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
  469. response = HttpResponse()
  470. response.xframe_options_exempt = True
  471. r = XFrameOptionsMiddleware().process_response(HttpRequest(),
  472. response)
  473. self.assertEqual(r.get('X-Frame-Options', None), None)
  474. def test_is_extendable(self):
  475. """
  476. Tests that the XFrameOptionsMiddleware method that determines the
  477. X-Frame-Options header value can be overridden based on something in
  478. the request or response.
  479. """
  480. class OtherXFrameOptionsMiddleware(XFrameOptionsMiddleware):
  481. # This is just an example for testing purposes...
  482. def get_xframe_options_value(self, request, response):
  483. if getattr(request, 'sameorigin', False):
  484. return 'SAMEORIGIN'
  485. if getattr(response, 'sameorigin', False):
  486. return 'SAMEORIGIN'
  487. return 'DENY'
  488. with override_settings(X_FRAME_OPTIONS='DENY'):
  489. response = HttpResponse()
  490. response.sameorigin = True
  491. r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(),
  492. response)
  493. self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
  494. request = HttpRequest()
  495. request.sameorigin = True
  496. r = OtherXFrameOptionsMiddleware().process_response(request,
  497. HttpResponse())
  498. self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
  499. with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):
  500. r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(),
  501. HttpResponse())
  502. self.assertEqual(r['X-Frame-Options'], 'DENY')
  503. class GZipMiddlewareTest(TestCase):
  504. """
  505. Tests the GZip middleware.
  506. """
  507. short_string = b"This string is too short to be worth compressing."
  508. compressible_string = b'a' * 500
  509. uncompressible_string = b''.join(six.int2byte(random.randint(0, 255)) for _ in xrange(500))
  510. sequence = [b'a' * 500, b'b' * 200, b'a' * 300]
  511. def setUp(self):
  512. self.req = HttpRequest()
  513. self.req.META = {
  514. 'SERVER_NAME': 'testserver',
  515. 'SERVER_PORT': 80,
  516. }
  517. self.req.path = self.req.path_info = "/"
  518. self.req.META['HTTP_ACCEPT_ENCODING'] = 'gzip, deflate'
  519. self.req.META['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1'
  520. self.resp = HttpResponse()
  521. self.resp.status_code = 200
  522. self.resp.content = self.compressible_string
  523. self.resp['Content-Type'] = 'text/html; charset=UTF-8'
  524. self.stream_resp = StreamingHttpResponse(self.sequence)
  525. self.stream_resp['Content-Type'] = 'text/html; charset=UTF-8'
  526. @staticmethod
  527. def decompress(gzipped_string):
  528. return gzip.GzipFile(mode='rb', fileobj=BytesIO(gzipped_string)).read()
  529. def test_compress_response(self):
  530. """
  531. Tests that compression is performed on responses with compressible content.
  532. """
  533. r = GZipMiddleware().process_response(self.req, self.resp)
  534. self.assertEqual(self.decompress(r.content), self.compressible_string)
  535. self.assertEqual(r.get('Content-Encoding'), 'gzip')
  536. self.assertEqual(r.get('Content-Length'), str(len(r.content)))
  537. def test_compress_streaming_response(self):
  538. """
  539. Tests that compression is performed on responses with streaming content.
  540. """
  541. r = GZipMiddleware().process_response(self.req, self.stream_resp)
  542. self.assertEqual(self.decompress(b''.join(r)), b''.join(self.sequence))
  543. self.assertEqual(r.get('Content-Encoding'), 'gzip')
  544. self.assertFalse(r.has_header('Content-Length'))
  545. def test_compress_non_200_response(self):
  546. """
  547. Tests that compression is performed on responses with a status other than 200.
  548. See #10762.
  549. """
  550. self.resp.status_code = 404
  551. r = GZipMiddleware().process_response(self.req, self.resp)
  552. self.assertEqual(self.decompress(r.content), self.compressible_string)
  553. self.assertEqual(r.get('Content-Encoding'), 'gzip')
  554. def test_no_compress_short_response(self):
  555. """
  556. Tests that compression isn't performed on responses with short content.
  557. """
  558. self.resp.content = self.short_string
  559. r = GZipMiddleware().process_response(self.req, self.resp)
  560. self.assertEqual(r.content, self.short_string)
  561. self.assertEqual(r.get('Content-Encoding'), None)
  562. def test_no_compress_compressed_response(self):
  563. """
  564. Tests that compression isn't performed on responses that are already compressed.
  565. """
  566. self.resp['Content-Encoding'] = 'deflate'
  567. r = GZipMiddleware().process_response(self.req, self.resp)
  568. self.assertEqual(r.content, self.compressible_string)
  569. self.assertEqual(r.get('Content-Encoding'), 'deflate')
  570. def test_no_compress_ie_js_requests(self):
  571. """
  572. Tests that compression isn't performed on JavaScript requests from Internet Explorer.
  573. """
  574. self.req.META['HTTP_USER_AGENT'] = 'Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)'
  575. self.resp['Content-Type'] = 'application/javascript; charset=UTF-8'
  576. r = GZipMiddleware().process_response(self.req, self.resp)
  577. self.assertEqual(r.content, self.compressible_string)
  578. self.assertEqual(r.get('Content-Encoding'), None)
  579. def test_no_compress_uncompressible_response(self):
  580. """
  581. Tests that compression isn't performed on responses with uncompressible content.
  582. """
  583. self.resp.content = self.uncompressible_string
  584. r = GZipMiddleware().process_response(self.req, self.resp)
  585. self.assertEqual(r.content, self.uncompressible_string)
  586. self.assertEqual(r.get('Content-Encoding'), None)
  587. @override_settings(USE_ETAGS=True)
  588. class ETagGZipMiddlewareTest(TestCase):
  589. """
  590. Tests if the ETag middleware behaves correctly with GZip middleware.
  591. """
  592. compressible_string = b'a' * 500
  593. def setUp(self):
  594. self.rf = RequestFactory()
  595. def test_compress_response(self):
  596. """
  597. Tests that ETag is changed after gzip compression is performed.
  598. """
  599. request = self.rf.get('/', HTTP_ACCEPT_ENCODING='gzip, deflate')
  600. response = GZipMiddleware().process_response(request,
  601. CommonMiddleware().process_response(request,
  602. HttpResponse(self.compressible_string)))
  603. gzip_etag = response.get('ETag')
  604. request = self.rf.get('/', HTTP_ACCEPT_ENCODING='')
  605. response = GZipMiddleware().process_response(request,
  606. CommonMiddleware().process_response(request,
  607. HttpResponse(self.compressible_string)))
  608. nogzip_etag = response.get('ETag')
  609. self.assertNotEqual(gzip_etag, nogzip_etag)
  610. class TransactionMiddlewareTest(IgnoreDeprecationWarningsMixin, TransactionTestCase):
  611. """
  612. Test the transaction middleware.
  613. """
  614. available_apps = ['middleware']
  615. def setUp(self):
  616. super(TransactionMiddlewareTest, self).setUp()
  617. self.request = HttpRequest()
  618. self.request.META = {
  619. 'SERVER_NAME': 'testserver',
  620. 'SERVER_PORT': 80,
  621. }
  622. self.request.path = self.request.path_info = "/"
  623. self.response = HttpResponse()
  624. self.response.status_code = 200
  625. def tearDown(self):
  626. transaction.abort()
  627. super(TransactionMiddlewareTest, self).tearDown()
  628. def test_request(self):
  629. TransactionMiddleware().process_request(self.request)
  630. self.assertFalse(transaction.get_autocommit())
  631. def test_managed_response(self):
  632. transaction.enter_transaction_management()
  633. Band.objects.create(name='The Beatles')
  634. self.assertTrue(transaction.is_dirty())
  635. TransactionMiddleware().process_response(self.request, self.response)
  636. self.assertFalse(transaction.is_dirty())
  637. self.assertEqual(Band.objects.count(), 1)
  638. def test_exception(self):
  639. transaction.enter_transaction_management()
  640. Band.objects.create(name='The Beatles')
  641. self.assertTrue(transaction.is_dirty())
  642. TransactionMiddleware().process_exception(self.request, None)
  643. self.assertFalse(transaction.is_dirty())
  644. self.assertEqual(Band.objects.count(), 0)
  645. def test_failing_commit(self):
  646. # It is possible that connection.commit() fails. Check that
  647. # TransactionMiddleware handles such cases correctly.
  648. try:
  649. def raise_exception():
  650. raise IntegrityError()
  651. connections[DEFAULT_DB_ALIAS].commit = raise_exception
  652. transaction.enter_transaction_management()
  653. Band.objects.create(name='The Beatles')
  654. self.assertTrue(transaction.is_dirty())
  655. with self.assertRaises(IntegrityError):
  656. TransactionMiddleware().process_response(self.request, None)
  657. self.assertFalse(transaction.is_dirty())
  658. self.assertEqual(Band.objects.count(), 0)
  659. self.assertFalse(transaction.is_managed())
  660. finally:
  661. del connections[DEFAULT_DB_ALIAS].commit