tests.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from io import BytesIO
  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. class NoNameFileTestCase(unittest.TestCase):
  65. """
  66. Other examples of unnamed files may be tempfile.SpooledTemporaryFile or
  67. urllib.urlopen()
  68. """
  69. def test_noname_file_default_name(self):
  70. self.assertEqual(File(BytesIO(b'A file with no name')).name, None)
  71. def test_noname_file_get_size(self):
  72. self.assertEqual(File(BytesIO(b'A file with no name')).size, 19)
  73. class ContentFileTestCase(unittest.TestCase):
  74. def test_content_file_default_name(self):
  75. self.assertEqual(ContentFile(b"content").name, None)
  76. def test_content_file_custom_name(self):
  77. """
  78. Test that the constructor of ContentFile accepts 'name' (#16590).
  79. """
  80. name = "I can have a name too!"
  81. self.assertEqual(ContentFile(b"content", name=name).name, name)
  82. def test_content_file_input_type(self):
  83. """
  84. Test that ContentFile can accept both bytes and unicode and that the
  85. retrieved content is of the same type.
  86. """
  87. self.assertIsInstance(ContentFile(b"content").read(), bytes)
  88. if six.PY3:
  89. self.assertIsInstance(ContentFile("español").read(), six.text_type)
  90. else:
  91. self.assertIsInstance(ContentFile("español").read(), bytes)
  92. class DimensionClosingBug(unittest.TestCase):
  93. """
  94. Test that get_image_dimensions() properly closes files (#8817)
  95. """
  96. @unittest.skipUnless(Image, "Pillow not installed")
  97. def test_not_closing_of_files(self):
  98. """
  99. Open files passed into get_image_dimensions() should stay opened.
  100. """
  101. empty_io = BytesIO()
  102. try:
  103. images.get_image_dimensions(empty_io)
  104. finally:
  105. self.assertTrue(not empty_io.closed)
  106. @unittest.skipUnless(Image, "Pillow not installed")
  107. def test_closing_of_filenames(self):
  108. """
  109. get_image_dimensions() called with a filename should closed the file.
  110. """
  111. # We need to inject a modified open() builtin into the images module
  112. # that checks if the file was closed properly if the function is
  113. # called with a filename instead of an file object.
  114. # get_image_dimensions will call our catching_open instead of the
  115. # regular builtin one.
  116. class FileWrapper(object):
  117. _closed = []
  118. def __init__(self, f):
  119. self.f = f
  120. def __getattr__(self, name):
  121. return getattr(self.f, name)
  122. def close(self):
  123. self._closed.append(True)
  124. self.f.close()
  125. def catching_open(*args):
  126. return FileWrapper(open(*args))
  127. images.open = catching_open
  128. try:
  129. images.get_image_dimensions(os.path.join(os.path.dirname(upath(__file__)), "test1.png"))
  130. finally:
  131. del images.open
  132. self.assertTrue(FileWrapper._closed)
  133. class InconsistentGetImageDimensionsBug(unittest.TestCase):
  134. """
  135. Test that get_image_dimensions() works properly after various calls
  136. using a file handler (#11158)
  137. """
  138. @unittest.skipUnless(Image, "Pillow not installed")
  139. def test_multiple_calls(self):
  140. """
  141. Multiple calls of get_image_dimensions() should return the same size.
  142. """
  143. img_path = os.path.join(os.path.dirname(upath(__file__)), "test.png")
  144. with open(img_path, 'rb') as fh:
  145. image = images.ImageFile(fh)
  146. image_pil = Image.open(fh)
  147. size_1 = images.get_image_dimensions(image)
  148. size_2 = images.get_image_dimensions(image)
  149. self.assertEqual(image_pil.size, size_1)
  150. self.assertEqual(size_1, size_2)
  151. @unittest.skipUnless(Image, "Pillow not installed")
  152. def test_bug_19457(self):
  153. """
  154. Regression test for #19457
  155. get_image_dimensions fails on some pngs, while Image.size is working good on them
  156. """
  157. img_path = os.path.join(os.path.dirname(upath(__file__)), "magic.png")
  158. try:
  159. size = images.get_image_dimensions(img_path)
  160. except zlib.error:
  161. self.fail("Exception raised from get_image_dimensions().")
  162. with open(img_path, 'rb') as fh:
  163. self.assertEqual(size, Image.open(fh).size)
  164. class FileMoveSafeTests(unittest.TestCase):
  165. def test_file_move_overwrite(self):
  166. handle_a, self.file_a = tempfile.mkstemp(dir=os.environ['DJANGO_TEST_TEMP_DIR'])
  167. handle_b, self.file_b = tempfile.mkstemp(dir=os.environ['DJANGO_TEST_TEMP_DIR'])
  168. # file_move_safe should raise an IOError exception if destination file exists and allow_overwrite is False
  169. self.assertRaises(IOError, lambda: file_move_safe(self.file_a, self.file_b, allow_overwrite=False))
  170. # should allow it and continue on if allow_overwrite is True
  171. self.assertIsNone(file_move_safe(self.file_a, self.file_b, allow_overwrite=True))
  172. os.close(handle_a)
  173. os.close(handle_b)