tests.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. #! -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import base64
  4. import errno
  5. import hashlib
  6. import json
  7. import os
  8. import shutil
  9. import tempfile as sys_tempfile
  10. import unittest
  11. from django.core.files import temp as tempfile
  12. from django.core.files.uploadedfile import SimpleUploadedFile
  13. from django.http.multipartparser import MultiPartParser, parse_header
  14. from django.test import TestCase, client
  15. from django.test import override_settings
  16. from django.utils.encoding import force_bytes
  17. from django.utils.http import urlquote
  18. from django.utils.six import BytesIO, PY2, StringIO
  19. from . import uploadhandler
  20. from .models import FileModel
  21. UNICODE_FILENAME = 'test-0123456789_中文_Orléans.jpg'
  22. MEDIA_ROOT = sys_tempfile.mkdtemp(dir=os.environ['DJANGO_TEST_TEMP_DIR'])
  23. UPLOAD_TO = os.path.join(MEDIA_ROOT, 'test_upload')
  24. @override_settings(MEDIA_ROOT=MEDIA_ROOT, ROOT_URLCONF='file_uploads.urls', MIDDLEWARE_CLASSES=[])
  25. class FileUploadTests(TestCase):
  26. @classmethod
  27. def setUpClass(cls):
  28. super(FileUploadTests, cls).setUpClass()
  29. if not os.path.isdir(MEDIA_ROOT):
  30. os.makedirs(MEDIA_ROOT)
  31. @classmethod
  32. def tearDownClass(cls):
  33. shutil.rmtree(MEDIA_ROOT)
  34. super(FileUploadTests, cls).tearDownClass()
  35. def test_simple_upload(self):
  36. with open(__file__, 'rb') as fp:
  37. post_data = {
  38. 'name': 'Ringo',
  39. 'file_field': fp,
  40. }
  41. response = self.client.post('/upload/', post_data)
  42. self.assertEqual(response.status_code, 200)
  43. def test_large_upload(self):
  44. tdir = tempfile.gettempdir()
  45. file = tempfile.NamedTemporaryFile
  46. with file(suffix=".file1", dir=tdir) as file1, file(suffix=".file2", dir=tdir) as file2:
  47. file1.write(b'a' * (2 ** 21))
  48. file1.seek(0)
  49. file2.write(b'a' * (10 * 2 ** 20))
  50. file2.seek(0)
  51. post_data = {
  52. 'name': 'Ringo',
  53. 'file_field1': file1,
  54. 'file_field2': file2,
  55. }
  56. for key in list(post_data):
  57. try:
  58. post_data[key + '_hash'] = hashlib.sha1(post_data[key].read()).hexdigest()
  59. post_data[key].seek(0)
  60. except AttributeError:
  61. post_data[key + '_hash'] = hashlib.sha1(force_bytes(post_data[key])).hexdigest()
  62. response = self.client.post('/verify/', post_data)
  63. self.assertEqual(response.status_code, 200)
  64. def _test_base64_upload(self, content, encode=base64.b64encode):
  65. payload = client.FakePayload("\r\n".join([
  66. '--' + client.BOUNDARY,
  67. 'Content-Disposition: form-data; name="file"; filename="test.txt"',
  68. 'Content-Type: application/octet-stream',
  69. 'Content-Transfer-Encoding: base64',
  70. '']))
  71. payload.write(b"\r\n" + encode(force_bytes(content)) + b"\r\n")
  72. payload.write('--' + client.BOUNDARY + '--\r\n')
  73. r = {
  74. 'CONTENT_LENGTH': len(payload),
  75. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  76. 'PATH_INFO': "/echo_content/",
  77. 'REQUEST_METHOD': 'POST',
  78. 'wsgi.input': payload,
  79. }
  80. response = self.client.request(**r)
  81. received = json.loads(response.content.decode('utf-8'))
  82. self.assertEqual(received['file'], content)
  83. def test_base64_upload(self):
  84. self._test_base64_upload("This data will be transmitted base64-encoded.")
  85. def test_big_base64_upload(self):
  86. self._test_base64_upload("Big data" * 68000) # > 512Kb
  87. def test_big_base64_newlines_upload(self):
  88. self._test_base64_upload(
  89. # encodestring is a deprecated alias on Python 3
  90. "Big data" * 68000, encode=base64.encodestring if PY2 else base64.encodebytes)
  91. def test_unicode_file_name(self):
  92. tdir = sys_tempfile.mkdtemp()
  93. self.addCleanup(shutil.rmtree, tdir, True)
  94. # This file contains chinese symbols and an accented char in the name.
  95. with open(os.path.join(tdir, UNICODE_FILENAME), 'w+b') as file1:
  96. file1.write(b'b' * (2 ** 10))
  97. file1.seek(0)
  98. post_data = {
  99. 'file_unicode': file1,
  100. }
  101. response = self.client.post('/unicode_name/', post_data)
  102. self.assertEqual(response.status_code, 200)
  103. def test_unicode_file_name_rfc2231(self):
  104. """
  105. Test receiving file upload when filename is encoded with RFC2231
  106. (#22971).
  107. """
  108. payload = client.FakePayload()
  109. payload.write('\r\n'.join([
  110. '--' + client.BOUNDARY,
  111. 'Content-Disposition: form-data; name="file_unicode"; filename*=UTF-8\'\'%s' % urlquote(UNICODE_FILENAME),
  112. 'Content-Type: application/octet-stream',
  113. '',
  114. 'You got pwnd.\r\n',
  115. '\r\n--' + client.BOUNDARY + '--\r\n'
  116. ]))
  117. r = {
  118. 'CONTENT_LENGTH': len(payload),
  119. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  120. 'PATH_INFO': "/unicode_name/",
  121. 'REQUEST_METHOD': 'POST',
  122. 'wsgi.input': payload,
  123. }
  124. response = self.client.request(**r)
  125. self.assertEqual(response.status_code, 200)
  126. def test_unicode_name_rfc2231(self):
  127. """
  128. Test receiving file upload when filename is encoded with RFC2231
  129. (#22971).
  130. """
  131. payload = client.FakePayload()
  132. payload.write('\r\n'.join([
  133. '--' + client.BOUNDARY,
  134. 'Content-Disposition: form-data; name*=UTF-8\'\'file_unicode; filename*=UTF-8\'\'%s' % urlquote(UNICODE_FILENAME),
  135. 'Content-Type: application/octet-stream',
  136. '',
  137. 'You got pwnd.\r\n',
  138. '\r\n--' + client.BOUNDARY + '--\r\n'
  139. ]))
  140. r = {
  141. 'CONTENT_LENGTH': len(payload),
  142. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  143. 'PATH_INFO': "/unicode_name/",
  144. 'REQUEST_METHOD': 'POST',
  145. 'wsgi.input': payload,
  146. }
  147. response = self.client.request(**r)
  148. self.assertEqual(response.status_code, 200)
  149. def test_dangerous_file_names(self):
  150. """Uploaded file names should be sanitized before ever reaching the view."""
  151. # This test simulates possible directory traversal attacks by a
  152. # malicious uploader We have to do some monkeybusiness here to construct
  153. # a malicious payload with an invalid file name (containing os.sep or
  154. # os.pardir). This similar to what an attacker would need to do when
  155. # trying such an attack.
  156. scary_file_names = [
  157. "/tmp/hax0rd.txt", # Absolute path, *nix-style.
  158. "C:\\Windows\\hax0rd.txt", # Absolute path, win-style.
  159. "C:/Windows/hax0rd.txt", # Absolute path, broken-style.
  160. "\\tmp\\hax0rd.txt", # Absolute path, broken in a different way.
  161. "/tmp\\hax0rd.txt", # Absolute path, broken by mixing.
  162. "subdir/hax0rd.txt", # Descendant path, *nix-style.
  163. "subdir\\hax0rd.txt", # Descendant path, win-style.
  164. "sub/dir\\hax0rd.txt", # Descendant path, mixed.
  165. "../../hax0rd.txt", # Relative path, *nix-style.
  166. "..\\..\\hax0rd.txt", # Relative path, win-style.
  167. "../..\\hax0rd.txt" # Relative path, mixed.
  168. ]
  169. payload = client.FakePayload()
  170. for i, name in enumerate(scary_file_names):
  171. payload.write('\r\n'.join([
  172. '--' + client.BOUNDARY,
  173. 'Content-Disposition: form-data; name="file%s"; filename="%s"' % (i, name),
  174. 'Content-Type: application/octet-stream',
  175. '',
  176. 'You got pwnd.\r\n'
  177. ]))
  178. payload.write('\r\n--' + client.BOUNDARY + '--\r\n')
  179. r = {
  180. 'CONTENT_LENGTH': len(payload),
  181. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  182. 'PATH_INFO': "/echo/",
  183. 'REQUEST_METHOD': 'POST',
  184. 'wsgi.input': payload,
  185. }
  186. response = self.client.request(**r)
  187. # The filenames should have been sanitized by the time it got to the view.
  188. received = json.loads(response.content.decode('utf-8'))
  189. for i, name in enumerate(scary_file_names):
  190. got = received["file%s" % i]
  191. self.assertEqual(got, "hax0rd.txt")
  192. def test_filename_overflow(self):
  193. """File names over 256 characters (dangerous on some platforms) get fixed up."""
  194. long_str = 'f' * 300
  195. cases = [
  196. # field name, filename, expected
  197. ('long_filename', '%s.txt' % long_str, '%s.txt' % long_str[:251]),
  198. ('long_extension', 'foo.%s' % long_str, '.%s' % long_str[:254]),
  199. ('no_extension', long_str, long_str[:255]),
  200. ('no_filename', '.%s' % long_str, '.%s' % long_str[:254]),
  201. ('long_everything', '%s.%s' % (long_str, long_str), '.%s' % long_str[:254]),
  202. ]
  203. payload = client.FakePayload()
  204. for name, filename, _ in cases:
  205. payload.write("\r\n".join([
  206. '--' + client.BOUNDARY,
  207. 'Content-Disposition: form-data; name="{}"; filename="{}"',
  208. 'Content-Type: application/octet-stream',
  209. '',
  210. 'Oops.',
  211. ''
  212. ]).format(name, filename))
  213. payload.write('\r\n--' + client.BOUNDARY + '--\r\n')
  214. r = {
  215. 'CONTENT_LENGTH': len(payload),
  216. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  217. 'PATH_INFO': "/echo/",
  218. 'REQUEST_METHOD': 'POST',
  219. 'wsgi.input': payload,
  220. }
  221. response = self.client.request(**r)
  222. result = json.loads(response.content.decode('utf-8'))
  223. for name, _, expected in cases:
  224. got = result[name]
  225. self.assertEqual(expected, got, 'Mismatch for {}'.format(name))
  226. self.assertLess(len(got), 256,
  227. "Got a long file name (%s characters)." % len(got))
  228. def test_file_content(self):
  229. tdir = tempfile.gettempdir()
  230. file = tempfile.NamedTemporaryFile
  231. with file(suffix=".ctype_extra", dir=tdir) as no_content_type, \
  232. file(suffix=".ctype_extra", dir=tdir) as simple_file:
  233. no_content_type.write(b'no content')
  234. no_content_type.seek(0)
  235. simple_file.write(b'text content')
  236. simple_file.seek(0)
  237. simple_file.content_type = 'text/plain'
  238. string_io = StringIO('string content')
  239. bytes_io = BytesIO(b'binary content')
  240. response = self.client.post('/echo_content/', {
  241. 'no_content_type': no_content_type,
  242. 'simple_file': simple_file,
  243. 'string': string_io,
  244. 'binary': bytes_io,
  245. })
  246. received = json.loads(response.content.decode('utf-8'))
  247. self.assertEqual(received['no_content_type'], 'no content')
  248. self.assertEqual(received['simple_file'], 'text content')
  249. self.assertEqual(received['string'], 'string content')
  250. self.assertEqual(received['binary'], 'binary content')
  251. def test_content_type_extra(self):
  252. """Uploaded files may have content type parameters available."""
  253. tdir = tempfile.gettempdir()
  254. file = tempfile.NamedTemporaryFile
  255. with file(suffix=".ctype_extra", dir=tdir) as no_content_type, file(suffix=".ctype_extra", dir=tdir) as simple_file:
  256. no_content_type.write(b'something')
  257. no_content_type.seek(0)
  258. simple_file.write(b'something')
  259. simple_file.seek(0)
  260. simple_file.content_type = 'text/plain; test-key=test_value'
  261. response = self.client.post('/echo_content_type_extra/', {
  262. 'no_content_type': no_content_type,
  263. 'simple_file': simple_file,
  264. })
  265. received = json.loads(response.content.decode('utf-8'))
  266. self.assertEqual(received['no_content_type'], {})
  267. self.assertEqual(received['simple_file'], {'test-key': 'test_value'})
  268. def test_truncated_multipart_handled_gracefully(self):
  269. """
  270. If passed an incomplete multipart message, MultiPartParser does not
  271. attempt to read beyond the end of the stream, and simply will handle
  272. the part that can be parsed gracefully.
  273. """
  274. payload_str = "\r\n".join([
  275. '--' + client.BOUNDARY,
  276. 'Content-Disposition: form-data; name="file"; filename="foo.txt"',
  277. 'Content-Type: application/octet-stream',
  278. '',
  279. 'file contents'
  280. '--' + client.BOUNDARY + '--',
  281. '',
  282. ])
  283. payload = client.FakePayload(payload_str[:-10])
  284. r = {
  285. 'CONTENT_LENGTH': len(payload),
  286. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  287. 'PATH_INFO': '/echo/',
  288. 'REQUEST_METHOD': 'POST',
  289. 'wsgi.input': payload,
  290. }
  291. got = json.loads(self.client.request(**r).content.decode('utf-8'))
  292. self.assertEqual(got, {})
  293. def test_empty_multipart_handled_gracefully(self):
  294. """
  295. If passed an empty multipart message, MultiPartParser will return
  296. an empty QueryDict.
  297. """
  298. r = {
  299. 'CONTENT_LENGTH': 0,
  300. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  301. 'PATH_INFO': '/echo/',
  302. 'REQUEST_METHOD': 'POST',
  303. 'wsgi.input': client.FakePayload(b''),
  304. }
  305. got = json.loads(self.client.request(**r).content.decode('utf-8'))
  306. self.assertEqual(got, {})
  307. def test_custom_upload_handler(self):
  308. file = tempfile.NamedTemporaryFile
  309. with file() as smallfile, file() as bigfile:
  310. # A small file (under the 5M quota)
  311. smallfile.write(b'a' * (2 ** 21))
  312. smallfile.seek(0)
  313. # A big file (over the quota)
  314. bigfile.write(b'a' * (10 * 2 ** 20))
  315. bigfile.seek(0)
  316. # Small file posting should work.
  317. response = self.client.post('/quota/', {'f': smallfile})
  318. got = json.loads(response.content.decode('utf-8'))
  319. self.assertIn('f', got)
  320. # Large files don't go through.
  321. response = self.client.post("/quota/", {'f': bigfile})
  322. got = json.loads(response.content.decode('utf-8'))
  323. self.assertNotIn('f', got)
  324. def test_broken_custom_upload_handler(self):
  325. with tempfile.NamedTemporaryFile() as file:
  326. file.write(b'a' * (2 ** 21))
  327. file.seek(0)
  328. # AttributeError: You cannot alter upload handlers after the upload has been processed.
  329. self.assertRaises(
  330. AttributeError,
  331. self.client.post,
  332. '/quota/broken/',
  333. {'f': file}
  334. )
  335. def test_fileupload_getlist(self):
  336. file = tempfile.NamedTemporaryFile
  337. with file() as file1, file() as file2, file() as file2a:
  338. file1.write(b'a' * (2 ** 23))
  339. file1.seek(0)
  340. file2.write(b'a' * (2 * 2 ** 18))
  341. file2.seek(0)
  342. file2a.write(b'a' * (5 * 2 ** 20))
  343. file2a.seek(0)
  344. response = self.client.post('/getlist_count/', {
  345. 'file1': file1,
  346. 'field1': 'test',
  347. 'field2': 'test3',
  348. 'field3': 'test5',
  349. 'field4': 'test6',
  350. 'field5': 'test7',
  351. 'file2': (file2, file2a)
  352. })
  353. got = json.loads(response.content.decode('utf-8'))
  354. self.assertEqual(got.get('file1'), 1)
  355. self.assertEqual(got.get('file2'), 2)
  356. def test_fileuploads_closed_at_request_end(self):
  357. file = tempfile.NamedTemporaryFile
  358. with file() as f1, file() as f2a, file() as f2b:
  359. response = self.client.post('/fd_closing/t/', {
  360. 'file': f1,
  361. 'file2': (f2a, f2b),
  362. })
  363. request = response.wsgi_request
  364. # Check that the files got actually parsed.
  365. self.assertTrue(hasattr(request, '_files'))
  366. file = request._files['file']
  367. self.assertTrue(file.closed)
  368. files = request._files.getlist('file2')
  369. self.assertTrue(files[0].closed)
  370. self.assertTrue(files[1].closed)
  371. def test_no_parsing_triggered_by_fd_closing(self):
  372. file = tempfile.NamedTemporaryFile
  373. with file() as f1, file() as f2a, file() as f2b:
  374. response = self.client.post('/fd_closing/f/', {
  375. 'file': f1,
  376. 'file2': (f2a, f2b),
  377. })
  378. request = response.wsgi_request
  379. # Check that the fd closing logic doesn't trigger parsing of the stream
  380. self.assertFalse(hasattr(request, '_files'))
  381. def test_file_error_blocking(self):
  382. """
  383. The server should not block when there are upload errors (bug #8622).
  384. This can happen if something -- i.e. an exception handler -- tries to
  385. access POST while handling an error in parsing POST. This shouldn't
  386. cause an infinite loop!
  387. """
  388. class POSTAccessingHandler(client.ClientHandler):
  389. """A handler that'll access POST during an exception."""
  390. def handle_uncaught_exception(self, request, resolver, exc_info):
  391. ret = super(POSTAccessingHandler, self).handle_uncaught_exception(request, resolver, exc_info)
  392. request.POST # evaluate
  393. return ret
  394. # Maybe this is a little more complicated that it needs to be; but if
  395. # the django.test.client.FakePayload.read() implementation changes then
  396. # this test would fail. So we need to know exactly what kind of error
  397. # it raises when there is an attempt to read more than the available bytes:
  398. try:
  399. client.FakePayload(b'a').read(2)
  400. except Exception as err:
  401. reference_error = err
  402. # install the custom handler that tries to access request.POST
  403. self.client.handler = POSTAccessingHandler()
  404. with open(__file__, 'rb') as fp:
  405. post_data = {
  406. 'name': 'Ringo',
  407. 'file_field': fp,
  408. }
  409. try:
  410. self.client.post('/upload_errors/', post_data)
  411. except reference_error.__class__ as err:
  412. self.assertFalse(
  413. str(err) == str(reference_error),
  414. "Caught a repeated exception that'll cause an infinite loop in file uploads."
  415. )
  416. except Exception as err:
  417. # CustomUploadError is the error that should have been raised
  418. self.assertEqual(err.__class__, uploadhandler.CustomUploadError)
  419. def test_filename_case_preservation(self):
  420. """
  421. The storage backend shouldn't mess with the case of the filenames
  422. uploaded.
  423. """
  424. # Synthesize the contents of a file upload with a mixed case filename
  425. # so we don't have to carry such a file in the Django tests source code
  426. # tree.
  427. vars = {'boundary': 'oUrBoUnDaRyStRiNg'}
  428. post_data = [
  429. '--%(boundary)s',
  430. 'Content-Disposition: form-data; name="file_field"; filename="MiXeD_cAsE.txt"',
  431. 'Content-Type: application/octet-stream',
  432. '',
  433. 'file contents\n'
  434. '',
  435. '--%(boundary)s--\r\n',
  436. ]
  437. response = self.client.post(
  438. '/filename_case/',
  439. '\r\n'.join(post_data) % vars,
  440. 'multipart/form-data; boundary=%(boundary)s' % vars
  441. )
  442. self.assertEqual(response.status_code, 200)
  443. id = int(response.content)
  444. obj = FileModel.objects.get(pk=id)
  445. # The name of the file uploaded and the file stored in the server-side
  446. # shouldn't differ.
  447. self.assertEqual(os.path.basename(obj.testfile.path), 'MiXeD_cAsE.txt')
  448. @override_settings(MEDIA_ROOT=MEDIA_ROOT)
  449. class DirectoryCreationTests(TestCase):
  450. """
  451. Tests for error handling during directory creation
  452. via _save_FIELD_file (ticket #6450)
  453. """
  454. @classmethod
  455. def setUpClass(cls):
  456. super(DirectoryCreationTests, cls).setUpClass()
  457. if not os.path.isdir(MEDIA_ROOT):
  458. os.makedirs(MEDIA_ROOT)
  459. @classmethod
  460. def tearDownClass(cls):
  461. shutil.rmtree(MEDIA_ROOT)
  462. super(DirectoryCreationTests, cls).tearDownClass()
  463. def setUp(self):
  464. self.obj = FileModel()
  465. def test_readonly_root(self):
  466. """Permission errors are not swallowed"""
  467. os.chmod(MEDIA_ROOT, 0o500)
  468. self.addCleanup(os.chmod, MEDIA_ROOT, 0o700)
  469. try:
  470. self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', b'x'))
  471. except OSError as err:
  472. self.assertEqual(err.errno, errno.EACCES)
  473. except Exception:
  474. self.fail("OSError [Errno %s] not raised." % errno.EACCES)
  475. def test_not_a_directory(self):
  476. """The correct IOError is raised when the upload directory name exists but isn't a directory"""
  477. # Create a file with the upload directory name
  478. open(UPLOAD_TO, 'wb').close()
  479. self.addCleanup(os.remove, UPLOAD_TO)
  480. with self.assertRaises(IOError) as exc_info:
  481. with SimpleUploadedFile('foo.txt', b'x') as file:
  482. self.obj.testfile.save('foo.txt', file)
  483. # The test needs to be done on a specific string as IOError
  484. # is raised even without the patch (just not early enough)
  485. self.assertEqual(exc_info.exception.args[0],
  486. "%s exists and is not a directory." % UPLOAD_TO)
  487. class MultiParserTests(unittest.TestCase):
  488. def test_empty_upload_handlers(self):
  489. # We're not actually parsing here; just checking if the parser properly
  490. # instantiates with empty upload handlers.
  491. MultiPartParser({
  492. 'CONTENT_TYPE': 'multipart/form-data; boundary=_foo',
  493. 'CONTENT_LENGTH': '1'
  494. }, StringIO('x'), [], 'utf-8')
  495. def test_rfc2231_parsing(self):
  496. test_data = (
  497. (b"Content-Type: application/x-stuff; title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A",
  498. "This is ***fun***"),
  499. (b"Content-Type: application/x-stuff; title*=UTF-8''foo-%c3%a4.html",
  500. "foo-ä.html"),
  501. (b"Content-Type: application/x-stuff; title*=iso-8859-1''foo-%E4.html",
  502. "foo-ä.html"),
  503. )
  504. for raw_line, expected_title in test_data:
  505. parsed = parse_header(raw_line)
  506. self.assertEqual(parsed[1]['title'], expected_title)
  507. def test_rfc2231_wrong_title(self):
  508. """
  509. Test wrongly formatted RFC 2231 headers (missing double single quotes).
  510. Parsing should not crash (#24209).
  511. """
  512. test_data = (
  513. (b"Content-Type: application/x-stuff; title*='This%20is%20%2A%2A%2Afun%2A%2A%2A",
  514. b"'This%20is%20%2A%2A%2Afun%2A%2A%2A"),
  515. (b"Content-Type: application/x-stuff; title*='foo.html",
  516. b"'foo.html"),
  517. (b"Content-Type: application/x-stuff; title*=bar.html",
  518. b"bar.html"),
  519. )
  520. for raw_line, expected_title in test_data:
  521. parsed = parse_header(raw_line)
  522. self.assertEqual(parsed[1]['title'], expected_title)