tests.py 9.6 KB

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