tests.py 15 KB

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