tests.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  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 smart_str
  23. from django.utils.functional import lazystr
  24. class QueryDictTests(unittest.TestCase):
  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.assertEqual(q.has_key('foo'), False)
  55. self.assertEqual('foo' in q, False)
  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.assertEqual(q.has_key('vote'), True)
  176. self.assertEqual('vote' in q, True)
  177. if six.PY2:
  178. self.assertEqual(q.has_key('foo'), False)
  179. self.assertEqual('foo' in q, False)
  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, True)
  212. q = QueryDict(str('a=b&c=d'))
  213. q1 = pickle.loads(pickle.dumps(q, 2))
  214. self.assertEqual(q == q1, True)
  215. q = QueryDict(str('a=b&c=d&a=1'))
  216. q1 = pickle.loads(pickle.dumps(q, 2))
  217. self.assertEqual(q == q1, True)
  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. class HttpResponseTests(unittest.TestCase):
  237. def test_headers_type(self):
  238. r = HttpResponse()
  239. # The following tests explicitly test types in addition to values
  240. # because in Python 2 u'foo' == b'foo'.
  241. # ASCII unicode or bytes values are converted to native strings.
  242. r['key'] = 'test'
  243. self.assertEqual(r['key'], str('test'))
  244. self.assertIsInstance(r['key'], str)
  245. r['key'] = 'test'.encode('ascii')
  246. self.assertEqual(r['key'], str('test'))
  247. self.assertIsInstance(r['key'], str)
  248. self.assertIn(b'test', r.serialize_headers())
  249. # Latin-1 unicode or bytes values are also converted to native strings.
  250. r['key'] = 'café'
  251. self.assertEqual(r['key'], smart_str('café', 'latin-1'))
  252. self.assertIsInstance(r['key'], str)
  253. r['key'] = 'café'.encode('latin-1')
  254. self.assertEqual(r['key'], smart_str('café', 'latin-1'))
  255. self.assertIsInstance(r['key'], str)
  256. self.assertIn('café'.encode('latin-1'), r.serialize_headers())
  257. # Other unicode values are MIME-encoded (there's no way to pass them as bytes).
  258. r['key'] = '†'
  259. self.assertEqual(r['key'], str('=?utf-8?b?4oCg?='))
  260. self.assertIsInstance(r['key'], str)
  261. self.assertIn(b'=?utf-8?b?4oCg?=', r.serialize_headers())
  262. # The response also converts unicode or bytes keys to strings, but requires
  263. # them to contain ASCII
  264. r = HttpResponse()
  265. del r['Content-Type']
  266. r['foo'] = 'bar'
  267. l = list(r.items())
  268. self.assertEqual(len(l), 1)
  269. self.assertEqual(l[0], ('foo', 'bar'))
  270. self.assertIsInstance(l[0][0], str)
  271. r = HttpResponse()
  272. del r['Content-Type']
  273. r[b'foo'] = 'bar'
  274. l = list(r.items())
  275. self.assertEqual(len(l), 1)
  276. self.assertEqual(l[0], ('foo', 'bar'))
  277. self.assertIsInstance(l[0][0], str)
  278. r = HttpResponse()
  279. with self.assertRaises(UnicodeError):
  280. r.__setitem__('føø', 'bar')
  281. with self.assertRaises(UnicodeError):
  282. r.__setitem__('føø'.encode('utf-8'), 'bar')
  283. def test_long_line(self):
  284. # Bug #20889: long lines trigger newlines to be added to headers
  285. # (which is not allowed due to bug #10188)
  286. h = HttpResponse()
  287. f = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz a\xcc\x88'.encode('latin-1')
  288. f = f.decode('utf-8')
  289. h['Content-Disposition'] = 'attachment; filename="%s"' % f
  290. # This one is triggering http://bugs.python.org/issue20747, that is Python
  291. # will itself insert a newline in the header
  292. h['Content-Disposition'] = 'attachment; filename="EdelRot_Blu\u0308te (3)-0.JPG"'
  293. def test_newlines_in_headers(self):
  294. # Bug #10188: Do not allow newlines in headers (CR or LF)
  295. r = HttpResponse()
  296. with self.assertRaises(BadHeaderError):
  297. r.__setitem__('test\rstr', 'test')
  298. with self.assertRaises(BadHeaderError):
  299. r.__setitem__('test\nstr', 'test')
  300. def test_dict_behavior(self):
  301. """
  302. Test for bug #14020: Make HttpResponse.get work like dict.get
  303. """
  304. r = HttpResponse()
  305. self.assertEqual(r.get('test'), None)
  306. def test_non_string_content(self):
  307. # Bug 16494: HttpResponse should behave consistently with non-strings
  308. r = HttpResponse(12345)
  309. self.assertEqual(r.content, b'12345')
  310. # test content via property
  311. r = HttpResponse()
  312. r.content = 12345
  313. self.assertEqual(r.content, b'12345')
  314. def test_iter_content(self):
  315. r = HttpResponse(['abc', 'def', 'ghi'])
  316. self.assertEqual(r.content, b'abcdefghi')
  317. # test iter content via property
  318. r = HttpResponse()
  319. r.content = ['idan', 'alex', 'jacob']
  320. self.assertEqual(r.content, b'idanalexjacob')
  321. r = HttpResponse()
  322. r.content = [1, 2, 3]
  323. self.assertEqual(r.content, b'123')
  324. # test odd inputs
  325. r = HttpResponse()
  326. r.content = ['1', '2', 3, '\u079e']
  327. # '\xde\x9e' == unichr(1950).encode('utf-8')
  328. self.assertEqual(r.content, b'123\xde\x9e')
  329. # .content can safely be accessed multiple times.
  330. r = HttpResponse(iter(['hello', 'world']))
  331. self.assertEqual(r.content, r.content)
  332. self.assertEqual(r.content, b'helloworld')
  333. # __iter__ can safely be called multiple times (#20187).
  334. self.assertEqual(b''.join(r), b'helloworld')
  335. self.assertEqual(b''.join(r), b'helloworld')
  336. # Accessing .content still works.
  337. self.assertEqual(r.content, b'helloworld')
  338. # Accessing .content also works if the response was iterated first.
  339. r = HttpResponse(iter(['hello', 'world']))
  340. self.assertEqual(b''.join(r), b'helloworld')
  341. self.assertEqual(r.content, b'helloworld')
  342. # Additional content can be written to the response.
  343. r = HttpResponse(iter(['hello', 'world']))
  344. self.assertEqual(r.content, b'helloworld')
  345. r.write('!')
  346. self.assertEqual(r.content, b'helloworld!')
  347. def test_iterator_isnt_rewound(self):
  348. # Regression test for #13222
  349. r = HttpResponse('abc')
  350. i = iter(r)
  351. self.assertEqual(list(i), [b'abc'])
  352. self.assertEqual(list(i), [])
  353. def test_lazy_content(self):
  354. r = HttpResponse(lazystr('helloworld'))
  355. self.assertEqual(r.content, b'helloworld')
  356. def test_file_interface(self):
  357. r = HttpResponse()
  358. r.write(b"hello")
  359. self.assertEqual(r.tell(), 5)
  360. r.write("привет")
  361. self.assertEqual(r.tell(), 17)
  362. r = HttpResponse(['abc'])
  363. r.write('def')
  364. self.assertEqual(r.tell(), 6)
  365. self.assertEqual(r.content, b'abcdef')
  366. # with Content-Encoding header
  367. r = HttpResponse()
  368. r['Content-Encoding'] = 'winning'
  369. r.write(b'abc')
  370. r.write(b'def')
  371. self.assertEqual(r.content, b'abcdef')
  372. def test_stream_interface(self):
  373. r = HttpResponse('asdf')
  374. self.assertEqual(r.getvalue(), b'asdf')
  375. r = HttpResponse()
  376. self.assertEqual(r.writable(), True)
  377. r.writelines(['foo\n', 'bar\n', 'baz\n'])
  378. self.assertEqual(r.content, b'foo\nbar\nbaz\n')
  379. def test_unsafe_redirect(self):
  380. bad_urls = [
  381. 'data:text/html,<script>window.alert("xss")</script>',
  382. 'mailto:test@example.com',
  383. 'file:///etc/passwd',
  384. ]
  385. for url in bad_urls:
  386. with self.assertRaises(SuspiciousOperation):
  387. HttpResponseRedirect(url)
  388. with self.assertRaises(SuspiciousOperation):
  389. HttpResponsePermanentRedirect(url)
  390. class HttpResponseSubclassesTests(SimpleTestCase):
  391. def test_redirect(self):
  392. response = HttpResponseRedirect('/redirected/')
  393. self.assertEqual(response.status_code, 302)
  394. # Test that standard HttpResponse init args can be used
  395. response = HttpResponseRedirect('/redirected/',
  396. content='The resource has temporarily moved',
  397. content_type='text/html')
  398. self.assertContains(response, 'The resource has temporarily moved', status_code=302)
  399. # Test that url attribute is right
  400. self.assertEqual(response.url, response['Location'])
  401. def test_redirect_lazy(self):
  402. """Make sure HttpResponseRedirect works with lazy strings."""
  403. r = HttpResponseRedirect(lazystr('/redirected/'))
  404. self.assertEqual(r.url, '/redirected/')
  405. def test_redirect_repr(self):
  406. response = HttpResponseRedirect('/redirected/')
  407. expected = '<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/redirected/">'
  408. self.assertEqual(repr(response), expected)
  409. def test_not_modified(self):
  410. response = HttpResponseNotModified()
  411. self.assertEqual(response.status_code, 304)
  412. # 304 responses should not have content/content-type
  413. with self.assertRaises(AttributeError):
  414. response.content = "Hello dear"
  415. self.assertNotIn('content-type', response)
  416. def test_not_allowed(self):
  417. response = HttpResponseNotAllowed(['GET'])
  418. self.assertEqual(response.status_code, 405)
  419. # Test that standard HttpResponse init args can be used
  420. response = HttpResponseNotAllowed(['GET'],
  421. content='Only the GET method is allowed',
  422. content_type='text/html')
  423. self.assertContains(response, 'Only the GET method is allowed', status_code=405)
  424. def test_not_allowed_repr(self):
  425. response = HttpResponseNotAllowed(['GET', 'OPTIONS'], content_type='text/plain')
  426. expected = '<HttpResponseNotAllowed [GET, OPTIONS] status_code=405, "text/plain">'
  427. self.assertEqual(repr(response), expected)
  428. class JsonResponseTests(SimpleTestCase):
  429. def test_json_response_non_ascii(self):
  430. data = {'key': 'łóżko'}
  431. response = JsonResponse(data)
  432. self.assertEqual(json.loads(response.content.decode()), data)
  433. def test_json_response_raises_type_error_with_default_setting(self):
  434. with self.assertRaisesMessage(
  435. TypeError,
  436. 'In order to allow non-dict objects to be serialized set the '
  437. 'safe parameter to False'
  438. ):
  439. JsonResponse([1, 2, 3])
  440. def test_json_response_text(self):
  441. response = JsonResponse('foobar', safe=False)
  442. self.assertEqual(json.loads(response.content.decode()), 'foobar')
  443. def test_json_response_list(self):
  444. response = JsonResponse(['foo', 'bar'], safe=False)
  445. self.assertEqual(json.loads(response.content.decode()), ['foo', 'bar'])
  446. def test_json_response_uuid(self):
  447. u = uuid.uuid4()
  448. response = JsonResponse(u, safe=False)
  449. self.assertEqual(json.loads(response.content.decode()), str(u))
  450. def test_json_response_custom_encoder(self):
  451. class CustomDjangoJSONEncoder(DjangoJSONEncoder):
  452. def encode(self, o):
  453. return json.dumps({'foo': 'bar'})
  454. response = JsonResponse({}, encoder=CustomDjangoJSONEncoder)
  455. self.assertEqual(json.loads(response.content.decode()), {'foo': 'bar'})
  456. def test_json_response_passing_arguments_to_json_dumps(self):
  457. response = JsonResponse({'foo': 'bar'}, json_dumps_params={'indent': 2})
  458. self.assertEqual(response.content.decode(), '{\n "foo": "bar"\n}')
  459. class StreamingHttpResponseTests(SimpleTestCase):
  460. def test_streaming_response(self):
  461. r = StreamingHttpResponse(iter(['hello', 'world']))
  462. # iterating over the response itself yields bytestring chunks.
  463. chunks = list(r)
  464. self.assertEqual(chunks, [b'hello', b'world'])
  465. for chunk in chunks:
  466. self.assertIsInstance(chunk, six.binary_type)
  467. # and the response can only be iterated once.
  468. self.assertEqual(list(r), [])
  469. # even when a sequence that can be iterated many times, like a list,
  470. # is given as content.
  471. r = StreamingHttpResponse(['abc', 'def'])
  472. self.assertEqual(list(r), [b'abc', b'def'])
  473. self.assertEqual(list(r), [])
  474. # iterating over Unicode strings still yields bytestring chunks.
  475. r.streaming_content = iter(['hello', 'café'])
  476. chunks = list(r)
  477. # '\xc3\xa9' == unichr(233).encode('utf-8')
  478. self.assertEqual(chunks, [b'hello', b'caf\xc3\xa9'])
  479. for chunk in chunks:
  480. self.assertIsInstance(chunk, six.binary_type)
  481. # streaming responses don't have a `content` attribute.
  482. self.assertFalse(hasattr(r, 'content'))
  483. # and you can't accidentally assign to a `content` attribute.
  484. with self.assertRaises(AttributeError):
  485. r.content = 'xyz'
  486. # but they do have a `streaming_content` attribute.
  487. self.assertTrue(hasattr(r, 'streaming_content'))
  488. # that exists so we can check if a response is streaming, and wrap or
  489. # replace the content iterator.
  490. r.streaming_content = iter(['abc', 'def'])
  491. r.streaming_content = (chunk.upper() for chunk in r.streaming_content)
  492. self.assertEqual(list(r), [b'ABC', b'DEF'])
  493. # coercing a streaming response to bytes doesn't return a complete HTTP
  494. # message like a regular response does. it only gives us the headers.
  495. r = StreamingHttpResponse(iter(['hello', 'world']))
  496. self.assertEqual(
  497. six.binary_type(r), b'Content-Type: text/html; charset=utf-8')
  498. # and this won't consume its content.
  499. self.assertEqual(list(r), [b'hello', b'world'])
  500. # additional content cannot be written to the response.
  501. r = StreamingHttpResponse(iter(['hello', 'world']))
  502. with self.assertRaises(Exception):
  503. r.write('!')
  504. # and we can't tell the current position.
  505. with self.assertRaises(Exception):
  506. r.tell()
  507. r = StreamingHttpResponse(iter(['hello', 'world']))
  508. self.assertEqual(r.getvalue(), b'helloworld')
  509. class FileCloseTests(SimpleTestCase):
  510. def setUp(self):
  511. # Disable the request_finished signal during this test
  512. # to avoid interfering with the database connection.
  513. request_finished.disconnect(close_old_connections)
  514. def tearDown(self):
  515. request_finished.connect(close_old_connections)
  516. def test_response(self):
  517. filename = os.path.join(os.path.dirname(upath(__file__)), 'abc.txt')
  518. # file isn't closed until we close the response.
  519. file1 = open(filename)
  520. r = HttpResponse(file1)
  521. self.assertTrue(file1.closed)
  522. r.close()
  523. # when multiple file are assigned as content, make sure they are all
  524. # closed with the response.
  525. file1 = open(filename)
  526. file2 = open(filename)
  527. r = HttpResponse(file1)
  528. r.content = file2
  529. self.assertTrue(file1.closed)
  530. self.assertTrue(file2.closed)
  531. def test_streaming_response(self):
  532. filename = os.path.join(os.path.dirname(upath(__file__)), 'abc.txt')
  533. # file isn't closed until we close the response.
  534. file1 = open(filename)
  535. r = StreamingHttpResponse(file1)
  536. self.assertFalse(file1.closed)
  537. r.close()
  538. self.assertTrue(file1.closed)
  539. # when multiple file are assigned as content, make sure they are all
  540. # closed with the response.
  541. file1 = open(filename)
  542. file2 = open(filename)
  543. r = StreamingHttpResponse(file1)
  544. r.streaming_content = file2
  545. self.assertFalse(file1.closed)
  546. self.assertFalse(file2.closed)
  547. r.close()
  548. self.assertTrue(file1.closed)
  549. self.assertTrue(file2.closed)
  550. class CookieTests(unittest.TestCase):
  551. def test_encode(self):
  552. """
  553. Test that we don't output tricky characters in encoded value
  554. """
  555. c = SimpleCookie()
  556. c['test'] = "An,awkward;value"
  557. self.assertNotIn(";", c.output().rstrip(';')) # IE compat
  558. self.assertNotIn(",", c.output().rstrip(';')) # Safari compat
  559. def test_decode(self):
  560. """
  561. Test that we can still preserve semi-colons and commas
  562. """
  563. c = SimpleCookie()
  564. c['test'] = "An,awkward;value"
  565. c2 = SimpleCookie()
  566. c2.load(c.output()[12:])
  567. self.assertEqual(c['test'].value, c2['test'].value)
  568. def test_decode_2(self):
  569. """
  570. Test that we haven't broken normal encoding
  571. """
  572. c = SimpleCookie()
  573. c['test'] = b"\xf0"
  574. c2 = SimpleCookie()
  575. c2.load(c.output()[12:])
  576. self.assertEqual(c['test'].value, c2['test'].value)
  577. def test_nonstandard_keys(self):
  578. """
  579. Test that a single non-standard cookie name doesn't affect all cookies. Ticket #13007.
  580. """
  581. self.assertIn('good_cookie', parse_cookie('good_cookie=yes;bad:cookie=yes').keys())
  582. def test_repeated_nonstandard_keys(self):
  583. """
  584. Test that a repeated non-standard name doesn't affect all cookies. Ticket #15852
  585. """
  586. self.assertIn('good_cookie', parse_cookie('a:=b; a:=c; good_cookie=yes').keys())
  587. def test_httponly_after_load(self):
  588. """
  589. Test that we can use httponly attribute on cookies that we load
  590. """
  591. c = SimpleCookie()
  592. c.load("name=val")
  593. c['name']['httponly'] = True
  594. self.assertTrue(c['name']['httponly'])
  595. def test_load_dict(self):
  596. c = SimpleCookie()
  597. c.load({'name': 'val'})
  598. self.assertEqual(c['name'].value, 'val')
  599. @unittest.skipUnless(six.PY2, "PY3 throws an exception on invalid cookie keys.")
  600. def test_bad_cookie(self):
  601. """
  602. Regression test for #18403
  603. """
  604. r = HttpResponse()
  605. r.set_cookie("a:.b/", 1)
  606. self.assertEqual(len(r.cookies.bad_cookies), 1)
  607. def test_pickle(self):
  608. rawdata = 'Customer="WILE_E_COYOTE"; Path=/acme; Version=1'
  609. expected_output = 'Set-Cookie: %s' % rawdata
  610. C = SimpleCookie()
  611. C.load(rawdata)
  612. self.assertEqual(C.output(), expected_output)
  613. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  614. C1 = pickle.loads(pickle.dumps(C, protocol=proto))
  615. self.assertEqual(C1.output(), expected_output)