tests.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import shutil
  4. import sys
  5. import tempfile
  6. import time
  7. import unittest
  8. from cStringIO import StringIO
  9. from django.conf import settings
  10. from django.core.exceptions import SuspiciousOperation
  11. from django.core.files.base import ContentFile
  12. from django.core.files.images import get_image_dimensions
  13. from django.core.files.storage import FileSystemStorage
  14. from django.core.files.uploadedfile import UploadedFile
  15. from unittest import TestCase
  16. try:
  17. import threading
  18. except ImportError:
  19. import dummy_threading as threading
  20. # Try to import PIL in either of the two ways it can end up installed.
  21. # Checking for the existence of Image is enough for CPython, but
  22. # for PyPy, you need to check for the underlying modules
  23. try:
  24. from PIL import Image, _imaging
  25. except ImportError:
  26. try:
  27. import Image, _imaging
  28. except ImportError:
  29. Image = None
  30. class FileStorageTests(unittest.TestCase):
  31. storage_class = FileSystemStorage
  32. def setUp(self):
  33. self.temp_dir = tempfile.mktemp()
  34. os.makedirs(self.temp_dir)
  35. self.storage = self.storage_class(location=self.temp_dir)
  36. def tearDown(self):
  37. os.rmdir(self.temp_dir)
  38. def test_file_access_options(self):
  39. """
  40. Standard file access options are available, and work as expected.
  41. """
  42. self.failIf(self.storage.exists('storage_test'))
  43. f = self.storage.open('storage_test', 'w')
  44. f.write('storage contents')
  45. f.close()
  46. self.assert_(self.storage.exists('storage_test'))
  47. f = self.storage.open('storage_test', 'r')
  48. self.assertEqual(f.read(), 'storage contents')
  49. f.close()
  50. self.storage.delete('storage_test')
  51. self.failIf(self.storage.exists('storage_test'))
  52. def test_file_storage_prevents_directory_traversal(self):
  53. """
  54. File storage prevents directory traversal (files can only be accessed if
  55. they're below the storage location).
  56. """
  57. self.assertRaises(SuspiciousOperation, self.storage.exists, '..')
  58. self.assertRaises(SuspiciousOperation, self.storage.exists, '/etc/passwd')
  59. class CustomStorage(FileSystemStorage):
  60. def get_available_name(self, name):
  61. """
  62. Append numbers to duplicate files rather than underscores, like Trac.
  63. """
  64. parts = name.split('.')
  65. basename, ext = parts[0], parts[1:]
  66. number = 2
  67. while self.exists(name):
  68. name = '.'.join([basename, str(number)] + ext)
  69. number += 1
  70. return name
  71. class CustomStorageTests(FileStorageTests):
  72. storage_class = CustomStorage
  73. def test_custom_get_available_name(self):
  74. first = self.storage.save('custom_storage', ContentFile('custom contents'))
  75. self.assertEqual(first, 'custom_storage')
  76. second = self.storage.save('custom_storage', ContentFile('more contents'))
  77. self.assertEqual(second, 'custom_storage.2')
  78. self.storage.delete(first)
  79. self.storage.delete(second)
  80. class UnicodeFileNameTests(unittest.TestCase):
  81. def test_unicode_file_names(self):
  82. """
  83. Regression test for #8156: files with unicode names I can't quite figure
  84. out the encoding situation between doctest and this file, but the actual
  85. repr doesn't matter; it just shouldn't return a unicode object.
  86. """
  87. uf = UploadedFile(name=u'¿Cómo?',content_type='text')
  88. self.assertEqual(type(uf.__repr__()), str)
  89. # Tests for a race condition on file saving (#4948).
  90. # This is written in such a way that it'll always pass on platforms
  91. # without threading.
  92. class SlowFile(ContentFile):
  93. def chunks(self):
  94. time.sleep(1)
  95. return super(ContentFile, self).chunks()
  96. class FileSaveRaceConditionTest(TestCase):
  97. def setUp(self):
  98. self.storage_dir = tempfile.mkdtemp()
  99. self.storage = FileSystemStorage(self.storage_dir)
  100. self.thread = threading.Thread(target=self.save_file, args=['conflict'])
  101. def tearDown(self):
  102. shutil.rmtree(self.storage_dir)
  103. def save_file(self, name):
  104. name = self.storage.save(name, SlowFile("Data"))
  105. def test_race_condition(self):
  106. self.thread.start()
  107. name = self.save_file('conflict')
  108. self.thread.join()
  109. self.assert_(self.storage.exists('conflict'))
  110. self.assert_(self.storage.exists('conflict_1'))
  111. self.storage.delete('conflict')
  112. self.storage.delete('conflict_1')
  113. class FileStoragePermissions(TestCase):
  114. def setUp(self):
  115. self.old_perms = settings.FILE_UPLOAD_PERMISSIONS
  116. settings.FILE_UPLOAD_PERMISSIONS = 0666
  117. self.storage_dir = tempfile.mkdtemp()
  118. self.storage = FileSystemStorage(self.storage_dir)
  119. def tearDown(self):
  120. settings.FILE_UPLOAD_PERMISSIONS = self.old_perms
  121. shutil.rmtree(self.storage_dir)
  122. def test_file_upload_permissions(self):
  123. name = self.storage.save("the_file", ContentFile("data"))
  124. actual_mode = os.stat(self.storage.path(name))[0] & 0777
  125. self.assertEqual(actual_mode, 0666)
  126. class FileStoragePathParsing(TestCase):
  127. def setUp(self):
  128. self.storage_dir = tempfile.mkdtemp()
  129. self.storage = FileSystemStorage(self.storage_dir)
  130. def tearDown(self):
  131. shutil.rmtree(self.storage_dir)
  132. def test_directory_with_dot(self):
  133. """Regression test for #9610.
  134. If the directory name contains a dot and the file name doesn't, make
  135. sure we still mangle the file name instead of the directory name.
  136. """
  137. self.storage.save('dotted.path/test', ContentFile("1"))
  138. self.storage.save('dotted.path/test', ContentFile("2"))
  139. self.failIf(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path')))
  140. self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test')))
  141. self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test_1')))
  142. def test_first_character_dot(self):
  143. """
  144. File names with a dot as their first character don't have an extension,
  145. and the underscore should get added to the end.
  146. """
  147. self.storage.save('dotted.path/.test', ContentFile("1"))
  148. self.storage.save('dotted.path/.test', ContentFile("2"))
  149. self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test')))
  150. # Before 2.6, a leading dot was treated as an extension, and so
  151. # underscore gets added to beginning instead of end.
  152. if sys.version_info < (2, 6):
  153. self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/_.test')))
  154. else:
  155. self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test_1')))
  156. if Image is not None:
  157. class DimensionClosingBug(TestCase):
  158. """
  159. Test that get_image_dimensions() properly closes files (#8817)
  160. """
  161. def test_not_closing_of_files(self):
  162. """
  163. Open files passed into get_image_dimensions() should stay opened.
  164. """
  165. empty_io = StringIO()
  166. try:
  167. get_image_dimensions(empty_io)
  168. finally:
  169. self.assert_(not empty_io.closed)
  170. def test_closing_of_filenames(self):
  171. """
  172. get_image_dimensions() called with a filename should closed the file.
  173. """
  174. # We need to inject a modified open() builtin into the images module
  175. # that checks if the file was closed properly if the function is
  176. # called with a filename instead of an file object.
  177. # get_image_dimensions will call our catching_open instead of the
  178. # regular builtin one.
  179. class FileWrapper(object):
  180. _closed = []
  181. def __init__(self, f):
  182. self.f = f
  183. def __getattr__(self, name):
  184. return getattr(self.f, name)
  185. def close(self):
  186. self._closed.append(True)
  187. self.f.close()
  188. def catching_open(*args):
  189. return FileWrapper(open(*args))
  190. from django.core.files import images
  191. images.open = catching_open
  192. try:
  193. get_image_dimensions(os.path.join(os.path.dirname(__file__), "test1.png"))
  194. finally:
  195. del images.open
  196. self.assert_(FileWrapper._closed)