tests.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import gzip
  4. import os
  5. import struct
  6. import tempfile
  7. import unittest
  8. from io import BytesIO, StringIO, TextIOWrapper
  9. from django.core.files import File
  10. from django.core.files.base import ContentFile
  11. from django.core.files.move import file_move_safe
  12. from django.core.files.temp import NamedTemporaryFile
  13. from django.core.files.uploadedfile import SimpleUploadedFile, UploadedFile
  14. from django.test import mock
  15. from django.utils import six
  16. from django.utils._os import upath
  17. try:
  18. from PIL import Image
  19. except ImportError:
  20. Image = None
  21. else:
  22. from django.core.files import images
  23. class FileTests(unittest.TestCase):
  24. def test_unicode_uploadedfile_name(self):
  25. uf = UploadedFile(name='¿Cómo?', content_type='text')
  26. self.assertIs(type(repr(uf)), str)
  27. def test_unicode_file_name(self):
  28. f = File(None, 'djángö')
  29. self.assertIs(type(repr(f)), str)
  30. def test_context_manager(self):
  31. orig_file = tempfile.TemporaryFile()
  32. base_file = File(orig_file)
  33. with base_file as f:
  34. self.assertIs(base_file, f)
  35. self.assertFalse(f.closed)
  36. self.assertTrue(f.closed)
  37. self.assertTrue(orig_file.closed)
  38. def test_namedtemporaryfile_closes(self):
  39. """
  40. The symbol django.core.files.NamedTemporaryFile is assigned as
  41. a different class on different operating systems. In
  42. any case, the result should minimally mock some of the API of
  43. tempfile.NamedTemporaryFile from the Python standard library.
  44. """
  45. tempfile = NamedTemporaryFile()
  46. self.assertTrue(hasattr(tempfile, "closed"))
  47. self.assertFalse(tempfile.closed)
  48. tempfile.close()
  49. self.assertTrue(tempfile.closed)
  50. def test_file_mode(self):
  51. # Should not set mode to None if it is not present.
  52. # See #14681, stdlib gzip module crashes if mode is set to None
  53. file = SimpleUploadedFile("mode_test.txt", b"content")
  54. self.assertFalse(hasattr(file, 'mode'))
  55. gzip.GzipFile(fileobj=file)
  56. def test_file_iteration(self):
  57. """
  58. File objects should yield lines when iterated over.
  59. Refs #22107.
  60. """
  61. file = File(BytesIO(b'one\ntwo\nthree'))
  62. self.assertEqual(list(file), [b'one\n', b'two\n', b'three'])
  63. def test_file_iteration_windows_newlines(self):
  64. """
  65. #8149 - File objects with \r\n line endings should yield lines
  66. when iterated over.
  67. """
  68. f = File(BytesIO(b'one\r\ntwo\r\nthree'))
  69. self.assertEqual(list(f), [b'one\r\n', b'two\r\n', b'three'])
  70. def test_file_iteration_mac_newlines(self):
  71. """
  72. #8149 - File objects with \r line endings should yield lines
  73. when iterated over.
  74. """
  75. f = File(BytesIO(b'one\rtwo\rthree'))
  76. self.assertEqual(list(f), [b'one\r', b'two\r', b'three'])
  77. def test_file_iteration_mixed_newlines(self):
  78. f = File(BytesIO(b'one\rtwo\nthree\r\nfour'))
  79. self.assertEqual(list(f), [b'one\r', b'two\n', b'three\r\n', b'four'])
  80. def test_file_iteration_with_unix_newline_at_chunk_boundary(self):
  81. f = File(BytesIO(b'one\ntwo\nthree'))
  82. # Set chunk size to create a boundary after \n:
  83. # b'one\n...
  84. # ^
  85. f.DEFAULT_CHUNK_SIZE = 4
  86. self.assertEqual(list(f), [b'one\n', b'two\n', b'three'])
  87. def test_file_iteration_with_windows_newline_at_chunk_boundary(self):
  88. f = File(BytesIO(b'one\r\ntwo\r\nthree'))
  89. # Set chunk size to create a boundary between \r and \n:
  90. # b'one\r\n...
  91. # ^
  92. f.DEFAULT_CHUNK_SIZE = 4
  93. self.assertEqual(list(f), [b'one\r\n', b'two\r\n', b'three'])
  94. def test_file_iteration_with_mac_newline_at_chunk_boundary(self):
  95. f = File(BytesIO(b'one\rtwo\rthree'))
  96. # Set chunk size to create a boundary after \r:
  97. # b'one\r...
  98. # ^
  99. f.DEFAULT_CHUNK_SIZE = 4
  100. self.assertEqual(list(f), [b'one\r', b'two\r', b'three'])
  101. def test_file_iteration_with_text(self):
  102. f = File(StringIO('one\ntwo\nthree'))
  103. self.assertEqual(list(f), ['one\n', 'two\n', 'three'])
  104. def test_readable(self):
  105. with tempfile.TemporaryFile() as temp, File(temp, name='something.txt') as test_file:
  106. self.assertTrue(test_file.readable())
  107. self.assertFalse(test_file.readable())
  108. def test_writable(self):
  109. with tempfile.TemporaryFile() as temp, File(temp, name='something.txt') as test_file:
  110. self.assertTrue(test_file.writable())
  111. self.assertFalse(test_file.writable())
  112. with tempfile.TemporaryFile('rb') as temp, File(temp, name='something.txt') as test_file:
  113. self.assertFalse(test_file.writable())
  114. def test_seekable(self):
  115. with tempfile.TemporaryFile() as temp, File(temp, name='something.txt') as test_file:
  116. self.assertTrue(test_file.seekable())
  117. self.assertFalse(test_file.seekable())
  118. def test_io_wrapper(self):
  119. content = "vive l'été\n"
  120. with tempfile.TemporaryFile() as temp, File(temp, name='something.txt') as test_file:
  121. test_file.write(content.encode('utf-8'))
  122. test_file.seek(0)
  123. wrapper = TextIOWrapper(test_file, 'utf-8', newline='\n')
  124. self.assertEqual(wrapper.read(), content)
  125. # The following seek() call is required on Windows Python 2 when
  126. # switching from reading to writing.
  127. wrapper.seek(0, 2)
  128. wrapper.write(content)
  129. wrapper.seek(0)
  130. self.assertEqual(wrapper.read(), content * 2)
  131. test_file = wrapper.detach()
  132. test_file.seek(0)
  133. self.assertEqual(test_file.read(), (content * 2).encode('utf-8'))
  134. class NoNameFileTestCase(unittest.TestCase):
  135. """
  136. Other examples of unnamed files may be tempfile.SpooledTemporaryFile or
  137. urllib.urlopen()
  138. """
  139. def test_noname_file_default_name(self):
  140. self.assertEqual(File(BytesIO(b'A file with no name')).name, None)
  141. def test_noname_file_get_size(self):
  142. self.assertEqual(File(BytesIO(b'A file with no name')).size, 19)
  143. class ContentFileTestCase(unittest.TestCase):
  144. def test_content_file_default_name(self):
  145. self.assertEqual(ContentFile(b"content").name, None)
  146. def test_content_file_custom_name(self):
  147. """
  148. Test that the constructor of ContentFile accepts 'name' (#16590).
  149. """
  150. name = "I can have a name too!"
  151. self.assertEqual(ContentFile(b"content", name=name).name, name)
  152. def test_content_file_input_type(self):
  153. """
  154. Test that ContentFile can accept both bytes and unicode and that the
  155. retrieved content is of the same type.
  156. """
  157. self.assertIsInstance(ContentFile(b"content").read(), bytes)
  158. if six.PY3:
  159. self.assertIsInstance(ContentFile("español").read(), six.text_type)
  160. else:
  161. self.assertIsInstance(ContentFile("español").read(), bytes)
  162. class DimensionClosingBug(unittest.TestCase):
  163. """
  164. Test that get_image_dimensions() properly closes files (#8817)
  165. """
  166. @unittest.skipUnless(Image, "Pillow not installed")
  167. def test_not_closing_of_files(self):
  168. """
  169. Open files passed into get_image_dimensions() should stay opened.
  170. """
  171. empty_io = BytesIO()
  172. try:
  173. images.get_image_dimensions(empty_io)
  174. finally:
  175. self.assertTrue(not empty_io.closed)
  176. @unittest.skipUnless(Image, "Pillow not installed")
  177. def test_closing_of_filenames(self):
  178. """
  179. get_image_dimensions() called with a filename should closed the file.
  180. """
  181. # We need to inject a modified open() builtin into the images module
  182. # that checks if the file was closed properly if the function is
  183. # called with a filename instead of an file object.
  184. # get_image_dimensions will call our catching_open instead of the
  185. # regular builtin one.
  186. class FileWrapper(object):
  187. _closed = []
  188. def __init__(self, f):
  189. self.f = f
  190. def __getattr__(self, name):
  191. return getattr(self.f, name)
  192. def close(self):
  193. self._closed.append(True)
  194. self.f.close()
  195. def catching_open(*args):
  196. return FileWrapper(open(*args))
  197. images.open = catching_open
  198. try:
  199. images.get_image_dimensions(os.path.join(os.path.dirname(upath(__file__)), "test1.png"))
  200. finally:
  201. del images.open
  202. self.assertTrue(FileWrapper._closed)
  203. class InconsistentGetImageDimensionsBug(unittest.TestCase):
  204. """
  205. Test that get_image_dimensions() works properly after various calls
  206. using a file handler (#11158)
  207. """
  208. @unittest.skipUnless(Image, "Pillow not installed")
  209. def test_multiple_calls(self):
  210. """
  211. Multiple calls of get_image_dimensions() should return the same size.
  212. """
  213. img_path = os.path.join(os.path.dirname(upath(__file__)), "test.png")
  214. with open(img_path, 'rb') as fh:
  215. image = images.ImageFile(fh)
  216. image_pil = Image.open(fh)
  217. size_1 = images.get_image_dimensions(image)
  218. size_2 = images.get_image_dimensions(image)
  219. self.assertEqual(image_pil.size, size_1)
  220. self.assertEqual(size_1, size_2)
  221. @unittest.skipUnless(Image, "Pillow not installed")
  222. def test_bug_19457(self):
  223. """
  224. Regression test for #19457
  225. get_image_dimensions fails on some pngs, while Image.size is working good on them
  226. """
  227. img_path = os.path.join(os.path.dirname(upath(__file__)), "magic.png")
  228. size = images.get_image_dimensions(img_path)
  229. with open(img_path, 'rb') as fh:
  230. self.assertEqual(size, Image.open(fh).size)
  231. @unittest.skipUnless(Image, "Pillow not installed")
  232. class GetImageDimensionsTests(unittest.TestCase):
  233. def test_invalid_image(self):
  234. """
  235. get_image_dimensions() should return (None, None) for the dimensions of
  236. invalid images (#24441).
  237. brokenimg.png is not a valid image and it has been generated by:
  238. $ echo "123" > brokenimg.png
  239. """
  240. img_path = os.path.join(os.path.dirname(upath(__file__)), "brokenimg.png")
  241. with open(img_path, 'rb') as fh:
  242. size = images.get_image_dimensions(fh)
  243. self.assertEqual(size, (None, None))
  244. def test_valid_image(self):
  245. """
  246. get_image_dimensions() should catch struct.error while feeding the PIL
  247. Image parser (#24544).
  248. Emulates the Parser feed error. Since the error is raised on every feed
  249. attempt, the resulting image size should be invalid: (None, None).
  250. """
  251. img_path = os.path.join(os.path.dirname(upath(__file__)), "test.png")
  252. with mock.patch('PIL.ImageFile.Parser.feed', side_effect=struct.error):
  253. with open(img_path, 'rb') as fh:
  254. size = images.get_image_dimensions(fh)
  255. self.assertEqual(size, (None, None))
  256. class FileMoveSafeTests(unittest.TestCase):
  257. def test_file_move_overwrite(self):
  258. handle_a, self.file_a = tempfile.mkstemp()
  259. handle_b, self.file_b = tempfile.mkstemp()
  260. # file_move_safe should raise an IOError exception if destination file exists and allow_overwrite is False
  261. with self.assertRaises(IOError):
  262. file_move_safe(self.file_a, self.file_b, allow_overwrite=False)
  263. # should allow it and continue on if allow_overwrite is True
  264. self.assertIsNone(file_move_safe(self.file_a, self.file_b, allow_overwrite=True))
  265. os.close(handle_a)
  266. os.close(handle_b)
  267. class SpooledTempTests(unittest.TestCase):
  268. def test_in_memory_spooled_temp(self):
  269. with tempfile.SpooledTemporaryFile() as temp:
  270. temp.write(b"foo bar baz quux\n")
  271. django_file = File(temp, name="something.txt")
  272. self.assertEqual(django_file.size, 17)
  273. def test_written_spooled_temp(self):
  274. with tempfile.SpooledTemporaryFile(max_size=4) as temp:
  275. temp.write(b"foo bar baz quux\n")
  276. django_file = File(temp, name="something.txt")
  277. self.assertEqual(django_file.size, 17)