1
# -*- coding: utf-8 -*-
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
19
import dummy_threading as threading
22
# Checking for the existence of Image is enough for CPython, but
23
# for PyPy, you need to check for the underlying modules
24
from PIL import Image, _imaging
28
class FileStorageTests(unittest.TestCase):
29
storage_class = FileSystemStorage
32
self.temp_dir = tempfile.mktemp()
33
os.makedirs(self.temp_dir)
34
self.storage = self.storage_class(location=self.temp_dir)
37
os.rmdir(self.temp_dir)
39
def test_file_access_options(self):
41
Standard file access options are available, and work as expected.
43
self.failIf(self.storage.exists('storage_test'))
44
f = self.storage.open('storage_test', 'w')
45
f.write('storage contents')
47
self.assert_(self.storage.exists('storage_test'))
49
f = self.storage.open('storage_test', 'r')
50
self.assertEqual(f.read(), 'storage contents')
53
self.storage.delete('storage_test')
54
self.failIf(self.storage.exists('storage_test'))
56
def test_file_storage_prevents_directory_traversal(self):
58
File storage prevents directory traversal (files can only be accessed if
59
they're below the storage location).
61
self.assertRaises(SuspiciousOperation, self.storage.exists, '..')
62
self.assertRaises(SuspiciousOperation, self.storage.exists, '/etc/passwd')
64
class CustomStorage(FileSystemStorage):
65
def get_available_name(self, name):
67
Append numbers to duplicate files rather than underscores, like Trac.
69
parts = name.split('.')
70
basename, ext = parts[0], parts[1:]
72
while self.exists(name):
73
name = '.'.join([basename, str(number)] + ext)
78
class CustomStorageTests(FileStorageTests):
79
storage_class = CustomStorage
81
def test_custom_get_available_name(self):
82
first = self.storage.save('custom_storage', ContentFile('custom contents'))
83
self.assertEqual(first, 'custom_storage')
84
second = self.storage.save('custom_storage', ContentFile('more contents'))
85
self.assertEqual(second, 'custom_storage.2')
86
self.storage.delete(first)
87
self.storage.delete(second)
89
class UnicodeFileNameTests(unittest.TestCase):
90
def test_unicode_file_names(self):
92
Regression test for #8156: files with unicode names I can't quite figure
93
out the encoding situation between doctest and this file, but the actual
94
repr doesn't matter; it just shouldn't return a unicode object.
96
uf = UploadedFile(name=u'¿Cómo?',content_type='text')
97
self.assertEqual(type(uf.__repr__()), str)
99
# Tests for a race condition on file saving (#4948).
100
# This is written in such a way that it'll always pass on platforms
103
class SlowFile(ContentFile):
106
return super(ContentFile, self).chunks()
108
class FileSaveRaceConditionTest(TestCase):
110
self.storage_dir = tempfile.mkdtemp()
111
self.storage = FileSystemStorage(self.storage_dir)
112
self.thread = threading.Thread(target=self.save_file, args=['conflict'])
115
shutil.rmtree(self.storage_dir)
117
def save_file(self, name):
118
name = self.storage.save(name, SlowFile("Data"))
120
def test_race_condition(self):
122
name = self.save_file('conflict')
124
self.assert_(self.storage.exists('conflict'))
125
self.assert_(self.storage.exists('conflict_'))
126
self.storage.delete('conflict')
127
self.storage.delete('conflict_')
129
class FileStoragePermissions(TestCase):
131
self.old_perms = settings.FILE_UPLOAD_PERMISSIONS
132
settings.FILE_UPLOAD_PERMISSIONS = 0666
133
self.storage_dir = tempfile.mkdtemp()
134
self.storage = FileSystemStorage(self.storage_dir)
137
settings.FILE_UPLOAD_PERMISSIONS = self.old_perms
138
shutil.rmtree(self.storage_dir)
140
def test_file_upload_permissions(self):
141
name = self.storage.save("the_file", ContentFile("data"))
142
actual_mode = os.stat(self.storage.path(name))[0] & 0777
143
self.assertEqual(actual_mode, 0666)
146
class FileStoragePathParsing(TestCase):
148
self.storage_dir = tempfile.mkdtemp()
149
self.storage = FileSystemStorage(self.storage_dir)
152
shutil.rmtree(self.storage_dir)
154
def test_directory_with_dot(self):
155
"""Regression test for #9610.
157
If the directory name contains a dot and the file name doesn't, make
158
sure we still mangle the file name instead of the directory name.
161
self.storage.save('dotted.path/test', ContentFile("1"))
162
self.storage.save('dotted.path/test', ContentFile("2"))
164
self.failIf(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path')))
165
self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test')))
166
self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test_')))
168
def test_first_character_dot(self):
170
File names with a dot as their first character don't have an extension,
171
and the underscore should get added to the end.
173
self.storage.save('dotted.path/.test', ContentFile("1"))
174
self.storage.save('dotted.path/.test', ContentFile("2"))
176
self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test')))
177
# Before 2.6, a leading dot was treated as an extension, and so
178
# underscore gets added to beginning instead of end.
179
if sys.version_info < (2, 6):
180
self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/_.test')))
182
self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test_')))
184
if Image is not None:
185
class DimensionClosingBug(TestCase):
187
Test that get_image_dimensions() properly closes files (#8817)
189
def test_not_closing_of_files(self):
191
Open files passed into get_image_dimensions() should stay opened.
193
empty_io = StringIO()
195
get_image_dimensions(empty_io)
197
self.assert_(not empty_io.closed)
199
def test_closing_of_filenames(self):
201
get_image_dimensions() called with a filename should closed the file.
203
# We need to inject a modified open() builtin into the images module
204
# that checks if the file was closed properly if the function is
205
# called with a filename instead of an file object.
206
# get_image_dimensions will call our catching_open instead of the
207
# regular builtin one.
209
class FileWrapper(object):
211
def __init__(self, f):
213
def __getattr__(self, name):
214
return getattr(self.f, name)
216
self._closed.append(True)
219
def catching_open(*args):
220
return FileWrapper(open(*args))
222
from django.core.files import images
223
images.open = catching_open
225
get_image_dimensions(os.path.join(os.path.dirname(__file__), "test1.png"))
228
self.assert_(FileWrapper._closed)