tests.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. # -*- encoding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import copy
  4. import json
  5. import os
  6. import pickle
  7. import unittest
  8. import uuid
  9. from django.core.exceptions import SuspiciousOperation
  10. from django.core.serializers.json import DjangoJSONEncoder
  11. from django.core.signals import request_finished
  12. from django.db import close_old_connections
  13. from django.http import (
  14. BadHeaderError, HttpResponse, HttpResponseNotAllowed,
  15. HttpResponseNotModified, HttpResponsePermanentRedirect,
  16. HttpResponseRedirect, JsonResponse, QueryDict, SimpleCookie,
  17. StreamingHttpResponse, parse_cookie,
  18. )
  19. from django.test import SimpleTestCase
  20. from django.utils import six
  21. from django.utils._os import upath
  22. from django.utils.encoding import force_str
  23. from django.utils.functional import lazystr
  24. class QueryDictTests(SimpleTestCase):
  25. def test_create_with_no_args(self):
  26. self.assertEqual(QueryDict(), QueryDict(str('')))
  27. def test_missing_key(self):
  28. q = QueryDict()
  29. with self.assertRaises(KeyError):
  30. q.__getitem__('foo')
  31. def test_immutability(self):
  32. q = QueryDict()
  33. with self.assertRaises(AttributeError):
  34. q.__setitem__('something', 'bar')
  35. with self.assertRaises(AttributeError):
  36. q.setlist('foo', ['bar'])
  37. with self.assertRaises(AttributeError):
  38. q.appendlist('foo', ['bar'])
  39. with self.assertRaises(AttributeError):
  40. q.update({'foo': 'bar'})
  41. with self.assertRaises(AttributeError):
  42. q.pop('foo')
  43. with self.assertRaises(AttributeError):
  44. q.popitem()
  45. with self.assertRaises(AttributeError):
  46. q.clear()
  47. def test_immutable_get_with_default(self):
  48. q = QueryDict()
  49. self.assertEqual(q.get('foo', 'default'), 'default')
  50. def test_immutable_basic_operations(self):
  51. q = QueryDict()
  52. self.assertEqual(q.getlist('foo'), [])
  53. if six.PY2:
  54. self.assertIs(q.has_key('foo'), False)
  55. self.assertNotIn('foo', q)
  56. self.assertEqual(list(six.iteritems(q)), [])
  57. self.assertEqual(list(six.iterlists(q)), [])
  58. self.assertEqual(list(six.iterkeys(q)), [])
  59. self.assertEqual(list(six.itervalues(q)), [])
  60. self.assertEqual(len(q), 0)
  61. self.assertEqual(q.urlencode(), '')
  62. def test_single_key_value(self):
  63. """Test QueryDict with one key/value pair"""
  64. q = QueryDict(str('foo=bar'))
  65. self.assertEqual(q['foo'], 'bar')
  66. with self.assertRaises(KeyError):
  67. q.__getitem__('bar')
  68. with self.assertRaises(AttributeError):
  69. q.__setitem__('something', 'bar')
  70. self.assertEqual(q.get('foo', 'default'), 'bar')
  71. self.assertEqual(q.get('bar', 'default'), 'default')
  72. self.assertEqual(q.getlist('foo'), ['bar'])
  73. self.assertEqual(q.getlist('bar'), [])
  74. with self.assertRaises(AttributeError):
  75. q.setlist('foo', ['bar'])
  76. with self.assertRaises(AttributeError):
  77. q.appendlist('foo', ['bar'])
  78. if six.PY2:
  79. self.assertTrue(q.has_key('foo'))
  80. self.assertIn('foo', q)
  81. if six.PY2:
  82. self.assertFalse(q.has_key('bar'))
  83. self.assertNotIn('bar', q)
  84. self.assertEqual(list(six.iteritems(q)), [('foo', 'bar')])
  85. self.assertEqual(list(six.iterlists(q)), [('foo', ['bar'])])
  86. self.assertEqual(list(six.iterkeys(q)), ['foo'])
  87. self.assertEqual(list(six.itervalues(q)), ['bar'])
  88. self.assertEqual(len(q), 1)
  89. with self.assertRaises(AttributeError):
  90. q.update({'foo': 'bar'})
  91. with self.assertRaises(AttributeError):
  92. q.pop('foo')
  93. with self.assertRaises(AttributeError):
  94. q.popitem()
  95. with self.assertRaises(AttributeError):
  96. q.clear()
  97. with self.assertRaises(AttributeError):
  98. q.setdefault('foo', 'bar')
  99. self.assertEqual(q.urlencode(), 'foo=bar')
  100. def test_urlencode(self):
  101. q = QueryDict(mutable=True)
  102. q['next'] = '/a&b/'
  103. self.assertEqual(q.urlencode(), 'next=%2Fa%26b%2F')
  104. self.assertEqual(q.urlencode(safe='/'), 'next=/a%26b/')
  105. q = QueryDict(mutable=True)
  106. q['next'] = '/t\xebst&key/'
  107. self.assertEqual(q.urlencode(), 'next=%2Ft%C3%ABst%26key%2F')
  108. self.assertEqual(q.urlencode(safe='/'), 'next=/t%C3%ABst%26key/')
  109. def test_mutable_copy(self):
  110. """A copy of a QueryDict is mutable."""
  111. q = QueryDict().copy()
  112. with self.assertRaises(KeyError):
  113. q.__getitem__("foo")
  114. q['name'] = 'john'
  115. self.assertEqual(q['name'], 'john')
  116. def test_mutable_delete(self):
  117. q = QueryDict(mutable=True)
  118. q['name'] = 'john'
  119. del q['name']
  120. self.assertNotIn('name', q)
  121. def test_basic_mutable_operations(self):
  122. q = QueryDict(mutable=True)
  123. q['name'] = 'john'
  124. self.assertEqual(q.get('foo', 'default'), 'default')
  125. self.assertEqual(q.get('name', 'default'), 'john')
  126. self.assertEqual(q.getlist('name'), ['john'])
  127. self.assertEqual(q.getlist('foo'), [])
  128. q.setlist('foo', ['bar', 'baz'])
  129. self.assertEqual(q.get('foo', 'default'), 'baz')
  130. self.assertEqual(q.getlist('foo'), ['bar', 'baz'])
  131. q.appendlist('foo', 'another')
  132. self.assertEqual(q.getlist('foo'), ['bar', 'baz', 'another'])
  133. self.assertEqual(q['foo'], 'another')
  134. if six.PY2:
  135. self.assertTrue(q.has_key('foo'))
  136. self.assertIn('foo', q)
  137. self.assertListEqual(sorted(six.iteritems(q)),
  138. [('foo', 'another'), ('name', 'john')])
  139. self.assertListEqual(sorted(six.iterlists(q)),
  140. [('foo', ['bar', 'baz', 'another']), ('name', ['john'])])
  141. self.assertListEqual(sorted(six.iterkeys(q)),
  142. ['foo', 'name'])
  143. self.assertListEqual(sorted(six.itervalues(q)),
  144. ['another', 'john'])
  145. q.update({'foo': 'hello'})
  146. self.assertEqual(q['foo'], 'hello')
  147. self.assertEqual(q.get('foo', 'not available'), 'hello')
  148. self.assertEqual(q.getlist('foo'), ['bar', 'baz', 'another', 'hello'])
  149. self.assertEqual(q.pop('foo'), ['bar', 'baz', 'another', 'hello'])
  150. self.assertEqual(q.pop('foo', 'not there'), 'not there')
  151. self.assertEqual(q.get('foo', 'not there'), 'not there')
  152. self.assertEqual(q.setdefault('foo', 'bar'), 'bar')
  153. self.assertEqual(q['foo'], 'bar')
  154. self.assertEqual(q.getlist('foo'), ['bar'])
  155. self.assertIn(q.urlencode(), ['foo=bar&name=john', 'name=john&foo=bar'])
  156. q.clear()
  157. self.assertEqual(len(q), 0)
  158. def test_multiple_keys(self):
  159. """Test QueryDict with two key/value pairs with same keys."""
  160. q = QueryDict(str('vote=yes&vote=no'))
  161. self.assertEqual(q['vote'], 'no')
  162. with self.assertRaises(AttributeError):
  163. q.__setitem__('something', 'bar')
  164. self.assertEqual(q.get('vote', 'default'), 'no')
  165. self.assertEqual(q.get('foo', 'default'), 'default')
  166. self.assertEqual(q.getlist('vote'), ['yes', 'no'])
  167. self.assertEqual(q.getlist('foo'), [])
  168. with self.assertRaises(AttributeError):
  169. q.setlist('foo', ['bar', 'baz'])
  170. with self.assertRaises(AttributeError):
  171. q.setlist('foo', ['bar', 'baz'])
  172. with self.assertRaises(AttributeError):
  173. q.appendlist('foo', ['bar'])
  174. if six.PY2:
  175. self.assertIs(q.has_key('vote'), True)
  176. self.assertIn('vote', q)
  177. if six.PY2:
  178. self.assertIs(q.has_key('foo'), False)
  179. self.assertNotIn('foo', q)
  180. self.assertEqual(list(six.iteritems(q)), [('vote', 'no')])
  181. self.assertEqual(list(six.iterlists(q)), [('vote', ['yes', 'no'])])
  182. self.assertEqual(list(six.iterkeys(q)), ['vote'])
  183. self.assertEqual(list(six.itervalues(q)), ['no'])
  184. self.assertEqual(len(q), 1)
  185. with self.assertRaises(AttributeError):
  186. q.update({'foo': 'bar'})
  187. with self.assertRaises(AttributeError):
  188. q.pop('foo')
  189. with self.assertRaises(AttributeError):
  190. q.popitem()
  191. with self.assertRaises(AttributeError):
  192. q.clear()
  193. with self.assertRaises(AttributeError):
  194. q.setdefault('foo', 'bar')
  195. with self.assertRaises(AttributeError):
  196. q.__delitem__('vote')
  197. if six.PY2:
  198. def test_invalid_input_encoding(self):
  199. """
  200. QueryDicts must be able to handle invalid input encoding (in this
  201. case, bad UTF-8 encoding), falling back to ISO-8859-1 decoding.
  202. This test doesn't apply under Python 3 because the URL is a string
  203. and not a bytestring.
  204. """
  205. q = QueryDict(str(b'foo=bar&foo=\xff'))
  206. self.assertEqual(q['foo'], '\xff')
  207. self.assertEqual(q.getlist('foo'), ['bar', '\xff'])
  208. def test_pickle(self):
  209. q = QueryDict()
  210. q1 = pickle.loads(pickle.dumps(q, 2))
  211. self.assertEqual(q, q1)
  212. q = QueryDict(str('a=b&c=d'))
  213. q1 = pickle.loads(pickle.dumps(q, 2))
  214. self.assertEqual(q, q1)
  215. q = QueryDict(str('a=b&c=d&a=1'))
  216. q1 = pickle.loads(pickle.dumps(q, 2))
  217. self.assertEqual(q, q1)
  218. def test_update_from_querydict(self):
  219. """Regression test for #8278: QueryDict.update(QueryDict)"""
  220. x = QueryDict(str("a=1&a=2"), mutable=True)
  221. y = QueryDict(str("a=3&a=4"))
  222. x.update(y)
  223. self.assertEqual(x.getlist('a'), ['1', '2', '3', '4'])
  224. def test_non_default_encoding(self):
  225. """#13572 - QueryDict with a non-default encoding"""
  226. q = QueryDict(str('cur=%A4'), encoding='iso-8859-15')
  227. self.assertEqual(q.encoding, 'iso-8859-15')
  228. self.assertEqual(list(six.iteritems(q)), [('cur', '€')])
  229. self.assertEqual(q.urlencode(), 'cur=%A4')
  230. q = q.copy()
  231. self.assertEqual(q.encoding, 'iso-8859-15')
  232. self.assertEqual(list(six.iteritems(q)), [('cur', '€')])
  233. self.assertEqual(q.urlencode(), 'cur=%A4')
  234. self.assertEqual(copy.copy(q).encoding, 'iso-8859-15')
  235. self.assertEqual(copy.deepcopy(q).encoding, 'iso-8859-15')
  236. def test_querydict_fromkeys(self):
  237. self.assertEqual(QueryDict.fromkeys(['key1', 'key2', 'key3']), QueryDict('key1&key2&key3'))
  238. def test_fromkeys_with_nonempty_value(self):
  239. self.assertEqual(
  240. QueryDict.fromkeys(['key1', 'key2', 'key3'], value='val'),
  241. QueryDict('key1=val&key2=val&key3=val')
  242. )
  243. def test_fromkeys_is_immutable_by_default(self):
  244. # Match behavior of __init__() which is also immutable by default.
  245. q = QueryDict.fromkeys(['key1', 'key2', 'key3'])
  246. with self.assertRaisesMessage(AttributeError, 'This QueryDict instance is immutable'):
  247. q['key4'] = 'nope'
  248. def test_fromkeys_mutable_override(self):
  249. q = QueryDict.fromkeys(['key1', 'key2', 'key3'], mutable=True)
  250. q['key4'] = 'yep'
  251. self.assertEqual(q, QueryDict('key1&key2&key3&key4=yep'))
  252. def test_duplicates_in_fromkeys_iterable(self):
  253. self.assertEqual(QueryDict.fromkeys('xyzzy'), QueryDict('x&y&z&z&y'))
  254. def test_fromkeys_with_nondefault_encoding(self):
  255. key_utf16 = b'\xff\xfe\x8e\x02\xdd\x01\x9e\x02'
  256. value_utf16 = b'\xff\xfe\xdd\x01n\x00l\x00P\x02\x8c\x02'
  257. q = QueryDict.fromkeys([key_utf16], value=value_utf16, encoding='utf-16')
  258. expected = QueryDict('', mutable=True)
  259. expected['ʎǝʞ'] = 'ǝnlɐʌ'
  260. self.assertEqual(q, expected)
  261. def test_fromkeys_empty_iterable(self):
  262. self.assertEqual(QueryDict.fromkeys([]), QueryDict(''))
  263. def test_fromkeys_noniterable(self):
  264. with self.assertRaises(TypeError):
  265. QueryDict.fromkeys(0)
  266. class HttpResponseTests(unittest.TestCase):
  267. def test_headers_type(self):
  268. r = HttpResponse()
  269. # The following tests explicitly test types in addition to values
  270. # because in Python 2 u'foo' == b'foo'.
  271. # ASCII unicode or bytes values are converted to native strings.
  272. r['key'] = 'test'
  273. self.assertEqual(r['key'], str('test'))
  274. self.assertIsInstance(r['key'], str)
  275. r['key'] = 'test'.encode('ascii')
  276. self.assertEqual(r['key'], str('test'))
  277. self.assertIsInstance(r['key'], str)
  278. self.assertIn(b'test', r.serialize_headers())
  279. # Latin-1 unicode or bytes values are also converted to native strings.
  280. r['key'] = 'café'
  281. self.assertEqual(r['key'], force_str('café', 'latin-1'))
  282. self.assertIsInstance(r['key'], str)
  283. r['key'] = 'café'.encode('latin-1')
  284. self.assertEqual(r['key'], force_str('café', 'latin-1'))
  285. self.assertIsInstance(r['key'], str)
  286. self.assertIn('café'.encode('latin-1'), r.serialize_headers())
  287. # Other unicode values are MIME-encoded (there's no way to pass them as bytes).
  288. r['key'] = '†'
  289. self.assertEqual(r['key'], str('=?utf-8?b?4oCg?='))
  290. self.assertIsInstance(r['key'], str)
  291. self.assertIn(b'=?utf-8?b?4oCg?=', r.serialize_headers())
  292. # The response also converts unicode or bytes keys to strings, but requires
  293. # them to contain ASCII
  294. r = HttpResponse()
  295. del r['Content-Type']
  296. r['foo'] = 'bar'
  297. l = list(r.items())
  298. self.assertEqual(len(l), 1)
  299. self.assertEqual(l[0], ('foo', 'bar'))
  300. self.assertIsInstance(l[0][0], str)
  301. r = HttpResponse()
  302. del r['Content-Type']
  303. r[b'foo'] = 'bar'
  304. l = list(r.items())
  305. self.assertEqual(len(l), 1)
  306. self.assertEqual(l[0], ('foo', 'bar'))
  307. self.assertIsInstance(l[0][0], str)
  308. r = HttpResponse()
  309. with self.assertRaises(UnicodeError):
  310. r.__setitem__('føø', 'bar')
  311. with self.assertRaises(UnicodeError):
  312. r.__setitem__('føø'.encode('utf-8'), 'bar')
  313. def test_long_line(self):
  314. # Bug #20889: long lines trigger newlines to be added to headers
  315. # (which is not allowed due to bug #10188)
  316. h = HttpResponse()
  317. f = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz a\xcc\x88'.encode('latin-1')
  318. f = f.decode('utf-8')
  319. h['Content-Disposition'] = 'attachment; filename="%s"' % f
  320. # This one is triggering http://bugs.python.org/issue20747, that is Python
  321. # will itself insert a newline in the header
  322. h['Content-Disposition'] = 'attachment; filename="EdelRot_Blu\u0308te (3)-0.JPG"'
  323. def test_newlines_in_headers(self):
  324. # Bug #10188: Do not allow newlines in headers (CR or LF)
  325. r = HttpResponse()
  326. with self.assertRaises(BadHeaderError):
  327. r.__setitem__('test\rstr', 'test')
  328. with self.assertRaises(BadHeaderError):
  329. r.__setitem__('test\nstr', 'test')
  330. def test_dict_behavior(self):
  331. """
  332. Test for bug #14020: Make HttpResponse.get work like dict.get
  333. """
  334. r = HttpResponse()
  335. self.assertIsNone(r.get('test'))
  336. def test_non_string_content(self):
  337. # Bug 16494: HttpResponse should behave consistently with non-strings
  338. r = HttpResponse(12345)
  339. self.assertEqual(r.content, b'12345')
  340. # test content via property
  341. r = HttpResponse()
  342. r.content = 12345
  343. self.assertEqual(r.content, b'12345')
  344. def test_iter_content(self):
  345. r = HttpResponse(['abc', 'def', 'ghi'])
  346. self.assertEqual(r.content, b'abcdefghi')
  347. # test iter content via property
  348. r = HttpResponse()
  349. r.content = ['idan', 'alex', 'jacob']
  350. self.assertEqual(r.content, b'idanalexjacob')
  351. r = HttpResponse()
  352. r.content = [1, 2, 3]
  353. self.assertEqual(r.content, b'123')
  354. # test odd inputs
  355. r = HttpResponse()
  356. r.content = ['1', '2', 3, '\u079e']
  357. # '\xde\x9e' == unichr(1950).encode('utf-8')
  358. self.assertEqual(r.content, b'123\xde\x9e')
  359. # .content can safely be accessed multiple times.
  360. r = HttpResponse(iter(['hello', 'world']))
  361. self.assertEqual(r.content, r.content)
  362. self.assertEqual(r.content, b'helloworld')
  363. # __iter__ can safely be called multiple times (#20187).
  364. self.assertEqual(b''.join(r), b'helloworld')
  365. self.assertEqual(b''.join(r), b'helloworld')
  366. # Accessing .content still works.
  367. self.assertEqual(r.content, b'helloworld')
  368. # Accessing .content also works if the response was iterated first.
  369. r = HttpResponse(iter(['hello', 'world']))
  370. self.assertEqual(b''.join(r), b'helloworld')
  371. self.assertEqual(r.content, b'helloworld')
  372. # Additional content can be written to the response.
  373. r = HttpResponse(iter(['hello', 'world']))
  374. self.assertEqual(r.content, b'helloworld')
  375. r.write('!')
  376. self.assertEqual(r.content, b'helloworld!')
  377. def test_iterator_isnt_rewound(self):
  378. # Regression test for #13222
  379. r = HttpResponse('abc')
  380. i = iter(r)
  381. self.assertEqual(list(i), [b'abc'])
  382. self.assertEqual(list(i), [])
  383. def test_lazy_content(self):
  384. r = HttpResponse(lazystr('helloworld'))
  385. self.assertEqual(r.content, b'helloworld')
  386. def test_file_interface(self):
  387. r = HttpResponse()
  388. r.write(b"hello")
  389. self.assertEqual(r.tell(), 5)
  390. r.write("привет")
  391. self.assertEqual(r.tell(), 17)
  392. r = HttpResponse(['abc'])
  393. r.write('def')
  394. self.assertEqual(r.tell(), 6)
  395. self.assertEqual(r.content, b'abcdef')
  396. # with Content-Encoding header
  397. r = HttpResponse()
  398. r['Content-Encoding'] = 'winning'
  399. r.write(b'abc')
  400. r.write(b'def')
  401. self.assertEqual(r.content, b'abcdef')
  402. def test_stream_interface(self):
  403. r = HttpResponse('asdf')
  404. self.assertEqual(r.getvalue(), b'asdf')
  405. r = HttpResponse()
  406. self.assertIs(r.writable(), True)
  407. r.writelines(['foo\n', 'bar\n', 'baz\n'])
  408. self.assertEqual(r.content, b'foo\nbar\nbaz\n')
  409. def test_unsafe_redirect(self):
  410. bad_urls = [
  411. 'data:text/html,<script>window.alert("xss")</script>',
  412. 'mailto:test@example.com',
  413. 'file:///etc/passwd',
  414. ]
  415. for url in bad_urls:
  416. with self.assertRaises(SuspiciousOperation):
  417. HttpResponseRedirect(url)
  418. with self.assertRaises(SuspiciousOperation):
  419. HttpResponsePermanentRedirect(url)
  420. class HttpResponseSubclassesTests(SimpleTestCase):
  421. def test_redirect(self):
  422. response = HttpResponseRedirect('/redirected/')
  423. self.assertEqual(response.status_code, 302)
  424. # Test that standard HttpResponse init args can be used
  425. response = HttpResponseRedirect(
  426. '/redirected/',
  427. content='The resource has temporarily moved',
  428. content_type='text/html',
  429. )
  430. self.assertContains(response, 'The resource has temporarily moved', status_code=302)
  431. # Test that url attribute is right
  432. self.assertEqual(response.url, response['Location'])
  433. def test_redirect_lazy(self):
  434. """Make sure HttpResponseRedirect works with lazy strings."""
  435. r = HttpResponseRedirect(lazystr('/redirected/'))
  436. self.assertEqual(r.url, '/redirected/')
  437. def test_redirect_repr(self):
  438. response = HttpResponseRedirect('/redirected/')
  439. expected = '<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/redirected/">'
  440. self.assertEqual(repr(response), expected)
  441. def test_not_modified(self):
  442. response = HttpResponseNotModified()
  443. self.assertEqual(response.status_code, 304)
  444. # 304 responses should not have content/content-type
  445. with self.assertRaises(AttributeError):
  446. response.content = "Hello dear"
  447. self.assertNotIn('content-type', response)
  448. def test_not_allowed(self):
  449. response = HttpResponseNotAllowed(['GET'])
  450. self.assertEqual(response.status_code, 405)
  451. # Test that standard HttpResponse init args can be used
  452. response = HttpResponseNotAllowed(['GET'], content='Only the GET method is allowed', content_type='text/html')
  453. self.assertContains(response, 'Only the GET method is allowed', status_code=405)
  454. def test_not_allowed_repr(self):
  455. response = HttpResponseNotAllowed(['GET', 'OPTIONS'], content_type='text/plain')
  456. expected = '<HttpResponseNotAllowed [GET, OPTIONS] status_code=405, "text/plain">'
  457. self.assertEqual(repr(response), expected)
  458. class JsonResponseTests(SimpleTestCase):
  459. def test_json_response_non_ascii(self):
  460. data = {'key': 'łóżko'}
  461. response = JsonResponse(data)
  462. self.assertEqual(json.loads(response.content.decode()), data)
  463. def test_json_response_raises_type_error_with_default_setting(self):
  464. with self.assertRaisesMessage(
  465. TypeError,
  466. 'In order to allow non-dict objects to be serialized set the '
  467. 'safe parameter to False'
  468. ):
  469. JsonResponse([1, 2, 3])
  470. def test_json_response_text(self):
  471. response = JsonResponse('foobar', safe=False)
  472. self.assertEqual(json.loads(response.content.decode()), 'foobar')
  473. def test_json_response_list(self):
  474. response = JsonResponse(['foo', 'bar'], safe=False)
  475. self.assertEqual(json.loads(response.content.decode()), ['foo', 'bar'])
  476. def test_json_response_uuid(self):
  477. u = uuid.uuid4()
  478. response = JsonResponse(u, safe=False)
  479. self.assertEqual(json.loads(response.content.decode()), str(u))
  480. def test_json_response_custom_encoder(self):
  481. class CustomDjangoJSONEncoder(DjangoJSONEncoder):
  482. def encode(self, o):
  483. return json.dumps({'foo': 'bar'})
  484. response = JsonResponse({}, encoder=CustomDjangoJSONEncoder)
  485. self.assertEqual(json.loads(response.content.decode()), {'foo': 'bar'})
  486. def test_json_response_passing_arguments_to_json_dumps(self):
  487. response = JsonResponse({'foo': 'bar'}, json_dumps_params={'indent': 2})
  488. self.assertEqual(response.content.decode(), '{\n "foo": "bar"\n}')
  489. class StreamingHttpResponseTests(SimpleTestCase):
  490. def test_streaming_response(self):
  491. r = StreamingHttpResponse(iter(['hello', 'world']))
  492. # iterating over the response itself yields bytestring chunks.
  493. chunks = list(r)
  494. self.assertEqual(chunks, [b'hello', b'world'])
  495. for chunk in chunks:
  496. self.assertIsInstance(chunk, six.binary_type)
  497. # and the response can only be iterated once.
  498. self.assertEqual(list(r), [])
  499. # even when a sequence that can be iterated many times, like a list,
  500. # is given as content.
  501. r = StreamingHttpResponse(['abc', 'def'])
  502. self.assertEqual(list(r), [b'abc', b'def'])
  503. self.assertEqual(list(r), [])
  504. # iterating over Unicode strings still yields bytestring chunks.
  505. r.streaming_content = iter(['hello', 'café'])
  506. chunks = list(r)
  507. # '\xc3\xa9' == unichr(233).encode('utf-8')
  508. self.assertEqual(chunks, [b'hello', b'caf\xc3\xa9'])
  509. for chunk in chunks:
  510. self.assertIsInstance(chunk, six.binary_type)
  511. # streaming responses don't have a `content` attribute.
  512. self.assertFalse(hasattr(r, 'content'))
  513. # and you can't accidentally assign to a `content` attribute.
  514. with self.assertRaises(AttributeError):
  515. r.content = 'xyz'
  516. # but they do have a `streaming_content` attribute.
  517. self.assertTrue(hasattr(r, 'streaming_content'))
  518. # that exists so we can check if a response is streaming, and wrap or
  519. # replace the content iterator.
  520. r.streaming_content = iter(['abc', 'def'])
  521. r.streaming_content = (chunk.upper() for chunk in r.streaming_content)
  522. self.assertEqual(list(r), [b'ABC', b'DEF'])
  523. # coercing a streaming response to bytes doesn't return a complete HTTP
  524. # message like a regular response does. it only gives us the headers.
  525. r = StreamingHttpResponse(iter(['hello', 'world']))
  526. self.assertEqual(
  527. six.binary_type(r), b'Content-Type: text/html; charset=utf-8')
  528. # and this won't consume its content.
  529. self.assertEqual(list(r), [b'hello', b'world'])
  530. # additional content cannot be written to the response.
  531. r = StreamingHttpResponse(iter(['hello', 'world']))
  532. with self.assertRaises(Exception):
  533. r.write('!')
  534. # and we can't tell the current position.
  535. with self.assertRaises(Exception):
  536. r.tell()
  537. r = StreamingHttpResponse(iter(['hello', 'world']))
  538. self.assertEqual(r.getvalue(), b'helloworld')
  539. class FileCloseTests(SimpleTestCase):
  540. def setUp(self):
  541. # Disable the request_finished signal during this test
  542. # to avoid interfering with the database connection.
  543. request_finished.disconnect(close_old_connections)
  544. def tearDown(self):
  545. request_finished.connect(close_old_connections)
  546. def test_response(self):
  547. filename = os.path.join(os.path.dirname(upath(__file__)), 'abc.txt')
  548. # file isn't closed until we close the response.
  549. file1 = open(filename)
  550. r = HttpResponse(file1)
  551. self.assertTrue(file1.closed)
  552. r.close()
  553. # when multiple file are assigned as content, make sure they are all
  554. # closed with the response.
  555. file1 = open(filename)
  556. file2 = open(filename)
  557. r = HttpResponse(file1)
  558. r.content = file2
  559. self.assertTrue(file1.closed)
  560. self.assertTrue(file2.closed)
  561. def test_streaming_response(self):
  562. filename = os.path.join(os.path.dirname(upath(__file__)), 'abc.txt')
  563. # file isn't closed until we close the response.
  564. file1 = open(filename)
  565. r = StreamingHttpResponse(file1)
  566. self.assertFalse(file1.closed)
  567. r.close()
  568. self.assertTrue(file1.closed)
  569. # when multiple file are assigned as content, make sure they are all
  570. # closed with the response.
  571. file1 = open(filename)
  572. file2 = open(filename)
  573. r = StreamingHttpResponse(file1)
  574. r.streaming_content = file2
  575. self.assertFalse(file1.closed)
  576. self.assertFalse(file2.closed)
  577. r.close()
  578. self.assertTrue(file1.closed)
  579. self.assertTrue(file2.closed)
  580. class CookieTests(unittest.TestCase):
  581. def test_encode(self):
  582. """
  583. Test that we don't output tricky characters in encoded value
  584. """
  585. c = SimpleCookie()
  586. c['test'] = "An,awkward;value"
  587. self.assertNotIn(";", c.output().rstrip(';')) # IE compat
  588. self.assertNotIn(",", c.output().rstrip(';')) # Safari compat
  589. def test_decode(self):
  590. """
  591. Test that we can still preserve semi-colons and commas
  592. """
  593. c = SimpleCookie()
  594. c['test'] = "An,awkward;value"
  595. c2 = SimpleCookie()
  596. c2.load(c.output()[12:])
  597. self.assertEqual(c['test'].value, c2['test'].value)
  598. c3 = parse_cookie(c.output()[12:])
  599. self.assertEqual(c['test'].value, c3['test'])
  600. def test_decode_2(self):
  601. """
  602. Test that we haven't broken normal encoding
  603. """
  604. c = SimpleCookie()
  605. c['test'] = b"\xf0"
  606. c2 = SimpleCookie()
  607. c2.load(c.output()[12:])
  608. self.assertEqual(c['test'].value, c2['test'].value)
  609. c3 = parse_cookie(c.output()[12:])
  610. self.assertEqual(c['test'].value, c3['test'])
  611. def test_nonstandard_keys(self):
  612. """
  613. Test that a single non-standard cookie name doesn't affect all cookies. Ticket #13007.
  614. """
  615. self.assertIn('good_cookie', parse_cookie('good_cookie=yes;bad:cookie=yes').keys())
  616. def test_repeated_nonstandard_keys(self):
  617. """
  618. Test that a repeated non-standard name doesn't affect all cookies. Ticket #15852
  619. """
  620. self.assertIn('good_cookie', parse_cookie('a:=b; a:=c; good_cookie=yes').keys())
  621. def test_python_cookies(self):
  622. """
  623. Test cases copied from Python's Lib/test/test_http_cookies.py
  624. """
  625. self.assertEqual(parse_cookie('chips=ahoy; vienna=finger'), {'chips': 'ahoy', 'vienna': 'finger'})
  626. # Here parse_cookie() differs from Python's cookie parsing in that it
  627. # treats all semicolons as delimiters, even within quotes.
  628. self.assertEqual(
  629. parse_cookie('keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"'),
  630. {'keebler': '"E=mc2', 'L': '\\"Loves\\"', 'fudge': '\\012', '': '"'}
  631. )
  632. # Illegal cookies that have an '=' char in an unquoted value.
  633. self.assertEqual(parse_cookie('keebler=E=mc2'), {'keebler': 'E=mc2'})
  634. # Cookies with ':' character in their name.
  635. self.assertEqual(parse_cookie('key:term=value:term'), {'key:term': 'value:term'})
  636. # Cookies with '[' and ']'.
  637. self.assertEqual(parse_cookie('a=b; c=[; d=r; f=h'), {'a': 'b', 'c': '[', 'd': 'r', 'f': 'h'})
  638. def test_cookie_edgecases(self):
  639. # Cookies that RFC6265 allows.
  640. self.assertEqual(parse_cookie('a=b; Domain=example.com'), {'a': 'b', 'Domain': 'example.com'})
  641. # parse_cookie() has historically kept only the last cookie with the
  642. # same name.
  643. self.assertEqual(parse_cookie('a=b; h=i; a=c'), {'a': 'c', 'h': 'i'})
  644. def test_invalid_cookies(self):
  645. """
  646. Cookie strings that go against RFC6265 but browsers will send if set
  647. via document.cookie.
  648. """
  649. # Chunks without an equals sign appear as unnamed values per
  650. # https://bugzilla.mozilla.org/show_bug.cgi?id=169091
  651. self.assertIn('django_language', parse_cookie('abc=def; unnamed; django_language=en').keys())
  652. # Even a double quote may be an unamed value.
  653. self.assertEqual(parse_cookie('a=b; "; c=d'), {'a': 'b', '': '"', 'c': 'd'})
  654. # Spaces in names and values, and an equals sign in values.
  655. self.assertEqual(parse_cookie('a b c=d e = f; gh=i'), {'a b c': 'd e = f', 'gh': 'i'})
  656. # More characters the spec forbids.
  657. self.assertEqual(parse_cookie('a b,c<>@:/[]?{}=d " =e,f g'), {'a b,c<>@:/[]?{}': 'd " =e,f g'})
  658. # Unicode characters. The spec only allows ASCII.
  659. self.assertEqual(parse_cookie('saint=André Bessette'), {'saint': force_str('André Bessette')})
  660. # Browsers don't send extra whitespace or semicolons in Cookie headers,
  661. # but parse_cookie() should parse whitespace the same way
  662. # document.cookie parses whitespace.
  663. self.assertEqual(parse_cookie(' = b ; ; = ; c = ; '), {'': 'b', 'c': ''})
  664. def test_httponly_after_load(self):
  665. """
  666. Test that we can use httponly attribute on cookies that we load
  667. """
  668. c = SimpleCookie()
  669. c.load("name=val")
  670. c['name']['httponly'] = True
  671. self.assertTrue(c['name']['httponly'])
  672. def test_load_dict(self):
  673. c = SimpleCookie()
  674. c.load({'name': 'val'})
  675. self.assertEqual(c['name'].value, 'val')
  676. @unittest.skipUnless(six.PY2, "PY3 throws an exception on invalid cookie keys.")
  677. def test_bad_cookie(self):
  678. """
  679. Regression test for #18403
  680. """
  681. r = HttpResponse()
  682. r.set_cookie("a:.b/", 1)
  683. self.assertEqual(len(r.cookies.bad_cookies), 1)
  684. def test_pickle(self):
  685. rawdata = 'Customer="WILE_E_COYOTE"; Path=/acme; Version=1'
  686. expected_output = 'Set-Cookie: %s' % rawdata
  687. C = SimpleCookie()
  688. C.load(rawdata)
  689. self.assertEqual(C.output(), expected_output)
  690. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  691. C1 = pickle.loads(pickle.dumps(C, protocol=proto))
  692. self.assertEqual(C1.output(), expected_output)