Debian Codegraph @

tests/model_fields/test_filefield.py

raw
1 import os
2 import pickle
3 import sys
4 import tempfile
5 import unittest
6 from pathlib import Path
7
8 from django.core.exceptions import FieldError, SuspiciousFileOperation
9 from django.core.files import File, temp
10 from django.core.files.base import ContentFile
11 from django.core.files.uploadedfile import TemporaryUploadedFile
12 from django.db import IntegrityError, models
13 from django.test import TestCase, override_settings
14 from django.test.utils import isolate_apps
15 from django.utils.version import PY311
16
17 from .models import Document
18
19
20 class FileFieldTests(TestCase):
21 def test_clearable(self):
22 """
23 FileField.save_form_data() will clear its instance attribute value if
24 passed False.
25 """
26 d = Document(myfile="something.txt")
27 self.assertEqual(d.myfile, "something.txt")
28 field = d._meta.get_field("myfile")
29 field.save_form_data(d, False)
30 self.assertEqual(d.myfile, "")
31
32 def test_unchanged(self):
33 """
34 FileField.save_form_data() considers None to mean "no change" rather
35 than "clear".
36 """
37 d = Document(myfile="something.txt")
38 self.assertEqual(d.myfile, "something.txt")
39 field = d._meta.get_field("myfile")
40 field.save_form_data(d, None)
41 self.assertEqual(d.myfile, "something.txt")
42
43 def test_changed(self):
44 """
45 FileField.save_form_data(), if passed a truthy value, updates its
46 instance attribute.
47 """
48 d = Document(myfile="something.txt")
49 self.assertEqual(d.myfile, "something.txt")
50 field = d._meta.get_field("myfile")
51 field.save_form_data(d, "else.txt")
52 self.assertEqual(d.myfile, "else.txt")
53
54 def test_delete_when_file_unset(self):
55 """
56 Calling delete on an unset FileField should not call the file deletion
57 process, but fail silently (#20660).
58 """
59 d = Document()
60 d.myfile.delete()
61
62 def test_refresh_from_db(self):
63 d = Document.objects.create(myfile="something.txt")
64 d.refresh_from_db()
65 self.assertIs(d.myfile.instance, d)
66
67 @unittest.skipIf(sys.platform == "win32", "Crashes with OSError on Windows.")
68 def test_save_without_name(self):
69 with tempfile.NamedTemporaryFile(suffix=".txt") as tmp:
70 document = Document.objects.create(myfile="something.txt")
71 document.myfile = File(tmp)
72 msg = f"Detected path traversal attempt in '{tmp.name}'"
73 with self.assertRaisesMessage(SuspiciousFileOperation, msg):
74 document.save()
75
76 def test_save_content_file_without_name(self):
77 d = Document()
78 d.myfile = ContentFile(b"")
79 msg = "File for myfile must have the name attribute specified to be saved."
80 with self.assertRaisesMessage(FieldError, msg) as cm:
81 d.save()
82
83 if PY311:
84 self.assertEqual(
85 cm.exception.__notes__, ["Pass a 'name' argument to ContentFile."]
86 )
87
88 def test_delete_content_file(self):
89 file = ContentFile(b"", name="foo")
90 d = Document.objects.create(myfile=file)
91 d.myfile.delete()
92 self.assertIsNone(d.myfile.name)
93 msg = "The 'myfile' attribute has no file associated with it."
94 with self.assertRaisesMessage(ValueError, msg):
95 getattr(d.myfile, "file")
96
97 def test_defer(self):
98 Document.objects.create(myfile="something.txt")
99 self.assertEqual(Document.objects.defer("myfile")[0].myfile, "something.txt")
100
101 def test_unique_when_same_filename(self):
102 """
103 A FileField with unique=True shouldn't allow two instances with the
104 same name to be saved.
105 """
106 Document.objects.create(myfile="something.txt")
107 with self.assertRaises(IntegrityError):
108 Document.objects.create(myfile="something.txt")
109
110 @unittest.skipIf(
111 sys.platform == "win32", "Windows doesn't support moving open files."
112 )
113 # The file's source and destination must be on the same filesystem.
114 @override_settings(MEDIA_ROOT=temp.gettempdir())
115 def test_move_temporary_file(self):
116 """
117 The temporary uploaded file is moved rather than copied to the
118 destination.
119 """
120 with TemporaryUploadedFile(
121 "something.txt", "text/plain", 0, "UTF-8"
122 ) as tmp_file:
123 tmp_file_path = tmp_file.temporary_file_path()
124 Document.objects.create(myfile=tmp_file)
125 self.assertFalse(
126 os.path.exists(tmp_file_path), "Temporary file still exists"
127 )
128
129 def test_open_returns_self(self):
130 """
131 FieldField.open() returns self so it can be used as a context manager.
132 """
133 d = Document.objects.create(myfile="something.txt")
134 # Replace the FileField's file with an in-memory ContentFile, so that
135 # open() doesn't write to disk.
136 d.myfile.file = ContentFile(b"", name="bla")
137 self.assertEqual(d.myfile, d.myfile.open())
138
139 def test_media_root_pathlib(self):
140 with tempfile.TemporaryDirectory() as tmp_dir:
141 with override_settings(MEDIA_ROOT=Path(tmp_dir)):
142 with TemporaryUploadedFile(
143 "foo.txt", "text/plain", 1, "utf-8"
144 ) as tmp_file:
145 document = Document.objects.create(myfile=tmp_file)
146 self.assertIs(
147 document.myfile.storage.exists(
148 os.path.join("unused", "foo.txt")
149 ),
150 True,
151 )
152
153 def test_pickle(self):
154 with tempfile.TemporaryDirectory() as tmp_dir:
155 with override_settings(MEDIA_ROOT=Path(tmp_dir)):
156 with open(__file__, "rb") as fp:
157 file1 = File(fp, name="test_file.py")
158 document = Document(myfile="test_file.py")
159 document.myfile.save("test_file.py", file1)
160 try:
161 dump = pickle.dumps(document)
162 loaded_document = pickle.loads(dump)
163 self.assertEqual(document.myfile, loaded_document.myfile)
164 self.assertEqual(
165 document.myfile.url,
166 loaded_document.myfile.url,
167 )
168 self.assertEqual(
169 document.myfile.storage,
170 loaded_document.myfile.storage,
171 )
172 self.assertEqual(
173 document.myfile.instance,
174 loaded_document.myfile.instance,
175 )
176 self.assertEqual(
177 document.myfile.field,
178 loaded_document.myfile.field,
179 )
180 myfile_dump = pickle.dumps(document.myfile)
181 loaded_myfile = pickle.loads(myfile_dump)
182 self.assertEqual(document.myfile, loaded_myfile)
183 self.assertEqual(document.myfile.url, loaded_myfile.url)
184 self.assertEqual(
185 document.myfile.storage,
186 loaded_myfile.storage,
187 )
188 self.assertEqual(
189 document.myfile.instance,
190 loaded_myfile.instance,
191 )
192 self.assertEqual(document.myfile.field, loaded_myfile.field)
193 finally:
194 document.myfile.delete()
195
196 @isolate_apps("model_fields")
197 def test_abstract_filefield_model(self):
198 """
199 FileField.model returns the concrete model for fields defined in an
200 abstract model.
201 """
202
203 class AbstractMyDocument(models.Model):
204 myfile = models.FileField(upload_to="unused")
205
206 class Meta:
207 abstract = True
208
209 class MyDocument(AbstractMyDocument):
210 pass
211
212 document = MyDocument(myfile="test_file.py")
213 self.assertEqual(document.myfile.field.model, MyDocument)