Code

Ticket #15644: 15644-2.diff

File 15644-2.diff, 2.3 KB (added by claudep, 2 years ago)

Patch with tests

Line 
1diff --git a/django/core/files/base.py b/django/core/files/base.py
2index 48d0be4..47c06ab 100644
3--- a/django/core/files/base.py
4+++ b/django/core/files/base.py
5@@ -36,8 +36,13 @@ class File(FileProxyMixin):
6         if not hasattr(self, '_size'):
7             if hasattr(self.file, 'size'):
8                 self._size = self.file.size
9-            elif os.path.exists(self.file.name):
10+            elif hasattr(self.file, 'name') and os.path.exists(self.file.name):
11                 self._size = os.path.getsize(self.file.name)
12+            elif hasattr(self.file, 'tell') and hasattr(self.file, 'seek'):
13+                pos = self.file.tell()
14+                self.file.seek(0, os.SEEK_END)
15+                self._size = self.file.tell()
16+                self.file.seek(pos)
17             else:
18                 raise AttributeError("Unable to determine the file's size.")
19         return self._size
20diff --git a/tests/regressiontests/file_storage/tests.py b/tests/regressiontests/file_storage/tests.py
21index 769e2c7..74d13e5 100644
22--- a/tests/regressiontests/file_storage/tests.py
23+++ b/tests/regressiontests/file_storage/tests.py
24@@ -18,7 +18,7 @@ except ImportError:
25 
26 from django.conf import settings
27 from django.core.exceptions import SuspiciousOperation, ImproperlyConfigured
28-from django.core.files.base import ContentFile
29+from django.core.files.base import File, ContentFile
30 from django.core.files.images import get_image_dimensions
31 from django.core.files.storage import FileSystemStorage, get_storage_class
32 from django.core.files.uploadedfile import UploadedFile
33@@ -550,6 +550,17 @@ class ContentFileTestCase(unittest.TestCase):
34     def test_content_file_default_name(self):
35         self.assertEqual(ContentFile("content").name, None)
36 
37-    def test_content_file_custome_name(self):
38+    def test_content_file_custom_name(self):
39         name = "I can have a name too!"
40         self.assertEqual(ContentFile("content", name=name).name, name)
41+
42+class NoNameFileTestCase(unittest.TestCase):
43+    """
44+    Other examples of unnamed files may be tempfile.SpooledTemporaryFile or
45+    urllib.urlopen()
46+    """
47+    def test_noname_file_default_name(self):
48+        self.assertEqual(File(StringIO('A file with no name')).name, None)
49+
50+    def test_noname_file_get_size(self):
51+        self.assertEqual(File(StringIO('A file with no name')).size, 19)