2
0

tests.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. from __future__ import unicode_literals
  2. import os
  3. import gzip
  4. import shutil
  5. import tempfile
  6. import unittest
  7. from django.core.cache import cache
  8. from django.core.files import File
  9. from django.core.files.move import file_move_safe
  10. from django.core.files.base import ContentFile
  11. from django.core.files.uploadedfile import SimpleUploadedFile
  12. from django.core.files.temp import NamedTemporaryFile
  13. from django.test import TestCase
  14. from django.utils.six import StringIO
  15. from .models import Storage, temp_storage, temp_storage_location
  16. class FileStorageTests(TestCase):
  17. def tearDown(self):
  18. shutil.rmtree(temp_storage_location)
  19. def test_files(self):
  20. temp_storage.save('tests/default.txt', ContentFile('default content'))
  21. # Attempting to access a FileField from the class raises a descriptive
  22. # error
  23. self.assertRaises(AttributeError, lambda: Storage.normal)
  24. # An object without a file has limited functionality.
  25. obj1 = Storage()
  26. self.assertEqual(obj1.normal.name, "")
  27. self.assertRaises(ValueError, lambda: obj1.normal.size)
  28. # Saving a file enables full functionality.
  29. obj1.normal.save("django_test.txt", ContentFile("content"))
  30. self.assertEqual(obj1.normal.name, "tests/django_test.txt")
  31. self.assertEqual(obj1.normal.size, 7)
  32. self.assertEqual(obj1.normal.read(), b"content")
  33. obj1.normal.close()
  34. # File objects can be assigned to FileField attributes, but shouldn't
  35. # get committed until the model it's attached to is saved.
  36. obj1.normal = SimpleUploadedFile("assignment.txt", b"content")
  37. dirs, files = temp_storage.listdir("tests")
  38. self.assertEqual(dirs, [])
  39. self.assertEqual(sorted(files), ["default.txt", "django_test.txt"])
  40. obj1.save()
  41. dirs, files = temp_storage.listdir("tests")
  42. self.assertEqual(
  43. sorted(files), ["assignment.txt", "default.txt", "django_test.txt"]
  44. )
  45. # Files can be read in a little at a time, if necessary.
  46. obj1.normal.open()
  47. self.assertEqual(obj1.normal.read(3), b"con")
  48. self.assertEqual(obj1.normal.read(), b"tent")
  49. self.assertEqual(list(obj1.normal.chunks(chunk_size=2)), [b"co", b"nt", b"en", b"t"])
  50. obj1.normal.close()
  51. # Save another file with the same name.
  52. obj2 = Storage()
  53. obj2.normal.save("django_test.txt", ContentFile("more content"))
  54. self.assertEqual(obj2.normal.name, "tests/django_test_1.txt")
  55. self.assertEqual(obj2.normal.size, 12)
  56. # Push the objects into the cache to make sure they pickle properly
  57. cache.set("obj1", obj1)
  58. cache.set("obj2", obj2)
  59. self.assertEqual(cache.get("obj2").normal.name, "tests/django_test_1.txt")
  60. # Deleting an object does not delete the file it uses.
  61. obj2.delete()
  62. obj2.normal.save("django_test.txt", ContentFile("more content"))
  63. self.assertEqual(obj2.normal.name, "tests/django_test_2.txt")
  64. # Multiple files with the same name get _N appended to them.
  65. objs = [Storage() for i in range(3)]
  66. for o in objs:
  67. o.normal.save("multiple_files.txt", ContentFile("Same Content"))
  68. self.assertEqual(
  69. [o.normal.name for o in objs],
  70. ["tests/multiple_files.txt", "tests/multiple_files_1.txt", "tests/multiple_files_2.txt"]
  71. )
  72. for o in objs:
  73. o.delete()
  74. # Default values allow an object to access a single file.
  75. obj3 = Storage.objects.create()
  76. self.assertEqual(obj3.default.name, "tests/default.txt")
  77. self.assertEqual(obj3.default.read(), b"default content")
  78. obj3.default.close()
  79. # But it shouldn't be deleted, even if there are no more objects using
  80. # it.
  81. obj3.delete()
  82. obj3 = Storage()
  83. self.assertEqual(obj3.default.read(), b"default content")
  84. obj3.default.close()
  85. # Verify the fix for #5655, making sure the directory is only
  86. # determined once.
  87. obj4 = Storage()
  88. obj4.random.save("random_file", ContentFile("random content"))
  89. self.assertTrue(obj4.random.name.endswith("/random_file"))
  90. # upload_to can be empty, meaning it does not use subdirectory.
  91. obj5 = Storage()
  92. obj5.empty.save('django_test.txt', ContentFile('more content'))
  93. self.assertEqual(obj5.empty.name, "./django_test.txt")
  94. self.assertEqual(obj5.empty.read(), b"more content")
  95. def test_file_object(self):
  96. # Create sample file
  97. temp_storage.save('tests/example.txt', ContentFile('some content'))
  98. # Load it as python file object
  99. with open(temp_storage.path('tests/example.txt')) as file_obj:
  100. # Save it using storage and read its content
  101. temp_storage.save('tests/file_obj', file_obj)
  102. self.assertTrue(temp_storage.exists('tests/file_obj'))
  103. with temp_storage.open('tests/file_obj') as f:
  104. self.assertEqual(f.read(), b'some content')
  105. def test_stringio(self):
  106. # Test passing StringIO instance as content argument to save
  107. output = StringIO()
  108. output.write('content')
  109. output.seek(0)
  110. # Save it and read written file
  111. temp_storage.save('tests/stringio', output)
  112. self.assertTrue(temp_storage.exists('tests/stringio'))
  113. with temp_storage.open('tests/stringio') as f:
  114. self.assertEqual(f.read(), b'content')
  115. class FileTests(unittest.TestCase):
  116. def test_context_manager(self):
  117. orig_file = tempfile.TemporaryFile()
  118. base_file = File(orig_file)
  119. with base_file as f:
  120. self.assertIs(base_file, f)
  121. self.assertFalse(f.closed)
  122. self.assertTrue(f.closed)
  123. self.assertTrue(orig_file.closed)
  124. def test_namedtemporaryfile_closes(self):
  125. """
  126. The symbol django.core.files.NamedTemporaryFile is assigned as
  127. a different class on different operating systems. In
  128. any case, the result should minimally mock some of the API of
  129. tempfile.NamedTemporaryFile from the Python standard library.
  130. """
  131. tempfile = NamedTemporaryFile()
  132. self.assertTrue(hasattr(tempfile, "closed"))
  133. self.assertFalse(tempfile.closed)
  134. tempfile.close()
  135. self.assertTrue(tempfile.closed)
  136. def test_file_mode(self):
  137. # Should not set mode to None if it is not present.
  138. # See #14681, stdlib gzip module crashes if mode is set to None
  139. file = SimpleUploadedFile("mode_test.txt", b"content")
  140. self.assertFalse(hasattr(file, 'mode'))
  141. g = gzip.GzipFile(fileobj=file)
  142. class FileMoveSafeTests(unittest.TestCase):
  143. def test_file_move_overwrite(self):
  144. handle_a, self.file_a = tempfile.mkstemp(dir=os.environ['DJANGO_TEST_TEMP_DIR'])
  145. handle_b, self.file_b = tempfile.mkstemp(dir=os.environ['DJANGO_TEST_TEMP_DIR'])
  146. # file_move_safe should raise an IOError exception if destination file exists and allow_overwrite is False
  147. self.assertRaises(IOError, lambda: file_move_safe(self.file_a, self.file_b, allow_overwrite=False))
  148. # should allow it and continue on if allow_overwrite is True
  149. self.assertIsNone(file_move_safe(self.file_a, self.file_b, allow_overwrite=True))
  150. os.close(handle_a)
  151. os.close(handle_b)