PageRenderTime 27ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/google_appengine/lib/django-1.2/tests/regressiontests/file_storage/tests.py

https://bitbucket.org/Liosan/gizapi
Python | 391 lines | 368 code | 5 blank | 18 comment | 8 complexity | 5893c53988b40227d3d0d2dfaab11bc9 MD5 | raw file
Possible License(s): LGPL-2.1, MIT, LGPL-2.0, BSD-3-Clause, GPL-2.0, Apache-2.0
  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, ImproperlyConfigured
  11. from django.core.files.base import ContentFile, File
  12. from django.core.files.images import get_image_dimensions
  13. from django.core.files.storage import FileSystemStorage, get_storage_class
  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 GetStorageClassTests(unittest.TestCase):
  31. def assertRaisesErrorWithMessage(self, error, message, callable,
  32. *args, **kwargs):
  33. self.assertRaises(error, callable, *args, **kwargs)
  34. try:
  35. callable(*args, **kwargs)
  36. except error, e:
  37. self.assertEqual(message, str(e))
  38. def test_get_filesystem_storage(self):
  39. """
  40. get_storage_class returns the class for a storage backend name/path.
  41. """
  42. self.assertEqual(
  43. get_storage_class('django.core.files.storage.FileSystemStorage'),
  44. FileSystemStorage)
  45. def test_get_invalid_storage_module(self):
  46. """
  47. get_storage_class raises an error if the requested import don't exist.
  48. """
  49. self.assertRaisesErrorWithMessage(
  50. ImproperlyConfigured,
  51. "NonExistingStorage isn't a storage module.",
  52. get_storage_class,
  53. 'NonExistingStorage')
  54. def test_get_nonexisting_storage_class(self):
  55. """
  56. get_storage_class raises an error if the requested class don't exist.
  57. """
  58. self.assertRaisesErrorWithMessage(
  59. ImproperlyConfigured,
  60. 'Storage module "django.core.files.storage" does not define a '\
  61. '"NonExistingStorage" class.',
  62. get_storage_class,
  63. 'django.core.files.storage.NonExistingStorage')
  64. def test_get_nonexisting_storage_module(self):
  65. """
  66. get_storage_class raises an error if the requested module don't exist.
  67. """
  68. self.assertRaisesErrorWithMessage(
  69. ImproperlyConfigured,
  70. 'Error importing storage module django.core.files.non_existing_'\
  71. 'storage: "No module named non_existing_storage"',
  72. get_storage_class,
  73. 'django.core.files.non_existing_storage.NonExistingStorage')
  74. class FileStorageTests(unittest.TestCase):
  75. storage_class = FileSystemStorage
  76. def setUp(self):
  77. self.temp_dir = tempfile.mktemp()
  78. os.makedirs(self.temp_dir)
  79. self.storage = self.storage_class(location=self.temp_dir,
  80. base_url='/test_media_url/')
  81. def tearDown(self):
  82. shutil.rmtree(self.temp_dir)
  83. def test_file_access_options(self):
  84. """
  85. Standard file access options are available, and work as expected.
  86. """
  87. self.assertFalse(self.storage.exists('storage_test'))
  88. f = self.storage.open('storage_test', 'w')
  89. f.write('storage contents')
  90. f.close()
  91. self.assert_(self.storage.exists('storage_test'))
  92. f = self.storage.open('storage_test', 'r')
  93. self.assertEqual(f.read(), 'storage contents')
  94. f.close()
  95. self.storage.delete('storage_test')
  96. self.assertFalse(self.storage.exists('storage_test'))
  97. def test_file_save_without_name(self):
  98. """
  99. File storage extracts the filename from the content object if no
  100. name is given explicitly.
  101. """
  102. self.assertFalse(self.storage.exists('test.file'))
  103. f = ContentFile('custom contents')
  104. f.name = 'test.file'
  105. storage_f_name = self.storage.save(None, f)
  106. self.assertEqual(storage_f_name, f.name)
  107. self.assert_(os.path.exists(os.path.join(self.temp_dir, f.name)))
  108. self.storage.delete(storage_f_name)
  109. def test_file_path(self):
  110. """
  111. File storage returns the full path of a file
  112. """
  113. self.assertFalse(self.storage.exists('test.file'))
  114. f = ContentFile('custom contents')
  115. f_name = self.storage.save('test.file', f)
  116. self.assertEqual(self.storage.path(f_name),
  117. os.path.join(self.temp_dir, f_name))
  118. self.storage.delete(f_name)
  119. def test_file_url(self):
  120. """
  121. File storage returns a url to access a given file from the Web.
  122. """
  123. self.assertEqual(self.storage.url('test.file'),
  124. '%s%s' % (self.storage.base_url, 'test.file'))
  125. # should encode special chars except ~!*()'
  126. # like encodeURIComponent() JavaScript function do
  127. self.assertEqual(self.storage.url(r"""~!*()'@#$%^&*abc`+=.file"""),
  128. """/test_media_url/~!*()'%40%23%24%25%5E%26*abc%60%2B%3D.file""")
  129. # should stanslate os path separator(s) to the url path separator
  130. self.assertEqual(self.storage.url("""a/b\\c.file"""),
  131. """/test_media_url/a/b/c.file""")
  132. self.storage.base_url = None
  133. self.assertRaises(ValueError, self.storage.url, 'test.file')
  134. def test_file_with_mixin(self):
  135. """
  136. File storage can get a mixin to extend the functionality of the
  137. returned file.
  138. """
  139. self.assertFalse(self.storage.exists('test.file'))
  140. class TestFileMixin(object):
  141. mixed_in = True
  142. f = ContentFile('custom contents')
  143. f_name = self.storage.save('test.file', f)
  144. self.assert_(isinstance(
  145. self.storage.open('test.file', mixin=TestFileMixin),
  146. TestFileMixin
  147. ))
  148. self.storage.delete('test.file')
  149. def test_listdir(self):
  150. """
  151. File storage returns a tuple containing directories and files.
  152. """
  153. self.assertFalse(self.storage.exists('storage_test_1'))
  154. self.assertFalse(self.storage.exists('storage_test_2'))
  155. self.assertFalse(self.storage.exists('storage_dir_1'))
  156. f = self.storage.save('storage_test_1', ContentFile('custom content'))
  157. f = self.storage.save('storage_test_2', ContentFile('custom content'))
  158. os.mkdir(os.path.join(self.temp_dir, 'storage_dir_1'))
  159. dirs, files = self.storage.listdir('')
  160. self.assertEqual(set(dirs), set([u'storage_dir_1']))
  161. self.assertEqual(set(files),
  162. set([u'storage_test_1', u'storage_test_2']))
  163. self.storage.delete('storage_test_1')
  164. self.storage.delete('storage_test_2')
  165. os.rmdir(os.path.join(self.temp_dir, 'storage_dir_1'))
  166. def test_file_storage_prevents_directory_traversal(self):
  167. """
  168. File storage prevents directory traversal (files can only be accessed if
  169. they're below the storage location).
  170. """
  171. self.assertRaises(SuspiciousOperation, self.storage.exists, '..')
  172. self.assertRaises(SuspiciousOperation, self.storage.exists, '/etc/passwd')
  173. class CustomStorage(FileSystemStorage):
  174. def get_available_name(self, name):
  175. """
  176. Append numbers to duplicate files rather than underscores, like Trac.
  177. """
  178. parts = name.split('.')
  179. basename, ext = parts[0], parts[1:]
  180. number = 2
  181. while self.exists(name):
  182. name = '.'.join([basename, str(number)] + ext)
  183. number += 1
  184. return name
  185. class CustomStorageTests(FileStorageTests):
  186. storage_class = CustomStorage
  187. def test_custom_get_available_name(self):
  188. first = self.storage.save('custom_storage', ContentFile('custom contents'))
  189. self.assertEqual(first, 'custom_storage')
  190. second = self.storage.save('custom_storage', ContentFile('more contents'))
  191. self.assertEqual(second, 'custom_storage.2')
  192. self.storage.delete(first)
  193. self.storage.delete(second)
  194. class UnicodeFileNameTests(unittest.TestCase):
  195. def test_unicode_file_names(self):
  196. """
  197. Regression test for #8156: files with unicode names I can't quite figure
  198. out the encoding situation between doctest and this file, but the actual
  199. repr doesn't matter; it just shouldn't return a unicode object.
  200. """
  201. uf = UploadedFile(name=u'¿Cómo?',content_type='text')
  202. self.assertEqual(type(uf.__repr__()), str)
  203. # Tests for a race condition on file saving (#4948).
  204. # This is written in such a way that it'll always pass on platforms
  205. # without threading.
  206. class SlowFile(ContentFile):
  207. def chunks(self):
  208. time.sleep(1)
  209. return super(ContentFile, self).chunks()
  210. class FileSaveRaceConditionTest(TestCase):
  211. def setUp(self):
  212. self.storage_dir = tempfile.mkdtemp()
  213. self.storage = FileSystemStorage(self.storage_dir)
  214. self.thread = threading.Thread(target=self.save_file, args=['conflict'])
  215. def tearDown(self):
  216. shutil.rmtree(self.storage_dir)
  217. def save_file(self, name):
  218. name = self.storage.save(name, SlowFile("Data"))
  219. def test_race_condition(self):
  220. self.thread.start()
  221. name = self.save_file('conflict')
  222. self.thread.join()
  223. self.assert_(self.storage.exists('conflict'))
  224. self.assert_(self.storage.exists('conflict_1'))
  225. self.storage.delete('conflict')
  226. self.storage.delete('conflict_1')
  227. class FileStoragePermissions(TestCase):
  228. def setUp(self):
  229. self.old_perms = settings.FILE_UPLOAD_PERMISSIONS
  230. settings.FILE_UPLOAD_PERMISSIONS = 0666
  231. self.storage_dir = tempfile.mkdtemp()
  232. self.storage = FileSystemStorage(self.storage_dir)
  233. def tearDown(self):
  234. settings.FILE_UPLOAD_PERMISSIONS = self.old_perms
  235. shutil.rmtree(self.storage_dir)
  236. def test_file_upload_permissions(self):
  237. name = self.storage.save("the_file", ContentFile("data"))
  238. actual_mode = os.stat(self.storage.path(name))[0] & 0777
  239. self.assertEqual(actual_mode, 0666)
  240. class FileStoragePathParsing(TestCase):
  241. def setUp(self):
  242. self.storage_dir = tempfile.mkdtemp()
  243. self.storage = FileSystemStorage(self.storage_dir)
  244. def tearDown(self):
  245. shutil.rmtree(self.storage_dir)
  246. def test_directory_with_dot(self):
  247. """Regression test for #9610.
  248. If the directory name contains a dot and the file name doesn't, make
  249. sure we still mangle the file name instead of the directory name.
  250. """
  251. self.storage.save('dotted.path/test', ContentFile("1"))
  252. self.storage.save('dotted.path/test', ContentFile("2"))
  253. self.assertFalse(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path')))
  254. self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test')))
  255. self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test_1')))
  256. def test_first_character_dot(self):
  257. """
  258. File names with a dot as their first character don't have an extension,
  259. and the underscore should get added to the end.
  260. """
  261. self.storage.save('dotted.path/.test', ContentFile("1"))
  262. self.storage.save('dotted.path/.test', ContentFile("2"))
  263. self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test')))
  264. # Before 2.6, a leading dot was treated as an extension, and so
  265. # underscore gets added to beginning instead of end.
  266. if sys.version_info < (2, 6):
  267. self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/_1.test')))
  268. else:
  269. self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test_1')))
  270. if Image is not None:
  271. class DimensionClosingBug(TestCase):
  272. """
  273. Test that get_image_dimensions() properly closes files (#8817)
  274. """
  275. def test_not_closing_of_files(self):
  276. """
  277. Open files passed into get_image_dimensions() should stay opened.
  278. """
  279. empty_io = StringIO()
  280. try:
  281. get_image_dimensions(empty_io)
  282. finally:
  283. self.assert_(not empty_io.closed)
  284. def test_closing_of_filenames(self):
  285. """
  286. get_image_dimensions() called with a filename should closed the file.
  287. """
  288. # We need to inject a modified open() builtin into the images module
  289. # that checks if the file was closed properly if the function is
  290. # called with a filename instead of an file object.
  291. # get_image_dimensions will call our catching_open instead of the
  292. # regular builtin one.
  293. class FileWrapper(object):
  294. _closed = []
  295. def __init__(self, f):
  296. self.f = f
  297. def __getattr__(self, name):
  298. return getattr(self.f, name)
  299. def close(self):
  300. self._closed.append(True)
  301. self.f.close()
  302. def catching_open(*args):
  303. return FileWrapper(open(*args))
  304. from django.core.files import images
  305. images.open = catching_open
  306. try:
  307. get_image_dimensions(os.path.join(os.path.dirname(__file__), "test1.png"))
  308. finally:
  309. del images.open
  310. self.assert_(FileWrapper._closed)
  311. class InconsistentGetImageDimensionsBug(TestCase):
  312. """
  313. Test that get_image_dimensions() works properly after various calls using a file handler (#11158)
  314. """
  315. def test_multiple_calls(self):
  316. """
  317. Multiple calls of get_image_dimensions() should return the same size.
  318. """
  319. from django.core.files.images import ImageFile
  320. img_path = os.path.join(os.path.dirname(__file__), "test.png")
  321. image = ImageFile(open(img_path, 'rb'))
  322. image_pil = Image.open(img_path)
  323. size_1, size_2 = get_image_dimensions(image), get_image_dimensions(image)
  324. self.assertEqual(image_pil.size, size_1)
  325. self.assertEqual(size_1, size_2)